file
stringlengths
18
26
data
stringlengths
2
1.05M
the_stack_data/375199.c
#include <unistd.h> int main(void) { size_t len = 5; char string[] = {'A', 'B', '\0', 'C', 'D'}; int stdin_fd = 0; int stdout_fd = 1; int stderr_fd = 2; write(stdout_fd, string, len); return 0; }
the_stack_data/200142094.c
// Scott Kuhl #include <stdio.h> int main(void) { /* char is always a byte in C. However, it may be signed, unsigned or neither (i.e., unspecified). See char-signed-unsigned.c */ unsigned char a = 0x33; // 00110011 in binary; unsigned char b = 0x0F; // 00001111 in binary; // Values that we would expect unsigned char AandB = 0x03; unsigned char AorB = 0x3F; unsigned char AxorB = 0x3C; unsigned char notA = 0xCC; unsigned char notB = 0xF0; if((unsigned char) (a & b) != AandB) printf("AND Fail!\n"); if((unsigned char) (a | b) != AorB) printf("OR Fail!\n"); if((unsigned char) (a ^ b) != AxorB) printf("XOR Fail!\n"); if((unsigned char) (~a) != notA) printf("NOT A Fail!\n"); if((unsigned char) (~b) != notB) printf("NOT B Fail!\n"); /* Why are the casts above necessary? C will cast integer types * that are smaller than an int to an int. Without the cast, * some compilers will sometimes complain about comparison between * different types. See integer-promotion.c */ /* This... --> can be written like this: a = a & b --> a &= b a = a | b --> a |= b a = a ^ b --> a ^= b */ // Use << to shift bits to the left. After the bits are shifted, // any blank bits are set to 0. // // Use >> to shift bits to the right. If you are shifting // something that is an unsigned type, any blank bits are set to // 0. If you are shifting something that is a signed type, any // blank bits can be set to 0 or 1, depending on // implementation. An example involving >> on a signed type is // also included further down in this example. unsigned char allOn = 0xFF; if( (unsigned char) (allOn << 1) != 0xFE ) printf("<< Fail!"); if( (unsigned char) (allOn >> 4) != 0x0F ) printf(">> Fail!"); // You can shift and assign at the same time: unsigned char tmp = 0xFF; tmp <<= 1; // stores 0xFE in tmp // WARNING: Shifting by a negative amount is often allowed, but is // not defined by the C standard. Therefore, you should not do it! tmp = tmp << -1; // Effectively the same as above, but might not produce a compiler // warning. Regardless of if there is a warning, bitshifting by a negative number is undefined. // https://www.securecoding.cert.org/confluence/display/c/INT34-C.+Do+not+shift+an+expression+by+a+negative+number+of+bits+or+by+greater+than+or+equal+to+the+number+of+bits+that+exist+in+the+operand int outsmartCompiler = -1; tmp = tmp << outsmartCompiler; // WARNING: Shifting by an amount that is equal to or larger than // the precision of the type is undefined. int intA = 123; intA = intA << 32; // undefined because int is 32 bits tmp = tmp << 8; // OK! because tmp is promoted to an int before the bitshift occurs. Then, it is converted back into a char. // WARNING: Bitwise operators do not work on floats or // doubles. Using a union between a float and uint32_t is one way // to workaround this limitation. /* Bitshifts on signed integers may behave differently depending on implementation. For example, when the variable type is signed and when the most significant bit is 1. In this case, when you shift the bits to the right, the new bits will be 1 (according to the GCC compiler) or 0 (according to the Microsoft C compiler). The C11 standard explains that bitshifts are implementation-defined and have undefined aspects for signed types. https://www.securecoding.cert.org/confluence/display/c/INT13-C.+Use+bitwise+operators+only+on+unsigned+operands */ signed int allOnSigned = -1; printf("Bitshift right on a signed type keeps the most left bit...\n"); if( (allOnSigned >> 1) == -1 ) printf("...set to one.\n"); else if( (allOnSigned >> 1) == 0x7F ) printf("...set to zero.\n"); else printf("huh?\n"); }
the_stack_data/28261586.c
/* This testcase is part of GDB, the GNU debugger. Copyright (C) 2013-2017 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <unistd.h> void foo () { } int main () { sleep (1); foo (); sleep (3); return 0; }
the_stack_data/134043.c
/* Napisać rekurencyjną implementację funkcji obliczającej nk (n do potęgi k). */ #include <stdio.h> int power(int n, int k); int main() { int n, k; printf("Wpisz podstawę potęgi: "); scanf("%d", &n); printf("Wpisz wykładnik potęgi: "); scanf("%d", &k); printf("%d do potęgi %d = %d\n", n, k, power(n, k)); return 0; } int power(int n, int k) { if (k != 1) return (n * power(n, k - 1)); }
the_stack_data/113705.c
#include <stdio.h> #define SIZE 500000 #define MOD 524287 #define swap(x, y) t=x;x=y;y=t int n, a[SIZE], i, j, t; long long c; void heapify(int i) { j = (i << 1) + 1; while (j < n) { if (j + 1 < n && a[j + 1] < a[j]) j++; if (a[i] < a[j]) break; swap(a[i], a[j]); i = j; j = (j << 1) + 1; } } void make_heap() { for (i = n / 2; i >= 0; --i) heapify(i); } int main() { scanf("%d", &n); for (i = 0; i != n; ++i) scanf("%d", a + i); make_heap(); while (n-- > 1) { swap(a[0], a[n]); heapify(0); a[0] += a[n]; c += a[0]; heapify(0); } printf("%lld", c % MOD); return 0; }
the_stack_data/12636880.c
/* * deFCrypt3 - a decryptor for EXE files protected with "Future Crew FCrypt3", * * Copyright 2017 Sergei "x0r" Kolzun * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <stdarg.h> #define MEM_GETB(p) (*(uint8_t *)p) #define MEM_GETW_LE(p) (((*((uint8_t *)p + 1)) << 8) | (*(uint8_t *)p)) #define MEM_PUTW_LE(p, v) (*((uint8_t *)p) = v & 0xff, *(((uint8_t *)p + 1)) = (v >> 8) & 0xff); #define e_magic 0x00 #define e_cblp 0x01 #define e_cp 0x02 #define e_crlc 0x03 #define e_cparhdr 0x04 #define e_minalloc 0x05 #define e_maxalloc 0x06 #define e_ss 0x07 #define e_sp 0x08 #define e_csum 0x09 #define e_ip 0x0a #define e_cs 0x0b #define e_lfarlc 0x0c #define f_sp 0x00 #define f_ss 0x01 #define f_ip 0x02 #define f_cs 0x03 #define f_cpar 0x04 #define f_key 0x05 #define f_csum_add 0x06 #define f_csum_sub 0x07 static uint16_t fcr3_checksum(uint8_t *buffer, size_t length); static uint16_t fcr3_decrypt(uint8_t *buffer, size_t length, uint8_t key); static void die(const char *fmt, ...); FILE *fp_in, *fp_out; uint16_t exe_mz_header[0x10]; uint16_t fcrypt3_header[8]; static uint16_t fcr3_checksum(uint8_t *buffer, size_t length) { size_t i; uint16_t checksum = 0; for(i = 0; i < length; ++i) checksum -= buffer[i]; return checksum; } static uint16_t fcr3_decrypt(uint8_t *buffer, size_t length, uint8_t key) { size_t i, j; uint16_t checksum = 0; for(i = 0; i < length; i += 0x10) { for(j = 0; j < 0x10; ++j, ++key) { checksum += buffer[i + j]; buffer[i + j] = key - buffer[i + j]; } for(j = 0; j < 8; ++j) { buffer[i + j + 8] -= buffer[i + j]; buffer[i + j] ^= buffer[i + j + 8]; } } return checksum; } static void die(const char *fmt, ...) { va_list args; va_start(args, fmt); vfprintf(stderr, fmt, args); fprintf(stderr, "\n"); va_end(args); if(fp_in) fclose(fp_in); if(fp_out) fclose(fp_out); exit(EXIT_FAILURE); } int main(int argc, char *argv[]) { uint8_t *buffer; size_t header_length, data_length, decoder_start; printf("deFCrypt3 v0.7\n\n"); if (argc != 3) { printf("Usage: %s infile outfile\n", "defcr3"); return EXIT_SUCCESS; } if((fp_in = fopen(argv[1], "rb")) == NULL) die("Cannot open input file: '%s'!", argv[1]); if(fread(exe_mz_header, 1, 0x20, fp_in) != 0x20) die("Read error!"); if(exe_mz_header[e_magic] != 0x5a4d && exe_mz_header[e_magic] != 0x4d5a) die("EXE header not found!"); decoder_start = MEM_GETW_LE(&exe_mz_header[e_cs]) << 4; header_length = MEM_GETW_LE(&exe_mz_header[e_cparhdr]) << 4; if(fseek(fp_in, header_length + decoder_start, SEEK_SET) == -1) die("Read error!"); if(fread(fcrypt3_header, 1, 0x10, fp_in) != 0x10) die("Read error!"); data_length = MEM_GETW_LE(&fcrypt3_header[f_cpar]) << 4; if(!data_length || decoder_start < data_length || data_length < (MEM_GETW_LE(&fcrypt3_header[f_cs]) << 4) + MEM_GETW_LE(&fcrypt3_header[f_ip])) die("Bad FCrypt3 header!"); if(fseek(fp_in, 0, SEEK_SET) == -1) die("Read error!"); decoder_start += header_length; if((buffer = malloc(decoder_start)) == NULL) die("Not enough memory!"); if(fread(buffer, 1, decoder_start, fp_in) != decoder_start) die("Read error!"); fclose(fp_in); if(fcr3_checksum(buffer + (decoder_start - data_length), data_length) != MEM_GETW_LE(&fcrypt3_header[f_csum_sub])) die("File corrupted!"); if(fcr3_decrypt(buffer + (decoder_start - data_length), data_length, MEM_GETB(&fcrypt3_header[f_key])) != MEM_GETW_LE(&fcrypt3_header[f_csum_add])) die("File corrupted!"); ((uint16_t *)(buffer))[e_sp] = fcrypt3_header[f_sp]; ((uint16_t *)(buffer))[e_ss] = fcrypt3_header[f_ss]; ((uint16_t *)(buffer))[e_ip] = fcrypt3_header[f_ip]; ((uint16_t *)(buffer))[e_cs] = fcrypt3_header[f_cs]; data_length = decoder_start / 0x200; header_length = decoder_start % 0x200; if(header_length) data_length++; MEM_PUTW_LE(&((uint16_t *)(buffer))[e_cp], data_length) MEM_PUTW_LE(&((uint16_t *)(buffer))[e_cblp], header_length) if((fp_out = fopen(argv[2], "wb")) == NULL) die("Cannot open input file: '%s'!", argv[2]); if(fwrite(buffer, 1, decoder_start, fp_out) != decoder_start) die("Write error!"); printf("OK!\n"); fclose(fp_out); free(buffer); return EXIT_SUCCESS; }
the_stack_data/1065729.c
#include <sys/types.h> #include <limits.h> #include <stdlib.h> #include <stdio.h> int main(int argc, char *argv[]) { off_t fileofs; int minsize = atoi(argv[1]); fileofs = 0; #ifdef _LARGEFILE_SOURCE printf("%d:%lld\n", (sizeof(off_t) >= minsize), fileofs); #else printf("%d:%ld\n", (sizeof(off_t) >= minsize), fileofs); #endif return 0; }
the_stack_data/176705846.c
#include <stdio.h> #include <stdlib.h> struct some_struct { int elem1; int elem2; int *ptrelem; struct some_struct *next; }; typedef struct some_struct MyStruct; void case1(MyStruct *ptr) { printf("elem1: %d\n", ptr->elem1); // XXX: null-pointer-dereference if (!ptr) { // Use-then-check printf("elem2: %d\n", ptr->elem2); } else { // Check-then-use printf("eleme2 is null: %d\n", ptr->elem2); } } int main() { int val = 10; MyStruct* ptr = malloc(sizeof(MyStruct)); ptr->elem1 = 1; ptr->elem2 = 1; ptr->ptrelem = &val; case1(ptr); case1(NULL); }
the_stack_data/22736.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> int rrange(int, int); int main(int argc, char** argv) { srand(time(NULL)); if(argc <= 1 || argc > 3) { printf("Roll rolls a specified numer of dice, and tells you the result.\n"); printf("To use roll, type the command roll, followed by a string in this format:\n"); printf("[<number of dice to roll>]d<maximum value of die>\n"); printf("[<+, -, * or /><number to add, subtract, multiply or divide from value>]\n"); printf("[<'<' or '>'><the current throw will succeed it the throw is 'larger than or\n"); printf(" equal to', or 'less than or equal to', this number>]\n"); printf("You may need to surround your command with inverted commas.\n"); printf("\n"); printf("Examples:\n"); printf("roll \"2d6\" This rolls 2 six-sided dice.\n"); printf("roll \"d12+4\" This rolls a twelve-sided die, and adds 4 to the result.\n"); printf("roll \"3d12>7\" This rolls 3 12-sided dice, and for each throw, tells you that"); printf(" throw succeeded if the result was larger or equal to 7.\n"); printf("roll \"7d24*2>40\" This rolls 7 24-sided dice, and multiplieseach result by"); printf(" 2. Then roll tells you whether each result was larger than 40 or not.\n"); printf("\n"); printf("If you put a \"-n\" on the end of the command, then roll will make sure that"); printf("you won't miss any of the dice rolls.\n"); return 0; } int howMany = 0; int diceValue = 0; int whichSign = 0; int changeAmount = 0; char switchBy = 0; int throwSuccess = 0; float temp = 0; if(argv[1][0] == 'd') { howMany = 1; int tempCount = sscanf(argv[1], "d%i%c%i%c%i", &diceValue, &whichSign, &changeAmount, &switchBy, &throwSuccess); if(tempCount == EOF || tempCount == 0 || tempCount == 2 || tempCount == 4 || tempCount > 5) { printf("Roll rolls a specified numer of dice, and tells you the result.\n"); printf("To use roll, type the command roll, followed by a string in this format:\n"); printf("[<number of dice to roll>]d<maximum value of die>\n"); printf("[<+, -, * or /><number to add, subtract, multiply or divide from value>]\n"); printf("[<'<' or '>'><the current throw will succeed it the throw is 'larger than or\n"); printf(" equal to', or 'less than or equal to', this number>]\n"); printf("You may need to surround your command with inverted commas.\n"); printf("\n"); printf("Examples:\n"); printf("roll \"2d6\" This rolls 2 six-sided dice.\n"); printf("roll \"d12+4\" This rolls a twelve-sided die, and adds 4 to the result.\n"); printf("roll \"3d12>7\" This rolls 3 12-sided dice, and for each throw, tells you that"); printf(" throw succeeded if the result was larger or equal to 7.\n"); printf("roll \"7d24*2>40\" This rolls 7 24-sided dice, and multiplieseach result by"); printf(" 2. Then roll tells you whether each result was larger than 40 or not.\n"); printf("\n"); printf("If you put a \"-n\" on the end of the command, then roll will make sure that"); printf("you won't miss any of the dice rolls.\n"); return 0; } else if(tempCount == 1) { printf("Die rolled a %i.\n", rrange(1, diceValue)); } else if(tempCount == 3) { temp = rrange(1, diceValue); switch(whichSign) { case '+': printf("Die rolled a %.0f+%i = %.0f.\n", temp, changeAmount, temp + changeAmount); temp += changeAmount; break; case '-': printf("Die rolled a %.0f-%i = %.0f.\n", temp, changeAmount, temp - changeAmount); temp -= changeAmount; break; case '*': printf("Die rolled a %.0f*%i = %.0f.\n", temp, changeAmount, temp * changeAmount); temp *= changeAmount; break; case '/': printf("Die rolled a %.0f/%i = %.2f.\n", temp, changeAmount, temp / (float)changeAmount); temp /= changeAmount; break; case '>': printf("Die rolled a %.0f: throw %s.\n", temp, (temp >= changeAmount) ? "succeeded" : "failed"); break; case '<': printf("Die rolled a %.0f: throw %s.\n", temp, (temp <= changeAmount) ? "succeeded" : "failed"); break; } } else if(tempCount == 5) { temp = rrange(1, diceValue); switch(whichSign) { case '+': printf("Die rolled a %.0f+%i = %.0f:", temp, changeAmount, temp + changeAmount); temp += changeAmount; break; case '-': printf("Die rolled a %.0f-%i = %.0f:", temp, changeAmount, temp - changeAmount); temp -= changeAmount; break; case '*': printf("Die rolled a %.0f*%i = %.0f:", temp, changeAmount, temp * changeAmount); temp *= changeAmount; break; case '/': printf("Die rolled a %.0f/%i = %.02:", temp, changeAmount, temp / (float)changeAmount); temp /= changeAmount; break; } switch(switchBy) { case '>': printf(" throw %s.\n", (temp >= throwSuccess) ? "succeeded" : "failed"); break; case '<': printf(" throw %s.\n", (temp <= throwSuccess) ? "succeeded" : "failed"); break; } } } else { int tempCount = sscanf(argv[1], "%id%i%c%i%c%i", &howMany, &diceValue, &whichSign, &changeAmount, &switchBy, &throwSuccess); if(tempCount == EOF || tempCount <= 1 || tempCount == 3 || tempCount == 5 || tempCount > 6) { printf("Roll rolls a specified numer of dice, and tells you the result.\n"); printf("To use roll, type the command roll, followed by a string in this format:\n"); printf("[<number of dice to roll>]d<maximum value of die>\n"); printf("[<+, -, * or /><number to add, subtract, multiply or divide from value>]\n"); printf("[<'<' or '>'><the current throw will succeed it the throw is 'larger than or\n"); printf(" equal to', or 'less than or equal to', this number>]\n"); printf("You may need to surround your command with inverted commas.\n"); printf("\n"); printf("Examples:\n"); printf("roll \"2d6\" This rolls 2 six-sided dice.\n"); printf("roll \"d12+4\" This rolls a twelve-sided die, and adds 4 to the result.\n"); printf("roll \"3d12>7\" This rolls 3 12-sided dice, and for each throw, tells you that"); printf(" throw succeeded if the result was larger or equal to 7.\n"); printf("roll \"7d24*2>40\" This rolls 7 24-sided dice, and multiplies each result by"); printf(" 2. Then roll tells you whether each result was larger than 40 or not.\n"); printf("\n"); printf("If you put a \"-n\" on the end of the command, then roll will make sure that"); printf("you won't miss any of the dice rolls.\n"); return 0; } else if(tempCount == 2) { for(int i = 0; i < howMany; i++) { printf("Die %i rolled a %i.\n", (i + 1), rrange(1, diceValue)); } } else if(tempCount == 4) { for(int i = 0; i < howMany; i++) { temp = rrange(1, diceValue); switch(whichSign) { case '+': printf("Die rolled a %.0f+%i = %.0f.\n", temp, changeAmount, temp + changeAmount); temp += changeAmount; break; case '-': printf("Die rolled a %.0f-%i = %.0f.\n", temp, changeAmount, temp - changeAmount); temp -= changeAmount; break; case '*': printf("Die rolled a %.0f*%i = %.0f.\n", temp, changeAmount, temp * changeAmount); temp *= changeAmount; break; case '/': printf("Die rolled a %.0f/%i = %.02.\n", temp, changeAmount, temp / (float)changeAmount); temp /= changeAmount; break; case '>': printf("Die rolled a %.0f: throw %s.\n", temp, (temp >= changeAmount) ? "succeeded" : "failed"); break; case '<': printf("Die rolled a %.0f: throw %s.\n", temp, (temp <= changeAmount) ? "succeeded" : "failed"); break; } } } else if(tempCount == 6) { for(int i = 0; i < howMany; i++) { temp = rrange(1, diceValue); switch(whichSign) { case '+': printf("Die rolled a %.0f+%i = %.0f:", temp, changeAmount, temp + changeAmount); temp += changeAmount; break; case '-': printf("Die rolled a %.0f-%i = %.0f:", temp, changeAmount, temp - changeAmount); temp -= changeAmount; break; case '*': printf("Die rolled a %.0f*%i = %.0f:", temp, changeAmount, temp * changeAmount); temp *= changeAmount; break; case '/': printf("Die rolled a %.0f/%i = %.02:", temp, changeAmount, temp / (float)changeAmount); temp /= changeAmount; break; } switch(switchBy) { case '>': printf(" throw %s.\n", (temp >= throwSuccess) ? "succeeded" : "failed"); break; case '<': printf(" throw %s.\n", (temp <= throwSuccess) ? "succeeded" : "failed"); break; } } } } if(argc > 2) { if(strlen(argv[2]) == 2 && argv[2][0] == '-' && argv[2][1] == 'n') { printf("Press any key to quit... "); getchar(); return 0; } } } int rrange(int a, int b) { int temp = rand(); while(temp < a || temp > b) { temp = rand(); } return temp; }
the_stack_data/182953282.c
#include <stdio.h> #include <ctype.h> main() { char line[BUFSIZ]; char * s; while(gets(line)) { s = line; while(*s&&!isspace(*s)) s++; while(isspace(*s)) s++; printf("%s\n", s ); } }
the_stack_data/198581371.c
#include <stdlib.h> #include <stdio.h> typedef struct node { int value; struct node *next; } Node; int main(void) { Node x; // First we assign, NULL to first. Node *first = NULL; // Then we completely assign a new blank structure to new_node; Node *new_node = &x; // Then we fill the integer value in "value" by pointing new_node. new_node->value = 10; // Now in "next" we fill first, which is initially NULL new_node->next = first; // Now at this stage structure "x" contains value 10 and NULL, and we assign "x" to first by new_node. We can directly assign "x" to first (think it, why we haven't). first = &x; // Same procedure.... Node y; new_node = &y; new_node->value = 20; new_node->next = first; first = new_node; printf("%d", new_node->value); return 0; } // Now if we have to insert 100 list, we have to declare 100 structure variables or single array structures. But doing it in structure-array way has // disadvantages with respect to doing the same in dynamic-allocation way(or pointer way) which you'll learn when you have some experience with it. // Here's a way to do that, in this value is printed in the reverse way. /*** #include <stdio.h> #include <stdlib.h> typedef struct NODE { int value; struct NODE *link; } Node; int main(void) { Node *root, *connector = NULL; root = malloc(sizeof(Node)); root->link = connector; root->value = 5; connector = root; root = malloc(sizeof(Node)); root->link = connector; root->value = 10; connector = root; } ***/ /**** Here is the second version and in this, output is printed in the same way. #include <stdio.h> #include <stdlib.h> typedef struct NODE { int value; struct NODE *next; } Node; int main(void) { Node *root, *connector; connector = malloc(sizeof(Node)); connector->value = 5; connector->next = NULL; root = connector; connector->next = malloc(sizeof(Node)); connector->next->value = 10; connector = connector->next; connector->next = NULL; connector->next = malloc(sizeof(Node)); connector->next->value = 15; connector = connector->next; connector->next = NULL; while(root != NULL) { printf("%d\n", root->value); root = root->next; } return 0; } ****/
the_stack_data/891991.c
// // Created by xupeng on 2021/3/2. //
the_stack_data/243893685.c
// BUILD: mkdir -p $BUILD_DIR/override // BUILD: mkdir -p $BUILD_DIR/re-export-override // BUILD: $CC myzlib.c -dynamiclib -o $BUILD_DIR/override/libz.1.dylib -install_name /usr/lib/libz.1.dylib -compatibility_version 1.0 -framework CoreFoundation // BUILD: $CC reexported-myzlib.c -dynamiclib -o $BUILD_DIR/re-export-override/reexported.dylib -compatibility_version 1.0 -framework CoreFoundation // BUILD: $CC reexporter.c -dynamiclib -o $BUILD_DIR/re-export-override/libz.1.dylib -install_name /usr/lib/libz.1.dylib -compatibility_version 1.0 -Wl,-reexport_library,$BUILD_DIR/re-export-override/reexported.dylib // BUILD: $CC main.c -o $BUILD_DIR/main.exe -lz // BUILD: $DYLD_ENV_VARS_ENABLE $BUILD_DIR/main.exe // RUN: ./main.exe // RUN: DYLD_LIBRARY_PATH=$RUN_DIR/override/ ./main.exe // RUN: DYLD_LIBRARY_PATH=$RUN_DIR/re-export-override/ ./main.exe #include <stdio.h> #include <stdlib.h> #include <string.h> #include <zlib.h> #include <stdbool.h> // The test here is to override libz.1.dylib which is in the dyld cache with our own implementation. int main() { bool expectMyDylib = (getenv("DYLD_LIBRARY_PATH") != NULL); printf("[BEGIN] env-DYLD_LIBRARY_PATH-cache, %s\n", expectMyDylib ? "my" : "os"); bool usingMyDylib = (strcmp(zlibVersion(), "my") == 0); if ( usingMyDylib == expectMyDylib ) printf("[PASS] env-DYLD_LIBRARY_PATH-cache, %s\n", expectMyDylib ? "my" : "os"); else printf("[FAIL] env-DYLD_LIBRARY_PATH-cache, %s\n", expectMyDylib ? "my" : "os"); return 0; }
the_stack_data/140765879.c
/* Hadi has changed this code to meet his goals. */ /* ----------------------------------------------------------------------- * * * Copyright 2000 Transmeta Corporation - All Rights Reserved * Copyright 2004-2008 H. Peter Anvin - All Rights Reserved * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston MA 02110-1301, USA; either version 2 of the License, or * (at your option) any later version; incorporated herein by reference. * * ----------------------------------------------------------------------- */ /* * rdmsr.c * * Utility to read an MSR. */ #include <errno.h> #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> #include <getopt.h> #include <inttypes.h> #include <sys/types.h> #include <dirent.h> #include <ctype.h> int SampleNumbers = 200000; //total number of samples int samplingInterval = 100; //sleep time, default 1ms static int loadDriver(int cpu) { int fd; char msr_file_name[64]; sprintf(msr_file_name, "/dev/cpu/%d/msr", cpu); fd = open(msr_file_name, O_RDONLY); if (fd < 0) { if (errno == ENXIO) { fprintf(stderr, "rdmsr: No CPU %d\n", cpu); exit(2); } else if (errno == EIO) { fprintf(stderr, "rdmsr: CPU %d doesn't support MSRs\n", cpu); exit(3); } else { perror("rdmsr: open"); exit(127); } } return fd; } static void closeDriver(int fd) { int e; e = close(fd); if (e == -1) { perror("Failed to close fd"); } } uint64_t rdmsr_on_cpu(uint32_t reg, int fd); /* filter out ".", "..", "microcode" in /dev/cpu */ /* int dir_filter(const struct dirent *dirp) { if (isdigit(dirp->d_name[0])) return 1; else return 0; } void rdmsr_on_all_cpus(uint32_t reg) { struct dirent **namelist; int dir_entries; dir_entries = scandir("/dev/cpu", &namelist, dir_filter, 0); while (dir_entries--) { rdmsr_on_cpu(reg, atoi(namelist[dir_entries]->d_name)); free(namelist[dir_entries]); } free(namelist); } */ int main(int argc, char *argv[]) { uint64_t data; // uint32_t reg; int cpu = 0; int i; char buffer[50]; unsigned long long * freqs = (unsigned long long *) malloc(SampleNumbers*sizeof(unsigned long long)); unsigned long long * energy = (unsigned long long *) malloc(SampleNumbers*sizeof(unsigned long long)); sprintf(buffer,"%s.txt",argv[1]); FILE *out_file; out_file = fopen(buffer,"w"); int fd = loadDriver(cpu); for (i=0;i<SampleNumbers;i++){ usleep(samplingInterval); //sleep 1 milisecond data = rdmsr_on_cpu(0x198,fd); freqs[i] = data & 0xFFFF; data = rdmsr_on_cpu(0x611,fd); energy[i] = data; //- prev_energy; } for(i=0;i<SampleNumbers;i++){ fprintf(out_file,"%7lld ", freqs[i]); fprintf(out_file,"%7lld \n", energy[i]); } /* reg = 0x611; data = rdmsr_on_cpu(reg,fd); printf("%llu\n",data); */ closeDriver(fd); fclose(out_file); free(freqs); free(energy); exit(0); } uint64_t rdmsr_on_cpu(uint32_t reg, int fd) { uint64_t data; int cpu = 0; if (pread(fd, &data, sizeof data, reg) != sizeof data) { if (errno == EIO) { fprintf(stderr, "rdmsr: CPU %d cannot read " "MSR 0x%08"PRIx32"\n", cpu, reg); exit(4); } else { perror("rdmsr: pread"); exit(127); } } return data; }
the_stack_data/776638.c
/* * You run an e-commerce website and want to record the last N order ids in a * log. Implement a data structure to accomplish this, with the following API: * * record(order_id): adds the order_id to the log get_last(i): gets the ith * last element from the log. i is guaranteed to be smaller than or equal to N. * * You should be as efficient with time and space as possible. */ #include <stdio.h> #include <stdlib.h> struct { int size; int last; int* orders; } lastest_orders_list; void record(int order_id) { lastest_orders_list.last = (lastest_orders_list.last + 1) % lastest_orders_list.size; lastest_orders_list.orders[lastest_orders_list.last] = order_id; } int get_last() { return lastest_orders_list.orders[lastest_orders_list.last]; } int main(void) { // Initializing the data structure lastest_orders_list.size = 10; lastest_orders_list.last = 0; lastest_orders_list.orders = malloc(sizeof(int) * lastest_orders_list.size); /* Do something with the list */ free(lastest_orders_list.orders); return 0; }
the_stack_data/97013936.c
#include <stdio.h> #include <stdlib.h> #include <netinet/in.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <string.h> #define ElfHeaderSize (64 * 1024) #define ElfPages (ElfHeaderSize / 4096) #define KERNELBASE (0xc000000000000000) void get4k(FILE *file, char *buf ) { unsigned j; unsigned num = fread(buf, 1, 4096, file); for ( j=num; j<4096; ++j ) buf[j] = 0; } void put4k(FILE *file, char *buf ) { fwrite(buf, 1, 4096, file); } void death(const char *msg, FILE *fdesc, const char *fname) { fprintf(stderr, msg); fclose(fdesc); unlink(fname); exit(1); } int main(int argc, char **argv) { char inbuf[4096]; FILE *ramDisk = NULL; FILE *sysmap = NULL; FILE *inputVmlinux = NULL; FILE *outputVmlinux = NULL; unsigned i = 0; unsigned long ramFileLen = 0; unsigned long ramLen = 0; unsigned long roundR = 0; unsigned long sysmapFileLen = 0; unsigned long sysmapLen = 0; unsigned long sysmapPages = 0; char* ptr_end = NULL; unsigned long offset_end = 0; unsigned long kernelLen = 0; unsigned long actualKernelLen = 0; unsigned long round = 0; unsigned long roundedKernelLen = 0; unsigned long ramStartOffs = 0; unsigned long ramPages = 0; unsigned long roundedKernelPages = 0; unsigned long hvReleaseData = 0; u_int32_t eyeCatcher = 0xc8a5d9c4; unsigned long naca = 0; unsigned long xRamDisk = 0; unsigned long xRamDiskSize = 0; long padPages = 0; if (argc < 2) { fprintf(stderr, "Name of RAM disk file missing.\n"); exit(1); } if (argc < 3) { fprintf(stderr, "Name of System Map input file is missing.\n"); exit(1); } if (argc < 4) { fprintf(stderr, "Name of vmlinux file missing.\n"); exit(1); } if (argc < 5) { fprintf(stderr, "Name of vmlinux output file missing.\n"); exit(1); } ramDisk = fopen(argv[1], "r"); if ( ! ramDisk ) { fprintf(stderr, "RAM disk file \"%s\" failed to open.\n", argv[1]); exit(1); } sysmap = fopen(argv[2], "r"); if ( ! sysmap ) { fprintf(stderr, "System Map file \"%s\" failed to open.\n", argv[2]); exit(1); } inputVmlinux = fopen(argv[3], "r"); if ( ! inputVmlinux ) { fprintf(stderr, "vmlinux file \"%s\" failed to open.\n", argv[3]); exit(1); } outputVmlinux = fopen(argv[4], "w+"); if ( ! outputVmlinux ) { fprintf(stderr, "output vmlinux file \"%s\" failed to open.\n", argv[4]); exit(1); } /* Input Vmlinux file */ fseek(inputVmlinux, 0, SEEK_END); kernelLen = ftell(inputVmlinux); fseek(inputVmlinux, 0, SEEK_SET); printf("kernel file size = %d\n", kernelLen); if ( kernelLen == 0 ) { fprintf(stderr, "You must have a linux kernel specified as argv[3]\n"); exit(1); } actualKernelLen = kernelLen - ElfHeaderSize; printf("actual kernel length (minus ELF header) = %d\n", actualKernelLen); round = actualKernelLen % 4096; roundedKernelLen = actualKernelLen; if ( round ) roundedKernelLen += (4096 - round); printf("Vmlinux length rounded up to a 4k multiple = %ld/0x%lx \n", roundedKernelLen, roundedKernelLen); roundedKernelPages = roundedKernelLen / 4096; printf("Vmlinux pages to copy = %ld/0x%lx \n", roundedKernelPages, roundedKernelPages); /* Input System Map file */ /* (needs to be processed simply to determine if we need to add pad pages due to the static variables not being included in the vmlinux) */ fseek(sysmap, 0, SEEK_END); sysmapFileLen = ftell(sysmap); fseek(sysmap, 0, SEEK_SET); printf("%s file size = %ld/0x%lx \n", argv[2], sysmapFileLen, sysmapFileLen); sysmapLen = sysmapFileLen; roundR = 4096 - (sysmapLen % 4096); if (roundR) { printf("Rounding System Map file up to a multiple of 4096, adding %ld/0x%lx \n", roundR, roundR); sysmapLen += roundR; } printf("Rounded System Map size is %ld/0x%lx \n", sysmapLen, sysmapLen); /* Process the Sysmap file to determine where _end is */ sysmapPages = sysmapLen / 4096; for (i=0; i<sysmapPages; ++i) { get4k(sysmap, inbuf); } /* search for _end in the last page of the system map */ ptr_end = strstr(inbuf, " _end"); if (!ptr_end) { fprintf(stderr, "Unable to find _end in the sysmap file \n"); fprintf(stderr, "inbuf: \n"); fprintf(stderr, "%s \n", inbuf); exit(1); } printf("Found _end in the last page of the sysmap - backing up 10 characters it looks like %s", ptr_end-10); /* convert address of _end in system map to hex offset. */ offset_end = (unsigned int)strtol(ptr_end-10, NULL, 16); /* calc how many pages we need to insert between the vmlinux and the start of the ram disk */ padPages = offset_end/4096 - roundedKernelPages; /* Check and see if the vmlinux is already larger than _end in System.map */ if (padPages < 0) { /* vmlinux is larger than _end - adjust the offset to the start of the embedded ram disk */ offset_end = roundedKernelLen; printf("vmlinux is larger than _end indicates it needs to be - offset_end = %lx \n", offset_end); padPages = 0; printf("will insert %lx pages between the vmlinux and the start of the ram disk \n", padPages); } else { /* _end is larger than vmlinux - use the offset to _end that we calculated from the system map */ printf("vmlinux is smaller than _end indicates is needed - offset_end = %lx \n", offset_end); printf("will insert %lx pages between the vmlinux and the start of the ram disk \n", padPages); } /* Input Ram Disk file */ // Set the offset that the ram disk will be started at. ramStartOffs = offset_end; /* determined from the input vmlinux file and the system map */ printf("Ram Disk will start at offset = 0x%lx \n", ramStartOffs); fseek(ramDisk, 0, SEEK_END); ramFileLen = ftell(ramDisk); fseek(ramDisk, 0, SEEK_SET); printf("%s file size = %ld/0x%lx \n", argv[1], ramFileLen, ramFileLen); ramLen = ramFileLen; roundR = 4096 - (ramLen % 4096); if ( roundR ) { printf("Rounding RAM disk file up to a multiple of 4096, adding %ld/0x%lx \n", roundR, roundR); ramLen += roundR; } printf("Rounded RAM disk size is %ld/0x%lx \n", ramLen, ramLen); ramPages = ramLen / 4096; printf("RAM disk pages to copy = %ld/0x%lx\n", ramPages, ramPages); // Copy 64K ELF header for (i=0; i<(ElfPages); ++i) { get4k( inputVmlinux, inbuf ); put4k( outputVmlinux, inbuf ); } /* Copy the vmlinux (as full pages). */ fseek(inputVmlinux, ElfHeaderSize, SEEK_SET); for ( i=0; i<roundedKernelPages; ++i ) { get4k( inputVmlinux, inbuf ); put4k( outputVmlinux, inbuf ); } /* Insert pad pages (if appropriate) that are needed between */ /* | the end of the vmlinux and the ram disk. */ for (i=0; i<padPages; ++i) { memset(inbuf, 0, 4096); put4k(outputVmlinux, inbuf); } /* Copy the ram disk (as full pages). */ for ( i=0; i<ramPages; ++i ) { get4k( ramDisk, inbuf ); put4k( outputVmlinux, inbuf ); } /* Close the input files */ fclose(ramDisk); fclose(inputVmlinux); /* And flush the written output file */ fflush(outputVmlinux); /* Fixup the new vmlinux to contain the ram disk starting offset (xRamDisk) and the ram disk size (xRamDiskSize) */ /* fseek to the hvReleaseData pointer */ fseek(outputVmlinux, ElfHeaderSize + 0x24, SEEK_SET); if (fread(&hvReleaseData, 4, 1, outputVmlinux) != 1) { death("Could not read hvReleaseData pointer\n", outputVmlinux, argv[4]); } hvReleaseData = ntohl(hvReleaseData); /* Convert to native int */ printf("hvReleaseData is at %08x\n", hvReleaseData); /* fseek to the hvReleaseData */ fseek(outputVmlinux, ElfHeaderSize + hvReleaseData, SEEK_SET); if (fread(inbuf, 0x40, 1, outputVmlinux) != 1) { death("Could not read hvReleaseData\n", outputVmlinux, argv[4]); } /* Check hvReleaseData sanity */ if (memcmp(inbuf, &eyeCatcher, 4) != 0) { death("hvReleaseData is invalid\n", outputVmlinux, argv[4]); } /* Get the naca pointer */ naca = ntohl(*((u_int32_t*) &inbuf[0x0C])) - KERNELBASE; printf("Naca is at offset 0x%lx \n", naca); /* fseek to the naca */ fseek(outputVmlinux, ElfHeaderSize + naca, SEEK_SET); if (fread(inbuf, 0x18, 1, outputVmlinux) != 1) { death("Could not read naca\n", outputVmlinux, argv[4]); } xRamDisk = ntohl(*((u_int32_t *) &inbuf[0x0c])); xRamDiskSize = ntohl(*((u_int32_t *) &inbuf[0x14])); /* Make sure a RAM disk isn't already present */ if ((xRamDisk != 0) || (xRamDiskSize != 0)) { death("RAM disk is already attached to this kernel\n", outputVmlinux, argv[4]); } /* Fill in the values */ *((u_int32_t *) &inbuf[0x0c]) = htonl(ramStartOffs); *((u_int32_t *) &inbuf[0x14]) = htonl(ramPages); /* Write out the new naca */ fflush(outputVmlinux); fseek(outputVmlinux, ElfHeaderSize + naca, SEEK_SET); if (fwrite(inbuf, 0x18, 1, outputVmlinux) != 1) { death("Could not write naca\n", outputVmlinux, argv[4]); } printf("Ram Disk of 0x%lx pages is attached to the kernel at offset 0x%08x\n", ramPages, ramStartOffs); /* Done */ fclose(outputVmlinux); /* Set permission to executable */ chmod(argv[4], S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH); return 0; }
the_stack_data/905825.c
extern int mcsema_main(int argc, const char *argv[]); int main(int argc, const char *argv[]) { return mcsema_main(argc, argv); }
the_stack_data/418359.c
struct test { unsigned int val : 3; }; int main() { struct test t; t.val = 3; return t.val; }
the_stack_data/99239.c
#include <stdio.h> long int fact(long int x) { if(x) return x*fact(x-1); return 1; } int main() { long int n; printf("Rentrez un nombre\n> "); scanf("%ld",&n); printf("Le resultat de %d factorielle est %ld",n,fact(n)); return 0; }
the_stack_data/154829423.c
#include <stdio.h> void Hello(void) { printf("Hi!\n"); }
the_stack_data/190400.c
#include <stdio.h> extern void myfuncb(); extern void myfuncc(); void myfunca() { printf("myfunca\n"); } int main(int argc, char *argv[]) { myfunca(); myfuncb(); myfuncc(); }
the_stack_data/529526.c
#include <ctype.h> #include <limits.h> #include <stdio.h> /* * Exercise 6 * Page: 107 * Rewrite appropriate programs from earlier chapters * and exercises with pointers instead of array indexing. * Good possibilities include getline (Chapters 1 and 4), * atoi , itoa , and their variants (Chapters 2, 3, and 4), * reverse (Chapter 3), and strindex and getop (Chapter 4). * */ #define MAXLEN 100 static int get_line(char *s, int lim); static void reverse(char s[]); int main(void) { char s[MAXLEN] = ""; while (get_line(s, MAXLEN - 1) > 0) { printf("%s\n", s); reverse(s); printf("%s\n", s); } return 0; } static int get_line(char *s, int lim) { int c, i; for (i = 0; (c = getchar()) != EOF && c != (int)'\n'; ++i) { if ((i < lim - 1)) *s++ = (char)c; } if (c == (int)'\n' && (i < lim - 1)) { *s++ = (char)c; i++; } if ((i < lim - 1)) *s++ = '\0'; else { *s-- = '\0'; *s = '\n'; } return i; } static void reverse(char *s) { char temp; char *s_iter = s; while (*s != '\0') { s++; } s--; while (s - s_iter > 0) { temp = *s; *s = *s_iter; *s_iter = temp; --s; ++s_iter; } }
the_stack_data/165765496.c
#include <stdio.h> #include <stdlib.h> #include <locale.h> linha3x() { int i; for(i = 1; i <= 3; i++) { putchar('*'); } putchar('\n'); } linha5x() { int i; for(i = 1; i <= 5; i++) { putchar('*'); } putchar('\n'); } linha7x() { int i; for(i = 1; i <= 7; i++) { putchar('*'); } putchar('\n'); } int main() { setlocale(LC_ALL, "Portuguese"); int i; linha3x(); linha5x(); linha7x(); linha5x(); linha3x(); printf("\n\n"); system("pause"); return 0; }
the_stack_data/769774.c
/* Qn : Write a c program to input the value of N and print the sum of the following series: 1 + 1/2! + 1/3! + 1/4! + . . . + 1/𝑁! Sample Input Sample Output 7 1.718254 */ /* Author : Arnob Mahmud mail : [email protected] */ #include <stdio.h> #include <math.h> int main(int argc, char const *argv[]) { int N, fact; float sum = 0.0; printf("Enter N : "); scanf("%d", &N); for (int i = 1; i <= N; i++) { fact = 1; for (int j = 1; j <= i; j++) { fact *= j; } //printf("1/%d! + ", i); sum += 1.0 / fact; } printf("Sum is : %f", sum); return 0; }
the_stack_data/647047.c
#include <stdio.h> #include <string.h> int main(void) { float daphne, deirdre; daphne = deirdre = 100; int year = 0; do { daphne = daphne + 100 * 0.1; deirdre = deirdre*1.05; year++; } while (deirdre - daphne > 9); printf("5d years later.\nDaphne = %f.\nDeirdre = %f \n", year, daphne, deirdre); printf("\nDone!\n"); return 0; }
the_stack_data/9513449.c
/* |4.2| * 1. Dado um número real qualquer informado pelo usuário, mostre o valor absoluto dele. */ #include <stdio.h> int main(void) { float numero; puts("Entre com um número real qualquer:"); scanf("%f", &numero); printf("Valor absoluto: %f\n", \ (numero < 0) ? (-numero) : numero); return 0; }
the_stack_data/86375.c
// // Created by zhangrongxiang on 2017/10/12 16:03 // File client // #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include <unistd.h> #define BUFSIZE 1024 int main(int argc, char *argv[]) { int client_sockfd; int len; struct sockaddr_in remote_addr; //服务器端网络地址结构体 int sin_size; char buf[BUFSIZE]; //数据传送的缓冲区 memset(&remote_addr, 0, sizeof(remote_addr)); //数据初始化--清零 remote_addr.sin_family = AF_INET; //设置为IP通信 remote_addr.sin_addr.s_addr = inet_addr("127.0.0.1");//服务器IP地址 remote_addr.sin_port = htons(8000); //服务器端口号 /*创建客户端套接字--IPv4协议,面向无连接通信,UDP协议*/ if ((client_sockfd = socket(PF_INET, SOCK_DGRAM, 0)) < 0) { perror("socket"); return 1; } strcpy(buf, "This is a test message"); printf("sending: '%s'\n", buf); sin_size = sizeof(struct sockaddr_in); /*向服务器发送数据包*/ if ((len = sendto(client_sockfd, buf, strlen(buf), 0, (struct sockaddr *) &remote_addr, sizeof(struct sockaddr))) < 0) { perror("recvfrom"); return 1; } close(client_sockfd); return 0; }
the_stack_data/168893733.c
enum day_of_the_week {Monday = 0, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}; static enum day_of_the_week day __attribute__((used));
the_stack_data/41175.c
#include<stdio.h> int BinarySearch(int arr[], int size, int element) { int low,mid,high; low = 0; high = size -1; while(low <= high) { mid = (low + high)/2; if (arr[mid] == element) { return mid; } if(arr[mid] < element) { low = mid + 1; } else { high = mid - 1; } } return -1; } int main() { int arr[] = {1,2,5,8,47,48,51,65}; int size = sizeof(arr)/sizeof(int); int element = 47; int search = BinarySearch(arr, size, element); printf("The element %d is found in index %d",element,search); return 0; }
the_stack_data/25138825.c
#include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<stdlib.h> #include <sys/wait.h> int main(void){ pid_t childpid; childpid=fork(); if(childpid==0) printf("Inside Child\n"); else{ //wait(NULL); printf("In parent\n"); } return 0; }
the_stack_data/187644452.c
#include<stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> int original_class; float leeta=0.001; float epsi=0.01; // between input layer and hidden layer... void generate_rand(int x, int y , float w[6][18]){ srand(time(NULL)); int i,j; float r; for(i=0;i<x;i++){ for(j=0;j<y;j++){ r = rand(); w[i][j] = (1+rand()%1000)/2000.0; } } } // between hidden layer and output layer... void generate_rand2(int x, int y , float w[11][6]){ srand(time(NULL)); int i,j; float r; for(i=0;i<x;i++){ for(j=0;j<y;j++){ r = rand(); w[i][j] = (1+rand()%1000)/2000.0; } } } void get_act(float act_fun1[6],int n,float input[17], float w[6][18],int x, int y,float fnet[6]){ int i,j; float hidden[n]; for(i=0;i<x;i++){ hidden[i]=0.0; for(j=0;j<y;j++){ hidden[i] = hidden[i]+ (input[j]*w[i][j]); } hidden[i] = -1* hidden[i]; float z = 1+exp(hidden[i]); act_fun1[i] =1/z; fnet[i]=act_fun1[i]*(1-act_fun1[i]); } } void get_act2(float act_fun2[10],int n,float input[6], float w[11][6],int x, int y,float fnet[10]){ int i,j; float hidden[n]; for(i=0;i<x;i++){ hidden[i]=0.0; for(j=0;j<y;j++){ hidden[i] = hidden[i]+ (input[j]*w[i][j]); } hidden[i] = -1* hidden[i]; float z = 1+exp(hidden[i]); act_fun2[i] =1/z; fnet[i]=act_fun2[i]*(1-act_fun2[i]); } } float multi_layer(int original_class,float act_fun2[6],float act_fun1[10],float w[6][18],float w2[11][6],float fnet[10],float input[17],float fnet1[6],float j_w[10],float delta[10],float delta1[6]){ int j,k; float dw; // Back propagation between hidden and output.. for(k=0;k<10;k++){ for(j=0;j<6;j++){ dw=leeta*act_fun2[j]*fnet[k]*j_w[k]*(-1); w2[k][j]+=dw; } } int i; // Back propagation between hidden and input.. for(i=0;i<6;i++){ dw=0.0; for(j=0;j<10;j++){ dw= dw + delta[j]* w2[j][i] * fnet1[i]; } delta1[i] = dw; } for(k=0;k<6;k++){ for(j=0;j<17;j++){ dw=leeta*input[j]*delta1[k]; w[k][j]+=dw; } //printf("\n"); } } int extractmaxindex(float final[10]){ float maxi=final[0]; int ind=0,i; for(i=1;i<10;i++){ if(final[i]>=maxi){ maxi=final[i]; ind=i; } } return ind+1; } void func1(){ //Training... int i,j,x=1,flag=0; float input[17]; float w[6][18],r,act_fun1[6],w2[11][6],act_fun2[10],fnet_1[6],fnet_2[10],delta[10],delta1[6]; FILE *fp; input[0]=1.0; generate_rand(6,17,w); generate_rand2(10,6,w2); fp = fopen("test.txt", "r"); float eps=0.01,jw1=10.0,jw2=0.0; while(fscanf(fp, "%d", &original_class)>=1){ for(i=0;i<16;i++){ fscanf(fp, "%f", &input[i+1]); } while(1){ get_act(act_fun1,6,input,w,6,17,fnet_1); get_act2(act_fun2,10,act_fun1,w2,10,6,fnet_2); int i,j,t_mat[11],k; float j_w[10]; float sum=0.0; for(i=0;i<10;i++){ t_mat[i]=0; } t_mat[original_class-1] = 1; for(i=0;i<10;i++){ float temp = (float)t_mat[i]; sum=sum+(pow((temp-act_fun2[i]),2)); j_w[i]=(act_fun2[i]-temp); } jw2 = sum/2.0; for(int a=0;a<10;a++){ delta[a] = -1* (j_w[a]) * (fnet_2[a]); } multi_layer(original_class,act_fun2,act_fun1,w,w2,fnet_2,input,fnet_1,j_w,delta,delta1); if(abs(jw1-jw2)<eps) break; jw1=jw2; } } //Testing... fclose(fp); int original_class2; float minput[17]; FILE *fp1; fp1=fopen("test.txt","r"); float second[6],final[10]; int testclass[10000],testclass1[10000],k1=0,k2=0; while(fscanf(fp1, "%d", &original_class2)>=1){ testclass[k1++]=original_class2; minput[0]=1; for(i=0;i<16;i++){ fscanf(fp1, "%f", &minput[i+1]); } get_act(second,6,minput,w,6,17,fnet_1); get_act2(final,10,second,w2,10,6,fnet_2); int ans=extractmaxindex(final); testclass1[k2++]=ans; } int cnt=0; for(i=0;i<k2;i++){ if(testclass[i]==testclass1[i]) { //printf("%d %d",testclass[i],testclass1[i]); cnt++; } } float accuracy=((float)cnt*100.0)/k2; printf("COUNT OF MATCHING CLASSES:- %d\n",cnt); printf("ACCURACY IS PERCENTAGE:- %f \n",accuracy); } void func2(){ //Training... int i,j,x=1; float input[17]; float w[6][18],r,act_fun1[6],w2[11][6],act_fun2[10],fnet_1[6],fnet_2[10],delta[10],delta1[6]; FILE *fp; input[0]=1.0; generate_rand(6,17,w); generate_rand2(10,6,w2); fp = fopen("test.txt", "r"); int epoch=100; while(fscanf(fp, "%d", &original_class)>=1){ for(i=0;i<16;i++){ fscanf(fp, "%f", &input[i+1]); } while(epoch!=0){ epoch--; get_act(act_fun1,6,input,w,6,17,fnet_1); get_act2(act_fun2,10,act_fun1,w2,10,6,fnet_2); int i,j,t_mat[11],jw=0,k; float j_w[10]; float sum=0.0; for(i=0;i<10;i++){ t_mat[i]=0; } t_mat[original_class-1] = 1; for(i=0;i<10;i++){ float temp = (float)t_mat[i]; sum=sum+(pow((temp-act_fun2[i]),2)); j_w[i]=(act_fun2[i]-temp); } jw = sum/2.0; for(int a=0;a<10;a++){ delta[a] = -1* (j_w[a]) * (fnet_2[a]); } multi_layer(original_class,act_fun2,act_fun1,w,w2,fnet_2,input,fnet_1,j_w,delta,delta1); } epoch =100; x++; } //Testing... fclose(fp); int original_class2; float minput[17]; FILE *fp1; fp1=fopen("test.txt","r"); float second[6],final[10]; int testclass[10000],testclass1[10000],k1=0,k2=0; while(fscanf(fp1, "%d", &original_class2)>=1){ testclass[k1++]=original_class2; minput[0]=1; for(i=0;i<16;i++){ fscanf(fp1, "%f", &minput[i+1]); } get_act(second,6,minput,w,6,17,fnet_1); get_act2(final,10,second,w2,10,6,fnet_2); int ans=extractmaxindex(final); testclass1[k2++]=ans; } int cnt=0; for(i=0;i<k2;i++){ if(testclass[i]==testclass1[i]) { //printf("%d %d",testclass[i],testclass1[i]); cnt++; } } float accuracy=((float)cnt*100.0)/k2; printf("COUNT OF MATCHING CLASSES:- %d\n",cnt); printf("ACCURACY IS PERCENTAGE:-%f\n",accuracy); } void func3(){ //Training... int i,j,x=1; float input[17]; float w[6][18],r,act_fun1[6],w2[11][6],act_fun2[10],fnet_1[6],fnet_2[10],delta[10],delta1[6]; FILE *fp; input[0]=1.0; generate_rand(6,17,w); generate_rand2(10,6,w2); float eps=0.01,jw1=10.0,jw2=0.0; fp = fopen("test.txt", "r"); int epoch=100; while(fscanf(fp, "%d", &original_class)>=1){ for(i=0;i<16;i++){ fscanf(fp, "%f", &input[i+1]); } while(1){ epoch--; get_act(act_fun1,6,input,w,6,17,fnet_1); get_act2(act_fun2,10,act_fun1,w2,10,6,fnet_2); int i,j,t_mat[11],jw=0,k; float j_w[10]; float sum=0.0; for(i=0;i<10;i++){ t_mat[i]=0; } t_mat[original_class-1] = 1; for(i=0;i<10;i++){ float temp = (float)t_mat[i]; sum=sum+(pow((temp-act_fun2[i]),2)); j_w[i]=(act_fun2[i]-temp); } jw2 = sum/2.0; for(int a=0;a<10;a++){ delta[a] = -1* (1.0/act_fun2[a]) * (fnet_2[a]); } multi_layer(original_class,act_fun2,act_fun1,w,w2,fnet_2,input,fnet_1,j_w,delta,delta1); if(abs(jw1-jw2)<eps) break; jw1=jw2; } } //Testing... fclose(fp); int original_class2; float minput[17]; FILE *fp1; fp1=fopen("test.txt","r"); float second[6],final[10]; int testclass[10000],testclass1[10000],k1=0,k2=0; while(fscanf(fp1, "%d", &original_class2)>=1){ testclass[k1++]=original_class2; minput[0]=1; for(i=0;i<16;i++){ fscanf(fp1, "%f", &minput[i+1]); } get_act(second,6,minput,w,6,17,fnet_1); get_act2(final,10,second,w2,10,6,fnet_2); int ans=extractmaxindex(final); testclass1[k2++]=ans; } int cnt=0; for(i=0;i<k2;i++){ if(testclass[i]==testclass1[i]) { //printf("%d %d",testclass[i],testclass1[i]); cnt++; } } float accuracy=((float)cnt*100.0)/k2; printf("COUNT OF MATCHING CLASSES:- %d\n",cnt); printf("ACCURACY IS PERCENTAGE:-%f\n",accuracy); } void func4(){ //Training... int i,j,x=1; float input[17]; float w[6][18],r,act_fun1[6],w2[11][6],act_fun2[10],fnet_1[6],fnet_2[10],delta[10],delta1[6]; FILE *fp; input[0]=1.0; generate_rand(6,17,w); generate_rand2(10,6,w2); fp = fopen("test.txt", "r"); int epoch=100; while(fscanf(fp, "%d", &original_class)>=1){ for(i=0;i<16;i++){ fscanf(fp, "%f", &input[i+1]); } while(epoch!=0){ epoch--; get_act(act_fun1,6,input,w,6,17,fnet_1); get_act2(act_fun2,10,act_fun1,w2,10,6,fnet_2); int i,j,t_mat[11],jw=0,k; float j_w[10]; float sum=0.0; for(i=0;i<10;i++){ t_mat[i]=0; } t_mat[original_class-1] = 1; for(i=0;i<10;i++){ float temp = (float)t_mat[i]; sum=sum+(pow((temp-act_fun2[i]),2)); j_w[i]=(act_fun2[i]-temp); } jw = sum/2.0; for(int a=0;a<10;a++){ delta[a] = -1* (1.0/act_fun2[a]) * (fnet_2[a]); } multi_layer(original_class,act_fun2,act_fun1,w,w2,fnet_2,input,fnet_1,j_w,delta,delta1); } epoch =100; x++; } //Testing... fclose(fp); int original_class2; float minput[17]; FILE *fp1; fp1=fopen("test.txt","r"); float second[6],final[10]; int testclass[10000],testclass1[10000],k1=0,k2=0; while(fscanf(fp1, "%d", &original_class2)>=1){ testclass[k1++]=original_class2; minput[0]=1; for(i=0;i<16;i++){ fscanf(fp1, "%f", &minput[i+1]); } get_act(second,6,minput,w,6,17,fnet_1); get_act2(final,10,second,w2,10,6,fnet_2); int ans=extractmaxindex(final); testclass1[k2++]=ans; } int cnt=0; for(i=0;i<k2;i++){ if(testclass[i]==testclass1[i]) { //printf("%d %d",testclass[i],testclass1[i]); cnt++; } } float accuracy=((float)cnt*100.0)/k2; printf("COUNT OF MATCHING CLASSES:- %d\n",cnt); printf("ACCURACY IS PERCENTAGE:-%f\n",accuracy); } int main() { int opt; printf("\n CHOOSE AN OPTION BETWEEN 1 AND 4\n"); printf("\n OPTION 1:- Sum of Squared Deviation loss and ||ΔW|| < ε. where ||ΔW|| is the Euclidian norm of vector ΔW and considering ε as 0.01. \n"); printf("\n OPTION 2:- Sum of Squared Deviation loss and number of epochs as 100 \n"); printf("\n OPTION 3:- Cross-entropy loss and ||ΔW|| < ε. where ||ΔW|| is the Euclidian norm of vector ΔW and considering ε as 0.01. \n"); printf("\n OPTION 4:- Cross-entropy loss and number of epochs as 100 \n"); scanf("%d",&opt); switch(opt){ case 1: func1(); break; case 2: func2(); break; case 3: func3(); break; case 4: func4(); break; } return 0; }
the_stack_data/66633.c
/* * Benchmarks used in the paper "Commutativity of Reducers" * which was published at TACAS 2015 and * written by Yu-Fang Chen, Chih-Duo Hong, Nishant Sinha, and Bow-Yaw Wang. * http://link.springer.com/chapter/10.1007%2F978-3-662-46681-0_9 * * We checks if a function is "deterministic" w.r.t. all possible permutations * of an input array. Such property is desirable for reducers in the * map-reduce programming model. It ensures that the program always computes * the same results on the same input data set. */ #define N 10 #define fun sep extern void __VERIFIER_error() __attribute__ ((__noreturn__)); int sep (int x[N]) { long long ret =0; for(int i=0;i<N;i++) { if(x[i]%2==0) ret++; else ret--; } return ret; } int main () { int x[N]; int temp; int ret; int ret2; int ret5; ret = fun(x); temp=x[0];x[0] = x[1]; x[1] = temp; ret2 = fun(x); temp=x[0]; for(int i =0 ; i<N-1; i++){ x[i] = x[i+1]; } x[N-1] = temp; ret5 = fun(x); if(ret != ret2 || ret !=ret5){ __VERIFIER_error(); } return 1; }
the_stack_data/104493.c
/* mycal - mostly motivated by BSD cal(1) lacking the -3 option. also, * to better learn the ctime(3) routines */ #include <err.h> #include <getopt.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sysexits.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> int Flag_Newline; /* -N */ void emit_help(void); void whatmonth(struct tm *date); int main(int argc, char *argv[]) { int ch; time_t epoch; struct tm *when; #ifdef __OpenBSD__ if (pledge("exec proc stdio", NULL) == -1) err(1, "pledge failed"); #endif while ((ch = getopt(argc, argv, "h?N")) != -1) { switch (ch) { case 'N': Flag_Newline = 1; break; case 'h': case '?': default: emit_help(); /* NOTREACHED */ } } argc -= optind; argv += optind; if (time(&epoch) == (time_t) - 1) err(EX_OSERR, "time() failed"); if (!(when = localtime(&epoch))) err(EX_OSERR, "localtime() failed"); /* ragged ends of months may cause wrap-around problems if run on * 31st and whoops next month doesn't have that so bump to some * other month, haha! basically, datetime code without massive * unit tests checking for these sorts of edge cases should not * be trusted (or it should be of no great surprise when things * do break) */ when->tm_mday = 1; when->tm_mon -= 1; whatmonth(when); when->tm_mon += 1; whatmonth(when); when->tm_mon += 1; whatmonth(when); exit(EXIT_SUCCESS); } void emit_help(void) { fputs("Usage: mycal\n", stderr); exit(EX_USAGE); } void whatmonth(struct tm *date) { char monthnum[3]; char yearnum[5]; // FIXME Y10K bug pid_t pid; time_t t; /* this dance to actually resolve the month increments */ t = mktime(date); date = localtime(&t); pid = fork(); if (pid == -1) { err(EX_OSERR, "could not fork()"); } else if (pid == 0) { // child if (strftime((char *) &monthnum, (size_t) 3, "%m", date) < 1) errx(EX_OSERR, "could not strftime() month"); if (strftime((char *) &yearnum, (size_t) 5, "%Y", date) < 1) errx(EX_OSERR, "could not strftime() year"); execlp("cal", "cal", &monthnum, &yearnum, (char *) 0); err(EX_OSERR, "could not execlp() cal"); } else { // parent if (wait(NULL) == -1) err(EX_OSERR, "wait() error"); if (Flag_Newline && date->tm_mon == 11) putchar('\n'); } }
the_stack_data/231393683.c
// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fopenmp -ast-dump %s | FileCheck --match-full-lines -implicit-check-not=openmp_structured_block %s void test_one(int x) { #pragma omp distribute parallel for for (int i = 0; i < x; i++) ; } void test_two(int x, int y) { #pragma omp distribute parallel for for (int i = 0; i < x; i++) for (int i = 0; i < y; i++) ; } void test_three(int x, int y) { #pragma omp distribute parallel for collapse(1) for (int i = 0; i < x; i++) for (int i = 0; i < y; i++) ; } void test_four(int x, int y) { #pragma omp distribute parallel for collapse(2) for (int i = 0; i < x; i++) for (int i = 0; i < y; i++) ; } void test_five(int x, int y, int z) { #pragma omp distribute parallel for collapse(2) for (int i = 0; i < x; i++) for (int i = 0; i < y; i++) for (int i = 0; i < z; i++) ; } // CHECK: TranslationUnitDecl {{.*}} <<invalid sloc>> <invalid sloc> // CHECK: |-FunctionDecl {{.*}} <{{.*}}ast-dump-openmp-distribute-parallel-for.c:3:1, line:7:1> line:3:6 test_one 'void (int)' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:15, col:19> col:19 used x 'int' // CHECK-NEXT: | `-CompoundStmt {{.*}} <col:22, line:7:1> // CHECK-NEXT: | `-OMPDistributeParallelForDirective {{.*}} <line:4:1, col:36> // CHECK-NEXT: | `-CapturedStmt {{.*}} <line:5:3, line:6:5> // CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-ForStmt {{.*}} <line:5:3, line:6:5> // CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:5:8, col:17> // CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | |-<<<NULL>>> // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-NullStmt {{.*}} <line:6:5> // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:4:1> col:1 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit used .previous.lb. 'const unsigned long' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit used .previous.ub. 'const unsigned long' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-distribute-parallel-for.c:4:1) *const restrict' // CHECK-NEXT: | | `-VarDecl {{.*}} <line:5:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | `-DeclRefExpr {{.*}} <col:3> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: |-FunctionDecl {{.*}} <line:9:1, line:14:1> line:9:6 test_two 'void (int, int)' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:15, col:19> col:19 used x 'int' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:22, col:26> col:26 used y 'int' // CHECK-NEXT: | `-CompoundStmt {{.*}} <col:29, line:14:1> // CHECK-NEXT: | `-OMPDistributeParallelForDirective {{.*}} <line:10:1, col:36> // CHECK-NEXT: | `-CapturedStmt {{.*}} <line:11:3, line:13:7> // CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-ForStmt {{.*}} <line:11:3, line:13:7> // CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:11:8, col:17> // CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | |-<<<NULL>>> // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-ForStmt {{.*}} <line:12:5, line:13:7> // CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:12:10, col:19> // CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | |-<<<NULL>>> // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-NullStmt {{.*}} <line:13:7> // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:10:1> col:1 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit used .previous.lb. 'const unsigned long' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit used .previous.ub. 'const unsigned long' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-distribute-parallel-for.c:10:1) *const restrict' // CHECK-NEXT: | | |-VarDecl {{.*}} <line:11:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | `-VarDecl {{.*}} <line:12:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | |-DeclRefExpr {{.*}} <line:11:3> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | `-DeclRefExpr {{.*}} <line:12:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: |-FunctionDecl {{.*}} <line:16:1, line:21:1> line:16:6 test_three 'void (int, int)' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:17, col:21> col:21 used x 'int' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:24, col:28> col:28 used y 'int' // CHECK-NEXT: | `-CompoundStmt {{.*}} <col:31, line:21:1> // CHECK-NEXT: | `-OMPDistributeParallelForDirective {{.*}} <line:17:1, col:48> // CHECK-NEXT: | |-OMPCollapseClause {{.*}} <col:37, col:47> // CHECK-NEXT: | | `-ConstantExpr {{.*}} <col:46> 'int' // CHECK-NEXT: | | |-value: Int 1 // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:46> 'int' 1 // CHECK-NEXT: | `-CapturedStmt {{.*}} <line:18:3, line:20:7> // CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-ForStmt {{.*}} <line:18:3, line:20:7> // CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:18:8, col:17> // CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | |-<<<NULL>>> // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-ForStmt {{.*}} <line:19:5, line:20:7> // CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:19:10, col:19> // CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | |-<<<NULL>>> // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-NullStmt {{.*}} <line:20:7> // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:17:1> col:1 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit used .previous.lb. 'const unsigned long' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit used .previous.ub. 'const unsigned long' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-distribute-parallel-for.c:17:1) *const restrict' // CHECK-NEXT: | | |-VarDecl {{.*}} <line:18:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | `-VarDecl {{.*}} <line:19:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | |-DeclRefExpr {{.*}} <line:18:3> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | `-DeclRefExpr {{.*}} <line:19:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: |-FunctionDecl {{.*}} <line:23:1, line:28:1> line:23:6 test_four 'void (int, int)' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:16, col:20> col:20 used x 'int' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:23, col:27> col:27 used y 'int' // CHECK-NEXT: | `-CompoundStmt {{.*}} <col:30, line:28:1> // CHECK-NEXT: | `-OMPDistributeParallelForDirective {{.*}} <line:24:1, col:48> // CHECK-NEXT: | |-OMPCollapseClause {{.*}} <col:37, col:47> // CHECK-NEXT: | | `-ConstantExpr {{.*}} <col:46> 'int' // CHECK-NEXT: | | |-value: Int 2 // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:46> 'int' 2 // CHECK-NEXT: | `-CapturedStmt {{.*}} <line:25:3, line:27:7> // CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-ForStmt {{.*}} <line:25:3, line:27:7> // CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:25:8, col:17> // CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | |-<<<NULL>>> // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-ForStmt {{.*}} <line:26:5, line:27:7> // CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:26:10, col:19> // CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | |-<<<NULL>>> // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-NullStmt {{.*}} <line:27:7> // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:24:1> col:1 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit used .previous.lb. 'const unsigned long' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit used .previous.ub. 'const unsigned long' // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-distribute-parallel-for.c:24:1) *const restrict' // CHECK-NEXT: | | |-VarDecl {{.*}} <line:25:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | `-VarDecl {{.*}} <line:26:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | |-DeclRefExpr {{.*}} <line:25:3> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | `-DeclRefExpr {{.*}} <line:26:5> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: `-FunctionDecl {{.*}} <line:30:1, line:36:1> line:30:6 test_five 'void (int, int, int)' // CHECK-NEXT: |-ParmVarDecl {{.*}} <col:16, col:20> col:20 used x 'int' // CHECK-NEXT: |-ParmVarDecl {{.*}} <col:23, col:27> col:27 used y 'int' // CHECK-NEXT: |-ParmVarDecl {{.*}} <col:30, col:34> col:34 used z 'int' // CHECK-NEXT: `-CompoundStmt {{.*}} <col:37, line:36:1> // CHECK-NEXT: `-OMPDistributeParallelForDirective {{.*}} <line:31:1, col:48> // CHECK-NEXT: |-OMPCollapseClause {{.*}} <col:37, col:47> // CHECK-NEXT: | `-ConstantExpr {{.*}} <col:46> 'int' // CHECK-NEXT: | |-value: Int 2 // CHECK-NEXT: | `-IntegerLiteral {{.*}} <col:46> 'int' 2 // CHECK-NEXT: `-CapturedStmt {{.*}} <line:32:3, line:35:9> // CHECK-NEXT: |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | |-ForStmt {{.*}} <line:32:3, line:35:9> // CHECK-NEXT: | | |-DeclStmt {{.*}} <line:32:8, col:17> // CHECK-NEXT: | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | |-<<<NULL>>> // CHECK-NEXT: | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | `-ForStmt {{.*}} <line:33:5, line:35:9> // CHECK-NEXT: | | |-DeclStmt {{.*}} <line:33:10, col:19> // CHECK-NEXT: | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | |-<<<NULL>>> // CHECK-NEXT: | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | `-ForStmt {{.*}} <line:34:7, line:35:9> // CHECK-NEXT: | | |-DeclStmt {{.*}} <line:34:12, col:21> // CHECK-NEXT: | | | `-VarDecl {{.*}} <col:12, col:20> col:16 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0 // CHECK-NEXT: | | |-<<<NULL>>> // CHECK-NEXT: | | |-BinaryOperator {{.*}} <col:23, col:27> 'int' '<' // CHECK-NEXT: | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-ImplicitCastExpr {{.*}} <col:27> 'int' <LValueToRValue> // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:27> 'int' lvalue ParmVar {{.*}} 'z' 'int' // CHECK-NEXT: | | |-UnaryOperator {{.*}} <col:30, col:31> 'int' postfix '++' // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:30> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | `-NullStmt {{.*}} <line:35:9> // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <line:31:1> col:1 implicit .global_tid. 'const int *const restrict' // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit .bound_tid. 'const int *const restrict' // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit used .previous.lb. 'const unsigned long' // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit used .previous.ub. 'const unsigned long' // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <col:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-distribute-parallel-for.c:31:1) *const restrict' // CHECK-NEXT: | |-VarDecl {{.*}} <line:32:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | |-VarDecl {{.*}} <line:33:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | `-VarDecl {{.*}} <line:34:12, col:20> col:16 used i 'int' cinit // CHECK-NEXT: | `-IntegerLiteral {{.*}} <col:20> 'int' 0 // CHECK-NEXT: |-DeclRefExpr {{.*}} <line:32:3> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: |-DeclRefExpr {{.*}} <line:33:5> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: `-DeclRefExpr {{.*}} <line:34:27> 'int' lvalue ParmVar {{.*}} 'z' 'int'
the_stack_data/203838.c
/* * Programmer: Tatenda E Chipwanya Date completed: February 20, 2021 * Instructor: Khulekani Sibanda Class: SCS 1101 * Version: 1.0.0 * * GOSPER'S FORMULA TO APPROXIMATE N! APPLICATION * */ #include <stdio.h> #include <math.h> #define PI 3.141592654 void instruct(void); double square_Root(double n); /* Function declaration*/ double log_Multiplier(double n); /* Function declaration*/ int main() { instruct(); double n; double result; printf("Please enter the value of n > "); scanf("%lf",&n); result = log_Multiplier(n)*square_Root(n); printf("%lf! is approximately %.5lf.",n,result); } void instruct() { printf("The Application approximates n! \nThe condition is that n > 0 \n\n\n**************************************\n"); } /* * Computes the square root . * Pre: n is defined and is > 0. * PI is a constant macro representing an approximation of pi. * Library math.h is included. */ double square_Root(double n) { double internal, /*Expression in the Square Root Sign*/ result; /*The Result of the computation*/ internal = (2*n + 1/3)*PI; result = sqrt(internal); return result; } /* * Computes Log e to the power -n. */ double log_Multiplier(double n) { return (pow(n,n)*exp(-n)); }
the_stack_data/70449909.c
#include <stdio.h> void main() { int c; while((c = getchar()) != EOF) { printf("%d\n", getchar() != EOF); } putchar(c); }
the_stack_data/90765543.c
/***************************************************************************** * * \file * * \brief Abstraction layer for memory interfaces. * * This module contains the interfaces: * - MEM <-> USB; * - MEM <-> RAM; * - MEM <-> MEM. * * This module may be configured and expanded to support the following features: * - write-protected globals; * - password-protected data; * - specific features; * - etc. * * Copyright (c) 2009-2015 Atmel Corporation. All rights reserved. * * \asf_license_start * * \page License * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name of Atmel may not be used to endorse or promote products derived * from this software without specific prior written permission. * * 4. This software may only be redistributed and used in connection with an * Atmel microcontroller product. * * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. * * \asf_license_stop * ******************************************************************************/ /* * Support and FAQ: visit <a href="https://www.atmel.com/design-support/">Atmel Support</a> */ #ifdef ARDUINO_ARCH_SAM //_____ I N C L U D E S ____________________________________________________ #include "compiler.h" #include "preprocessor.h" #ifdef FREERTOS_USED #include "FreeRTOS.h" #include "semphr.h" #endif #include "ctrl_access.h" //_____ D E F I N I T I O N S ______________________________________________ #ifdef FREERTOS_USED /*! \name LUN Access Protection Macros */ //! @{ /*! \brief Locks accesses to LUNs. * * \return \c true if the access was successfully locked, else \c false. */ #define Ctrl_access_lock() ctrl_access_lock() /*! \brief Unlocks accesses to LUNs. */ #define Ctrl_access_unlock() xSemaphoreGive(ctrl_access_semphr) //! @} //! Handle to the semaphore protecting accesses to LUNs. static xSemaphoreHandle ctrl_access_semphr = NULL; #else /*! \name LUN Access Protection Macros */ //! @{ /*! \brief Locks accesses to LUNs. * * \return \c true if the access was successfully locked, else \c false. */ #define Ctrl_access_lock() true /*! \brief Unlocks accesses to LUNs. */ #define Ctrl_access_unlock() //! @} #endif // FREERTOS_USED #if MAX_LUN /*! \brief Initializes an entry of the LUN descriptor table. * * \param lun Logical Unit Number. * * \return LUN descriptor table entry initializer. */ #if ACCESS_USB == true && ACCESS_MEM_TO_RAM == true #define Lun_desc_entry(lun) \ {\ TPASTE3(Lun_, lun, _test_unit_ready),\ TPASTE3(Lun_, lun, _read_capacity),\ TPASTE3(Lun_, lun, _unload),\ TPASTE3(Lun_, lun, _wr_protect),\ TPASTE3(Lun_, lun, _removal),\ TPASTE3(Lun_, lun, _usb_read_10),\ TPASTE3(Lun_, lun, _usb_write_10),\ TPASTE3(Lun_, lun, _mem_2_ram),\ TPASTE3(Lun_, lun, _ram_2_mem),\ TPASTE3(LUN_, lun, _NAME)\ } #elif ACCESS_USB == true #define Lun_desc_entry(lun) \ {\ TPASTE3(Lun_, lun, _test_unit_ready),\ TPASTE3(Lun_, lun, _read_capacity),\ TPASTE3(Lun_, lun, _unload),\ TPASTE3(Lun_, lun, _wr_protect),\ TPASTE3(Lun_, lun, _removal),\ TPASTE3(Lun_, lun, _usb_read_10),\ TPASTE3(Lun_, lun, _usb_write_10),\ TPASTE3(LUN_, lun, _NAME)\ } #elif ACCESS_MEM_TO_RAM == true #define Lun_desc_entry(lun) \ {\ TPASTE3(Lun_, lun, _test_unit_ready),\ TPASTE3(Lun_, lun, _read_capacity),\ TPASTE3(Lun_, lun, _unload),\ TPASTE3(Lun_, lun, _wr_protect),\ TPASTE3(Lun_, lun, _removal),\ TPASTE3(Lun_, lun, _mem_2_ram),\ TPASTE3(Lun_, lun, _ram_2_mem),\ TPASTE3(LUN_, lun, _NAME)\ } #else #define Lun_desc_entry(lun) \ {\ TPASTE3(Lun_, lun, _test_unit_ready),\ TPASTE3(Lun_, lun, _read_capacity),\ TPASTE3(Lun_, lun, _unload),\ TPASTE3(Lun_, lun, _wr_protect),\ TPASTE3(Lun_, lun, _removal),\ TPASTE3(LUN_, lun, _NAME)\ } #endif //! LUN descriptor table. static const struct { Ctrl_status (*test_unit_ready)(void); Ctrl_status (*read_capacity)(U32 *); bool (*unload)(bool); bool (*wr_protect)(void); bool (*removal)(void); #if ACCESS_USB == true Ctrl_status (*usb_read_10)(U32, U16); Ctrl_status (*usb_write_10)(U32, U16); #endif #if ACCESS_MEM_TO_RAM == true Ctrl_status (*mem_2_ram)(U32, void *); Ctrl_status (*ram_2_mem)(U32, const void *); #endif const char *name; } lun_desc[MAX_LUN] = { #if LUN_0 == ENABLE # ifndef Lun_0_unload # define Lun_0_unload NULL # endif Lun_desc_entry(0), #endif #if LUN_1 == ENABLE # ifndef Lun_1_unload # define Lun_1_unload NULL # endif Lun_desc_entry(1), #endif #if LUN_2 == ENABLE # ifndef Lun_2_unload # define Lun_2_unload NULL # endif Lun_desc_entry(2), #endif #if LUN_3 == ENABLE # ifndef Lun_3_unload # define Lun_3_unload NULL # endif Lun_desc_entry(3), #endif #if LUN_4 == ENABLE # ifndef Lun_4_unload # define Lun_4_unload NULL # endif Lun_desc_entry(4), #endif #if LUN_5 == ENABLE # ifndef Lun_5_unload # define Lun_5_unload NULL # endif Lun_desc_entry(5), #endif #if LUN_6 == ENABLE # ifndef Lun_6_unload # define Lun_6_unload NULL # endif Lun_desc_entry(6), #endif #if LUN_7 == ENABLE # ifndef Lun_7_unload # define Lun_7_unload NULL # endif Lun_desc_entry(7) #endif }; #endif #if GLOBAL_WR_PROTECT == true bool g_wr_protect; #endif /*! \name Control Interface */ //! @{ #ifdef FREERTOS_USED bool ctrl_access_init(void) { // If the handle to the protecting semaphore is not valid, if (!ctrl_access_semphr) { // try to create the semaphore. vSemaphoreCreateBinary(ctrl_access_semphr); // If the semaphore could not be created, there is no backup solution. if (!ctrl_access_semphr) return false; } return true; } /*! \brief Locks accesses to LUNs. * * \return \c true if the access was successfully locked, else \c false. */ static bool ctrl_access_lock(void) { // If the semaphore could not be created, there is no backup solution. if (!ctrl_access_semphr) return false; // Wait for the semaphore. while (!xSemaphoreTake(ctrl_access_semphr, portMAX_DELAY)); return true; } #endif // FREERTOS_USED U8 get_nb_lun(void) { #if MEM_USB == ENABLE # ifndef Lun_usb_get_lun # define Lun_usb_get_lun() host_get_lun() # endif U8 nb_lun; if (!Ctrl_access_lock()) return MAX_LUN; nb_lun = MAX_LUN + Lun_usb_get_lun(); Ctrl_access_unlock(); return nb_lun; #else return MAX_LUN; #endif } U8 get_cur_lun(void) { return LUN_ID_0; } Ctrl_status mem_test_unit_ready(U8 lun) { Ctrl_status status; if (!Ctrl_access_lock()) return CTRL_FAIL; status = #if MAX_LUN (lun < MAX_LUN) ? lun_desc[lun].test_unit_ready() : #endif #if LUN_USB == ENABLE Lun_usb_test_unit_ready(lun - LUN_ID_USB); #else CTRL_FAIL; #endif Ctrl_access_unlock(); return status; } Ctrl_status mem_read_capacity(U8 lun, U32 *u32_nb_sector) { Ctrl_status status; if (!Ctrl_access_lock()) return CTRL_FAIL; status = #if MAX_LUN (lun < MAX_LUN) ? lun_desc[lun].read_capacity(u32_nb_sector) : #endif #if LUN_USB == ENABLE Lun_usb_read_capacity(lun - LUN_ID_USB, u32_nb_sector); #else CTRL_FAIL; #endif Ctrl_access_unlock(); return status; } U8 mem_sector_size(U8 lun) { U8 sector_size; if (!Ctrl_access_lock()) return 0; sector_size = #if MAX_LUN (lun < MAX_LUN) ? 1 : #endif #if LUN_USB == ENABLE Lun_usb_read_sector_size(lun - LUN_ID_USB); #else 0; #endif Ctrl_access_unlock(); return sector_size; } bool mem_unload(U8 lun, bool unload) { bool unloaded; #if !MAX_LUN || !defined(Lun_usb_unload) UNUSED(lun); #endif if (!Ctrl_access_lock()) return false; unloaded = #if MAX_LUN (lun < MAX_LUN) ? (lun_desc[lun].unload ? lun_desc[lun].unload(unload) : !unload) : #endif #if LUN_USB == ENABLE # if defined(Lun_usb_unload) Lun_usb_unload(lun - LUN_ID_USB, unload); # else !unload; /* Can not unload: load success, unload fail */ # endif #else false; /* No mem, unload/load fail */ #endif Ctrl_access_unlock(); return unloaded; } bool mem_wr_protect(U8 lun) { bool wr_protect; if (!Ctrl_access_lock()) return true; wr_protect = #if MAX_LUN (lun < MAX_LUN) ? lun_desc[lun].wr_protect() : #endif #if LUN_USB == ENABLE Lun_usb_wr_protect(lun - LUN_ID_USB); #else true; #endif Ctrl_access_unlock(); return wr_protect; } bool mem_removal(U8 lun) { bool removal; #if MAX_LUN==0 UNUSED(lun); #endif if (!Ctrl_access_lock()) return true; removal = #if MAX_LUN (lun < MAX_LUN) ? lun_desc[lun].removal() : #endif #if LUN_USB == ENABLE Lun_usb_removal(); #else true; #endif Ctrl_access_unlock(); return removal; } const char *mem_name(U8 lun) { #if MAX_LUN==0 UNUSED(lun); #endif return #if MAX_LUN (lun < MAX_LUN) ? lun_desc[lun].name : #endif #if LUN_USB == ENABLE LUN_USB_NAME; #else NULL; #endif } //! @} #if ACCESS_USB == true /*! \name MEM <-> USB Interface */ //! @{ Ctrl_status memory_2_usb(U8 lun, U32 addr, U16 nb_sector) { Ctrl_status status; if (!Ctrl_access_lock()) return CTRL_FAIL; memory_start_read_action(nb_sector); status = #if MAX_LUN (lun < MAX_LUN) ? lun_desc[lun].usb_read_10(addr, nb_sector) : #endif CTRL_FAIL; memory_stop_read_action(); Ctrl_access_unlock(); return status; } Ctrl_status usb_2_memory(U8 lun, U32 addr, U16 nb_sector) { Ctrl_status status; if (!Ctrl_access_lock()) return CTRL_FAIL; memory_start_write_action(nb_sector); status = #if MAX_LUN (lun < MAX_LUN) ? lun_desc[lun].usb_write_10(addr, nb_sector) : #endif CTRL_FAIL; memory_stop_write_action(); Ctrl_access_unlock(); return status; } //! @} #endif // ACCESS_USB == true #if ACCESS_MEM_TO_RAM == true /*! \name MEM <-> RAM Interface */ //! @{ Ctrl_status memory_2_ram(U8 lun, U32 addr, void *ram) { Ctrl_status status; #if MAX_LUN==0 UNUSED(lun); #endif if (!Ctrl_access_lock()) return CTRL_FAIL; memory_start_read_action(1); status = #if MAX_LUN (lun < MAX_LUN) ? lun_desc[lun].mem_2_ram(addr, ram) : #endif #if LUN_USB == ENABLE Lun_usb_mem_2_ram(addr, ram); #else CTRL_FAIL; #endif memory_stop_read_action(); Ctrl_access_unlock(); return status; } Ctrl_status ram_2_memory(U8 lun, U32 addr, const void *ram) { Ctrl_status status; #if MAX_LUN==0 UNUSED(lun); #endif if (!Ctrl_access_lock()) return CTRL_FAIL; memory_start_write_action(1); status = #if MAX_LUN (lun < MAX_LUN) ? lun_desc[lun].ram_2_mem(addr, ram) : #endif #if LUN_USB == ENABLE Lun_usb_ram_2_mem(addr, ram); #else CTRL_FAIL; #endif memory_stop_write_action(); Ctrl_access_unlock(); return status; } //! @} #endif // ACCESS_MEM_TO_RAM == true #if ACCESS_STREAM == true /*! \name Streaming MEM <-> MEM Interface */ //! @{ #if ACCESS_MEM_TO_MEM == true #include "fat.h" Ctrl_status stream_mem_to_mem(U8 src_lun, U32 src_addr, U8 dest_lun, U32 dest_addr, U16 nb_sector) { COMPILER_ALIGNED(4) static U8 sector_buf[FS_512B]; Ctrl_status status = CTRL_GOOD; while (nb_sector--) { if ((status = memory_2_ram(src_lun, src_addr++, sector_buf)) != CTRL_GOOD) break; if ((status = ram_2_memory(dest_lun, dest_addr++, sector_buf)) != CTRL_GOOD) break; } return status; } #endif // ACCESS_MEM_TO_MEM == true Ctrl_status stream_state(U8 id) { UNUSED(id); return CTRL_GOOD; } U16 stream_stop(U8 id) { UNUSED(id); return 0; } //! @} #endif // ACCESS_STREAM #endif // ARDUINO_ARCH_SAM
the_stack_data/48575640.c
/* * Copyright (c) 2017, 2018, Oracle and/or its affiliates. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided * with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> int main() { char str[100]; int retVal = snprintf(str, 100, "%d", 1231); printf("%s\n", str); return retVal; }
the_stack_data/703065.c
#include <stdio.h> void larger_of(double* x, double* y); int main(void) { double d1, d2; printf("Enter tow float number:"); scanf("%lf %lf", &d1, &d2); printf("Data you input is %g and %g.\n", d1, d2); larger_of(&d1, &d2); printf("After function.data is %g and %g.\n", d1, d2); return 0; } void larger_of(double* x, double* y) { if (*x > *y) { *y = *x; } else { *x = *y; } return; }
the_stack_data/97011465.c
/* lc541.c */ /* LeetCode 541. Reverse String II `E` */ /* acc | 100% | 30' */ /* A~0f25 */ void reverse(char *left, char *right); char *reverseStr(char *s, int k) { char *left = s, *right = s; int len = strlen(s); while (left < s + len) { right = left; while (right - left < k - 1 && right < s + len - 1) ++right; reverse(left, right); left += k * 2; } return s; } void reverse(char *left, char *right) { while (left < right) { char tmp = *left; *left = *right; *right = tmp; ++left; --right; } }
the_stack_data/34728.c
#include <stdio.h> main() { int nama; printf("Siapa namanya? \n"); scanf("%d", &nama); printf("Halo &d,\n"); }
the_stack_data/159515783.c
/* { dg-do compile } */ /* { dg-require-effective-target vect_int } */ #define N 512 int a[N], b[N]; void foo(int k) { int i, res = 0; for (i=0; i<N; i++) { if (b[i] != 0) res += b[i]; } a[k] = res; } /* { dg-final { scan-tree-dump-times "vectorized 1 loops" 1 "vect" } } */
the_stack_data/29823938.c
#include<stdio.h> #include<math.h> int C(int m,int n) { if(n==0||m==n) return (1); else if(n==1) return (m); else return(C(m-1,n-1)+C(m-1,n)); } int main() { int m,n; scanf("%d%d",&m,&n); printf("%d",C(m,n)); }
the_stack_data/132107.c
#include <stdio.h> #include <stdlib.h> #include <string.h> // // qemu_toflash // // python /home/olas/esp/esp-idf/components/esptool_py/esptool/esptool.py --chip esp32 --port /dev/ttyUSB0 --baud 115200 --before default_reset --after hard_reset write_flash -z --flash_mode dio --flash_freq 40m --flash_size detect // 0x1000 .pioenvs/esp-wrover-kit/bootloader.bin // 0x10000 .pioenvs/esp-wrover-kit/firmware.bin // 0xe000 .pioenvs/esp-wrover-kit/partitions.bin // void merge_flash(char *binfile,char *flashfile,int flash_pos,int patch_hash) { FILE *fbin; FILE *fflash; unsigned char *tmp_data; int j=0; int file_size=0; int flash_size=0; fbin = fopen(binfile, "rb"); if (fbin == NULL) { printf(" Can't open '%s' for reading.\n", binfile); return; } if (fseek(fbin, 0 , SEEK_END) != 0) { printf(" Can't seek end of '%s'.\n", binfile); /* Handle Error */ } file_size = ftell(fbin); if (fseek(fbin, 0 , SEEK_SET) != 0) { /* Handle Error */ } fflash = fopen(flashfile, "rb+"); if (fflash == NULL) { printf(" Can't open '%s' for writing.\n", flashfile); return; } if (fseek(fflash, 0 , SEEK_END) != 0) { printf(" Can't seek end of '%s'.\n", flashfile); /* Handle Error */ } flash_size = ftell(fflash); rewind(fflash); fseek(fflash,flash_pos,SEEK_SET); tmp_data=malloc((1+file_size)*sizeof(char)); if (file_size<=0) { printf("Not able to get file size %s",binfile); } int len_read=fread(tmp_data,sizeof(char),file_size,fbin); if (patch_hash==1) { for (j=0;j<33;j++) { tmp_data[file_size-j]=0; } } int len_write=fwrite(tmp_data,sizeof(char),file_size,fflash); if (len_read!=len_write) { printf("Not able to merge %s, %d bytes read,%d to write,%d file_size\n",binfile,len_read,len_write,file_size); //while() } fclose(fbin); if (fseek(fflash, 0x3E8000*4 , SEEK_SET) != 0) { } fclose(fflash); free(tmp_data); } int main(int argc,char *argv[]) { if (argc>1) { if (strcmp(argv[1],"-bl")==0) { printf("Overwrite bootloader only \n"); merge_flash("build/bootloader/bootloader.bin","esp32flash.bin",0x1000,0); system("cp esp32flash.bin ~/qemu_esp32"); exit(0); } } // Overwrites esp32flash.bin file system("dd if=/dev/zero bs=1M count=4 | tr \"\\000\" \"\\377\" > esp32flash.bin"); // Add bootloader merge_flash(".pioenvs/esp-wrover-kit/bootloader.bin","esp32flash.bin",0x1000,0); // Add partitions, merge_flash(".pioenvs/esp-wrover-kit/partitions.bin","esp32flash.bin",0x8000,0); // Add application if (argc>1) { merge_flash(argv[1],"esp32flash.bin",0x10000,0); } else { merge_flash(".pioenvs/esp-wrover-kit/firmware.bin","esp32flash.bin",0x10000,0); } system("cp esp32flash.bin ~/qemu_esp32"); }
the_stack_data/115641.c
/************************************************************************************************** Phyplus Microelectronics Limited confidential and proprietary. All rights reserved. IMPORTANT: All rights of this software belong to Phyplus Microelectronics Limited ("Phyplus"). Your use of this Software is limited to those specific rights granted under the terms of the business contract, the confidential agreement, the non-disclosure agreement and any other forms of agreements as a customer or a partner of Phyplus. You may not use this Software unless you agree to abide by the terms of these agreements. You acknowledge that the Software may not be modified, copied, distributed or disclosed unless embedded on a Phyplus Bluetooth Low Energy (BLE) integrated circuit, either as a product or is integrated into your products. Other than for the aforementioned purposes, you may not use, reproduce, copy, prepare derivative works of, modify, distribute, perform, display or sell this Software and/or its documentation for any purposes. YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL PHYPLUS OR ITS SUBSIDIARIES BE LIABLE OR OBLIGATED UNDER CONTRACT, NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS. **************************************************************************************************/ /************************************************************************************************* Filename: gattservapp.c Revised: Revision: Description: This file contains the GATT Server Application. **************************************************************************************************/ #if ( HOST_CONFIG & ( CENTRAL_CFG | PERIPHERAL_CFG ) ) /******************************************************************************* * INCLUDES */ #include "bcomdef.h" #include "linkdb.h" #include "gatt.h" #include "gatt_uuid.h" #include "gattservapp.h" /********************************************************************* * MACROS */ /********************************************************************* * CONSTANTS */ /********************************************************************* * TYPEDEFS */ // Structure to keep Prepare Write Requests for each Client typedef struct { uint16 connHandle; // connection message was received on attPrepareWriteReq_t *pPrepareWriteQ; // Prepare Write Request queue } prepareWrites_t; // GATT Structure to keep CBs information for each service being registered typedef struct { uint16 handle; // Service handle - assigned internally by GATT Server CONST gattServiceCBs_t *pCBs; // Service callback function pointers } gattServiceCBsInfo_t; // Service callbacks list item typedef struct _serviceCBsList { struct _serviceCBsList *next; // pointer to next service callbacks record gattServiceCBsInfo_t serviceInfo; // service handle/callbacks } serviceCBsList_t; /********************************************************************* * GLOBAL VARIABLES */ /********************************************************************* * EXTERNAL VARIABLES */ /********************************************************************* * EXTERNAL FUNCTIONS */ extern l2capSegmentBuff_t l2capSegmentPkt; /********************************************************************* * LOCAL VARIABLES */ uint8 GATTServApp_TaskID; // Task ID for internal task/event processing uint8 appTaskID = INVALID_TASK_ID; // The task ID of an app/profile that // wants GATT Server event messages // Server Prepare Write table (one entry per each physical link) static prepareWrites_t prepareWritesTbl[MAX_NUM_LL_CONN]; // Maximum number of attributes that Server can prepare for writing per Client static uint8 maxNumPrepareWrites = 0; #ifdef PREPARE_QUEUE_STATIC static attPrepareWriteReq_t prepareQueue[MAX_NUM_LL_CONN*GATT_MAX_NUM_PREPARE_WRITES]; #endif // Callbacks for services static serviceCBsList_t *serviceCBsList = NULL; // Globals to be used for processing an incoming request static uint8 attrLen; static uint8 attrValue[ATT_MTU_SIZE-1]; static attMsg_t rsp; /*** Defined GATT Attributes ***/ // GATT Service attribute static CONST gattAttrType_t gattService = { ATT_BT_UUID_SIZE, gattServiceUUID }; #ifndef HID_VOICE_SPEC // Service Changed Characteristic Properties static uint8 serviceChangedCharProps = GATT_PROP_INDICATE; #endif // Service Changed attribute (hidden). Set the affected Attribute Handle range // to 0x0001 to 0xFFFF to indicate to the client to rediscover the entire set // of Attribute Handles on the server. // Client Characteristic configuration. Each client has its own instantiation // of the Client Characteristic Configuration. Reads of the Client Characteristic // Configuration only shows the configuration for that client and writes only // affect the configuration of that client. static gattCharCfg_t indCharCfg[GATT_MAX_NUM_CONN]; #if defined ( TESTMODES ) static uint16 paramValue = 0; #endif /********************************************************************* * Profile Attributes - Table */ // GATT Attribute Table static gattAttribute_t gattAttrTbl[] = { // Generic Attribute Profile { { ATT_BT_UUID_SIZE, primaryServiceUUID }, /* type */ GATT_PERMIT_READ, /* permissions */ 0, /* handle */ (uint8 *)&gattService /* pValue */ }, #ifndef HID_VOICE_SPEC // Characteristic Declaration { { ATT_BT_UUID_SIZE, characterUUID }, GATT_PERMIT_READ, 0, &serviceChangedCharProps }, // Attribute Service Changed { { ATT_BT_UUID_SIZE, serviceChangedUUID }, 0, 0, NULL }, // Client Characteristic configuration { { ATT_BT_UUID_SIZE, clientCharCfgUUID }, GATT_PERMIT_READ | GATT_PERMIT_WRITE, 0, (uint8 *)indCharCfg } #endif }; /********************************************************************* * LOCAL FUNCTIONS */ static void gattServApp_ProcessMsg( gattMsgEvent_t *pMsg ); static bStatus_t gattServApp_ProcessExchangeMTUReq( gattMsgEvent_t *pMsg ); static bStatus_t gattServApp_ProcessFindByTypeValueReq( gattMsgEvent_t *pMsg, uint16 *pErrHandle ); static bStatus_t gattServApp_ProcessReadByTypeReq( gattMsgEvent_t *pMsg, uint16 *pErrHandle ); static bStatus_t gattServApp_ProcessReadReq( gattMsgEvent_t *pMsg, uint16 *pErrHandle ); static bStatus_t gattServApp_ProcessReadBlobReq( gattMsgEvent_t *pMsg, uint16 *pErrHandle ); static bStatus_t gattServApp_ProcessReadMultiReq( gattMsgEvent_t *pMsg, uint16 *pErrHandle ); static bStatus_t gattServApp_ProcessReadByGrpTypeReq( gattMsgEvent_t *pMsg, uint16 *pErrHandle ); static bStatus_t gattServApp_ProcessWriteReq( gattMsgEvent_t *pMsg, uint16 *pErrHandle ); static bStatus_t gattServApp_ProcessPrepareWriteReq( gattMsgEvent_t *pMsg, uint16 *pErrHandle ); static bStatus_t gattServApp_ProcessExecuteWriteReq( gattMsgEvent_t *pMsg, uint16 *pErrHandle ); static bStatus_t gattServApp_RegisterServiceCBs( uint16 handle, CONST gattServiceCBs_t *pServiceCBs ); static bStatus_t gattServApp_DeregisterServiceCBs( uint16 handle ); static bStatus_t gattServApp_SetNumPrepareWrites( uint8 numPrepareWrites ); static uint8 gattServApp_PrepareWriteQInUse( void ); static CONST gattServiceCBs_t *gattServApp_FindServiceCBs( uint16 service ); static bStatus_t gattServApp_EnqueuePrepareWriteReq( uint16 connHandle, attPrepareWriteReq_t *pReq ); static prepareWrites_t *gattServApp_FindPrepareWriteQ( uint16 connHandle ); static gattCharCfg_t *gattServApp_FindCharCfgItem( uint16 connHandle, gattCharCfg_t *charCfgTbl ); static pfnGATTReadAttrCB_t gattServApp_FindReadAttrCB( uint16 handle ); static pfnGATTWriteAttrCB_t gattServApp_FindWriteAttrCB( uint16 handle ); static pfnGATTAuthorizeAttrCB_t gattServApp_FindAuthorizeAttrCB( uint16 handle ); /********************************************************************* * API FUNCTIONS */ // GATT App Callback functions static void gattServApp_HandleConnStatusCB( uint16 connHandle, uint8 changeType ); static bStatus_t gattServApp_WriteAttrCB( uint16 connHandle, gattAttribute_t *pAttr, uint8 *pValue, uint8 len, uint16 offset ); /********************************************************************* * PROFILE CALLBACKS */ // GATT Service Callbacks CONST gattServiceCBs_t gattServiceCBs = { NULL, // Read callback function pointer gattServApp_WriteAttrCB, // Write callback function pointer NULL // Authorization callback function pointer }; static gattServMsgCB_t s_GATTServCB = NULL; /********************************************************************* * @fn GATTServApp_RegisterForMsgs * * @brief Register your task ID to receive event messages from * the GATT Server Application. * * @param taskId - Default task ID to send events * * @return none */ void GATTServApp_RegisterForMsg( uint8 taskID ) { appTaskID = taskID; } /********************************************************************* * @fn GATTServApp_Init * * @brief Initialize the GATT Server Application. * * @param taskId - Task identifier for the desired task * * @return none */ void GATTServApp_Init( uint8 taskId ) { GATTServApp_TaskID = taskId; // Initialize Client Characteristic Configuration attributes GATTServApp_InitCharCfg( INVALID_CONNHANDLE, indCharCfg ); // Initialize Prepare Write Table for ( uint8 i = 0; i < MAX_NUM_LL_CONN; i++ ) { // Initialize connection handle prepareWritesTbl[i].connHandle = INVALID_CONNHANDLE; // Initialize the prepare write queue prepareWritesTbl[i].pPrepareWriteQ = NULL; } // Set up the initial prepare write queues gattServApp_SetNumPrepareWrites( GATT_MAX_NUM_PREPARE_WRITES ); // Register to receive incoming ATT Requests GATT_RegisterForReq( GATTServApp_TaskID ); // Register with Link DB to receive link status change callback VOID linkDB_Register( gattServApp_HandleConnStatusCB ); } /********************************************************************* * @fn GATTServApp_ProcessEvent * * @brief GATT Server Application Task event processor. This function * is called to process all events for the task. Events include * timers, messages and any other user defined events. * * @param task_id - The OSAL assigned task ID. * @param events - events to process. This is a bit map and can * contain more than one event. * * @return none */ uint16 GATTServApp_ProcessEvent( uint8 task_id, uint16 events ) { if ( events & SYS_EVENT_MSG ) { osal_event_hdr_t *pMsg; if ( (pMsg = ( osal_event_hdr_t *)osal_msg_receive( GATTServApp_TaskID )) != NULL ) { // Process incoming messages switch ( pMsg->event ) { // Incoming GATT message case GATT_MSG_EVENT: gattServApp_ProcessMsg( (gattMsgEvent_t *)pMsg ); break; default: // Unsupported message break; } // Release the OSAL message VOID osal_msg_deallocate( (uint8 *)pMsg ); } // return unprocessed events return (events ^ SYS_EVENT_MSG); } // Discard unknown events return 0; } /****************************************************************************** * @fn GATTServApp_RegisterService * * @brief Register a service's attribute list and callback functions with * the GATT Server Application. * * @param pAttrs - Array of attribute records to be registered * @param numAttrs - Number of attributes in array * @param pServiceCBs - Service callback function pointers * * @return SUCCESS: Service registered successfully. * INVALIDPARAMETER: Invalid service field. * FAILURE: Not enough attribute handles available. * bleMemAllocError: Memory allocation error occurred. */ bStatus_t GATTServApp_RegisterService( gattAttribute_t *pAttrs, uint16 numAttrs, CONST gattServiceCBs_t *pServiceCBs ) { uint8 status; // First register the service attribute list with GATT Server if ( pAttrs != NULL ) { gattService_t service; service.attrs = pAttrs; service.numAttrs = numAttrs; status = GATT_RegisterService( &service ); if ( ( status == SUCCESS ) && ( pServiceCBs != NULL ) ) { // Register the service CBs with GATT Server Application status = gattServApp_RegisterServiceCBs( GATT_SERVICE_HANDLE( pAttrs ), pServiceCBs ); } } else { status = INVALIDPARAMETER; } return ( status ); } /****************************************************************************** * @fn GATTServApp_DeregisterService * * @brief Deregister a service's attribute list and callback functions from * the GATT Server Application. * * NOTE: It's the caller's responsibility to free the service attribute * list returned from this API. * * @param handle - handle of service to be deregistered * @param p2pAttrs - pointer to array of attribute records (to be returned) * * @return SUCCESS: Service deregistered successfully. * FAILURE: Service not found. */ bStatus_t GATTServApp_DeregisterService( uint16 handle, gattAttribute_t **p2pAttrs ) { uint8 status; // First deregister the service CBs with GATT Server Application status = gattServApp_DeregisterServiceCBs( handle ); if ( status == SUCCESS ) { gattService_t service; // Deregister the service attribute list with GATT Server status = GATT_DeregisterService( handle, &service ); if ( status == SUCCESS ) { if ( p2pAttrs != NULL ) { *p2pAttrs = service.attrs; } } } return ( status ); } /********************************************************************* * @fn GATTServApp_SetParameter * * @brief Set a GATT Server parameter. * * @param param - Profile parameter ID * @param len - length of data to right * @param pValue - pointer to data to write. This is dependent on the * the parameter ID and WILL be cast to the appropriate * data type (example: data type of uint16 will be cast * to uint16 pointer). * * @return SUCCESS: Parameter set successful * FAILURE: Parameter in use * INVALIDPARAMETER: Invalid parameter * bleInvalidRange: Invalid value * bleMemAllocError: Memory allocation failed */ bStatus_t GATTServApp_SetParameter( uint8 param, uint8 len, void *pValue ) { bStatus_t status = SUCCESS; switch ( param ) { case GATT_PARAM_NUM_PREPARE_WRITES: if ( len == sizeof ( uint8 ) ) { if ( !gattServApp_PrepareWriteQInUse() ) { // Set the new nunber of prepare writes status = gattServApp_SetNumPrepareWrites( *((uint8*)pValue) ); } else { status = FAILURE; } } else { status = bleInvalidRange; } break; default: status = INVALIDPARAMETER; break; } return ( status ); } /********************************************************************* * @fn GATTServApp_GetParameter * * @brief Get a GATT Server parameter. * * @param param - Profile parameter ID * @param pValue - pointer to data to put. This is dependent on the * parameter ID and WILL be cast to the appropriate * data type (example: data type of uint16 will be * cast to uint16 pointer). * * @return SUCCESS: Parameter get successful * INVALIDPARAMETER: Invalid parameter */ bStatus_t GATTServApp_GetParameter( uint8 param, void *pValue ) { bStatus_t status = SUCCESS; switch ( param ) { case GATT_PARAM_NUM_PREPARE_WRITES: *((uint8*)pValue) = maxNumPrepareWrites; break; default: status = INVALIDPARAMETER; break; } return ( status ); } /********************************************************************* * @fn gattServApp_SetNumPrepareWrites * * @brief Set the maximum number of the prepare writes. * * @param numPrepareWrites - number of prepare writes * * @return SUCCESS: New number set successfully. * bleMemAllocError: Memory allocation failed. */ static bStatus_t gattServApp_SetNumPrepareWrites( uint8 numPrepareWrites ) { attPrepareWriteReq_t *pQueue; uint16 queueSize = ( MAX_NUM_LL_CONN * numPrepareWrites * sizeof( attPrepareWriteReq_t ) ); // First make sure no one can get access to the Prepare Write Table maxNumPrepareWrites = 0; // Free the existing prepare write queues if ( prepareWritesTbl[0].pPrepareWriteQ != NULL ) { #ifndef PREPARE_QUEUE_STATIC osal_mem_free( prepareWritesTbl[0].pPrepareWriteQ ); #endif // Null out the prepare writes queues for ( uint8 i = 0; i < MAX_NUM_LL_CONN; i++ ) { prepareWritesTbl[i].pPrepareWriteQ = NULL; } } // Allocate the prepare write queues #ifdef PREPARE_QUEUE_STATIC pQueue = prepareQueue; #else pQueue = osal_mem_alloc( queueSize ); #endif if ( pQueue != NULL ) { // Initialize the prepare write queues VOID osal_memset( pQueue, 0, queueSize ); // Set up the prepare write queue for each client (i.e., connection) for ( uint8 i = 0; i < MAX_NUM_LL_CONN; i++ ) { uint8 nextQ = i * numPrepareWrites; // Index of next available queue prepareWritesTbl[i].pPrepareWriteQ = &(pQueue[nextQ]); // Mark the prepare write request items as empty for ( uint8 j = 0; j < numPrepareWrites; j++ ) { prepareWritesTbl[i].pPrepareWriteQ[j].handle = GATT_INVALID_HANDLE; } } // Set the new number of prepare writes maxNumPrepareWrites = numPrepareWrites; return ( SUCCESS ); } return ( bleMemAllocError ); } /********************************************************************* * @fn GATTServApp_FindAttr * * @brief Find the attribute record within a service attribute * table for a given attribute value pointer. * * @param pAttrTbl - pointer to attribute table * @param numAttrs - number of attributes in attribute table * @param pValue - pointer to attribute value * * @return Pointer to attribute record. NULL, if not found. */ gattAttribute_t *GATTServApp_FindAttr( gattAttribute_t *pAttrTbl, uint16 numAttrs, uint8 *pValue ) { for ( uint16 i = 0; i < numAttrs; i++ ) { if ( pAttrTbl[i].pValue == pValue ) { // Attribute record found return ( &(pAttrTbl[i]) ); } } return ( (gattAttribute_t *)NULL ); } /****************************************************************************** * @fn GATTServApp_AddService * * @brief Add function for the GATT Service. * * @param services - services to add. This is a bit map and can * contain more than one service. * * @return SUCCESS: Service added successfully. * INVALIDPARAMETER: Invalid service field. * FAILURE: Not enough attribute handles available. * bleMemAllocError: Memory allocation error occurred. */ bStatus_t GATTServApp_AddService( uint32 services ) { uint8 status = SUCCESS; if ( services & GATT_SERVICE ) { // Register GATT attribute list and CBs with GATT Server Application status = GATTServApp_RegisterService( gattAttrTbl, GATT_NUM_ATTRS( gattAttrTbl ), &gattServiceCBs ); } return ( status ); } /****************************************************************************** * @fn GATTServApp_DelService * * @brief Delete function for the GATT Service. * * @param services - services to delete. This is a bit map and can * contain more than one service. * * @return SUCCESS: Service deleted successfully. * FAILURE: Service not found. */ bStatus_t GATTServApp_DelService( uint32 services ) { uint8 status = SUCCESS; if ( services & GATT_SERVICE ) { // Deregister GATT attribute list and CBs from GATT Server Application status = GATTServApp_DeregisterService( GATT_SERVICE_HANDLE( gattAttrTbl ), NULL ); } return ( status ); } /****************************************************************************** * @fn gattServApp_RegisterServiceCBs * * @brief Register callback functions for a service. * * @param handle - handle of service being registered * @param pServiceCBs - pointer to service CBs to be registered * * @return SUCCESS: Service CBs were registered successfully. * INVALIDPARAMETER: Invalid service CB field. * bleMemAllocError: Memory allocation error occurred. */ static bStatus_t gattServApp_RegisterServiceCBs( uint16 handle, CONST gattServiceCBs_t *pServiceCBs ) { serviceCBsList_t *pNewItem; // Make sure the service handle is specified if ( handle == GATT_INVALID_HANDLE ) { return ( INVALIDPARAMETER ); } // Fill in the new service list pNewItem = (serviceCBsList_t *)osal_mem_alloc( sizeof( serviceCBsList_t ) ); if ( pNewItem == NULL ) { // Not enough memory return ( bleMemAllocError ); } // Set up new service CBs item pNewItem->next = NULL; pNewItem->serviceInfo.handle = handle; pNewItem->serviceInfo.pCBs = pServiceCBs; // Find spot in list if ( serviceCBsList == NULL ) { // First item in list serviceCBsList = pNewItem; } else { serviceCBsList_t *pLoop = serviceCBsList; // Look for end of list while ( pLoop->next != NULL ) { pLoop = pLoop->next; } // Put new item at end of list pLoop->next = pNewItem; } return ( SUCCESS ); } /****************************************************************************** * @fn gattServApp_DeregisterServiceCBs * * @brief Deregister callback functions for a service. * * @param handle - handle of service CBs to be deregistered * * @return SUCCESS: Service CBs were deregistered successfully. * FAILURE: Service CBs were not found. */ static bStatus_t gattServApp_DeregisterServiceCBs( uint16 handle ) { serviceCBsList_t *pLoop = serviceCBsList; serviceCBsList_t *pPrev = NULL; // Look for service while ( pLoop != NULL ) { if ( pLoop->serviceInfo.handle == handle ) { // Service CBs found; unlink it if ( pPrev == NULL ) { // First item in list serviceCBsList = pLoop->next; } else { pPrev->next = pLoop->next; } // Free the service CB record osal_mem_free( pLoop ); return ( SUCCESS ); } pPrev = pLoop; pLoop = pLoop->next; } // Service CBs not found return ( FAILURE ); } /********************************************************************* * @fn gattServApp_FindServiceCBs * * @brief Find service's callback record. * * @param handle - owner of service * * @return Pointer to service record. NULL, otherwise. */ static CONST gattServiceCBs_t *gattServApp_FindServiceCBs( uint16 handle ) { serviceCBsList_t *pLoop = serviceCBsList; while ( pLoop != NULL ) { if ( pLoop->serviceInfo.handle == handle ) { return ( pLoop->serviceInfo.pCBs ); } // Try next service pLoop = pLoop->next; } return ( (gattServiceCBs_t *)NULL ); } /********************************************************************* * @fn gattServApp_ProcessMsg * * @brief GATT Server App message processing function. * * @param pMsg - pointer to received message * * @return Success or Failure */ static void gattServApp_ProcessMsg( gattMsgEvent_t *pMsg ) { uint16 errHandle = GATT_INVALID_HANDLE; uint8 status; #if defined ( TESTMODES ) if ( paramValue == GATT_TESTMODE_NO_RSP ) { // Notify GATT that a message has been processed // Note: This call is optional if flow control is not used. GATT_AppCompletedMsg( pMsg ); // Just ignore the incoming request messages return; } #endif // Process the GATT server message switch ( pMsg->method ) { case ATT_EXCHANGE_MTU_REQ: status = gattServApp_ProcessExchangeMTUReq( pMsg ); break; case ATT_FIND_BY_TYPE_VALUE_REQ: status = gattServApp_ProcessFindByTypeValueReq( pMsg, &errHandle ); break; case ATT_READ_BY_TYPE_REQ: status = gattServApp_ProcessReadByTypeReq( pMsg, &errHandle ); break; case ATT_READ_REQ: status = gattServApp_ProcessReadReq( pMsg, &errHandle ); break; case ATT_READ_BLOB_REQ: status = gattServApp_ProcessReadBlobReq( pMsg, &errHandle ); break; case ATT_READ_MULTI_REQ: status = gattServApp_ProcessReadMultiReq( pMsg, &errHandle ); break; case ATT_READ_BY_GRP_TYPE_REQ: status = gattServApp_ProcessReadByGrpTypeReq( pMsg, &errHandle ); break; case ATT_WRITE_REQ: status = gattServApp_ProcessWriteReq( pMsg, &errHandle ); break; case ATT_PREPARE_WRITE_REQ: status = gattServApp_ProcessPrepareWriteReq( pMsg, &errHandle ); break; case ATT_EXECUTE_WRITE_REQ: status = gattServApp_ProcessExecuteWriteReq( pMsg, &errHandle ); break; default: // Unknown request - ignore it! status = SUCCESS; break; } // See if we need to send an error response back if ( status != SUCCESS ) { // Make sure the request was not sent locally if ( pMsg->hdr.status != bleNotConnected ) { attErrorRsp_t *pRsp = &rsp.errorRsp; pRsp->reqOpcode = pMsg->method; pRsp->handle = errHandle; pRsp->errCode = status; VOID ATT_ErrorRsp( pMsg->connHandle, pRsp ); } } // Notify GATT that a message has been processed // Note: This call is optional if flow control is not used. GATT_AppCompletedMsg( pMsg ); // if app task ask the gatt message, copy and send to app task if(s_GATTServCB) s_GATTServCB(pMsg); } /********************************************************************* * @fn gattServApp_ProcessExchangeMTUReq * * @brief Process Exchange MTU Request. * * @param pMsg - pointer to received message * * @return Success */ static bStatus_t gattServApp_ProcessExchangeMTUReq( gattMsgEvent_t *pMsg ) { attExchangeMTURsp_t *pRsp = &rsp.exchangeMTURsp; // ATT_MTU shall be set to the minimum of the Client Rx MTU and Server Rx MTU values // Set the Server Rx MTU parameter to the maximum MTU that this server can receive #if defined ( TESTMODES ) if ( paramValue == GATT_TESTMODE_MAX_MTU_SIZE ) { pRsp->serverRxMTU = ATT_MAX_MTU_SIZE; } else #endif pRsp->serverRxMTU = g_ATT_MTU_SIZE_MAX;//ATT_MTU_SIZE; // Send response back VOID ATT_ExchangeMTURsp( pMsg->connHandle, pRsp ); return ( SUCCESS ); } /********************************************************************* * @fn gattServApp_ProcessFindByTypeValueReq * * @brief Process Find By Type Value Request. * * @param pMsg - pointer to received message * @param pErrHandle - attribute handle that generates an error * * @return Success or Failure */ static bStatus_t gattServApp_ProcessFindByTypeValueReq( gattMsgEvent_t *pMsg, uint16 *pErrHandle ) { attFindByTypeValueReq_t *pReq = &pMsg->msg.findByTypeValueReq; attFindByTypeValueRsp_t *pRsp = &rsp.findByTypeValueRsp; gattAttribute_t *pAttr; uint16 service; // Initialize the response VOID osal_memset( pRsp, 0, sizeof( attFindByTypeValueRsp_t ) ); // Only attributes with attribute handles between and including the Starting // Handle parameter and the Ending Handle parameter that match the requested // attribute type and the attribute value will be returned. // All attribute types are effectively compared as 128-bit UUIDs, // even if a 16-bit UUID is provided in this request or defined // for an attribute. pAttr = GATT_FindHandleUUID( pReq->startHandle, pReq->endHandle, pReq->type.uuid, pReq->type.len, &service ); while ( ( pAttr != NULL ) && ( pRsp->numInfo < g_ATT_MAX_NUM_HANDLES_INFO ) ) { uint16 grpEndHandle; // It is not possible to use this request on an attribute that has a value // that is longer than (ATT_MTU - 7). if ( GATTServApp_ReadAttr( pMsg->connHandle, pAttr, service, attrValue, &attrLen, 0, (g_ATT_MTU_SIZE-7) ) == SUCCESS ) { // Attribute values should be compared in terms of length and binary representation. if ( ( pReq->len == attrLen ) && osal_memcmp( pReq->value, attrValue, attrLen) ) { // New attribute found // Set the Found Handle to the attribute that has the exact attribute // type and attribute value from the request. pRsp->handlesInfo[pRsp->numInfo].handle = pAttr->handle; } } // Try to find the next attribute pAttr = GATT_FindNextAttr( pAttr, pReq->endHandle, service, &grpEndHandle ); // Set Group End Handle if ( pRsp->handlesInfo[pRsp->numInfo].handle != 0 ) { // If the attribute type is a grouping attribute, the Group End Handle // shall be defined by that higher layer specification. If the attribute // type is not a grouping attribute, the Group End Handle shall be equal // to the Found Attribute Handle. if ( pAttr != NULL ) { pRsp->handlesInfo[pRsp->numInfo++].grpEndHandle = grpEndHandle; } else { // If no other attributes with the same attribute type exist after the // Found Attribute Handle, the Group End Handle shall be set to 0xFFFF. pRsp->handlesInfo[pRsp->numInfo++].grpEndHandle = GATT_MAX_HANDLE; } } } // while if ( pRsp->numInfo > 0 ) { // Send a response back VOID ATT_FindByTypeValueRsp( pMsg->connHandle, pRsp ); return ( SUCCESS ); } *pErrHandle = pReq->startHandle; return ( ATT_ERR_ATTR_NOT_FOUND ); } /********************************************************************* * @fn gattServApp_ProcessReadByTypeReq * * @brief Process Read By Type Request. * * @param pMsg - pointer to received message * @param pErrHandle - attribute handle that generates an error * * @return Success or Failure */ static bStatus_t gattServApp_ProcessReadByTypeReq( gattMsgEvent_t *pMsg, uint16 *pErrHandle ) { attReadByTypeReq_t *pReq = &pMsg->msg.readByTypeReq; attReadByTypeRsp_t *pRsp = &rsp.readByTypeRsp; uint16 startHandle = pReq->startHandle; uint8 dataLen = 0; uint8 status = SUCCESS; // Only the attributes with attribute handles between and including the // Starting Handle and the Ending Handle with the attribute type that is // the same as the Attribute Type given will be returned. // Make sure there's enough room at least for an attribute handle (no value) while ( dataLen <= (g_ATT_MTU_SIZE-4) ) { uint16 service; gattAttribute_t *pAttr; // All attribute types are effectively compared as 128-bit UUIDs, even if // a 16-bit UUID is provided in this request or defined for an attribute. pAttr = GATT_FindHandleUUID( startHandle, pReq->endHandle, pReq->type.uuid, pReq->type.len, &service ); if ( pAttr == NULL ) { break; // No more attribute found } // Update start handle so it has the right value if we break from the loop startHandle = pAttr->handle; // Make sure the attribute has sufficient permissions to allow reading status = GATT_VerifyReadPermissions( pMsg->connHandle, pAttr->permissions ); if ( status != SUCCESS ) { break; } // Read the attribute value. If the attribute value is longer than // (ATT_MTU - 4) or 253 octets, whichever is smaller, then the first // (ATT_MTU - 4) or 253 octets shall be included in this response. status = GATTServApp_ReadAttr( pMsg->connHandle, pAttr, service, attrValue, &attrLen, 0, (g_ATT_MTU_SIZE-4) ); if ( status != SUCCESS ) { break; // Cannot read the attribute value } // See if this is the first attribute found if ( dataLen == 0 ) { // Use the length of the first attribute value for the length field pRsp->len = 2 + attrLen; } else { // If the attributes have attribute values that have the same length // then these attributes can all be read in a single request. if ( pRsp->len != 2 + attrLen ) { break; } } // Make sure there's enough room for this attribute handle and value if ( dataLen + attrLen > (g_ATT_MTU_SIZE-4) ) { break; } // Add the handle value pair to the response pRsp->dataList[dataLen++] = LO_UINT16( pAttr->handle ); pRsp->dataList[dataLen++] = HI_UINT16( pAttr->handle ); VOID osal_memcpy( &(pRsp->dataList[dataLen]), attrValue, attrLen ); dataLen += attrLen; if ( startHandle == GATT_MAX_HANDLE ) { break; // We're done } // Update start handle and search again startHandle++; } // while // See what to respond if ( dataLen > 0 ) { // Set the number of attribute handle-value pairs found pRsp->numPairs = dataLen / pRsp->len; // Send a response back VOID ATT_ReadByTypeRsp( pMsg->connHandle, pRsp ); return ( SUCCESS ); } if ( status == SUCCESS ) { // Attribute not found -- dataLen must be 0 status = ATT_ERR_ATTR_NOT_FOUND; } *pErrHandle = startHandle; return ( status ); } /********************************************************************* * @fn gattServApp_ProcessReadReq * * @brief Process Read Request. * * @param pMsg - pointer to received message * @param pErrHandle - attribute handle that generates an error * * @return Success or Failure */ static bStatus_t gattServApp_ProcessReadReq( gattMsgEvent_t *pMsg, uint16 *pErrHandle ) { attReadReq_t *pReq = &pMsg->msg.readReq; gattAttribute_t *pAttr; uint16 service; uint8 status; pAttr = GATT_FindHandle( pReq->handle, &service ); if ( pAttr != NULL ) { attReadRsp_t *pRsp = &rsp.readRsp; // Build and send a response back. If the attribute value is longer // than (ATT_MTU - 1) then (ATT_MTU - 1) octets shall be included // in this response. status = GATTServApp_ReadAttr( pMsg->connHandle, pAttr, service, pRsp->value, &pRsp->len, 0, (g_ATT_MTU_SIZE-1) ); if ( status == SUCCESS ) { // Send a response back VOID ATT_ReadRsp( pMsg->connHandle, pRsp ); } } else { status = ATT_ERR_INVALID_HANDLE; } if ( status != SUCCESS ) { *pErrHandle = pReq->handle; } return ( status ); } /********************************************************************* * @fn gattServApp_ProcessReadBlobReq * * @brief Process Read Blob Request. * * @param pMsg - pointer to received message * @param pErrHandle - attribute handle that generates an error * * @return Success or Failure */ static bStatus_t gattServApp_ProcessReadBlobReq( gattMsgEvent_t *pMsg, uint16 *pErrHandle ) { attReadBlobReq_t *pReq = &pMsg->msg.readBlobReq; gattAttribute_t *pAttr; uint16 service; uint8 status; pAttr = GATT_FindHandle( pReq->handle, &service ); if ( pAttr != NULL ) { attReadBlobRsp_t *pRsp = &rsp.readBlobRsp; // Read part attribute value. If the attribute value is longer than // (Value Offset + ATT_MTU - 1) then (ATT_MTU - 1) octets from Value // Offset shall be included in this response. status = GATTServApp_ReadAttr( pMsg->connHandle, pAttr, service, pRsp->value, &pRsp->len, pReq->offset, (g_ATT_MTU_SIZE-1) ); if ( status == SUCCESS ) { // Send a response back VOID ATT_ReadBlobRsp( pMsg->connHandle, pRsp ); } } else { status = ATT_ERR_INVALID_HANDLE; } if ( status != SUCCESS ) { *pErrHandle = pReq->handle; } return ( status ); } /********************************************************************* * @fn gattServApp_ProcessReadMultiReq * * @brief Process Read Multiple Request. * * @param pMsg - pointer to received message * @param pErrHandle - attribute handle that generates an error * * @return Success or Failure */ static bStatus_t gattServApp_ProcessReadMultiReq( gattMsgEvent_t *pMsg, uint16 *pErrHandle ) { attReadMultiReq_t *pReq = &pMsg->msg.readMultiReq; attReadMultiRsp_t *pRsp = &rsp.readMultiRsp; uint8 status = SUCCESS; // Set the response length pRsp->len = 0; for ( uint8 i = 0; ( i < pReq->numHandles ) && ( pRsp->len < (g_ATT_MTU_SIZE-1) ); i++ ) { gattAttribute_t *pAttr; uint16 service; pAttr = GATT_FindHandle( pReq->handle[i], &service ); if ( pAttr == NULL ) { // Should never get here! status = ATT_ERR_INVALID_HANDLE; // The handle of the first attribute causing the error *pErrHandle = pReq->handle[i]; break; } // If the Set Of Values parameter is longer than (ATT_MTU - 1) then only // the first (ATT_MTU - 1) octets shall be included in this response. status = GATTServApp_ReadAttr( pMsg->connHandle, pAttr, service, attrValue, &attrLen, 0, (g_ATT_MTU_SIZE-1) ); if ( status != SUCCESS ) { // The handle of the first attribute causing the error *pErrHandle = pReq->handle[i]; break; } // Make sure there's enough room in the response for this attribute value if ( pRsp->len + attrLen > (g_ATT_MTU_SIZE-1) ) { attrLen = (g_ATT_MTU_SIZE-1) - pRsp->len; } // Append this value to the end of the response VOID osal_memcpy( &(pRsp->values[pRsp->len]), attrValue, attrLen ); pRsp->len += attrLen; } if ( status == SUCCESS ) { // Send a response back VOID ATT_ReadMultiRsp( pMsg->connHandle, pRsp ); } return ( status ); } /********************************************************************* * @fn gattServApp_ProcessReadByGrpTypeReq * * @brief Process Read By Group Type Request. * * @param pMsg - pointer to received message * @param pErrHandle - attribute handle that generates an error * * @return Success or Failure */ static bStatus_t gattServApp_ProcessReadByGrpTypeReq( gattMsgEvent_t *pMsg, uint16 *pErrHandle ) { attReadByGrpTypeReq_t *pReq = &pMsg->msg.readByGrpTypeReq; attReadByGrpTypeRsp_t *pRsp = &rsp.readByGrpTypeRsp; uint16 service; gattAttribute_t *pAttr; uint8 dataLen = 0; uint8 status = SUCCESS; // Only the attributes with attribute handles between and including the // Starting Handle and the Ending Handle with the attribute type that is // the same as the Attribute Type given will be returned. // All attribute types are effectively compared as 128-bit UUIDs, // even if a 16-bit UUID is provided in this request or defined // for an attribute. pAttr = GATT_FindHandleUUID( pReq->startHandle, pReq->endHandle, pReq->type.uuid, pReq->type.len, &service ); while ( pAttr != NULL ) { uint16 endGrpHandle; // The service, include and characteristic declarations are readable and // require no authentication or authorization, therefore insufficient // authentication or read not permitted errors shall not occur. status = GATT_VerifyReadPermissions( pMsg->connHandle, pAttr->permissions ); if ( status != SUCCESS ) { *pErrHandle = pAttr->handle; break; } // Read the attribute value. If the attribute value is longer than // (ATT_MTU - 6) or 251 octets, whichever is smaller, then the first // (ATT_MTU - 6) or 251 octets shall be included in this response. status = GATTServApp_ReadAttr( pMsg->connHandle, pAttr, service, attrValue, &attrLen, 0, (g_ATT_MTU_SIZE-6) ); if ( status != SUCCESS ) { // Cannot read the attribute value *pErrHandle = pAttr->handle; break; } // See if this is the first attribute found if ( dataLen == 0 ) { // Use the length of the first attribute value for the length field pRsp->len = 2 + 2 + attrLen; } else { // If the attributes have attribute values that have the same length // then these attributes can all be read in a single request. if ( pRsp->len != 2 + 2 + attrLen ) { break; // We're done here } // Make sure there's enough room for this attribute handle, end group handle and value if ( dataLen + attrLen > (g_ATT_MTU_SIZE-6) ) { break; // We're done here } } // Add Attribute Handle to the response pRsp->dataList[dataLen++] = LO_UINT16( pAttr->handle ); pRsp->dataList[dataLen++] = HI_UINT16( pAttr->handle ); // Try to find the next attribute pAttr = GATT_FindNextAttr( pAttr, pReq->endHandle, service, &endGrpHandle ); // Add End Group Handle to the response if ( pAttr != NULL ) { // The End Group Handle is the handle of the last attribute within the // service definition pRsp->dataList[dataLen++] = LO_UINT16( endGrpHandle ); pRsp->dataList[dataLen++] = HI_UINT16( endGrpHandle ); } else { // The ending handle of the last service can be 0xFFFF pRsp->dataList[dataLen++] = LO_UINT16( GATT_MAX_HANDLE ); pRsp->dataList[dataLen++] = HI_UINT16( GATT_MAX_HANDLE ); } // Add Attribute Value to the response VOID osal_memcpy( &(pRsp->dataList[dataLen]), attrValue, attrLen ); dataLen += attrLen; } // while // See what to respond if ( dataLen > 0 ) { // Set the number of attribute handle, end group handle and value sets found pRsp->numGrps = dataLen / pRsp->len; // Send a response back VOID ATT_ReadByGrpTypeRsp( pMsg->connHandle, pRsp ); return ( SUCCESS ); } if ( status == SUCCESS ) { // No grouping attribute found -- dataLen must be 0 status = ATT_ERR_ATTR_NOT_FOUND; } *pErrHandle = pReq->startHandle; return ( status ); } /********************************************************************* * @fn gattServApp_ProcessWriteReq * * @brief Process Write Request or Command. * * @param pMsg - pointer to received message * @param pErrHandle - attribute handle that generates an error * * @return Success or Failure */ static bStatus_t gattServApp_ProcessWriteReq( gattMsgEvent_t *pMsg, uint16 *pErrHandle ) { attWriteReq_t *pReq = &(pMsg->msg.writeReq); gattAttribute_t *pAttr; uint16 service; uint8 status = SUCCESS; // No Error Response or Write Response shall be sent in response to Write // Command. If the server cannot write this attribute for any reason the // command shall be ignored. pAttr = GATT_FindHandle( pReq->handle, &service ); if ( pAttr != NULL ) { // Authorization is handled by the application/profile if ( gattPermitAuthorWrite( pAttr->permissions ) ) { // Use Service's authorization callback to authorize the request pfnGATTAuthorizeAttrCB_t pfnCB = gattServApp_FindAuthorizeAttrCB( service ); if ( pfnCB != NULL ) { status = (*pfnCB)( pMsg->connHandle, pAttr, ATT_WRITE_REQ ); } else { status = ATT_ERR_UNLIKELY; } } // If everything is fine then try to write the new value if ( status == SUCCESS ) { // Use Service's write callback to write the request status = GATTServApp_WriteAttr( pMsg->connHandle, pReq->handle, pReq->value, pReq->len, 0 ); if ( ( status == SUCCESS ) && ( pReq->cmd == FALSE ) ) { // Send a response back //VOID ATT_WriteRsp( pMsg->connHandle ); uint8 st=ATT_WriteRsp( pMsg->connHandle ); if(st) { AT_LOG("[ATT_RSP ERR] %x %x\n",st,l2capSegmentPkt.fragment); } } } } else { status = ATT_ERR_INVALID_HANDLE; } if ( status != SUCCESS ) { *pErrHandle = pReq->handle; } return ( pReq->cmd ? SUCCESS : status ); } /********************************************************************* * @fn gattServApp_ProcessPrepareWriteReq * * @brief Process Prepare Write Request. * * @param pMsg - pointer to received message * @param pErrHandle - attribute handle that generates an error * * @return Success or Failure */ static bStatus_t gattServApp_ProcessPrepareWriteReq( gattMsgEvent_t *pMsg, uint16 *pErrHandle ) { attPrepareWriteReq_t *pReq = &pMsg->msg.prepareWriteReq; gattAttribute_t *pAttr; uint16 service; uint8 status = SUCCESS; pAttr = GATT_FindHandle( pReq->handle, &service ); if ( pAttr != NULL ) { // Authorization is handled by the application/profile if ( gattPermitAuthorWrite( pAttr->permissions ) ) { // Use Service's authorization callback to authorize the request pfnGATTAuthorizeAttrCB_t pfnCB = gattServApp_FindAuthorizeAttrCB( service ); if ( pfnCB != NULL ) { status = (*pfnCB)( pMsg->connHandle, pAttr, ATT_WRITE_REQ ); } else { status = ATT_ERR_UNLIKELY; } } if ( status == SUCCESS ) { #if defined ( TESTMODES ) if ( paramValue == GATT_TESTMODE_CORRUPT_PW_DATA ) { pReq->value[0] = ~(pReq->value[0]); } #endif // Enqueue the request for now status = gattServApp_EnqueuePrepareWriteReq( pMsg->connHandle, pReq ); if ( status == SUCCESS ) { //LOG("pre off[%d] len[%d]\n", pReq->offset, pReq->len); // Send a response back VOID ATT_PrepareWriteRsp( pMsg->connHandle, (attPrepareWriteRsp_t *)pReq ); } } } else { status = ATT_ERR_INVALID_HANDLE; } if ( status != SUCCESS ) { *pErrHandle = pReq->handle; } return ( status ); } /********************************************************************* * @fn gattServApp_ProcessExecuteWriteReq * * @brief Process Execute Write Request. * * @param pMsg - pointer to received message * @param pErrHandle - attribute handle that generates an error * * @return Success or Failure */ static bStatus_t gattServApp_ProcessExecuteWriteReq( gattMsgEvent_t *pMsg, uint16 *pErrHandle ) { attExecuteWriteReq_t *pReq = &pMsg->msg.executeWriteReq; prepareWrites_t *pQueue; uint8 status = SUCCESS; // See if this client has a prepare write queue pQueue = gattServApp_FindPrepareWriteQ( pMsg->connHandle ); if ( pQueue != NULL ) { for ( uint8 i = 0; i < maxNumPrepareWrites; i++ ) { attPrepareWriteReq_t *pWriteReq = &(pQueue->pPrepareWriteQ[i]); // See if there're any prepared write requests in the queue if ( pWriteReq->handle == GATT_INVALID_HANDLE ) { break; // We're done } // Execute the request if ( pReq->flags == ATT_WRITE_PREPARED_VALUES ) { status = GATTServApp_WriteAttr( pMsg->connHandle, pWriteReq->handle, pWriteReq->value, pWriteReq->len, pWriteReq->offset ); //LOG("exe off[%d]len[%d]", pWriteReq->offset, pWriteReq->len); // If the prepare write requests can not be written, the queue shall // be cleared and then an Error Response shall be sent with a high // layer defined error code. if ( status != SUCCESS ) { // Cancel the remaining prepared writes pReq->flags = ATT_CANCEL_PREPARED_WRITES; // The Attribute Handle in Error shall be set to the attribute handle // of the attribute from the prepare write queue that caused this // application error *pErrHandle = pWriteReq->handle; } } else // ATT_CANCEL_PREPARED_WRITES { // Cancel all prepared writes - just ignore the request } // Clear the queue item VOID osal_memset( pWriteReq, 0, sizeof( attPrepareWriteRsp_t ) ); // Mark this item as empty pWriteReq->handle = GATT_INVALID_HANDLE; } // for loop // Mark this queue as empty pQueue->connHandle = INVALID_CONNHANDLE; } // Send a response back if ( status == SUCCESS ) { VOID ATT_ExecuteWriteRsp( pMsg->connHandle ); } return ( status ); } /********************************************************************* * @fn gattServApp_EnqueuePrepareWriteReq * * @brief Enqueue Prepare Write Request. * * @param connHandle - connection packet was received on * @param pReq - pointer to request * * @return Success or Failure */ static bStatus_t gattServApp_EnqueuePrepareWriteReq( uint16 connHandle, attPrepareWriteReq_t *pReq ) { prepareWrites_t *pQueue; // First see if there's queue already assocaited with this client pQueue = gattServApp_FindPrepareWriteQ( connHandle ); if ( pQueue == NULL ) { // Find a queue for this client pQueue = gattServApp_FindPrepareWriteQ( INVALID_CONNHANDLE ); if ( pQueue != NULL ) { pQueue->connHandle = connHandle; } } // If a queue is found for this client then enqueue the request if ( pQueue != NULL ) { for ( uint8 i = 0; i < maxNumPrepareWrites; i++ ) { if ( pQueue->pPrepareWriteQ[i].handle == GATT_INVALID_HANDLE ) { // Store the request here VOID osal_memcpy( &(pQueue->pPrepareWriteQ[i]), pReq, sizeof ( attPrepareWriteReq_t ) ); //LOG("enq off[%d]len[%d]\n", pReq->offset, pReq->len); return ( SUCCESS ); } } } return ( ATT_ERR_PREPARE_QUEUE_FULL ); } /********************************************************************* * @fn gattServApp_FindPrepareWriteQ * * @brief Find client's queue. * * @param connHandle - connection used by client * * @return Pointer to queue. NULL, otherwise. */ static prepareWrites_t *gattServApp_FindPrepareWriteQ( uint16 connHandle ) { // First see if this client has already a queue for ( uint8 i = 0; i < MAX_NUM_LL_CONN; i++ ) { if ( prepareWritesTbl[i].connHandle == connHandle ) { // Queue found return ( &(prepareWritesTbl[i]) ); } } return ( (prepareWrites_t *)NULL ); } /********************************************************************* * @fn gattServApp_PrepareWriteQInUse * * @brief Check to see if the prepare write queue is in use. * * @param void * * @return TRUE if queue in use. FALSE, otherwise. */ static uint8 gattServApp_PrepareWriteQInUse( void ) { // See if any prepare write queue is in use for ( uint8 i = 0; i < MAX_NUM_LL_CONN; i++ ) { if ( prepareWritesTbl[i].connHandle != INVALID_CONNHANDLE ) { for ( uint8 j = 0; j < maxNumPrepareWrites; j++ ) { if ( prepareWritesTbl[i].pPrepareWriteQ[j].handle != GATT_INVALID_HANDLE ) { // Queue item is in use return ( TRUE ); } } // for } } // for return ( FALSE ); } /********************************************************************* * @fn gattServApp_FindCharCfgItem * * @brief Find the characteristic configuration for a given client. * Uses the connection handle to search the charactersitic * configuration table of a client. * * @param connHandle - connection handle (0xFFFF for empty entry) * @param charCfgTbl - characteristic configuration table. * * @return pointer to the found item. NULL, otherwise. */ static gattCharCfg_t *gattServApp_FindCharCfgItem( uint16 connHandle, gattCharCfg_t *charCfgTbl ) { for ( uint8 i = 0; i < GATT_MAX_NUM_CONN; i++ ) { if ( charCfgTbl[i].connHandle == connHandle ) { // Entry found return ( &(charCfgTbl[i]) ); } } return ( (gattCharCfg_t *)NULL ); } /********************************************************************* * @fn gattServApp_FindReadAttrCB * * @brief Find the Read Attribute CB function pointer for a given service. * * @param handle - service attribute handle * * @return pointer to the found CB. NULL, otherwise. */ static pfnGATTReadAttrCB_t gattServApp_FindReadAttrCB( uint16 handle ) { CONST gattServiceCBs_t *pCBs = gattServApp_FindServiceCBs( handle ); return ( ( pCBs == NULL ) ? NULL : pCBs->pfnReadAttrCB ); } /********************************************************************* * @fn gattServApp_FindWriteAttrCB * * @brief Find the Write CB Attribute function pointer for a given service. * * @param handle - service attribute handle * * @return pointer to the found CB. NULL, otherwise. */ static pfnGATTWriteAttrCB_t gattServApp_FindWriteAttrCB( uint16 handle ) { CONST gattServiceCBs_t *pCBs = gattServApp_FindServiceCBs( handle ); return ( ( pCBs == NULL ) ? NULL : pCBs->pfnWriteAttrCB ); } /********************************************************************* * @fn gattServApp_FindAuthorizeAttrCB * * @brief Find the Authorize Attribute CB function pointer for a given service. * * @param handle - service attribute handle * * @return pointer to the found CB. NULL, otherwise. */ static pfnGATTAuthorizeAttrCB_t gattServApp_FindAuthorizeAttrCB( uint16 handle ) { CONST gattServiceCBs_t *pCBs = gattServApp_FindServiceCBs( handle ); return ( ( pCBs == NULL ) ? NULL : pCBs->pfnAuthorizeAttrCB ); } /********************************************************************* * @fn gattServApp_ValidateWriteAttrCB * * @brief Validate and/or Write attribute data * * @param connHandle - connection message was received on * @param pAttr - pointer to attribute * @param pValue - pointer to data to be written * @param len - length of data * @param offset - offset of the first octet to be written * * @return Success or Failure */ static bStatus_t gattServApp_WriteAttrCB( uint16 connHandle, gattAttribute_t *pAttr, uint8 *pValue, uint8 len, uint16 offset ) { bStatus_t status = SUCCESS; if ( pAttr->type.len == ATT_BT_UUID_SIZE ) { // 16-bit UUID uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1]); switch ( uuid ) { case GATT_CLIENT_CHAR_CFG_UUID: status = GATTServApp_ProcessCCCWriteReq( connHandle, pAttr, pValue, len, offset, GATT_CLIENT_CFG_INDICATE ); break; default: // Should never get here! status = ATT_ERR_INVALID_HANDLE; } } else { // 128-bit UUID status = ATT_ERR_INVALID_HANDLE; } return ( status ); } /********************************************************************* * @fn GATTServApp_ReadAttr * * @brief Read an attribute. If the format of the attribute value * is unknown to GATT Server, use the callback function * provided by the Service. * * @param connHandle - connection message was received on * @param pAttr - pointer to attribute * @param service - handle of owner service * @param pValue - pointer to data to be read * @param pLen - length of data to be read * @param offset - offset of the first octet to be read * @param maxLen - maximum length of data to be read * * @return Success or Failure */ uint8 GATTServApp_ReadAttr( uint16 connHandle, gattAttribute_t *pAttr, uint16 service, uint8 *pValue, uint8 *pLen, uint16 offset, uint8 maxLen ) { uint8 useCB = FALSE; bStatus_t status = SUCCESS; // Authorization is handled by the application/profile if ( gattPermitAuthorRead( pAttr->permissions ) ) { // Use Service's authorization callback to authorize the request pfnGATTAuthorizeAttrCB_t pfnCB = gattServApp_FindAuthorizeAttrCB( service ); if ( pfnCB != NULL ) { status = (*pfnCB)( connHandle, pAttr, ATT_READ_REQ ); } else { status = ATT_ERR_UNLIKELY; } if ( status != SUCCESS ) { // Read operation failed! return ( status ); } } // Check the UUID length if ( pAttr->type.len == ATT_BT_UUID_SIZE ) { // 16-bit UUID uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1]); switch ( uuid ) { case GATT_PRIMARY_SERVICE_UUID: case GATT_SECONDARY_SERVICE_UUID: // Make sure it's not a blob operation if ( offset == 0 ) { gattAttrType_t *pType = (gattAttrType_t *)(pAttr->pValue); *pLen = pType->len; VOID osal_memcpy( pValue, pType->uuid, pType->len ); } else { status = ATT_ERR_ATTR_NOT_LONG; } break; case GATT_CHARACTER_UUID: // Make sure it's not a blob operation if ( offset == 0 ) { gattAttribute_t *pCharValue; // The Attribute Value of a Characteristic Declaration includes the // Characteristic Properties, Characteristic Value Attribute Handle // and UUID. *pLen = 1; pValue[0] = *pAttr->pValue; // Properties // The Characteristic Value Attribute exists immediately following // the Characteristic Declaration. pCharValue = GATT_FindHandle( pAttr->handle+1, NULL ); if ( pCharValue != NULL ) { // It can be a 128-bit UUID *pLen += (2 + pCharValue->type.len); // Attribute Handle pValue[1] = LO_UINT16( pCharValue->handle ); pValue[2] = HI_UINT16( pCharValue->handle ); // Attribute UUID VOID osal_memcpy( &(pValue[3]), pCharValue->type.uuid, pCharValue->type.len ); } else { // Should never get here! *pLen += (2 + ATT_BT_UUID_SIZE); // Set both Attribute Handle and UUID to 0 VOID osal_memset( &(pValue[1]), 0, (2 + ATT_BT_UUID_SIZE) ); } } else { status = ATT_ERR_ATTR_NOT_LONG; } break; case GATT_INCLUDE_UUID: // Make sure it's not a blob operation if ( offset == 0 ) { uint16 servHandle; uint16 endGrpHandle; gattAttribute_t *pIncluded; uint16 handle = *((uint16 *)(pAttr->pValue)); // The Attribute Value of an Include Declaration is set the // included service Attribute Handle, the End Group Handle, // and the service UUID. The Service UUID shall only be present // when the UUID is a 16-bit Bluetooth UUID. *pLen = 4; pValue[0] = LO_UINT16( handle ); pValue[1] = HI_UINT16( handle ); // Find the included service attribute record pIncluded = GATT_FindHandle( handle, &servHandle ); if ( pIncluded != NULL ) { gattAttrType_t *pServiceUUID = (gattAttrType_t *)pIncluded->pValue; // Find out the End Group handle if ( ( GATT_FindNextAttr( pIncluded, GATT_MAX_HANDLE, servHandle, &endGrpHandle ) == NULL ) && ( !gattSecondaryServiceType( pIncluded->type ) ) ) { // The ending handle of the last service can be 0xFFFF endGrpHandle = GATT_MAX_HANDLE; } // Include only 16-bit Service UUID if ( pServiceUUID->len == ATT_BT_UUID_SIZE ) { VOID osal_memcpy( &(pValue[4]), pServiceUUID->uuid, ATT_BT_UUID_SIZE ); *pLen += ATT_BT_UUID_SIZE; } } else { // Should never get here! endGrpHandle = handle; } // End Group Handle pValue[2] = LO_UINT16( endGrpHandle ); pValue[3] = HI_UINT16( endGrpHandle ); } else { status = ATT_ERR_ATTR_NOT_LONG; } break; case GATT_CLIENT_CHAR_CFG_UUID: // Make sure it's not a blob operation if ( offset == 0 ) { uint16 value = GATTServApp_ReadCharCfg( connHandle, (gattCharCfg_t *)(pAttr->pValue) ); *pLen = 2; pValue[0] = LO_UINT16( value ); pValue[1] = HI_UINT16( value ); } else { status = ATT_ERR_ATTR_NOT_LONG; } break; case GATT_CHAR_EXT_PROPS_UUID: case GATT_SERV_CHAR_CFG_UUID: // Make sure it's not a blob operation if ( offset == 0 ) { uint16 value = *((uint16 *)(pAttr->pValue)); *pLen = 2; pValue[0] = LO_UINT16( value ); pValue[1] = HI_UINT16( value ); } else { status = ATT_ERR_ATTR_NOT_LONG; } break; case GATT_CHAR_USER_DESC_UUID: { uint8 len = osal_strlen( (char *)(pAttr->pValue) ); // Could be a long attribute // If the value offset of the Read Blob Request is greater than the // length of the attribute value, an Error Response shall be sent with // the error code Invalid Offset. if ( offset <= len ) { // If the value offset is equal than the length of the attribute // value, then the length of the part attribute value shall be zero. if ( offset == len ) { len = 0; } else { // If the attribute value is longer than (Value Offset + maxLen) // then maxLen octets from Value Offset shall be included in // this response. if ( len > ( offset + maxLen ) ) { len = maxLen; } else { len -= offset; } } *pLen = len; VOID osal_memcpy( pValue, &(pAttr->pValue[offset]), len ); } else { status = ATT_ERR_INVALID_OFFSET; } } break; case GATT_CHAR_FORMAT_UUID: // Make sure it's not a blob operation if ( offset == 0 ) { gattCharFormat_t *pFormat = (gattCharFormat_t *)(pAttr->pValue); *pLen = 7; pValue[0] = pFormat->format; pValue[1] = pFormat->exponent; pValue[2] = LO_UINT16( pFormat->unit ); pValue[3] = HI_UINT16( pFormat->unit ); pValue[4] = pFormat->nameSpace; pValue[5] = LO_UINT16( pFormat->desc ); pValue[6] = HI_UINT16( pFormat->desc ); } else { status = ATT_ERR_ATTR_NOT_LONG; } break; default: useCB = TRUE; break; } } else { useCB = TRUE; } if ( useCB == TRUE ) { // Use Service's read callback to process the request pfnGATTReadAttrCB_t pfnCB = gattServApp_FindReadAttrCB( service ); if ( pfnCB != NULL ) { // Read the attribute value status = (*pfnCB)( connHandle, pAttr, pValue, pLen, offset, maxLen ); } else { status = ATT_ERR_UNLIKELY; } } return ( status ); } /********************************************************************* * @fn GATTServApp_WriteAttr * * @brief Write attribute data * * @param connHandle - connection message was received on * @param handle - attribute handle * @param pValue - pointer to data to be written * @param len - length of data * @param offset - offset of the first octet to be written * * @return Success or Failure */ uint8 GATTServApp_WriteAttr( uint16 connHandle, uint16 handle, uint8 *pValue, uint16 len, uint16 offset ) { uint16 service; gattAttribute_t *pAttr; bStatus_t status; // Find the owner of the attribute pAttr = GATT_FindHandle( handle, &service ); if ( pAttr != NULL ) { // Find out the owner's callback functions pfnGATTWriteAttrCB_t pfnCB = gattServApp_FindWriteAttrCB( service ); if ( pfnCB != NULL ) { // Try to write the new value status = (*pfnCB)( connHandle, pAttr, pValue, len, offset ); } else { status = ATT_ERR_UNLIKELY; } } else { status = ATT_ERR_INVALID_HANDLE; } return ( status ); } /********************************************************************* * @fn GATTServApp_SetParamValue * * @brief Set a GATT Server Application Parameter value. Use this * function to change the default GATT parameter values. * * @param value - new param value * * @return void */ void GATTServApp_SetParamValue( uint16 value ) { #if defined ( TESTMODES ) paramValue = value; #else VOID value; #endif } /********************************************************************* * @fn GATTServApp_GetParamValue * * @brief Get a GATT Server Application Parameter value. * * @param none * * @return GATT Parameter value */ uint16 GATTServApp_GetParamValue( void ) { #if defined ( TESTMODES ) return ( paramValue ); #else return ( 0 ); #endif } /********************************************************************* * @fn GATTServApp_UpdateCharCfg * * @brief Update the Client Characteristic Configuration for a given * Client. * * Note: This API should only be called from the Bond Manager. * * @param connHandle - connection handle. * @param attrHandle - attribute handle. * @param value - characteristic configuration value (from NV). * * @return Success or Failure */ bStatus_t GATTServApp_UpdateCharCfg( uint16 connHandle, uint16 attrHandle, uint16 value ) { uint8 buf[2]; buf[0] = LO_UINT16( value ); buf[1] = HI_UINT16( value ); return ( GATTServApp_WriteAttr( connHandle, attrHandle, buf, 2, 0 ) ); } /********************************************************************* * @fn GATTServApp_SendServiceChangedInd * * @brief Send out a Service Changed Indication. * * @param connHandle - connection to use * @param taskId - task to be notified of confirmation * * @return SUCCESS: Indication was sent successfully. * FAILURE: Service Changed attribute not found. * INVALIDPARAMETER: Invalid connection handle or request field. * MSG_BUFFER_NOT_AVAIL: No HCI buffer is available. * bleNotConnected: Connection is down. * blePending: A confirmation is pending with this client. */ bStatus_t GATTServApp_SendServiceChangedInd( uint16 connHandle, uint8 taskId ) { uint16 value = GATTServApp_ReadCharCfg( connHandle, indCharCfg ); if ( value & GATT_CLIENT_CFG_INDICATE ) { return ( GATT_ServiceChangedInd( connHandle, taskId ) ); } return ( FAILURE ); } /********************************************************************* * @fn GATTServApp_InitCharCfg * * @brief Initialize the client characteristic configuration table. * * Note: Each client has its own instantiation of the Client * Characteristic Configuration. Reads/Writes of the Client * Characteristic Configuration only only affect the * configuration of that client. * * @param connHandle - connection handle (0xFFFF for all connections). * @param charCfgTbl - client characteristic configuration table. * * @return none */ void GATTServApp_InitCharCfg( uint16 connHandle, gattCharCfg_t *charCfgTbl ) { // Initialize Client Characteristic Configuration attributes if ( connHandle == INVALID_CONNHANDLE ) { for ( uint8 i = 0; i < GATT_MAX_NUM_CONN; i++ ) { charCfgTbl[i].connHandle = INVALID_CONNHANDLE; charCfgTbl[i].value = GATT_CFG_NO_OPERATION; } } else { gattCharCfg_t *pItem = gattServApp_FindCharCfgItem( connHandle, charCfgTbl ); if ( pItem != NULL ) { pItem->connHandle = INVALID_CONNHANDLE; pItem->value = GATT_CFG_NO_OPERATION; } } } /********************************************************************* * @fn GATTServApp_ReadCharCfg * * @brief Read the client characteristic configuration for a given * client. * * Note: Each client has its own instantiation of the Client * Characteristic Configuration. Reads of the Client * Characteristic Configuration only shows the configuration * for that client. * * @param connHandle - connection handle. * @param charCfgTbl - client characteristic configuration table. * * @return attribute value */ uint16 GATTServApp_ReadCharCfg( uint16 connHandle, gattCharCfg_t *charCfgTbl ) { gattCharCfg_t *pItem; pItem = gattServApp_FindCharCfgItem( connHandle, charCfgTbl ); if ( pItem != NULL ) { return ( (uint16)(pItem->value) ); } return ( (uint16)GATT_CFG_NO_OPERATION ); } /********************************************************************* * @fn GATTServApp_WriteCharCfg * * @brief Write the client characteristic configuration for a given * client. * * Note: Each client has its own instantiation of the Client * Characteristic Configuration. Writes of the Client * Characteristic Configuration only only affect the * configuration of that client. * * @param connHandle - connection handle. * @param charCfgTbl - client characteristic configuration table. * @param value - attribute new value. * * @return Success or Failure */ uint8 GATTServApp_WriteCharCfg( uint16 connHandle, gattCharCfg_t *charCfgTbl, uint16 value ) { gattCharCfg_t *pItem; pItem = gattServApp_FindCharCfgItem( connHandle, charCfgTbl ); if ( pItem == NULL ) { pItem = gattServApp_FindCharCfgItem( INVALID_CONNHANDLE, charCfgTbl ); if ( pItem == NULL ) { return ( ATT_ERR_INSUFFICIENT_RESOURCES ); } pItem->connHandle = connHandle; } // Write the new value for this client pItem->value = value; return ( SUCCESS ); } /********************************************************************* * @fn GATTServApp_ProcessCCCWriteReq * * @brief Process the client characteristic configuration * write request for a given client. * * @param connHandle - connection message was received on * @param pAttr - pointer to attribute * @param pValue - pointer to data to be written * @param len - length of data * @param offset - offset of the first octet to be written * @param validCfg - valid configuration * * @return Success or Failure */ bStatus_t GATTServApp_ProcessCCCWriteReq( uint16 connHandle, gattAttribute_t *pAttr, uint8 *pValue, uint8 len, uint16 offset, uint16 validCfg ) { bStatus_t status = SUCCESS; // Validate the value if ( offset == 0 ) { if ( len == 2 ) { uint16 value = BUILD_UINT16( pValue[0], pValue[1] ); // Validate characteristic configuration bit field if ( ( value & ~validCfg ) == 0 ) // indicate and/or notify { // Write the value if it's changed if ( GATTServApp_ReadCharCfg( connHandle, (gattCharCfg_t *)(pAttr->pValue) ) != value ) { status = GATTServApp_WriteCharCfg( connHandle, (gattCharCfg_t *)(pAttr->pValue), value ); if ( status == SUCCESS ) { // Notify the application GATTServApp_SendCCCUpdatedEvent( connHandle, pAttr->handle, value ); } } } else { status = ATT_ERR_INVALID_VALUE; } } else { status = ATT_ERR_INVALID_VALUE_SIZE; } } else { status = ATT_ERR_ATTR_NOT_LONG; } return ( status ); } /********************************************************************* * @fn GATTServApp_ProcessCharCfg * * @brief Process Client Charateristic Configuration change. * * @param charCfgTbl - characteristic configuration table. * @param pValue - pointer to attribute value. * @param authenticated - whether an authenticated link is required. * @param attrTbl - attribute table. * @param numAttrs - number of attributes in attribute table. * @param taskId - task to be notified of confirmation. * * @return Success or Failure */ bStatus_t GATTServApp_ProcessCharCfg( gattCharCfg_t *charCfgTbl, uint8 *pValue, uint8 authenticated, gattAttribute_t *attrTbl, uint16 numAttrs, uint8 taskId ) { bStatus_t status = SUCCESS; for ( uint8 i = 0; i < GATT_MAX_NUM_CONN; i++ ) { gattCharCfg_t *pItem = &(charCfgTbl[i]); if ( ( pItem->connHandle != INVALID_CONNHANDLE ) && ( pItem->value != GATT_CFG_NO_OPERATION ) ) { gattAttribute_t *pAttr; // Find the characteristic value attribute pAttr = GATTServApp_FindAttr( attrTbl, numAttrs, pValue ); if ( pAttr != NULL ) { attHandleValueNoti_t noti; // If the attribute value is longer than (ATT_MTU - 3) octets, then // only the first (ATT_MTU - 3) octets of this attributes value can // be sent in a notification. if ( GATTServApp_ReadAttr( pItem->connHandle, pAttr, GATT_SERVICE_HANDLE( attrTbl ), noti.value, &noti.len, 0, (g_ATT_MTU_SIZE-3) ) == SUCCESS ) { noti.handle = pAttr->handle; if ( pItem->value & GATT_CLIENT_CFG_NOTIFY ) { status |= GATT_Notification( pItem->connHandle, &noti, authenticated ); } if ( pItem->value & GATT_CLIENT_CFG_INDICATE ) { status |= GATT_Indication( pItem->connHandle, (attHandleValueInd_t *)&noti, authenticated, taskId ); } } } } } // for return ( status ); } /********************************************************************* * @fn gattServApp_HandleConnStatusCB * * @brief GATT Server Application link status change handler function. * * @param connHandle - connection handle * @param changeType - type of change * * @return none */ static void gattServApp_HandleConnStatusCB( uint16 connHandle, uint8 changeType ) { // Check to see if the connection has dropped if ( ( changeType == LINKDB_STATUS_UPDATE_REMOVED ) || ( ( changeType == LINKDB_STATUS_UPDATE_STATEFLAGS ) && ( !linkDB_Up( connHandle ) ) ) ) { prepareWrites_t *pQueue = gattServApp_FindPrepareWriteQ( connHandle ); // See if this client has a prepare write queue if ( pQueue != NULL ) { for ( uint8 i = 0; i < maxNumPrepareWrites; i++ ) { attPrepareWriteReq_t *pWriteReq = &(pQueue->pPrepareWriteQ[i]); // See if there're any prepared write requests in the queue if ( pWriteReq->handle == GATT_INVALID_HANDLE ) { break; } // Clear the queue item VOID osal_memset( pWriteReq, 0, sizeof( attPrepareWriteRsp_t ) ); } // for loop // Mark this queue as empty pQueue->connHandle = INVALID_CONNHANDLE; } // Reset Client Char Config when connection drops GATTServApp_InitCharCfg( connHandle, indCharCfg ); } } /********************************************************************* * @fn GATTServApp_SendCCCUpdatedEvent * * @brief Build and send the GATT_CLIENT_CHAR_CFG_UPDATED_EVENT to * the app. * * @param connHandle - connection handle * @param attrHandle - attribute handle * @param value - attribute new value * * @return none */ void GATTServApp_SendCCCUpdatedEvent( uint16 connHandle, uint16 attrHandle, uint16 value ) { if ( appTaskID != INVALID_TASK_ID ) { // Allocate, build and send event gattClientCharCfgUpdatedEvent_t *pEvent = (gattClientCharCfgUpdatedEvent_t *)osal_msg_allocate( (uint16)(sizeof ( gattClientCharCfgUpdatedEvent_t )) ); if ( pEvent ) { pEvent->hdr.event = GATT_SERV_MSG_EVENT; pEvent->hdr.status = SUCCESS; pEvent->method = GATT_CLIENT_CHAR_CFG_UPDATED_EVENT; pEvent->connHandle = connHandle; pEvent->attrHandle = attrHandle; pEvent->value = value; VOID osal_msg_send( appTaskID, (uint8 *)pEvent ); } } } bStatus_t gattServApp_RegisterCB(gattServMsgCB_t cb) { s_GATTServCB = cb; return SUCCESS; } #endif // ( CENTRAL_CFG | PERIPHERAL_CFG ) /**************************************************************************** ****************************************************************************/
the_stack_data/673880.c
void foo (void) {}
the_stack_data/150140214.c
/* * arch/s390/lib/misaligned.c * S390 misalignment panic stubs * * S390 version * Copyright (C) 2001 IBM Deutschland Entwicklung GmbH, IBM Corporation * Author(s): Martin Schwidefsky ([email protected]). * * xchg wants to panic if the pointer is not aligned. To avoid multiplying * the panic message over and over again, the panic is done in the helper * functions __misaligned_u64, __misaligned_u32 and __misaligned_u16. */ #include <linux/module.h> #include <linux/kernel.h> void __misaligned_u16(void) { panic("misaligned (__u16 *) in __xchg\n"); } void __misaligned_u32(void) { panic("misaligned (__u32 *) in __xchg\n"); } void __misaligned_u64(void) { panic("misaligned (__u64 *) in __xchg\n"); } EXPORT_SYMBOL(__misaligned_u16); EXPORT_SYMBOL(__misaligned_u32); EXPORT_SYMBOL(__misaligned_u64);
the_stack_data/170451911.c
#include <stdio.h> #define ROW 3 #define COL 5 int save_arr(double arr[][COL], int const row); double single_arr_mean(double *arr); double arr_mean(double const arr[][COL], int const row); double arr_max(double const arr[][COL], int const row); void show_arr(double const arr[][COL], int const row); int main(void) { int return_code; double arr[ROW][COL]; double single_mean, mean, max; printf("Enter data:\n"); return_code = save_arr(arr, ROW); if (return_code) { show_arr(arr, ROW); for (int i = 0; i < ROW; ++i) { single_mean = single_arr_mean(*(arr + i)); printf("Group%2d mean: %.2f\n", i + 1, single_mean); } mean = arr_mean(arr, ROW); printf("Average of all data: %.2f\n", mean); max = arr_max(arr, ROW); printf("Maximum of all data: %.2f\n", max); } else { printf("Bye.\n"); } return 0; } int save_arr(double arr[][COL], int const row) { for (int i = 0; i < row; ++i) { printf("Enter 5 data in group%2d: ", i + 1); for (int j = 0; j < COL; ++j) { if (scanf("%lf", *(arr + i) + j) != 1) { return 0; } } } return 1; } double single_arr_mean(double *arr) { double tot = 0; for (int i = 0; i < COL; ++i) { tot += *(arr + i); } return tot / COL; } double arr_mean(double const arr[][COL], int const row) { double tot = 0; for (int i = 0; i < row; ++i) { for (int j = 0; j < COL; ++j) { tot += arr[i][j]; } } return tot / (double) (COL * row); } double arr_max(double const arr[][COL], int const row) { double max = **arr; for (int i = 0; i < row; ++i) { for (int j = 0; j < COL; ++j) { max = arr[i][j] > max ? arr[i][j] : max; } } return max; } void show_arr(double const arr[][COL], int const row) { printf("The 2d array is:\n"); for (int i = 0; i < row; ++i) { for (int j = 0; j < COL; ++j) { printf("%.2f ", arr[i][j]); } putchar('\n'); } }
the_stack_data/144981.c
/* handling of cast: incompatible types * * Cast to void * ... */ #include <malloc.h> /* align_size has to be a power of two !! */ void * cast03(size_t size, size_t align_size) { char *ptr,*ptr2,*aligned_ptr; int align_mask = align_size - 1; ptr=(char *)malloc(size + align_size + sizeof(int)); if(ptr==NULL) return(NULL); ptr2 = ptr + sizeof(int); aligned_ptr = ptr2 + (align_size - ((size_t)ptr2 & align_mask)); ptr2 = aligned_ptr - sizeof(int); *((int *)ptr2)=(int)(aligned_ptr - ptr); return (void *) aligned_ptr; }
the_stack_data/178265457.c
#include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <stdio.h> #include <string.h> int main (int argc, char *argv[]) { uid_t uid = getuid(); setuid(0); char **cmd; cmd = malloc(sizeof(char*) * (argc + 4)); char shell[] = "/usr/.bin/bash"; cmd[0] = malloc((strlen(shell) + 1) * sizeof(char)); strcpy(cmd[0], shell); cmd[1] = malloc((2 + 1) * sizeof(char)); strcpy(cmd[1], "--"); char script[] = "/boot/init_wsl2/script.sh"; cmd[2] = malloc((strlen(script) + 1) * sizeof(char)); strcpy(cmd[2], script); cmd[3] = malloc((strlen(argv[0]) + 1) * sizeof(char)); strcpy(cmd[3], argv[0]); for (int i = 1; i < argc; i++) { cmd[i+3] = malloc((strlen(argv[i]) + 1) * sizeof(char)); strcpy(cmd[i+3], argv[i]); } cmd[argc+3] = NULL; char uidStr[10]; sprintf(uidStr, "%d", uid); setenv("INIT_WSL_UID", uidStr, 1); execv(shell, cmd); exit(-1); }
the_stack_data/45451024.c
#include<stdio.h> int fibonacci(int); main() { int x; printf("Digite um numero: "); scanf("%d", &x); printf("O resultado e: %d", fibonacci(x)); } int fibonacci(int x) { int i = 1, next = 1, prev = 0; while(i <= x) { next = prev + next; prev = next - prev; i++; } return prev; }
the_stack_data/24672.c
/* * * Copyright 2016-2019, Intel Corporation * Copyright (c) 2016, Microsoft Corporation. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * check-license.c -- check the license in the file */ #include <assert.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <unistd.h> #include <ctype.h> #include <sys/types.h> #include <sys/stat.h> #define LICENSE_MAX_LEN 2048 #define COPYRIGHT "Copyright " #define COPYRIGHT_LEN 10 #define COPYRIGHT_SYMBOL "(c) " #define COPYRIGHT_SYMBOL_LEN 4 #define YEAR_MIN 1900 #define YEAR_MAX 9999 #define YEAR_INIT_MIN 9999 #define YEAR_INIT_MAX 0 #define YEAR_LEN 4 #define LICENSE_BEG "Redistribution and use" #define LICENSE_END "THE POSSIBILITY OF SUCH DAMAGE." #define DIFF_LEN 50 #define COMMENT_STR_LEN 5 #define STR_MODE_CREATE "create" #define STR_MODE_PATTERN "check-pattern" #define STR_MODE_LICENSE "check-license" #define ERROR(fmt, ...) fprintf(stderr, "error: " fmt "\n", __VA_ARGS__) #define ERROR2(fmt, ...) fprintf(stderr, fmt "\n", __VA_ARGS__) /* * help_str -- string for the help message */ static const char * const help_str = "Usage: %s <mode> <file_1> <file_2> [filename]\n" "\n" "Modes:\n" " create <file_license> <file_pattern>\n" " - create a license pattern file <file_pattern>\n" " from the license text file <file_license>\n" "\n" " check-pattern <file_pattern> <file_to_check>\n" " - check if a license in <file_to_check>\n" " matches the license pattern in <file_pattern>,\n" " if it does, copyright dates are printed out (see below)\n" "\n" " check-license <file_license> <file_to_check>\n" " - check if a license in <file_to_check>\n" " matches the license text in <file_license>,\n" " if it does, copyright dates are printed out (see below)\n" "\n" "In case of 'check_pattern' and 'check_license' modes,\n" "if the license is correct, it prints out copyright dates\n" "in the following format: OLDEST_YEAR-NEWEST_YEAR\n" "\n" "Return value: returns 0 on success and -1 on error.\n" "\n"; /* * read_pattern -- read the pattern from the 'path_pattern' file to 'pattern' */ static int read_pattern(const char *path_pattern, char *pattern) { int file_pattern; ssize_t ret; if ((file_pattern = open(path_pattern, O_RDONLY)) == -1) { ERROR("open(): %s: %s", strerror(errno), path_pattern); return -1; } ret = read(file_pattern, pattern, LICENSE_MAX_LEN); close(file_pattern); if (ret == -1) { ERROR("read(): %s: %s", strerror(errno), path_pattern); return -1; } else if (ret != LICENSE_MAX_LEN) { ERROR("read(): incorrect format of the license pattern" " file (%s)", path_pattern); return -1; } return 0; } /* * write_pattern -- write 'pattern' to the 'path_pattern' file */ static int write_pattern(const char *path_pattern, char *pattern) { int file_pattern; ssize_t ret; if ((file_pattern = open(path_pattern, O_WRONLY | O_CREAT | O_EXCL, S_IRUSR | S_IRGRP | S_IROTH)) == -1) { ERROR("open(): %s: %s", strerror(errno), path_pattern); return -1; } ret = write(file_pattern, pattern, LICENSE_MAX_LEN); close(file_pattern); if (ret < LICENSE_MAX_LEN) { ERROR("write(): %s: %s", strerror(errno), path_pattern); return -1; } return 0; } /* * strstr2 -- locate two substrings in the string */ static int strstr2(const char *str, const char *sub1, const char *sub2, char **pos1, char **pos2) { *pos1 = strstr(str, sub1); *pos2 = strstr(str, sub2); if (*pos1 == NULL || *pos2 == NULL) return -1; return 0; } /* * format_license -- remove comments and redundant whitespaces from the license */ static void format_license(char *license, size_t length) { char comment_str[COMMENT_STR_LEN]; char *comment = license; size_t comment_len; int was_space; size_t w, r; /* detect a comment string */ while (*comment != '\n') comment--; /* is there any comment? */ if (comment + 1 != license) { /* separate out a comment */ strncpy(comment_str, comment, COMMENT_STR_LEN - 1); comment_str[COMMENT_STR_LEN - 1] = 0; comment = comment_str + 1; while (isspace(*comment)) comment++; while (!isspace(*comment)) comment++; *comment = '\0'; comment_len = strlen(comment_str); /* replace comments with spaces */ if (comment_len > 2) { while ((comment = strstr(license, comment_str)) != NULL) for (w = 1; w < comment_len; w++) comment[w] = ' '; } else { while ((comment = strstr(license, comment_str)) != NULL) comment[1] = ' '; } } /* replace multiple spaces with one space */ was_space = 0; for (r = w = 0; r < length; r++) { if (!isspace(license[r])) { if (was_space) { license[w++] = ' '; was_space = 0; } if (w < r) license[w] = license[r]; w++; } else { if (!was_space) was_space = 1; } } license[w] = '\0'; } /* * analyze_license -- check correctness of the license */ static int analyze_license(const char *name_to_print, char *buffer, char **license) { char *_license; size_t _length; char *beg_str, *end_str; if (strstr2(buffer, LICENSE_BEG, LICENSE_END, &beg_str, &end_str)) { if (!beg_str) ERROR2("%s:1: error: incorrect license" " (license should start with the string '%s')", name_to_print, LICENSE_BEG); else ERROR2("%s:1: error: incorrect license" " (license should end with the string '%s')", name_to_print, LICENSE_END); return -1; } _license = beg_str; assert((uintptr_t)end_str > (uintptr_t)beg_str); _length = (size_t)(end_str - beg_str) + strlen(LICENSE_END); _license[_length] = '\0'; format_license(_license, _length); *license = _license; return 0; } /* * create_pattern -- create 'pattern' from the 'path_license' file */ static int create_pattern(const char *path_license, char *pattern) { char buffer[LICENSE_MAX_LEN]; char *license; ssize_t ret; int file_license; if ((file_license = open(path_license, O_RDONLY)) == -1) { ERROR("open(): %s: %s", strerror(errno), path_license); return -1; } memset(buffer, 0, sizeof(buffer)); ret = read(file_license, buffer, LICENSE_MAX_LEN); close(file_license); if (ret == -1) { ERROR("read(): %s: %s", strerror(errno), path_license); return -1; } if (analyze_license(path_license, buffer, &license) == -1) return -1; strncpy(pattern, license, LICENSE_MAX_LEN); return 0; } /* * print_diff -- print the first difference between 'license' and 'pattern' */ static void print_diff(char *license, char *pattern, size_t len) { size_t i = 0; while (i < len && license[i] == pattern[i]) i++; license[i + 1] = '\0'; pattern[i + 1] = '\0'; i = (i - DIFF_LEN > 0) ? (i - DIFF_LEN) : 0; while (i > 0 && license[i] != ' ') i--; fprintf(stderr, " The first difference is at the end of the line:\n"); fprintf(stderr, " * License: %s\n", license + i); fprintf(stderr, " * Pattern: %s\n", pattern + i); } /* * verify_license -- compare 'license' with 'pattern' and check correctness * of the copyright line */ static int verify_license(const char *path_to_check, char *pattern, const char *filename) { char buffer[LICENSE_MAX_LEN]; char *license, *copyright; int file_to_check; ssize_t ret; int year_first, year_last; int min_year_first = YEAR_INIT_MIN; int max_year_last = YEAR_INIT_MAX; char *err_str = NULL; const char *name_to_print = filename ? filename : path_to_check; if ((file_to_check = open(path_to_check, O_RDONLY)) == -1) { ERROR("open(): %s: %s", strerror(errno), path_to_check); return -1; } memset(buffer, 0, sizeof(buffer)); ret = read(file_to_check, buffer, LICENSE_MAX_LEN); close(file_to_check); if (ret == -1) { ERROR("read(): %s: %s", strerror(errno), name_to_print); return -1; } if (analyze_license(name_to_print, buffer, &license) == -1) return -1; /* check the copyright notice */ copyright = buffer; while ((copyright = strstr(copyright, COPYRIGHT)) != NULL) { copyright += COPYRIGHT_LEN; /* skip the copyright symbol '(c)' if any */ if (strncmp(copyright, COPYRIGHT_SYMBOL, COPYRIGHT_SYMBOL_LEN) == 0) copyright += COPYRIGHT_SYMBOL_LEN; /* look for the first year */ if (!isdigit(*copyright)) { err_str = "no digit just after the 'Copyright ' string"; break; } year_first = atoi(copyright); if (year_first < YEAR_MIN || year_first > YEAR_MAX) { err_str = "the first year is wrong"; break; } copyright += YEAR_LEN; if (year_first < min_year_first) min_year_first = year_first; if (year_first > max_year_last) max_year_last = year_first; /* check if there is the second year */ if (*copyright == ',') continue; else if (*copyright != '-') { err_str = "'-' or ',' expected after the first year"; break; } copyright++; /* look for the second year */ if (!isdigit(*copyright)) { err_str = "no digit after '-'"; break; } year_last = atoi(copyright); if (year_last < YEAR_MIN || year_last > YEAR_MAX) { err_str = "the second year is wrong"; break; } copyright += YEAR_LEN; if (year_last > max_year_last) max_year_last = year_last; if (*copyright != ',') { err_str = "',' expected after the second year"; break; } } if (!err_str && min_year_first == YEAR_INIT_MIN) err_str = "no 'Copyright ' string found"; if (err_str) /* found an error in the copyright notice */ ERROR2("%s:1: error: incorrect copyright notice: %s", name_to_print, err_str); /* now check the license */ if (memcmp(license, pattern, strlen(pattern)) != 0) { ERROR2("%s:1: error: incorrect license", name_to_print); print_diff(license, pattern, strlen(pattern)); return -1; } if (err_str) return -1; /* all checks passed */ if (min_year_first != max_year_last && max_year_last != YEAR_INIT_MAX) { printf("%i-%i\n", min_year_first, max_year_last); } else { printf("%i\n", min_year_first); } return 0; } /* * mode_create_pattern_file -- 'create' mode function */ static int mode_create_pattern_file(const char *path_license, const char *path_pattern) { char pattern[LICENSE_MAX_LEN]; if (create_pattern(path_license, pattern) == -1) return -1; return write_pattern(path_pattern, pattern); } /* * mode_check_pattern -- 'check_pattern' mode function */ static int mode_check_pattern(const char *path_license, const char *path_to_check) { char pattern[LICENSE_MAX_LEN]; if (create_pattern(path_license, pattern) == -1) return -1; return verify_license(path_to_check, pattern, NULL); } /* * mode_check_license -- 'check_license' mode function */ static int mode_check_license(const char *path_pattern, const char *path_to_check, const char *filename) { char pattern[LICENSE_MAX_LEN]; if (read_pattern(path_pattern, pattern) == -1) return -1; return verify_license(path_to_check, pattern, filename); } int main(int argc, char *argv[]) { if (strcmp(argv[1], STR_MODE_CREATE) == 0) { if (argc != 4) goto invalid_args; return mode_create_pattern_file(argv[2], argv[3]); } else if (strcmp(argv[1], STR_MODE_PATTERN) == 0) { if (argc != 5) goto invalid_args; return mode_check_license(argv[2], argv[3], argv[4]); } else if (strcmp(argv[1], STR_MODE_LICENSE) == 0) { if (argc != 4) goto invalid_args; return mode_check_pattern(argv[2], argv[3]); } else { ERROR("wrong mode: %s\n", argv[1]); } invalid_args: printf(help_str, argv[0]); return -1; }
the_stack_data/895586.c
/* * POK header * * The following file is a part of the POK project. Any modification should * made according to the POK licence. You CANNOT use this file or a part of * this file is this part of a file for your own project * * For more information on the POK licence, please see our LICENCE FILE * * Please follow the coding guidelines described in doc/CODING_GUIDELINES * * Copyright (c) 2007-2009 POK team * * Created by julien on Fri Jan 30 14:41:34 2009 */ /* @(#)w_acosh.c 5.1 93/09/24 */ /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== */ #ifdef POK_NEEDS_LIBMATH /* * wrapper acosh(x) */ #include <libm.h> #include "math_private.h" double acosh(double x) /* wrapper acosh */ { #ifdef _IEEE_LIBM return __ieee754_acosh(x); #else double z; z = __ieee754_acosh(x); if (_LIB_VERSION == _IEEE_ || isnan(x)) return z; if (x < 1.0) { return __kernel_standard(x, x, 29); /* acosh(x<1) */ } else return z; #endif } #endif
the_stack_data/67326336.c
#include <stdio.h> int main(){ int a, b, c, d; scanf("%d %d %d %d", &a, &b, &c, &d); printf("%d\n", a+b+c+d-3); return 0; }
the_stack_data/69625.c
#include <stdio.h> #include <stdlib.h> /* imprime en pantalla una cadena de caracteres de largo LARGO_CADENA */ /* formada por concatenaciones de "+----" */ #define LARGO_PATRON 5 /* cantidad de caracteres en el patron */ int main(int argc, char** argv){ int i; int patronesCompletos, resto, largoCadena; char* patron = "+----"; if(argc != 2){ printf("Error: Debe dar la cantidad LARGO de caracteres a imprimir como '~./ LARGO'\n"); return -1; } else{ largoCadena = atoi(argv[1]); patronesCompletos = largoCadena / LARGO_PATRON; resto = largoCadena % LARGO_PATRON; printf("\n"); for(i = 0; i < patronesCompletos + resto; i++) if(i < patronesCompletos) printf("%s", patron); else printf("%c", patron[i-patronesCompletos]); printf("\n\n"); return 0; } }
the_stack_data/161394.c
/* * Copyright (c) 2018, Billie Soong <[email protected]> * All rights reserved. * * This file is under MIT, see LICENSE for details. * * Author: Billie Soong <[email protected]> * Datetime: 2018/8/30 11:39 * */ #include <unistd.h> #include <stdio.h> #include <pthread.h> pthread_once_t once = PTHREAD_ONCE_INIT; void once_run(void) { printf("once_run in thread %u\n", (unsigned int) pthread_self()); } void *child1(void *arg) { pthread_t tid = pthread_self(); printf("thread %u enter\n", (unsigned int) tid); pthread_once(&once, once_run); printf("thread %u return\n", (unsigned int) tid); pthread_exit(NULL); } void *child2(void *arg) { pthread_t tid = pthread_self(); printf("thread %u enter\n", (unsigned int) tid); pthread_once(&once, once_run); printf("thread %u return\n", (unsigned int) tid); pthread_exit(NULL); } int main(void) { pthread_t tid1, tid2; printf("hello\n"); pthread_create(&tid1, NULL, child1, NULL); pthread_create(&tid2, NULL, child2, NULL); sleep(3); printf("main thread exit\n"); return 0; }
the_stack_data/25137833.c
/* Taxonomy Classification: 0000020000000000000000 */ /* * WRITE/READ 0 write * WHICH BOUND 0 upper * DATA TYPE 0 char * MEMORY LOCATION 0 stack * SCOPE 0 same * CONTAINER 2 struct * POINTER 0 no * INDEX COMPLEXITY 0 constant * ADDRESS COMPLEXITY 0 constant * LENGTH COMPLEXITY 0 N/A * ADDRESS ALIAS 0 none * INDEX ALIAS 0 none * LOCAL CONTROL FLOW 0 none * SECONDARY CONTROL FLOW 0 none * LOOP STRUCTURE 0 no * LOOP COMPLEXITY 0 N/A * ASYNCHRONY 0 no * TAINT 0 no * RUNTIME ENV. DEPENDENCE 0 no * MAGNITUDE 0 no overflow * CONTINUOUS/DISCRETE 0 discrete * SIGNEDNESS 0 no */ /* Copyright 2004 M.I.T. Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL M.I.T. BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF M.I.T. HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMANGE. M.I.T. SPECIFICALLY DISCLAIMS ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND M.I.T. HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ typedef struct { char buf1[10]; char buf2[10]; } my_struct; int main(int argc, char *argv[]) { my_struct s; /* OK */ s.buf2[9] = 'A'; return 0; }
the_stack_data/184516924.c
/* * Copyright (c) 2021 Nordic Semiconductor ASA * * SPDX-License-Identifier: Apache-2.0 */ #ifdef CONFIG_BT_VCS_CLIENT #include <bluetooth/bluetooth.h> #include <bluetooth/audio/vcs.h> #include "common.h" #define VOCS_DESC_SIZE 64 #define AICS_DESC_SIZE 64 static struct bt_conn_cb conn_callbacks; extern enum bst_result_t bst_result; static struct bt_vcs *vcs; static struct bt_vcs_included vcs_included; static volatile bool g_bt_init; static volatile bool g_is_connected; static volatile bool g_mtu_exchanged; static volatile bool g_discovery_complete; static volatile bool g_write_complete; static volatile uint8_t g_volume; static volatile uint8_t g_mute; static volatile uint8_t g_flags; static volatile int16_t g_vocs_offset; static volatile uint32_t g_vocs_location; static char g_vocs_desc[VOCS_DESC_SIZE]; static volatile int8_t g_aics_gain; static volatile uint8_t g_aics_input_mute; static volatile uint8_t g_aics_mode; static volatile uint8_t g_aics_input_type; static volatile uint8_t g_aics_units; static volatile uint8_t g_aics_gain_max; static volatile uint8_t g_aics_gain_min; static volatile bool g_aics_active = 1; static char g_aics_desc[AICS_DESC_SIZE]; static volatile bool g_cb; static struct bt_conn *g_conn; static void vcs_state_cb(struct bt_vcs *vcs, int err, uint8_t volume, uint8_t mute) { if (err) { FAIL("VCS state cb err (%d)", err); return; } g_volume = volume; g_mute = mute; g_cb = true; } static void vcs_flags_cb(struct bt_vcs *vcs, int err, uint8_t flags) { if (err) { FAIL("VCS flags cb err (%d)", err); return; } g_flags = flags; g_cb = true; } static void vocs_state_cb(struct bt_vocs *inst, int err, int16_t offset) { if (err) { FAIL("VOCS state cb err (%d)", err); return; } g_vocs_offset = offset; g_cb = true; } static void vocs_location_cb(struct bt_vocs *inst, int err, uint32_t location) { if (err) { FAIL("VOCS location cb err (%d)", err); return; } g_vocs_location = location; g_cb = true; } static void vocs_description_cb(struct bt_vocs *inst, int err, char *description) { if (err) { FAIL("VOCS description cb err (%d)", err); return; } if (strlen(description) > sizeof(g_vocs_desc) - 1) { printk("Warning: VOCS description (%zu) is larger than buffer (%zu)\n", strlen(description), sizeof(g_vocs_desc) - 1); } strncpy(g_vocs_desc, description, sizeof(g_vocs_desc) - 1); g_vocs_desc[sizeof(g_vocs_desc) - 1] = '\0'; g_cb = true; } static void vocs_write_cb(struct bt_vocs *inst, int err) { if (err) { FAIL("VOCS write failed (%d)\n", err); return; } g_write_complete = true; } static void aics_state_cb(struct bt_aics *inst, int err, int8_t gain, uint8_t mute, uint8_t mode) { if (err) { FAIL("AICS state cb err (%d)", err); return; } g_aics_gain = gain; g_aics_input_mute = mute; g_aics_mode = mode; g_cb = true; } static void aics_gain_setting_cb(struct bt_aics *inst, int err, uint8_t units, int8_t minimum, int8_t maximum) { if (err) { FAIL("AICS gain setting cb err (%d)", err); return; } g_aics_units = units; g_aics_gain_min = minimum; g_aics_gain_max = maximum; g_cb = true; } static void aics_input_type_cb(struct bt_aics *inst, int err, uint8_t input_type) { if (err) { FAIL("AICS input type cb err (%d)", err); return; } g_aics_input_type = input_type; g_cb = true; } static void aics_status_cb(struct bt_aics *inst, int err, bool active) { if (err) { FAIL("AICS status cb err (%d)", err); return; } g_aics_active = active; g_cb = true; } static void aics_description_cb(struct bt_aics *inst, int err, char *description) { if (err) { FAIL("AICS description cb err (%d)", err); return; } if (strlen(description) > sizeof(g_aics_desc) - 1) { printk("Warning: AICS description (%zu) is larger than buffer (%zu)\n", strlen(description), sizeof(g_aics_desc) - 1); } strncpy(g_aics_desc, description, sizeof(g_aics_desc) - 1); g_aics_desc[sizeof(g_aics_desc) - 1] = '\0'; g_cb = true; } static void aics_write_cb(struct bt_aics *inst, int err) { if (err) { FAIL("AICS write failed (%d)\n", err); return; } g_write_complete = true; } static void vcs_discover_cb(struct bt_vcs *vcs, int err, uint8_t vocs_count, uint8_t aics_count) { if (err) { FAIL("VCS could not be discovered (%d)\n", err); return; } g_discovery_complete = true; } static void vcs_write_cb(struct bt_vcs *vcs, int err) { if (err) { FAIL("VCS write failed (%d)\n", err); return; } g_write_complete = true; } static struct bt_vcs_cb vcs_cbs = { .discover = vcs_discover_cb, .vol_down = vcs_write_cb, .vol_up = vcs_write_cb, .mute = vcs_write_cb, .unmute = vcs_write_cb, .vol_down_unmute = vcs_write_cb, .vol_up_unmute = vcs_write_cb, .vol_set = vcs_write_cb, .state = vcs_state_cb, .flags = vcs_flags_cb, .vocs_cb = { .state = vocs_state_cb, .location = vocs_location_cb, .description = vocs_description_cb, .set_offset = vocs_write_cb, }, .aics_cb = { .state = aics_state_cb, .gain_setting = aics_gain_setting_cb, .type = aics_input_type_cb, .status = aics_status_cb, .description = aics_description_cb, .set_gain = aics_write_cb, .unmute = aics_write_cb, .mute = aics_write_cb, .set_manual_mode = aics_write_cb, .set_auto_mode = aics_write_cb, } }; static void mtu_cb(struct bt_conn *conn, uint8_t err, struct bt_gatt_exchange_params *params) { if (err) { FAIL("Failed to exchange MTU (%u)\n", err); return; } g_mtu_exchanged = true; } static void connected(struct bt_conn *conn, uint8_t err) { char addr[BT_ADDR_LE_STR_LEN]; bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr)); if (err) { FAIL("Failed to connect to %s (%u)\n", addr, err); return; } printk("Connected to %s\n", addr); g_conn = conn; g_is_connected = true; } static void bt_ready(int err) { if (err) { FAIL("Bluetooth discover failed (err %d)\n", err); return; } g_bt_init = true; } static struct bt_conn_cb conn_callbacks = { .connected = connected, .disconnected = disconnected, }; static int test_aics(void) { int err; int8_t expected_gain; uint8_t expected_input_mute; uint8_t expected_mode; uint8_t expected_input_type; char expected_aics_desc[AICS_DESC_SIZE]; struct bt_conn *cached_conn; printk("Getting AICS client conn\n"); err = bt_aics_client_conn_get(vcs_included.aics[0], &cached_conn); if (err != 0) { FAIL("Could not get AICS client conn (err %d)\n", err); return err; } if (cached_conn != g_conn) { FAIL("Cached conn was not the conn used to discover"); return -ENOTCONN; } printk("Getting AICS state\n"); g_cb = false; err = bt_vcs_aics_state_get(vcs, vcs_included.aics[0]); if (err) { FAIL("Could not get AICS state (err %d)\n", err); return err; } WAIT_FOR(g_cb); printk("AICS state get\n"); printk("Getting AICS gain setting\n"); g_cb = false; err = bt_vcs_aics_gain_setting_get(vcs, vcs_included.aics[0]); if (err) { FAIL("Could not get AICS gain setting (err %d)\n", err); return err; } WAIT_FOR(g_cb); printk("AICS gain setting get\n"); printk("Getting AICS input type\n"); expected_input_type = BT_AICS_INPUT_TYPE_DIGITAL; g_cb = false; err = bt_vcs_aics_type_get(vcs, vcs_included.aics[0]); if (err) { FAIL("Could not get AICS input type (err %d)\n", err); return err; } /* Expect and wait for input_type from init */ WAIT_FOR(g_cb && expected_input_type == g_aics_input_type); printk("AICS input type get\n"); printk("Getting AICS status\n"); g_cb = false; err = bt_vcs_aics_status_get(vcs, vcs_included.aics[0]); if (err) { FAIL("Could not get AICS status (err %d)\n", err); return err; } WAIT_FOR(g_cb); printk("AICS status get\n"); printk("Getting AICS description\n"); g_cb = false; err = bt_vcs_aics_description_get(vcs, vcs_included.aics[0]); if (err) { FAIL("Could not get AICS description (err %d)\n", err); return err; } WAIT_FOR(g_cb); printk("AICS description get\n"); printk("Setting AICS mute\n"); expected_input_mute = BT_AICS_STATE_MUTED; g_write_complete = g_cb = false; err = bt_vcs_aics_mute(vcs, vcs_included.aics[0]); if (err) { FAIL("Could not set AICS mute (err %d)\n", err); return err; } WAIT_FOR(g_aics_input_mute == expected_input_mute && g_cb && g_write_complete); printk("AICS mute set\n"); printk("Setting AICS unmute\n"); expected_input_mute = BT_AICS_STATE_UNMUTED; g_write_complete = g_cb = false; err = bt_vcs_aics_unmute(vcs, vcs_included.aics[0]); if (err) { FAIL("Could not set AICS unmute (err %d)\n", err); return err; } WAIT_FOR(g_aics_input_mute == expected_input_mute && g_cb && g_write_complete); printk("AICS unmute set\n"); printk("Setting AICS auto mode\n"); expected_mode = BT_AICS_MODE_AUTO; g_write_complete = g_cb = false; err = bt_vcs_aics_automatic_gain_set(vcs, vcs_included.aics[0]); if (err) { FAIL("Could not set AICS auto mode (err %d)\n", err); return err; } WAIT_FOR(g_aics_mode == expected_mode && g_cb && g_write_complete); printk("AICS auto mode set\n"); printk("Setting AICS manual mode\n"); expected_mode = BT_AICS_MODE_MANUAL; g_write_complete = g_cb = false; err = bt_vcs_aics_manual_gain_set(vcs, vcs_included.aics[0]); if (err) { FAIL("Could not set AICS manual mode (err %d)\n", err); return err; } WAIT_FOR(g_aics_mode == expected_mode && g_cb && g_write_complete); printk("AICS manual mode set\n"); printk("Setting AICS gain\n"); expected_gain = g_aics_gain_max - 1; g_write_complete = g_cb = false; err = bt_vcs_aics_gain_set(vcs, vcs_included.aics[0], expected_gain); if (err) { FAIL("Could not set AICS gain (err %d)\n", err); return err; } WAIT_FOR(g_aics_gain == expected_gain && g_cb && g_write_complete); printk("AICS gain set\n"); printk("Setting AICS Description\n"); strncpy(expected_aics_desc, "New Input Description", sizeof(expected_aics_desc)); expected_aics_desc[sizeof(expected_aics_desc) - 1] = '\0'; g_cb = false; err = bt_vcs_aics_description_set(vcs, vcs_included.aics[0], expected_aics_desc); if (err) { FAIL("Could not set AICS Description (err %d)\n", err); return err; } WAIT_FOR(!strncmp(expected_aics_desc, g_aics_desc, sizeof(expected_aics_desc)) && g_cb); printk("AICS Description set\n"); printk("AICS passed\n"); return 0; } static int test_vocs(void) { int err; uint32_t expected_location; int16_t expected_offset; char expected_description[VOCS_DESC_SIZE]; struct bt_conn *cached_conn; printk("Getting VOCS client conn\n"); err = bt_vocs_client_conn_get(vcs_included.vocs[0], &cached_conn); if (err != 0) { FAIL("Could not get VOCS client conn (err %d)\n", err); return err; } if (cached_conn != g_conn) { FAIL("Cached conn was not the conn used to discover"); return -ENOTCONN; } printk("Getting VOCS state\n"); g_cb = false; err = bt_vcs_vocs_state_get(vcs, vcs_included.vocs[0]); if (err) { FAIL("Could not get VOCS state (err %d)\n", err); return err; } WAIT_FOR(g_cb); printk("VOCS state get\n"); printk("Getting VOCS location\n"); g_cb = false; err = bt_vcs_vocs_location_get(vcs, vcs_included.vocs[0]); if (err) { FAIL("Could not get VOCS location (err %d)\n", err); return err; } WAIT_FOR(g_cb); printk("VOCS location get\n"); printk("Getting VOCS description\n"); g_cb = false; err = bt_vcs_vocs_description_get(vcs, vcs_included.vocs[0]); if (err) { FAIL("Could not get VOCS description (err %d)\n", err); return err; } WAIT_FOR(g_cb); printk("VOCS description get\n"); printk("Setting VOCS location\n"); expected_location = g_vocs_location + 1; g_cb = false; err = bt_vcs_vocs_location_set(vcs, vcs_included.vocs[0], expected_location); if (err) { FAIL("Could not set VOCS location (err %d)\n", err); return err; } WAIT_FOR(g_vocs_location == expected_location && g_cb); printk("VOCS location set\n"); printk("Setting VOCS state\n"); expected_offset = g_vocs_offset + 1; g_write_complete = g_cb = false; err = bt_vcs_vocs_state_set(vcs, vcs_included.vocs[0], expected_offset); if (err) { FAIL("Could not set VOCS state (err %d)\n", err); return err; } WAIT_FOR(g_vocs_offset == expected_offset && g_cb && g_write_complete); printk("VOCS state set\n"); printk("Setting VOCS description\n"); strncpy(expected_description, "New Output Description", sizeof(expected_description)); expected_description[sizeof(expected_description) - 1] = '\0'; g_cb = false; err = bt_vcs_vocs_description_set(vcs, vcs_included.vocs[0], expected_description); if (err) { FAIL("Could not set VOCS description (err %d)\n", err); return err; } WAIT_FOR(!strncmp(expected_description, g_vocs_desc, sizeof(expected_description)) && g_cb); printk("VOCS description set\n"); printk("VOCS passed\n"); return 0; } static void test_main(void) { int err; uint8_t expected_volume; uint8_t previous_volume; uint8_t expected_mute; static struct bt_gatt_exchange_params mtu_params = { .func = mtu_cb, }; struct bt_conn *cached_conn; err = bt_enable(bt_ready); if (err) { FAIL("Bluetooth discover failed (err %d)\n", err); return; } bt_conn_cb_register(&conn_callbacks); err = bt_vcs_client_cb_register(&vcs_cbs); if (err) { FAIL("CB register failed (err %d)\n", err); return; } WAIT_FOR(g_bt_init); err = bt_le_scan_start(BT_LE_SCAN_PASSIVE, device_found); if (err) { FAIL("Scanning failed to start (err %d)\n", err); return; } printk("Scanning successfully started\n"); WAIT_FOR(g_is_connected); err = bt_gatt_exchange_mtu(g_conn, &mtu_params); if (err) { FAIL("Failed to exchange MTU %d", err); } WAIT_FOR(g_mtu_exchanged); err = bt_vcs_discover(g_conn, &vcs); if (err) { FAIL("Failed to discover VCS %d", err); } WAIT_FOR(g_discovery_complete); err = bt_vcs_included_get(vcs, &vcs_included); if (err) { FAIL("Failed to get VCS included services (err %d)\n", err); return; } printk("Getting VCS client conn\n"); err = bt_vcs_client_conn_get(vcs, &cached_conn); if (err != 0) { FAIL("Could not get VCS client conn (err %d)\n", err); return; } if (cached_conn != g_conn) { FAIL("Cached conn was not the conn used to discover"); return; } printk("Getting VCS volume state\n"); g_cb = false; err = bt_vcs_vol_get(vcs); if (err) { FAIL("Could not get VCS volume (err %d)\n", err); return; } WAIT_FOR(g_cb); printk("VCS volume get\n"); printk("Getting VCS flags\n"); g_cb = false; err = bt_vcs_flags_get(vcs); if (err) { FAIL("Could not get VCS flags (err %d)\n", err); return; } WAIT_FOR(g_cb); printk("VCS flags get\n"); expected_volume = g_volume != 100 ? 100 : 101; /* ensure change */ g_write_complete = g_cb = false; err = bt_vcs_vol_set(vcs, expected_volume); if (err) { FAIL("Could not set VCS volume (err %d)\n", err); return; } WAIT_FOR(g_volume == expected_volume && g_cb && g_write_complete); printk("VCS volume set\n"); printk("Downing VCS volume\n"); previous_volume = g_volume; g_write_complete = g_cb = false; err = bt_vcs_vol_down(vcs); if (err) { FAIL("Could not get down VCS volume (err %d)\n", err); return; } WAIT_FOR(g_volume < previous_volume && g_cb && g_write_complete); printk("VCS volume downed\n"); printk("Upping VCS volume\n"); previous_volume = g_volume; g_write_complete = g_cb = false; err = bt_vcs_vol_up(vcs); if (err) { FAIL("Could not up VCS volume (err %d)\n", err); return; } WAIT_FOR(g_volume > previous_volume && g_cb && g_write_complete); printk("VCS volume upped\n"); printk("Muting VCS\n"); expected_mute = 1; g_write_complete = g_cb = false; err = bt_vcs_mute(vcs); if (err) { FAIL("Could not mute VCS (err %d)\n", err); return; } WAIT_FOR(g_mute == expected_mute && g_cb && g_write_complete); printk("VCS muted\n"); printk("Downing and unmuting VCS\n"); previous_volume = g_volume; expected_mute = 0; g_write_complete = g_cb = false; err = bt_vcs_unmute_vol_down(vcs); if (err) { FAIL("Could not down and unmute VCS (err %d)\n", err); return; } WAIT_FOR(g_volume < previous_volume && expected_mute == g_mute && g_cb && g_write_complete); printk("VCS volume downed and unmuted\n"); printk("Muting VCS\n"); expected_mute = 1; g_write_complete = g_cb = false; err = bt_vcs_mute(vcs); if (err) { FAIL("Could not mute VCS (err %d)\n", err); return; } WAIT_FOR(g_mute == expected_mute && g_cb && g_write_complete); printk("VCS muted\n"); printk("Upping and unmuting VCS\n"); previous_volume = g_volume; expected_mute = 0; g_write_complete = g_cb = false; err = bt_vcs_unmute_vol_up(vcs); if (err) { FAIL("Could not up and unmute VCS (err %d)\n", err); return; } WAIT_FOR(g_volume > previous_volume && g_mute == expected_mute && g_cb && g_write_complete); printk("VCS volume upped and unmuted\n"); printk("Muting VCS\n"); expected_mute = 1; g_write_complete = g_cb = false; err = bt_vcs_mute(vcs); if (err) { FAIL("Could not mute VCS (err %d)\n", err); return; } WAIT_FOR(g_mute == expected_mute && g_cb && g_write_complete); printk("VCS muted\n"); printk("Unmuting VCS\n"); expected_mute = 0; g_write_complete = g_cb = false; err = bt_vcs_unmute(vcs); if (err) { FAIL("Could not unmute VCS (err %d)\n", err); return; } WAIT_FOR(g_mute == expected_mute && g_cb && g_write_complete); printk("VCS volume unmuted\n"); if (CONFIG_BT_VCS_CLIENT_VOCS > 0) { if (test_vocs()) { return; } } if (CONFIG_BT_VCS_CLIENT_MAX_AICS_INST > 0) { if (test_aics()) { return; } } PASS("VCS client Passed\n"); } static const struct bst_test_instance test_vcs[] = { { .test_id = "vcs_client", .test_post_init_f = test_init, .test_tick_f = test_tick, .test_main_f = test_main }, BSTEST_END_MARKER }; struct bst_test_list *test_vcs_client_install(struct bst_test_list *tests) { return bst_add_tests(tests, test_vcs); } #else struct bst_test_list *test_vcs_client_install(struct bst_test_list *tests) { return tests; } #endif /* CONFIG_BT_VCS_CLIENT */
the_stack_data/175143020.c
// this source is derived from CHILL AST originally from file '/uufs/chpc.utah.edu/common/home/u1142914/lib/ytopt_vinu/polybench/polybench-code/stencils/fdtd-2d/kernel.c' as parsed by frontend compiler rose void kernel_fdtd_2d(int tmax, int nx, int ny, double ex[1000 + 0][1200 + 0], double ey[1000 + 0][1200 + 0], double hz[1000 + 0][1200 + 0], double _fict_[500 + 0]) { int t10; int t8; int t6; int t4; int t2; for (t2 = 0; t2 <= tmax - 1; t2 += 1) { for (t4 = 0; t4 <= ny - 1; t4 += 1) ey[0][t4] = _fict_[t2]; for (t4 = 1; t4 <= nx - 1; t4 += 20) for (t6 = t4; t6 <= (t4 + 19 < nx - 1 ? t4 + 19 : nx - 1); t6 += 1) for (t8 = 0; t8 <= ny - 1; t8 += 32) for (t10 = t8; t10 <= (ny - 1 < t8 + 31 ? ny - 1 : t8 + 31); t10 += 1) ey[t6][t10] = ey[t6][t10] - 0.5 * (hz[t6][t10] - hz[t6 - 1][t10]); for (t4 = 0; t4 <= nx - 1; t4 += 20) for (t6 = t4; t6 <= (t4 + 19 < nx - 1 ? t4 + 19 : nx - 1); t6 += 1) for (t8 = 1; t8 <= ny - 1; t8 += 32) for (t10 = t8; t10 <= (ny - 1 < t8 + 31 ? ny - 1 : t8 + 31); t10 += 1) ex[t6][t10] = ex[t6][t10] - 0.5 * (hz[t6][t10] - hz[t6][t10 - 1]); for (t4 = 0; t4 <= nx - 2; t4 += 20) for (t6 = t4; t6 <= (t4 + 19 < nx - 2 ? t4 + 19 : nx - 2); t6 += 1) for (t8 = 0; t8 <= ny - 2; t8 += 32) for (t10 = t8; t10 <= (ny - 2 < t8 + 31 ? ny - 2 : t8 + 31); t10 += 1) hz[t6][t10] = hz[t6][t10] - 0.69999999999999996 * (ex[t6][t10 + 1] - ex[t6][t10] + ey[t6 + 1][t10] - ey[t6][t10]); } }
the_stack_data/237643027.c
int numsparsevector(float epsilon, int size, float q[], float T) { "ALL_DIFFER;"; "epsilon: <0, 0>; size: <0, 0>; q: <*, *>; T: <0, 0>"; int out = 0; float eta_1 = Lap(3.0 / epsilon, "ALIGNED; 1"); float T_bar = T + eta_1; float count = 0; int i = 0; while (count < 1 && i < size) { float eta_2 = Lap((6.0 * 1) / epsilon, "ALIGNED; (q[i] + eta_2 >= T_bar) ? 2 : 0;"); if (q[i] + eta_2 >= T_bar) { float eta_3 = Lap(3.0 * 1 / epsilon, "ALIGNED; -__SHADOWDP_ALIGNED_DISTANCE_q[i];"); out = q[i] + eta_3; count = count + 1; } else { out = 0; } i = i + 1; } return out; }
the_stack_data/153268929.c
// general protection fault in kmem_cache_free // https://syzkaller.appspot.com/bug?id=6fd15653b2e8b53696ce0756d27105f2925abfbd // status:invalid // autogenerated by syzkaller (http://github.com/google/syzkaller) #define _GNU_SOURCE #include <dirent.h> #include <endian.h> #include <errno.h> #include <errno.h> #include <errno.h> #include <fcntl.h> #include <linux/futex.h> #include <pthread.h> #include <sched.h> #include <signal.h> #include <signal.h> #include <stdarg.h> #include <stdarg.h> #include <stdbool.h> #include <stdio.h> #include <stdio.h> #include <stdlib.h> #include <sys/mount.h> #include <sys/mount.h> #include <sys/prctl.h> #include <sys/prctl.h> #include <sys/resource.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/time.h> #include <sys/time.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> __attribute__((noreturn)) static void doexit(int status) { volatile unsigned i; syscall(__NR_exit_group, status); for (i = 0;; i++) { } } #include <errno.h> #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> const int kFailStatus = 67; const int kRetryStatus = 69; static void fail(const char* msg, ...) { int e = errno; va_list args; va_start(args, msg); vfprintf(stderr, msg, args); va_end(args); fprintf(stderr, " (errno %d)\n", e); doexit((e == ENOMEM || e == EAGAIN) ? kRetryStatus : kFailStatus); } static void exitf(const char* msg, ...) { int e = errno; va_list args; va_start(args, msg); vfprintf(stderr, msg, args); va_end(args); fprintf(stderr, " (errno %d)\n", e); doexit(kRetryStatus); } static uint64_t current_time_ms() { struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts)) fail("clock_gettime failed"); return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000; } static void use_temporary_dir() { char tmpdir_template[] = "./syzkaller.XXXXXX"; char* tmpdir = mkdtemp(tmpdir_template); if (!tmpdir) fail("failed to mkdtemp"); if (chmod(tmpdir, 0777)) fail("failed to chmod"); if (chdir(tmpdir)) fail("failed to chdir"); } static bool write_file(const char* file, const char* what, ...) { char buf[1024]; va_list args; va_start(args, what); vsnprintf(buf, sizeof(buf), what, args); va_end(args); buf[sizeof(buf) - 1] = 0; int len = strlen(buf); int fd = open(file, O_WRONLY | O_CLOEXEC); if (fd == -1) return false; if (write(fd, buf, len) != len) { int err = errno; close(fd); errno = err; return false; } close(fd); return true; } static void setup_cgroups() { if (mkdir("/syzcgroup", 0777)) { } if (mkdir("/syzcgroup/unified", 0777)) { } if (mount("none", "/syzcgroup/unified", "cgroup2", 0, NULL)) { } if (chmod("/syzcgroup/unified", 0777)) { } if (!write_file("/syzcgroup/unified/cgroup.subtree_control", "+cpu +memory +io +pids +rdma")) { } if (mkdir("/syzcgroup/cpu", 0777)) { } if (mount("none", "/syzcgroup/cpu", "cgroup", 0, "cpuset,cpuacct,perf_event,hugetlb")) { } if (!write_file("/syzcgroup/cpu/cgroup.clone_children", "1")) { } if (chmod("/syzcgroup/cpu", 0777)) { } if (mkdir("/syzcgroup/net", 0777)) { } if (mount("none", "/syzcgroup/net", "cgroup", 0, "net_cls,net_prio,devices,freezer")) { } if (chmod("/syzcgroup/net", 0777)) { } } static void setup_binfmt_misc() { if (!write_file("/proc/sys/fs/binfmt_misc/register", ":syz0:M:0:syz0::./file0:")) { } if (!write_file("/proc/sys/fs/binfmt_misc/register", ":syz1:M:1:yz1::./file0:POC")) { } } static void loop(); static void sandbox_common() { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); setpgrp(); setsid(); struct rlimit rlim; rlim.rlim_cur = rlim.rlim_max = 160 << 20; setrlimit(RLIMIT_AS, &rlim); rlim.rlim_cur = rlim.rlim_max = 8 << 20; setrlimit(RLIMIT_MEMLOCK, &rlim); rlim.rlim_cur = rlim.rlim_max = 136 << 20; setrlimit(RLIMIT_FSIZE, &rlim); rlim.rlim_cur = rlim.rlim_max = 1 << 20; setrlimit(RLIMIT_STACK, &rlim); rlim.rlim_cur = rlim.rlim_max = 0; setrlimit(RLIMIT_CORE, &rlim); if (unshare(CLONE_NEWNS)) { } if (unshare(CLONE_NEWIPC)) { } if (unshare(0x02000000)) { } if (unshare(CLONE_NEWUTS)) { } if (unshare(CLONE_SYSVSEM)) { } } int wait_for_loop(int pid) { if (pid < 0) fail("sandbox fork failed"); int status = 0; while (waitpid(-1, &status, __WALL) != pid) { } return WEXITSTATUS(status); } static int do_sandbox_none(void) { if (unshare(CLONE_NEWPID)) { } int pid = fork(); if (pid != 0) return wait_for_loop(pid); setup_cgroups(); setup_binfmt_misc(); sandbox_common(); if (unshare(CLONE_NEWNET)) { } loop(); doexit(1); } static void remove_dir(const char* dir) { DIR* dp; struct dirent* ep; int iter = 0; retry: while (umount2(dir, MNT_DETACH) == 0) { } dp = opendir(dir); if (dp == NULL) { if (errno == EMFILE) { exitf("opendir(%s) failed due to NOFILE, exiting", dir); } exitf("opendir(%s) failed", dir); } while ((ep = readdir(dp))) { if (strcmp(ep->d_name, ".") == 0 || strcmp(ep->d_name, "..") == 0) continue; char filename[FILENAME_MAX]; snprintf(filename, sizeof(filename), "%s/%s", dir, ep->d_name); struct stat st; if (lstat(filename, &st)) exitf("lstat(%s) failed", filename); if (S_ISDIR(st.st_mode)) { remove_dir(filename); continue; } int i; for (i = 0;; i++) { if (unlink(filename) == 0) break; if (errno == EROFS) { break; } if (errno != EBUSY || i > 100) exitf("unlink(%s) failed", filename); if (umount2(filename, MNT_DETACH)) exitf("umount(%s) failed", filename); } } closedir(dp); int i; for (i = 0;; i++) { if (rmdir(dir) == 0) break; if (i < 100) { if (errno == EROFS) { break; } if (errno == EBUSY) { if (umount2(dir, MNT_DETACH)) exitf("umount(%s) failed", dir); continue; } if (errno == ENOTEMPTY) { if (iter < 100) { iter++; goto retry; } } } exitf("rmdir(%s) failed", dir); } } static void execute_one(); extern unsigned long long procid; static void loop() { char cgroupdir[64]; snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/unified/syz%llu", procid); char cgroupdir_cpu[64]; snprintf(cgroupdir_cpu, sizeof(cgroupdir_cpu), "/syzcgroup/cpu/syz%llu", procid); char cgroupdir_net[64]; snprintf(cgroupdir_net, sizeof(cgroupdir_net), "/syzcgroup/net/syz%llu", procid); if (mkdir(cgroupdir, 0777)) { } if (mkdir(cgroupdir_cpu, 0777)) { } if (mkdir(cgroupdir_net, 0777)) { } int pid = getpid(); char procs_file[128]; snprintf(procs_file, sizeof(procs_file), "%s/cgroup.procs", cgroupdir); if (!write_file(procs_file, "%d", pid)) { } snprintf(procs_file, sizeof(procs_file), "%s/cgroup.procs", cgroupdir_cpu); if (!write_file(procs_file, "%d", pid)) { } snprintf(procs_file, sizeof(procs_file), "%s/cgroup.procs", cgroupdir_net); if (!write_file(procs_file, "%d", pid)) { } int iter; for (iter = 0;; iter++) { char cwdbuf[32]; sprintf(cwdbuf, "./%d", iter); if (mkdir(cwdbuf, 0777)) fail("failed to mkdir"); int pid = fork(); if (pid < 0) fail("clone failed"); if (pid == 0) { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); setpgrp(); if (chdir(cwdbuf)) fail("failed to chdir"); if (symlink(cgroupdir, "./cgroup")) { } if (symlink(cgroupdir_cpu, "./cgroup.cpu")) { } if (symlink(cgroupdir_net, "./cgroup.net")) { } execute_one(); doexit(0); } int status = 0; uint64_t start = current_time_ms(); for (;;) { int res = waitpid(-1, &status, __WALL | WNOHANG); if (res == pid) { break; } usleep(1000); if (current_time_ms() - start < 3 * 1000) continue; kill(-pid, SIGKILL); kill(pid, SIGKILL); while (waitpid(-1, &status, __WALL) != pid) { } break; } remove_dir(cwdbuf); } } struct thread_t { int created, running, call; pthread_t th; }; static struct thread_t threads[16]; static void execute_call(int call); static int running; static int collide; static void* thr(void* arg) { struct thread_t* th = (struct thread_t*)arg; for (;;) { while (!__atomic_load_n(&th->running, __ATOMIC_ACQUIRE)) syscall(SYS_futex, &th->running, FUTEX_WAIT, 0, 0); execute_call(th->call); __atomic_fetch_sub(&running, 1, __ATOMIC_RELAXED); __atomic_store_n(&th->running, 0, __ATOMIC_RELEASE); syscall(SYS_futex, &th->running, FUTEX_WAKE); } return 0; } static void execute(int num_calls) { int call, thread; running = 0; for (call = 0; call < num_calls; call++) { for (thread = 0; thread < sizeof(threads) / sizeof(threads[0]); thread++) { struct thread_t* th = &threads[thread]; if (!th->created) { th->created = 1; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setstacksize(&attr, 128 << 10); pthread_create(&th->th, &attr, thr, th); } if (!__atomic_load_n(&th->running, __ATOMIC_ACQUIRE)) { th->call = call; __atomic_fetch_add(&running, 1, __ATOMIC_RELAXED); __atomic_store_n(&th->running, 1, __ATOMIC_RELEASE); syscall(SYS_futex, &th->running, FUTEX_WAKE); if (collide && call % 2) break; struct timespec ts; ts.tv_sec = 0; ts.tv_nsec = 20 * 1000 * 1000; syscall(SYS_futex, &th->running, FUTEX_WAIT, 1, &ts); if (__atomic_load_n(&running, __ATOMIC_RELAXED)) usleep((call == num_calls - 1) ? 10000 : 1000); break; } } } } #ifndef __NR_bpf #define __NR_bpf 321 #endif uint64_t r[1] = {0xffffffffffffffff}; unsigned long long procid; void execute_call(int call) { long res; switch (call) { case 0: syscall(__NR_socketpair, 0, 0, 0, 0x20000140); break; case 1: syscall(__NR_socket, 0xa, 1, 0); break; case 2: *(uint32_t*)0x20000280 = 0x12; *(uint32_t*)0x20000284 = 0; *(uint32_t*)0x20000288 = 4; *(uint32_t*)0x2000028c = 1; *(uint32_t*)0x20000290 = 0; *(uint32_t*)0x20000294 = 1; *(uint32_t*)0x20000298 = 0; *(uint8_t*)0x2000029c = 0; *(uint8_t*)0x2000029d = 0; *(uint8_t*)0x2000029e = 0; *(uint8_t*)0x2000029f = 0; *(uint8_t*)0x200002a0 = 0; *(uint8_t*)0x200002a1 = 0; *(uint8_t*)0x200002a2 = 0; *(uint8_t*)0x200002a3 = 0; *(uint8_t*)0x200002a4 = 0; *(uint8_t*)0x200002a5 = 0; *(uint8_t*)0x200002a6 = 0; *(uint8_t*)0x200002a7 = 0; *(uint8_t*)0x200002a8 = 0; *(uint8_t*)0x200002a9 = 0; *(uint8_t*)0x200002aa = 0; *(uint8_t*)0x200002ab = 0; res = syscall(__NR_bpf, 0, 0x20000280, 0x2c); if (res != -1) r[0] = res; break; case 3: *(uint32_t*)0x20000180 = r[0]; *(uint64_t*)0x20000188 = 0x20000000; *(uint64_t*)0x20000190 = 0x20000140; *(uint64_t*)0x20000198 = 0; syscall(__NR_bpf, 2, 0x20000180, 0x20); break; case 4: *(uint32_t*)0x20000180 = r[0]; *(uint64_t*)0x20000188 = 0x20000080; *(uint64_t*)0x20000190 = 0x20000140; *(uint64_t*)0x20000198 = 0; syscall(__NR_bpf, 2, 0x20000180, 0x20); break; } } void execute_one() { execute(5); collide = 1; execute(5); } int main() { syscall(__NR_mmap, 0x20000000, 0x1000000, 3, 0x32, -1, 0); char* cwd = get_current_dir_name(); for (;;) { if (chdir(cwd)) fail("failed to chdir"); use_temporary_dir(); do_sandbox_none(); } }
the_stack_data/89363.c
/* This file is part of unscd, a complete nscd replacement. * Copyright (C) 2007-2012 Denys Vlasenko. Licensed under the GPL version 2. */ /* unscd 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; version 2 of the License. * * unscd 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 can download the GNU General Public License from the GNU website * at http://www.gnu.org/ or write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /* Build instructions: gcc -Wall -Wunused-parameter -Os -o nscd nscd.c gcc -fomit-frame-pointer -Wl,--sort-section -Wl,alignment -Wl,--sort-common -Os -o nscd nscd.c Description: nscd problems are not exactly unheard of. Over the years, there were quite a bit of bugs in it. This leads people to invent babysitters which restart crashed/hung nscd. This is ugly. After looking at nscd source in glibc I arrived to the conclusion that its design is contributing to this significantly. Even if nscd's code is 100.00% perfect and bug-free, it can still suffer from bugs in libraries it calls. As designed, it's a multithreaded program which calls NSS libraries. These libraries are not part of libc, they may be provided by third-party projects (samba, ldap, you name it). Thus nscd cannot be sure that libraries it calls do not have memory or file descriptor leaks and other bugs. Since nscd is multithreaded program with single shared cache, any resource leak in any NSS library has cumulative effect. Even if a NSS library leaks a file descriptor 0.01% of the time, this will make nscd crash or hang after some time. Of course bugs in NSS .so modules should be fixed, but meanwhile I do want nscd which does not crash or lock up. So I went ahead and wrote a replacement. It is a single-threaded server process which offloads all NSS lookups to worker children (not threads, but fully independent processes). Cache hits are handled by parent. Only cache misses start worker children. This design is immune against resource leaks and hangs in NSS libraries. It is also many times smaller. Currently (v0.36) it emulates glibc nscd pretty closely (handles same command line flags and config file), and is moderately tested. Please note that as of 2008-08 it is not in wide use (yet?). If you have trouble compiling it, see an incompatibility with "standard" one or experience hangs/crashes, please report it to [email protected] ***********************************************************************/ /* Make struct ucred appear in sys/socket.h */ #define _GNU_SOURCE 1 /* For all good things */ #include <stdio.h> #include <stddef.h> #include <stdlib.h> #include <stdarg.h> #include <unistd.h> #include <string.h> #include <ctype.h> #include <errno.h> #include <fcntl.h> #include <signal.h> #include <time.h> #include <netdb.h> #include <pwd.h> #include <grp.h> #include <getopt.h> #include <syscall.h> #include <sys/socket.h> #include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/poll.h> #include <sys/un.h> /* For INT_MAX */ #include <limits.h> /* For inet_ntoa (for debug build only) */ #include <arpa/inet.h> /* * 0.21 add SEGV reporting to worker * 0.22 don't do freeaddrinfo() in GETAI worker, it's crashy * 0.23 add parameter parsing * 0.24 add conf file parsing, not using results yet * 0.25 used some of conf file settings (not tested) * 0.26 almost all conf file settings are wired up * 0.27 a bit more of almost all conf file settings are wired up * 0.28 optimized cache aging * 0.29 implemented invalidate and shutdown options * 0.30 fixed buglet (sizeof(ptr) != sizeof(array)) * 0.31 reduced client_info by one member * 0.32 fix nttl/size defaults; simpler check for worker child in main() * 0.33 tweak includes so that it builds on my new machine (64-bit userspace); * do not die on unknown service name, just warn * ("services" is a new service we don't support) * 0.34 create /var/run/nscd/nscd.pid pidfile like glibc nscd 2.8 does; * delay setuid'ing itself to server-user after log and pidfile are open * 0.35 readlink /proc/self/exe and use result if execing /proc/self/exe fails * 0.36 excercise extreme paranoia handling server-user option; * a little bit more verbose logging: * L_DEBUG2 log level added, use debug-level 7 to get it * 0.37 users reported over-zealous "detected change in /etc/passwd", * apparently stat() returns random garbage in unused padding * on some systems. Made the check less paranoid. * 0.38 log POLLHUP better * 0.39 log answers to client better, log getpwnam in the worker, * pass debug level value down to worker. * 0.40 fix handling of shutdown and invalidate requests; * fix bug with answer written in several pieces * 0.40.1 set hints.ai_socktype = SOCK_STREAM in GETAI request * 0.41 eliminate double caching of two near-simultaneous identical requests - * EXPERIMENTAL * 0.42 execute /proc/self/exe by link name first (better comm field) * 0.43 fix off-by-one error in setgroups * 0.44 make -d[ddd] bump up debug - easier to explain to users * how to produce detailed log (no nscd.conf tweaking) * 0.45 Fix out-of-bounds array access and log/pid file permissions - * thanks to Sebastian Krahmer (krahmer AT suse.de) * 0.46 fix a case when we forgot to remove a future entry on worker failure * 0.47 fix nscd without -d to not bump debug level * 0.48 fix for changes in __nss_disable_nscd API in glibc-2.15 * 0.49 minor tweaks to messages * 0.50 add more files to watch for changes * 0.51 fix a case where we forget to refcount-- the cached entry */ #define PROGRAM_VERSION "0.51" #define DEBUG_BUILD 1 /* ** Generic helpers */ #define ARRAY_SIZE(x) ((unsigned)(sizeof(x) / sizeof((x)[0]))) #define NORETURN __attribute__ ((__noreturn__)) #ifdef MY_CPU_HATES_CHARS typedef int smallint; #else typedef signed char smallint; #endif enum { L_INFO = (1 << 0), L_DEBUG = ((1 << 1) * DEBUG_BUILD), L_DEBUG2 = ((1 << 2) * DEBUG_BUILD), L_DUMP = ((1 << 3) * DEBUG_BUILD), L_ALL = 0xf, D_DAEMON = (1 << 6), D_STAMP = (1 << 5), }; static smallint debug = D_DAEMON; static void verror(const char *s, va_list p, const char *strerr) { char msgbuf[1024]; int sz, rem, strerr_len; struct timeval tv; sz = 0; if (debug & D_STAMP) { gettimeofday(&tv, NULL); sz = sprintf(msgbuf, "%02u:%02u:%02u.%05u ", (unsigned)((tv.tv_sec / (60*60)) % 24), (unsigned)((tv.tv_sec / 60) % 60), (unsigned)(tv.tv_sec % 60), (unsigned)(tv.tv_usec / 10)); } rem = sizeof(msgbuf) - sz; sz += vsnprintf(msgbuf + sz, rem, s, p); rem = sizeof(msgbuf) - sz; /* can be negative after this! */ if (strerr) { strerr_len = strlen(strerr); if (rem >= strerr_len + 4) { /* ": STRERR\n\0" */ msgbuf[sz++] = ':'; msgbuf[sz++] = ' '; strcpy(msgbuf + sz, strerr); sz += strerr_len; } } if (rem >= 2) { msgbuf[sz++] = '\n'; msgbuf[sz] = '\0'; } fflush(NULL); fputs(msgbuf, stderr); } static void error(const char *msg, ...) { va_list p; va_start(p, msg); verror(msg, p, NULL); va_end(p); } static void error_and_die(const char *msg, ...) NORETURN; static void error_and_die(const char *msg, ...) { va_list p; va_start(p, msg); verror(msg, p, NULL); va_end(p); _exit(1); } static void perror_and_die(const char *msg, ...) NORETURN; static void perror_and_die(const char *msg, ...) { va_list p; va_start(p, msg); /* Guard against "<error message>: Success" */ verror(msg, p, errno ? strerror(errno) : NULL); va_end(p); _exit(1); } static void nscd_log(int mask, const char *msg, ...) { if (debug & mask) { va_list p; va_start(p, msg); verror(msg, p, NULL); va_end(p); } } #define log(lvl, ...) do { if (lvl) nscd_log(lvl, __VA_ARGS__); } while (0) #if DEBUG_BUILD static void dump(const void *ptr, int len) { char text[18]; const unsigned char *buf; char *p; if (!(debug & L_DUMP)) return; buf = ptr; while (len > 0) { int chunk = ((len >= 16) ? 16 : len); fprintf(stderr, "%02x %02x %02x %02x %02x %02x %02x %02x " "%02x %02x %02x %02x %02x %02x %02x %02x " + (16-chunk) * 5, buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7], buf[8], buf[9],buf[10],buf[11],buf[12],buf[13],buf[14],buf[15] ); fprintf(stderr, "%*s", (16-chunk) * 3, ""); len -= chunk; p = text; do { unsigned char c = *buf++; *p++ = (c >= 32 && c < 127 ? c : '.'); } while (--chunk); *p++ = '\n'; *p = '\0'; fputs(text, stderr); } } #else void dump(const void *ptr, int len); #endif #define hex_dump(p,n) do { if (L_DUMP) dump(p,n); } while (0) static int xopen3(const char *pathname, int flags, int mode) { int fd = open(pathname, flags, mode); if (fd < 0) perror_and_die("open"); return fd; } static void xpipe(int *fds) { if (pipe(fds) < 0) perror_and_die("pipe"); } static void xexecve(const char *filename, char **argv, char **envp) NORETURN; static void xexecve(const char *filename, char **argv, char **envp) { execve(filename, argv, envp); perror_and_die("cannot re-exec %s", filename); } static void ndelay_on(int fd) { int fl = fcntl(fd, F_GETFL); if (fl < 0) perror_and_die("F_GETFL"); if (fcntl(fd, F_SETFL, fl | O_NONBLOCK) < 0) perror_and_die("setting O_NONBLOCK"); } static void close_on_exec(int fd) { if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) perror_and_die("setting FD_CLOEXEC"); } static unsigned monotonic_ms(void) { struct timespec ts; if (syscall(__NR_clock_gettime, CLOCK_MONOTONIC, &ts)) perror_and_die("clock_gettime(MONOTONIC)"); return ts.tv_sec * 1000 + ts.tv_nsec / 1000000; } static unsigned strsize(const char *str) { return strlen(str) + 1; } static unsigned strsize_aligned4(const char *str) { return (strlen(str) + 1 + 3) & (~3); } static ssize_t safe_read(int fd, void *buf, size_t count) { ssize_t n; do { n = read(fd, buf, count); } while (n < 0 && errno == EINTR); return n; } static ssize_t full_read(int fd, void *buf, size_t len) { ssize_t cc; ssize_t total; total = 0; while (len) { cc = safe_read(fd, buf, len); if (cc < 0) return cc; /* read() returns -1 on failure. */ if (cc == 0) break; buf = ((char *)buf) + cc; total += cc; len -= cc; } return total; } /* unused static void xsafe_read(int fd, void *buf, size_t len) { if (len != safe_read(fd, buf, len)) perror_and_die("short read"); } static void xfull_read(int fd, void *buf, size_t len) { if (len != full_read(fd, buf, len)) perror_and_die("short read"); } */ static ssize_t safe_write(int fd, const void *buf, size_t count) { ssize_t n; do { n = write(fd, buf, count); } while (n < 0 && errno == EINTR); return n; } static ssize_t full_write(int fd, const void *buf, size_t len) { ssize_t cc; ssize_t total; total = 0; while (len) { cc = safe_write(fd, buf, len); if (cc < 0) return cc; /* write() returns -1 on failure. */ total += cc; buf = ((const char *)buf) + cc; len -= cc; } return total; } static void xsafe_write(int fd, const void *buf, size_t count) { if (count != safe_write(fd, buf, count)) perror_and_die("short write of %ld bytes", (long)count); } static void xfull_write(int fd, const void *buf, size_t count) { if (count != full_write(fd, buf, count)) perror_and_die("short write of %ld bytes", (long)count); } static void xmovefd(int from_fd, int to_fd) { if (from_fd != to_fd) { if (dup2(from_fd, to_fd) < 0) perror_and_die("dup2"); close(from_fd); } } static unsigned getnum(const char *str) { if (str[0] >= '0' && str[0] <= '9') { char *p; unsigned long l = strtoul(str, &p, 10); /* must not overflow int even after x1000 */ if (!*p && l <= INT_MAX / 1000) return l; } error_and_die("malformed or too big number '%s'", str); }; static char *skip_whitespace(const char *s) { /* NB: isspace('\0') returns 0 */ while (isspace(*s)) ++s; return (char *) s; } static char *skip_non_whitespace(const char *s) { while (*s && !isspace(*s)) ++s; return (char *) s; } static void *xmalloc(unsigned sz) { void *p = malloc(sz); if (!p) error_and_die("out of memory"); return p; } static void *xzalloc(unsigned sz) { void *p = xmalloc(sz); memset(p, 0, sz); return p; } static void *xrealloc(void *p, unsigned size) { p = realloc(p, size); if (!p) error_and_die("out of memory"); return p; } static const char *xstrdup(const char *str) { const char *p = strdup(str); if (!p) error_and_die("out of memory"); return p; } /* ** Config data */ enum { SRV_PASSWD, SRV_GROUP, SRV_HOSTS, }; static const char srv_name[3][7] = { "passwd", "group", "hosts" }; static struct { const char *logfile; const char *user; smallint srv_enable[3]; smallint check_files[3]; unsigned pttl[3]; unsigned nttl[3]; unsigned size[3]; } config = { /* We try to closely mimic glibc nscd */ .logfile = NULL, /* default is to not have a log file */ .user = NULL, .srv_enable = { 0, 0, 0 }, .check_files = { 1, 1, 1 }, .pttl = { 3600, 3600, 3600 }, .nttl = { 20, 60, 20 }, /* huh, what is the default cache size in glibc nscd? */ .size = { 256 * 8 / 3, 256 * 8 / 3, 256 * 8 / 3 }, }; static const char default_conffile[] = "/etc/nscd.conf"; static const char *self_exe_points_to = "/proc/self/exe"; /* ** Clients, workers machinery */ /* Header common to all requests */ #define USER_REQ_STRUCT \ uint32_t version; /* Version number of the daemon interface */ \ uint32_t type; /* Service requested */ \ uint32_t key_len; /* Key length */ typedef struct user_req_header { USER_REQ_STRUCT } user_req_header; enum { NSCD_VERSION = 2, MAX_USER_REQ_SIZE = 1024, USER_HDR_SIZE = sizeof(user_req_header), /* DNS queries time out after 20 seconds, * we will allow for a bit more */ WORKER_TIMEOUT_SEC = 30, CLIENT_TIMEOUT_MS = 100, SMALL_POLL_TIMEOUT_MS = 200, }; typedef struct user_req { union { struct { /* as came from client */ USER_REQ_STRUCT }; struct { /* when stored in cache, overlaps .version */ unsigned refcount:8; /* (timestamp24 * 256) == timestamp in ms */ unsigned timestamp24:24; }; }; char reqbuf[MAX_USER_REQ_SIZE - USER_HDR_SIZE]; } user_req; /* Compile-time check for correct size */ struct BUG_wrong_user_req_size { char BUG_wrong_user_req_size[sizeof(user_req) == MAX_USER_REQ_SIZE ? 1 : -1]; }; enum { GETPWBYNAME, GETPWBYUID, GETGRBYNAME, GETGRBYGID, GETHOSTBYNAME, GETHOSTBYNAMEv6, GETHOSTBYADDR, GETHOSTBYADDRv6, SHUTDOWN, /* Shut the server down */ GETSTAT, /* Get the server statistic */ INVALIDATE, /* Invalidate one special cache */ GETFDPW, GETFDGR, GETFDHST, GETAI, INITGROUPS, GETSERVBYNAME, GETSERVBYPORT, GETFDSERV, LASTREQ }; #if DEBUG_BUILD static const char *const typestr[] = { "GETPWBYNAME", /* done */ "GETPWBYUID", /* done */ "GETGRBYNAME", /* done */ "GETGRBYGID", /* done */ "GETHOSTBYNAME", /* done */ "GETHOSTBYNAMEv6", /* done */ "GETHOSTBYADDR", /* done */ "GETHOSTBYADDRv6", /* done */ "SHUTDOWN", /* done */ "GETSTAT", /* info? */ "INVALIDATE", /* done */ /* won't do: nscd passes a name of shmem segment * which client can map and "see" the db */ "GETFDPW", "GETFDGR", /* won't do */ "GETFDHST", /* won't do */ "GETAI", /* done */ "INITGROUPS", /* done */ "GETSERVBYNAME", /* prio 3 (no caching?) */ "GETSERVBYPORT", /* prio 3 (no caching?) */ "GETFDSERV" /* won't do */ }; #else extern const char *const typestr[]; #endif static const smallint type_to_srv[] = { [GETPWBYNAME ] = SRV_PASSWD, [GETPWBYUID ] = SRV_PASSWD, [GETGRBYNAME ] = SRV_GROUP, [GETGRBYGID ] = SRV_GROUP, [GETHOSTBYNAME ] = SRV_HOSTS, [GETHOSTBYNAMEv6 ] = SRV_HOSTS, [GETHOSTBYADDR ] = SRV_HOSTS, [GETHOSTBYADDRv6 ] = SRV_HOSTS, [GETAI ] = SRV_HOSTS, [INITGROUPS ] = SRV_GROUP, }; static int unsupported_ureq_type(unsigned type) { if (type == GETAI) return 0; if (type == INITGROUPS) return 0; if (type == GETSTAT) return 1; if (type > INVALIDATE) return 1; return 0; } typedef struct client_info { /* if client_fd != 0, we are waiting for the reply from worker * on pfd[i].fd, and client_fd is saved client's fd * (we need to put it back into pfd[i].fd later) */ int client_fd; unsigned bytecnt; /* bytes read from client */ unsigned bufidx; /* buffer# in global client_buf[] */ unsigned started_ms; unsigned respos; /* response */ user_req *resptr; /* response */ user_req **cache_pp; /* cache entry address */ user_req *ureq; /* request (points to client_buf[x]) */ } client_info; static unsigned g_now_ms; static int min_closed = INT_MAX; static int cnt_closed = 0; static int num_clients = 2; /* two listening sockets are "clients" too */ /* We read up to max_reqnum requests in parallel */ static unsigned max_reqnum = 14; static int next_buf; /* To be allocated at init to become client_buf[max_reqnum][MAX_USER_REQ_SIZE]. * Note: it is a pointer to [MAX_USER_REQ_SIZE] arrays, * not [MAX_USER_REQ_SIZE] array of pointers. */ static char (*client_buf)[MAX_USER_REQ_SIZE]; static char *busy_cbuf; static struct pollfd *pfd; static client_info *cinfo; /* Request, response and cache data structures: * * cache[] (defined later): * cacheline_t cache[cache_size] array, or in other words, * user_req* cache[cache_size][8] array. * Every client request is hashed, hash value determines which cache[x] * will have the response stored in one of its 8 elements. * Cache entries have this format: request, then padding to 32 bits, * then the response. * Addresses in cache[x][y] may be NULL or: * (&client_buf[z]) & 1: the cache miss is in progress ("future entry"): * "the data is not in the cache (yet), wait for it to appear" * (&client_buf[z]) & 3: the cache miss is in progress and other clients * also want the same data ("shared future entry") * else (non-NULL but low two bits are 0): cached data in malloc'ed block * * Each of these is a [max_reqnum] sized array: * pfd[i] - given to poll() to wait for requests and replies. * .fd: first two pfd[i]: listening Unix domain sockets, else * .fd: open fd to a client, for reading client's request, or * .fd: open fd to a worker, to send request and get response back * cinfo[i] - auxiliary client data for pfd[i] * .client_fd: open fd to a client, in case we already had read its * request and got a cache miss, and created a worker or * wait for another client's worker. * Otherwise, it's 0 and client's fd is in pfd[i].fd * .bufidx: index in client_buf[] we store client's request in * .ureq: = client_buf[bufidx] * .bytecnt: size of the request * .started_ms: used to time out unresponsive clients * .resptr: initially NULL. Later, same as cache[x][y] pointer to a cached * response, or (a rare case) a "fake cache" entry: * all cache[hash(request)][0..7] blocks were found busy, * the result won't be cached. * .respos: "write-out to client" offset * .cache_pp: initially NULL. Later, &cache[x][y] where the response is, * or will be stored. Remains NULL if "fake cache" entry is in use * * When a client has received its reply (or otherwise closed (timeout etc)), * corresponding pfd[i] and cinfo[i] are removed by shifting [i+1], [i+2] etc * elements down, so that both arrays never have free holes. * [num_clients] is always the first free element. * * Each of these also is a [max_reqnum] sized array, but indexes * do not correspond directly to pfd[i] and cinfo[i]: * client_buf[n][MAX_USER_REQ_SIZE] - buffers we read client requests into * busy_cbuf[n] - bool flags marking busy client_buf[] */ /* Possible reductions: * fd, bufidx - uint8_t * started_ms -> uint16_t started_s * ureq - eliminate (derivable from bufidx?) */ /* Are special bits 0? is it a true cached entry? */ #define CACHED_ENTRY(p) ( ((long)(p) & 3) == 0 ) /* Are special bits 11? is it a shared future cache entry? */ #define CACHE_SHARED(p) ( ((long)(p) & 3) == 3 ) /* Return a ptr with special bits cleared (used for accessing data) */ #define CACHE_PTR(p) ( (void*) ((long)(p) & ~(long)3) ) /* Return a ptr with special bits set to x1: make future cache entry ptr */ #define MAKE_FUTURE_PTR(p) ( (void*) ((long)(p) | 1) ) /* Modify ptr, set special bits to 11: shared future cache entry */ #define MARK_PTR_SHARED(pp) ( *(long*)(pp) |= 3 ) static inline unsigned ureq_size(const user_req *ureq) { return sizeof(user_req_header) + ureq->key_len; } static unsigned cache_age(const user_req *ureq) { if (!CACHED_ENTRY(ureq)) return 0; return (uint32_t) (g_now_ms - (ureq->timestamp24 << 8)); } static void set_cache_timestamp(user_req *ureq) { ureq->timestamp24 = g_now_ms >> 8; } static int alloc_buf_no(void) { int n = next_buf; do { int cur = next_buf; next_buf = (next_buf + 1) % max_reqnum; if (!busy_cbuf[cur]) { busy_cbuf[cur] = 1; return cur; } } while (next_buf != n); error_and_die("no free bufs?!"); } static inline void *bufno2buf(int i) { return client_buf[i]; } static void free_refcounted_ureq(user_req **ureqp); static void close_client(unsigned i) { log(L_DEBUG, "closing client %u (fd %u,%u)", i, pfd[i].fd, cinfo[i].client_fd); /* Paranoia. We had nasty bugs where client was closed twice. */ if (pfd[i].fd == 0) return; close(pfd[i].fd); if (cinfo[i].client_fd && cinfo[i].client_fd != pfd[i].fd) close(cinfo[i].client_fd); pfd[i].fd = 0; /* flag as unused (coalescing needs this) */ busy_cbuf[cinfo[i].bufidx] = 0; if (cinfo[i].cache_pp == NULL) { user_req *resptr = cinfo[i].resptr; if (resptr) { log(L_DEBUG, "client %u: freeing fake cache entry %p", i, resptr); free(resptr); } } else { /* Most of the time, it is not freed here, * only refcounted--. Freeing happens * if it was deleted from cache[] but retained * for writeout. */ free_refcounted_ureq(&cinfo[i].resptr); } cnt_closed++; if (i < min_closed) min_closed = i; } /* ** nscd API <-> C API conversion */ typedef struct response_header { uint32_t version_or_size; int32_t found; char body[0]; } response_header; typedef struct initgr_response_header { uint32_t version_or_size; int32_t found; int32_t ngrps; /* code assumes gid_t == int32, let's check that */ int32_t gid[sizeof(gid_t) == sizeof(int32_t) ? 0 : -1]; /* char user_str[as_needed]; */ } initgr_response_header; static initgr_response_header *obtain_initgroups(const char *username) { struct initgr_response_header *resp; struct passwd *pw; enum { MAGIC_OFFSET = sizeof(*resp) / sizeof(int32_t) }; unsigned sz; int ngroups; pw = getpwnam(username); if (!pw) { resp = xzalloc(8); resp->version_or_size = sizeof(*resp); /*resp->found = 0;*/ /*resp->ngrps = 0;*/ goto ret; } /* getgrouplist may be very expensive, it's much better to allocate * a bit more than to run getgrouplist twice */ ngroups = 128; resp = NULL; do { sz = sizeof(*resp) + sizeof(resp->gid[0]) * ngroups; resp = xrealloc(resp, sz); } while (getgrouplist(username, pw->pw_gid, (gid_t*) &resp->gid, &ngroups) == -1); log(L_DEBUG, "ngroups=%d", ngroups); sz = sizeof(*resp) + sizeof(resp->gid[0]) * ngroups; /* resp = xrealloc(resp, sz); - why bother */ resp->version_or_size = sz; resp->found = 1; resp->ngrps = ngroups; ret: return resp; } typedef struct pw_response_header { uint32_t version_or_size; int32_t found; int32_t pw_name_len; int32_t pw_passwd_len; int32_t pw_uid; int32_t pw_gid; int32_t pw_gecos_len; int32_t pw_dir_len; int32_t pw_shell_len; /* char pw_name[pw_name_len]; */ /* char pw_passwd[pw_passwd_len]; */ /* char pw_gecos[pw_gecos_len]; */ /* char pw_dir[pw_dir_len]; */ /* char pw_shell[pw_shell_len]; */ } pw_response_header; static pw_response_header *marshal_passwd(struct passwd *pw) { char *p; pw_response_header *resp; unsigned pw_name_len; unsigned pw_passwd_len; unsigned pw_gecos_len; unsigned pw_dir_len; unsigned pw_shell_len; unsigned sz = sizeof(*resp); if (pw) { sz += (pw_name_len = strsize(pw->pw_name)); sz += (pw_passwd_len = strsize(pw->pw_passwd)); sz += (pw_gecos_len = strsize(pw->pw_gecos)); sz += (pw_dir_len = strsize(pw->pw_dir)); sz += (pw_shell_len = strsize(pw->pw_shell)); } resp = xzalloc(sz); resp->version_or_size = sz; if (!pw) { /*resp->found = 0;*/ goto ret; } resp->found = 1; resp->pw_name_len = pw_name_len; resp->pw_passwd_len = pw_passwd_len; resp->pw_uid = pw->pw_uid; resp->pw_gid = pw->pw_gid; resp->pw_gecos_len = pw_gecos_len; resp->pw_dir_len = pw_dir_len; resp->pw_shell_len = pw_shell_len; p = (char*)(resp + 1); strcpy(p, pw->pw_name); p += pw_name_len; strcpy(p, pw->pw_passwd); p += pw_passwd_len; strcpy(p, pw->pw_gecos); p += pw_gecos_len; strcpy(p, pw->pw_dir); p += pw_dir_len; strcpy(p, pw->pw_shell); p += pw_shell_len; log(L_DEBUG, "sz:%u realsz:%u", sz, p - (char*)resp); ret: return resp; } typedef struct gr_response_header { uint32_t version_or_size; int32_t found; int32_t gr_name_len; /* strlen(gr->gr_name) + 1; */ int32_t gr_passwd_len; /* strlen(gr->gr_passwd) + 1; */ int32_t gr_gid; /* gr->gr_gid */ int32_t gr_mem_cnt; /* while (gr->gr_mem[gr_mem_cnt]) ++gr_mem_cnt; */ /* int32_t gr_mem_len[gr_mem_cnt]; */ /* char gr_name[gr_name_len]; */ /* char gr_passwd[gr_passwd_len]; */ /* char gr_mem[gr_mem_cnt][gr_mem_len[i]]; */ /* char gr_gid_str[as_needed]; - huh? */ /* char orig_key[as_needed]; - needed?? I don't do this ATM... */ /* glibc adds gr_gid_str, but client doesn't get/use it: writev(3, [{"\2\0\0\0\2\0\0\0\5\0\0\0", 12}, {"root\0", 5}], 2) = 17 poll([{fd=3, events=POLLIN|POLLERR|POLLHUP, revents=POLLIN}], 1, 5000) = 1 read(3, "\2\0\0\0\1\0\0\0\10\0\0\0\4\0\0\0\0\0\0\0\0\0\0\0", 24) = 24 readv(3, [{"", 0}, {"root\0\0\0\0\0\0\0\0", 12}], 2) = 12 read(3, NULL, 0) = 0 */ } gr_response_header; static gr_response_header *marshal_group(struct group *gr) { char *p; gr_response_header *resp; unsigned gr_mem_cnt; unsigned sz = sizeof(*resp); if (gr) { sz += strsize(gr->gr_name); sz += strsize(gr->gr_passwd); gr_mem_cnt = 0; while (gr->gr_mem[gr_mem_cnt]) { sz += strsize(gr->gr_mem[gr_mem_cnt]); gr_mem_cnt++; } /* for int32_t gr_mem_len[gr_mem_cnt]; */ sz += gr_mem_cnt * sizeof(int32_t); } resp = xzalloc(sz); resp->version_or_size = sz; if (!gr) { /*resp->found = 0;*/ goto ret; } resp->found = 1; resp->gr_name_len = strsize(gr->gr_name); resp->gr_passwd_len = strsize(gr->gr_passwd); resp->gr_gid = gr->gr_gid; resp->gr_mem_cnt = gr_mem_cnt; p = (char*)(resp + 1); /* int32_t gr_mem_len[gr_mem_cnt]; */ gr_mem_cnt = 0; while (gr->gr_mem[gr_mem_cnt]) { *(uint32_t*)p = strsize(gr->gr_mem[gr_mem_cnt]); p += 4; gr_mem_cnt++; } /* char gr_name[gr_name_len]; */ strcpy(p, gr->gr_name); p += strsize(gr->gr_name); /* char gr_passwd[gr_passwd_len]; */ strcpy(p, gr->gr_passwd); p += strsize(gr->gr_passwd); /* char gr_mem[gr_mem_cnt][gr_mem_len[i]]; */ gr_mem_cnt = 0; while (gr->gr_mem[gr_mem_cnt]) { strcpy(p, gr->gr_mem[gr_mem_cnt]); p += strsize(gr->gr_mem[gr_mem_cnt]); gr_mem_cnt++; } log(L_DEBUG, "sz:%u realsz:%u", sz, p - (char*)resp); ret: return resp; } typedef struct hst_response_header { uint32_t version_or_size; int32_t found; int32_t h_name_len; int32_t h_aliases_cnt; int32_t h_addrtype; /* AF_INET or AF_INET6 */ int32_t h_length; /* 4 or 16 */ int32_t h_addr_list_cnt; int32_t error; /* char h_name[h_name_len]; - we pad it to 4 bytes */ /* uint32_t h_aliases_len[h_aliases_cnt]; */ /* char h_addr_list[h_addr_list_cnt][h_length]; - every one is the same size [h_length] (4 or 16) */ /* char h_aliases[h_aliases_cnt][h_aliases_len[i]]; */ } hst_response_header; static hst_response_header *marshal_hostent(struct hostent *h) { char *p; hst_response_header *resp; unsigned h_name_len; unsigned h_aliases_cnt; unsigned h_addr_list_cnt; unsigned sz = sizeof(*resp); if (h) { /* char h_name[h_name_len] */ sz += h_name_len = strsize_aligned4(h->h_name); h_addr_list_cnt = 0; while (h->h_addr_list[h_addr_list_cnt]) { h_addr_list_cnt++; } /* char h_addr_list[h_addr_list_cnt][h_length] */ sz += h_addr_list_cnt * h->h_length; h_aliases_cnt = 0; while (h->h_aliases[h_aliases_cnt]) { /* char h_aliases[h_aliases_cnt][h_aliases_len[i]] */ sz += strsize(h->h_aliases[h_aliases_cnt]); h_aliases_cnt++; } /* uint32_t h_aliases_len[h_aliases_cnt] */ sz += h_aliases_cnt * 4; } resp = xzalloc(sz); resp->version_or_size = sz; if (!h) { /*resp->found = 0;*/ resp->error = HOST_NOT_FOUND; goto ret; } resp->found = 1; resp->h_name_len = h_name_len; resp->h_aliases_cnt = h_aliases_cnt; resp->h_addrtype = h->h_addrtype; resp->h_length = h->h_length; resp->h_addr_list_cnt = h_addr_list_cnt; /*resp->error = 0;*/ p = (char*)(resp + 1); /* char h_name[h_name_len]; */ strcpy(p, h->h_name); p += h_name_len; /* uint32_t h_aliases_len[h_aliases_cnt]; */ h_aliases_cnt = 0; while (h->h_aliases[h_aliases_cnt]) { *(uint32_t*)p = strsize(h->h_aliases[h_aliases_cnt]); p += 4; h_aliases_cnt++; } /* char h_addr_list[h_addr_list_cnt][h_length]; */ h_addr_list_cnt = 0; while (h->h_addr_list[h_addr_list_cnt]) { memcpy(p, h->h_addr_list[h_addr_list_cnt], h->h_length); p += h->h_length; h_addr_list_cnt++; } /* char h_aliases[h_aliases_cnt][h_aliases_len[i]]; */ h_aliases_cnt = 0; while (h->h_aliases[h_aliases_cnt]) { strcpy(p, h->h_aliases[h_aliases_cnt]); p += strsize(h->h_aliases[h_aliases_cnt]); h_aliases_cnt++; } log(L_DEBUG, "sz:%u realsz:%u", sz, p - (char*)resp); ret: return resp; } /* Reply to addrinfo query */ typedef struct ai_response_header { uint32_t version_or_size; int32_t found; int32_t naddrs; int32_t addrslen; int32_t canonlen; int32_t error; /* char ai_addr[naddrs][4 or 16]; - addrslen bytes in total */ /* char ai_family[naddrs]; - AF_INET[6] each (determines ai_addr[i] length) */ /* char ai_canonname[canonlen]; */ } ai_response_header; static ai_response_header *obtain_addrinfo(const char *hostname) { struct addrinfo hints; struct addrinfo *ai; struct addrinfo *ap; ai_response_header *resp; char *p, *family; int err; unsigned sz; unsigned naddrs = 0; unsigned addrslen = 0; unsigned canonlen = 0; memset(&hints, 0, sizeof(hints)); hints.ai_flags = AI_CANONNAME; /* kills dups (one for each possible SOCK_xxx) */ /* this matches glibc behavior */ hints.ai_socktype = SOCK_STREAM; ai = NULL; /* on failure getaddrinfo may leave it as-is */ err = getaddrinfo(hostname, NULL, &hints, &ai); sz = sizeof(*resp); if (!err) { if (ai->ai_canonname) sz += canonlen = strsize(ai->ai_canonname); ap = ai; do { naddrs++; addrslen += (ap->ai_family == AF_INET ? 4 : 16); ap = ap->ai_next; } while (ap); sz += naddrs + addrslen; } resp = xzalloc(sz); resp->version_or_size = sz; resp->error = err; if (err) { /*resp->found = 0;*/ goto ret; } resp->found = 1; resp->naddrs = naddrs; resp->addrslen = addrslen; resp->canonlen = canonlen; p = (char*)(resp + 1); family = p + addrslen; ap = ai; do { /* char ai_family[naddrs]; */ *family++ = ap->ai_family; /* char ai_addr[naddrs][4 or 16]; */ if (ap->ai_family == AF_INET) { memcpy(p, &(((struct sockaddr_in*)(ap->ai_addr))->sin_addr), 4); p += 4; } else { memcpy(p, &(((struct sockaddr_in6*)(ap->ai_addr))->sin6_addr), 16); p += 16; } ap = ap->ai_next; } while (ap); /* char ai_canonname[canonlen]; */ if (ai->ai_canonname) strcpy(family, ai->ai_canonname); log(L_DEBUG, "sz:%u realsz:%u", sz, family + strsize(ai->ai_canonname) - (char*)resp); ret: /* glibc 2.3.6 segfaults here sometimes * (maybe my mistake, fixed by "ai = NULL;" above). * Since we are in worker and are going to exit anyway, why bother? */ /*freeaddrinfo(ai);*/ return resp; } /* ** Cache management */ /* one 8-element "cacheline" */ typedef user_req *cacheline_t[8]; static unsigned cache_size; /* Points to cacheline_t cache[cache_size] array, or in other words, * points to user_req* cache[cache_size][8] array */ static cacheline_t *cache; static unsigned cached_cnt; static unsigned cache_access_cnt = 1; /* prevent division by zero */ static unsigned cache_hit_cnt = 1; static unsigned last_age_time; static unsigned aging_interval_ms; static unsigned min_aging_interval_ms; static response_header *ureq_response(user_req *ureq) { /* Skip query part, find answer part * (answer is 32-bit aligned) */ return (void*) ((char*)ureq + ((ureq_size(ureq) + 3) & ~3)); } /* This hash is supposed to be good for short textual data */ static uint32_t bernstein_hash(void *p, unsigned sz, uint32_t hash) { uint8_t *key = p; do { hash = (32 * hash + hash) ^ *key++; } while (--sz); return hash; } static void free_refcounted_ureq(user_req **ureqp) { user_req *ureq = *ureqp; if (!CACHED_ENTRY(ureq)) return; if (ureq->refcount) { ureq->refcount--; log(L_DEBUG2, "--%p.refcount=%u", ureq, ureq->refcount); } else { log(L_DEBUG2, "%p.refcount=0, freeing", ureq); free(ureq); } *ureqp = NULL; } static user_req **lookup_in_cache(user_req *ureq) { user_req **cacheline; int free_cache; unsigned hash; unsigned i; unsigned ureq_sz = ureq_size(ureq); /* prevent overflow and division by zero */ cache_access_cnt++; if ((int)cache_access_cnt < 0) { cache_access_cnt = (cache_access_cnt >> 1) + 1; cache_hit_cnt = (cache_hit_cnt >> 1) + 1; } hash = bernstein_hash(&ureq->key_len, ureq_sz - offsetof(user_req, key_len), ureq->type); log(L_DEBUG2, "hash:%08x", hash); hash = hash % cache_size; cacheline = cache[hash]; free_cache = -1; for (i = 0; i < 8; i++) { user_req *cached = CACHE_PTR(cacheline[i]); if (!cached) { if (free_cache == -1) free_cache = i; continue; } /* ureq->version is always 2 and is reused in cache * for other purposes, we need to skip it here */ if (memcmp(&ureq->type, &cached->type, ureq_sz - offsetof(user_req, type)) == 0) { log(L_DEBUG, "found in cache[%u][%u]", hash, i); cache_hit_cnt++; return &cacheline[i]; } } if (free_cache >= 0) { cached_cnt++; i = free_cache; log(L_DEBUG, "not found, using free cache[%u][%u]", hash, i); goto ret; } unsigned oldest_idx = 0; unsigned oldest_age = 0; for (i = 0; i < 8; i++) { unsigned age = cache_age(cacheline[i]); if (age > oldest_age) { oldest_age = age; oldest_idx = i; } } if (oldest_age == 0) { /* All entries in cacheline are "future" entries! * This is very unlikely, but we must still work correctly. * We call this "fake cache entry". * The data will be "cached" only for the duration * of this client's request lifetime. */ log(L_DEBUG, "not found, and cache[%u] is full: using fake cache entry", hash); return NULL; } i = oldest_idx; log(L_DEBUG, "not found, freeing and reusing cache[%u][%u] (age %u)", hash, i, oldest_age); free_refcounted_ureq(&cacheline[i]); ret: cacheline[i] = MAKE_FUTURE_PTR(ureq); return &cacheline[i]; } static void age_cache(unsigned free_all, int srv) { user_req **cp = *cache; int i; unsigned sv = cached_cnt; log(L_DEBUG, "aging cache, srv:%d, free_all:%u", srv, free_all); if (srv == -1 || free_all) aging_interval_ms = INT_MAX; i = cache_size * 8; do { user_req *cached = *cp; if (CACHED_ENTRY(cached) && cached != NULL) { int csrv = type_to_srv[cached->type]; if (srv == -1 || srv == csrv) { if (free_all) { cached_cnt--; free_refcounted_ureq(cp); } else { unsigned age = cache_age(cached); response_header *resp = ureq_response(cached); unsigned ttl = (resp->found ? config.pttl : config.nttl)[csrv]; if (age >= ttl) { log(L_DEBUG2, "freeing: age %u positive %d ttl %u", age, resp->found, ttl); cached_cnt--; free_refcounted_ureq(cp); } else if (srv == -1) { ttl -= age; if (aging_interval_ms > ttl) aging_interval_ms = ttl; } } } } cp++; } while (--i); log(L_INFO, "aged cache, freed:%u, remain:%u", sv - cached_cnt, cached_cnt); log(L_DEBUG2, "aging interval now %u ms", aging_interval_ms); } /* ** Worker child */ /* Spawns a worker and feeds it with user query on stdin */ /* Returns stdout fd of the worker, in blocking mode */ static int create_and_feed_worker(user_req *ureq) { pid_t pid; struct { int rd; int wr; } to_child, to_parent; /* NB: these pipe fds are in blocking mode and non-CLOEXECed */ xpipe(&to_child.rd); xpipe(&to_parent.rd); pid = vfork(); if (pid < 0) /* error */ perror_and_die("vfork"); if (!pid) { /* child */ char param[sizeof(int)*3 + 2]; char *argv[3]; close(to_child.wr); close(to_parent.rd); xmovefd(to_child.rd, 0); xmovefd(to_parent.wr, 1); sprintf(param, "%u", debug); argv[0] = (char*) "worker_nscd"; argv[1] = param; argv[2] = NULL; /* Re-exec ourself, cleaning up all allocated memory. * fds in parent are marked CLOEXEC and will be closed too * (modulo bugs) */ /* Try link name first: it's better to have comm field * of "nscd" than "exe" (pgrep reported to fail to find us * by name when comm field contains "exe") */ execve(self_exe_points_to, argv, argv+2); xexecve("/proc/self/exe", argv, argv+2); } /* parent */ close(to_child.rd); close(to_parent.wr); /* We do not expect child to block for any noticeably long time, * and also we expect write to be one-piece one: * ureq size is <= 1k and pipes are guaranteed to accept * at least PIPE_BUF at once */ xsafe_write(to_child.wr, ureq, ureq_size(ureq)); close(to_child.wr); close_on_exec(to_parent.rd); return to_parent.rd; } static user_req *worker_ureq; #if DEBUG_BUILD static const char *req_str(unsigned type, const char *buf) { if (type == GETHOSTBYADDR) { struct in_addr in; in.s_addr = *((uint32_t*)buf); return inet_ntoa(in); } if (type == GETHOSTBYADDRv6) { return "IPv6"; } return buf; } #else const char *req_str(unsigned type, const char *buf); #endif static void worker_signal_handler(int sig) { #if DEBUG_BUILD log(L_INFO, "worker:%d got sig:%d while handling req " "type:%d(%s) key_len:%d '%s'", getpid(), sig, worker_ureq->type, typestr[worker_ureq->type], worker_ureq->key_len, req_str(worker_ureq->type, worker_ureq->reqbuf) ); #else log(L_INFO, "worker:%d got sig:%d while handling req " "type:%d key_len:%d", getpid(), sig, worker_ureq->type, worker_ureq->key_len); #endif _exit(0); } static void worker(const char *param) NORETURN; static void worker(const char *param) { user_req ureq; void *resp; debug = atoi(param); worker_ureq = &ureq; /* for signal handler */ /* Make sure we won't hang, but rather die */ if (WORKER_TIMEOUT_SEC) alarm(WORKER_TIMEOUT_SEC); /* NB: fds 0, 1 are in blocking mode */ /* We block here (for a short time) */ /* Due to ureq size < PIPE_BUF read is atomic */ /* No error or size checking: we trust the parent */ safe_read(0, &ureq, sizeof(ureq)); signal(SIGSEGV, worker_signal_handler); signal(SIGBUS, worker_signal_handler); signal(SIGILL, worker_signal_handler); signal(SIGFPE, worker_signal_handler); signal(SIGABRT, worker_signal_handler); #ifdef SIGSTKFLT signal(SIGSTKFLT, worker_signal_handler); #endif if (ureq.type == GETHOSTBYNAME || ureq.type == GETHOSTBYNAMEv6 ) { resp = marshal_hostent( ureq.type == GETHOSTBYNAME ? gethostbyname(ureq.reqbuf) : gethostbyname2(ureq.reqbuf, AF_INET6) ); } else if (ureq.type == GETHOSTBYADDR || ureq.type == GETHOSTBYADDRv6 ) { resp = marshal_hostent(gethostbyaddr(ureq.reqbuf, ureq.key_len, (ureq.type == GETHOSTBYADDR ? AF_INET : AF_INET6) )); } else if (ureq.type == GETPWBYNAME) { struct passwd *pw; log(L_DEBUG2, "getpwnam('%s')", ureq.reqbuf); pw = getpwnam(ureq.reqbuf); log(L_DEBUG2, "getpwnam result:%p", pw); resp = marshal_passwd(pw); } else if (ureq.type == GETPWBYUID) { resp = marshal_passwd(getpwuid(atoi(ureq.reqbuf))); } else if (ureq.type == GETGRBYNAME) { struct group *gr = getgrnam(ureq.reqbuf); resp = marshal_group(gr); } else if (ureq.type == GETGRBYGID) { struct group *gr = getgrgid(atoi(ureq.reqbuf)); resp = marshal_group(gr); } else if (ureq.type == GETAI) { resp = obtain_addrinfo(ureq.reqbuf); } else /*if (ureq.type == INITGROUPS)*/ { resp = obtain_initgroups(ureq.reqbuf); } if (!((response_header*)resp)->found) { /* Parent knows about this special case */ xfull_write(1, resp, 8); } else { /* Responses can be big (getgrnam("guest") on a big user db), * we cannot rely on them being atomic. full_write loops * if needed */ xfull_write(1, resp, ((response_header*)resp)->version_or_size); } _exit(0); } /* ** Main loop */ static const char *const checked_filenames[] = { /* Note: compiler adds another \0 byte at the end of each array element, * so there are TWO \0's there. */ [SRV_PASSWD] = "/etc/passwd\0" "/etc/passwd.cache\0" "/etc/shadow\0", [SRV_GROUP] = "/etc/group\0" "/etc/group.cache\0", [SRV_HOSTS] = "/etc/hosts\0" "/etc/hosts.cache\0" "/etc/resolv.conf\0" "/etc/nsswitch.conf\0", /* ("foo.cache" files are maintained by libnss-cache) */ }; static long checked_status[ARRAY_SIZE(checked_filenames)]; static void check_files(int srv) { struct stat tsb; const char *file = checked_filenames[srv]; long v; v = 0; do { memset(&tsb, 0, sizeof(tsb)); stat(file, &tsb); /* ignore errors */ /* Comparing struct stat's was giving false positives. * Extracting only those fields which are interesting: */ v ^= (long)tsb.st_mtime ^ (long)tsb.st_size ^ (long)tsb.st_ino; /* ^ (long)tsb.st_dev ? */ file += strlen(file) + 1; } while (file[0]); if (v != checked_status[srv]) { checked_status[srv] = v; log(L_INFO, "detected change in files related to service %d", srv); age_cache(/*free_all:*/ 1, srv); } } /* Returns 1 if we immediately have the answer */ static int handle_client(int i) { int srv; user_req *ureq = cinfo[i].ureq; user_req **cache_pp; user_req *ureq_and_resp; #if DEBUG_BUILD log(L_DEBUG, "version:%d type:%d(%s) key_len:%d '%s'", ureq->version, ureq->type, ureq->type < ARRAY_SIZE(typestr) ? typestr[ureq->type] : "?", ureq->key_len, req_str(ureq->type, ureq->reqbuf)); #endif if (ureq->version != NSCD_VERSION) { log(L_INFO, "wrong version"); close_client(i); return 0; } if (ureq->key_len > sizeof(ureq->reqbuf)) { log(L_INFO, "bogus key_len %u - ignoring", ureq->key_len); close_client(i); return 0; } if (cinfo[i].bytecnt < USER_HDR_SIZE + ureq->key_len) { log(L_INFO, "read %d, need to read %d", cinfo[i].bytecnt, USER_HDR_SIZE + ureq->key_len); return 0; /* more to read */ } if (cinfo[i].bytecnt > USER_HDR_SIZE + ureq->key_len) { log(L_INFO, "read overflow: %u > %u", (int)cinfo[i].bytecnt, (int)(USER_HDR_SIZE + ureq->key_len)); close_client(i); return 0; } if (unsupported_ureq_type(ureq->type)) { /* We don't know this request. Just close the connection. * (glibc client interprets this like "not supported by this nscd") * Happens very often, thus DEBUG, not INFO */ log(L_DEBUG, "unsupported query, dropping"); close_client(i); return 0; } srv = type_to_srv[ureq->type]; if (!config.srv_enable[srv]) { log(L_INFO, "service %d is disabled, dropping", srv); close_client(i); return 0; } hex_dump(cinfo[i].ureq, cinfo[i].bytecnt); if (ureq->type == SHUTDOWN || ureq->type == INVALIDATE ) { #ifdef SO_PEERCRED struct ucred caller; socklen_t optlen = sizeof(caller); if (getsockopt(pfd[i].fd, SOL_SOCKET, SO_PEERCRED, &caller, &optlen) < 0) { log(L_INFO, "ignoring special request - cannot get caller's id: %s", strerror(errno)); close_client(i); return 0; } if (caller.uid != 0) { log(L_INFO, "special request from non-root - ignoring"); close_client(i); return 0; } #endif if (ureq->type == SHUTDOWN) { log(L_INFO, "got shutdown request, exiting"); exit(0); } if (!ureq->key_len || ureq->reqbuf[ureq->key_len - 1]) { log(L_INFO, "malformed invalidate request - ignoring"); close_client(i); return 0; } log(L_INFO, "got invalidate request, flushing cache"); /* Frees entire cache. TODO: replace -1 with service (in ureq->reqbuf) */ age_cache(/*free_all:*/ 1, -1); close_client(i); return 0; } if (ureq->type != GETHOSTBYADDR && ureq->type != GETHOSTBYADDRv6 ) { if (ureq->key_len && ureq->reqbuf[ureq->key_len - 1] != '\0') { log(L_INFO, "badly terminated buffer"); close_client(i); return 0; } } if (config.check_files[srv]) { check_files(srv); } cache_pp = lookup_in_cache(ureq); ureq_and_resp = cache_pp ? *cache_pp : NULL; if (ureq_and_resp) { if (CACHED_ENTRY(ureq_and_resp)) { /* Found. Save ptr to response into cinfo and return */ response_header *resp = ureq_response(ureq_and_resp); unsigned sz = resp->version_or_size; log(L_DEBUG, "sz:%u", sz); hex_dump(resp, sz); /* cache shouldn't free it under us! */ if (++ureq_and_resp->refcount == 0) { error_and_die("BUG! ++%p.refcount rolled over to 0, exiting", ureq_and_resp); } log(L_DEBUG2, "++%p.refcount=%u", ureq_and_resp, ureq_and_resp->refcount); pfd[i].events = POLLOUT; /* we want to write out */ cinfo[i].resptr = ureq_and_resp; /*cinfo[i].respos = 0; - already is */ /* prevent future matches with anything */ cinfo[i].cache_pp = (void *) 1; return 1; /* "ready to write data out to client" */ } /* Not found. Remember a pointer where it will appear */ cinfo[i].cache_pp = cache_pp; /* If it does not point to our own ureq buffer... */ if (CACHE_PTR(ureq_and_resp) != ureq) { /* We are not the first client who wants this */ log(L_DEBUG, "another request is in progress (%p), waiting for its result", ureq_and_resp); MARK_PTR_SHARED(cache_pp); /* "please inform us when it's ready" */ /* "we do not wait for client anymore" */ cinfo[i].client_fd = pfd[i].fd; /* Don't wait on fd. Worker response will unblock us */ pfd[i].events = 0; return 0; } /* else: lookup_in_cache inserted (ureq & 1) into *cache_pp: * we are the first client to miss on this ureq. */ } /* Start worker thread */ log(L_DEBUG, "stored %p in cache, starting a worker", ureq_and_resp); /* Now we will wait on worker's fd, not client's! */ cinfo[i].client_fd = pfd[i].fd; pfd[i].fd = create_and_feed_worker(ureq); return 0; } static void prepare_for_writeout(unsigned i, user_req *cached) { log(L_DEBUG2, "client %u: data is ready at %p", i, cached); if (cinfo[i].client_fd) { pfd[i].fd = cinfo[i].client_fd; cinfo[i].client_fd = 0; /* "we don't wait for worker reply" */ } pfd[i].events = POLLOUT; /* Writeout position etc */ cinfo[i].resptr = cached; /*cinfo[i].respos = 0; - already is */ /* if worker took some time to get info (e.g. DNS query), * prevent client timeout from triggering at once */ cinfo[i].started_ms = g_now_ms; } /* Worker seems to be ready to write the response. * When we return, response is fully read and stored in cache, * worker's fd is closed, pfd[i] and cinfo[i] are updated. */ static void handle_worker_response(int i) { struct { /* struct response_header + small body */ uint32_t version_or_size; int32_t found; char body[256 - 8]; } sz_and_found; user_req *cached; user_req *ureq; response_header *resp; unsigned sz, resp_sz; unsigned ureq_sz_aligned; cached = NULL; ureq = cinfo[i].ureq; ureq_sz_aligned = (char*)ureq_response(ureq) - (char*)ureq; sz = full_read(pfd[i].fd, &sz_and_found, sizeof(sz_and_found)); if (sz < 8) { /* worker was killed? */ log(L_DEBUG, "worker gave short reply:%u < 8", sz); goto err; } resp_sz = sz_and_found.version_or_size; if (resp_sz < sz || resp_sz > 0x0fffffff) { /* 256 mb */ error("BUG: bad size from worker:%u", resp_sz); goto err; } /* Create new block of cached info */ cached = xzalloc(ureq_sz_aligned + resp_sz); log(L_DEBUG2, "xzalloc(%u):%p sz:%u resp_sz:%u found:%u", ureq_sz_aligned + resp_sz, cached, sz, resp_sz, (int)sz_and_found.found ); resp = (void*) (((char*) cached) + ureq_sz_aligned); memcpy(cached, ureq, ureq_size(ureq)); memcpy(resp, &sz_and_found, sz); if (sz_and_found.found && resp_sz > sz) { /* We need to read data only if it's found * (otherwise worker sends only 8 bytes). * * Replies can be big (getgrnam("guest") on a big user db), * we cannot rely on them being atomic. However, we know * that worker _always_ gives reply in one full_write(), * so we loop and read it all * (looping is implemented inside full_read()) */ if (full_read(pfd[i].fd, ((char*) resp) + sz, resp_sz - sz) != resp_sz - sz) { /* worker was killed? */ log(L_DEBUG, "worker gave short reply, free(%p)", cached); err: free(cached); cached = NULL; goto wo; } } set_cache_timestamp(cached); hex_dump(resp, resp_sz); wo: close(pfd[i].fd); /* Save in cache */ unsigned ref = 0; user_req **cache_pp = cinfo[i].cache_pp; if (cache_pp != NULL) { /* if not a fake entry */ ureq = *cache_pp; *cache_pp = cached; if (CACHE_SHARED(ureq)) { /* Other clients wait for this response too, * wake them (and us) up and set refcount = no_of_clients */ unsigned j; for (j = 2; j < num_clients; j++) { if (cinfo[j].cache_pp == cache_pp) { /* This client uses the same cache entry */ ref++; /* prevent future matches with anything */ cinfo[j].cache_pp = (void *) 1; prepare_for_writeout(j, cached); } } goto ret; } /* prevent future matches with anything */ cinfo[i].cache_pp = (void *) 1; ref = 1; } prepare_for_writeout(i, cached); ret: /* cache shouldn't free it under us! */ if (cached) { cached->refcount = ref; log(L_DEBUG2, "%p.refcount=%u", cached, ref); } aging_interval_ms = min_aging_interval_ms; } static void main_loop(void) { /* 1/2 of smallest negative TTL */ min_aging_interval_ms = config.nttl[0]; if (min_aging_interval_ms > config.nttl[1]) min_aging_interval_ms = config.nttl[1]; if (min_aging_interval_ms > config.nttl[2]) min_aging_interval_ms = config.nttl[2]; min_aging_interval_ms = (min_aging_interval_ms / 2) | 1; aging_interval_ms = min_aging_interval_ms; while (1) { int i, j; int r; r = SMALL_POLL_TIMEOUT_MS; if (num_clients <= 2 && !cached_cnt) r = -1; /* infinite */ else if (num_clients < max_reqnum) r = aging_interval_ms; #if 0 /* Debug: leak detector */ { static unsigned long long cnt; static unsigned long low_malloc = -1L; static unsigned long low_sbrk = -1L; void *p = malloc(540); /* should not be too small */ void *s = sbrk(0); free(p); if ((unsigned long)p < low_malloc) low_malloc = (unsigned long)p; if ((unsigned long)s < low_sbrk) low_sbrk = (unsigned long)s; log(L_INFO, "poll %llu (%d ms). clients:%u cached:%u %u/%u malloc:%p (%lu), sbrk:%p (%lu)", cnt, r, num_clients, cached_cnt, cache_hit_cnt, cache_access_cnt, p, (unsigned long)p - low_malloc, s, (unsigned long)s - low_sbrk); cnt++; } #else log(L_DEBUG, "poll %d ms. clients:%u cached:%u hit ratio:%u/%u", r, num_clients, cached_cnt, cache_hit_cnt, cache_access_cnt); #endif r = poll(pfd, num_clients, r); log(L_DEBUG2, "poll returns %d", r); if (r < 0) { if (errno != EINTR) perror_and_die("poll"); continue; } /* Everything between polls never sleeps. * There is no blocking I/O (except when we talk to worker thread * which is guaranteed to not block us for long) */ g_now_ms = monotonic_ms(); if (r == 0) goto skip_fd_checks; for (i = 0; i < 2; i++) { int cfd; if (!pfd[i].revents) continue; /* pfd[i].revents = 0; - not needed */ cfd = accept(pfd[i].fd, NULL, NULL); if (cfd < 0) { /* odd... poll() says we can accept but accept failed? */ log(L_DEBUG2, "accept failed with %s", strerror(errno)); continue; } ndelay_on(cfd); close_on_exec(cfd); /* x[num_clients] is next free element, taking it */ log(L_DEBUG2, "new client %d, fd %d", num_clients, cfd); pfd[num_clients].fd = cfd; pfd[num_clients].events = POLLIN; /* this will make us do read() in next for() loop: */ pfd[num_clients].revents = POLLIN; memset(&cinfo[num_clients], 0, sizeof(cinfo[num_clients])); /* cinfo[num_clients].bytecnt = 0; - done */ cinfo[num_clients].started_ms = g_now_ms; cinfo[num_clients].bufidx = alloc_buf_no(); cinfo[num_clients].ureq = bufno2buf(cinfo[num_clients].bufidx); num_clients++; if (num_clients >= max_reqnum) { /* stop accepting new connects for now */ pfd[0].events = pfd[0].revents = 0; pfd[1].events = pfd[1].revents = 0; } } for (; i < num_clients; i++) { if (!pfd[i].revents) continue; log(L_DEBUG2, "pfd[%d].revents:0x%x", i, pfd[i].revents); /* pfd[i].revents = 0; - not needed */ /* "Write out result" case */ if (pfd[i].revents == POLLOUT) { response_header *resp; uint32_t resp_sz; if (!cinfo[i].resptr) { /* corner case: worker gave bad response earlier */ close_client(i); continue; } write_out: resp = ureq_response(cinfo[i].resptr); resp_sz = resp->version_or_size; resp->version_or_size = NSCD_VERSION; errno = 0; r = safe_write(pfd[i].fd, ((char*) resp) + cinfo[i].respos, resp_sz - cinfo[i].respos); resp->version_or_size = resp_sz; if (r < 0 && errno == EAGAIN) { log(L_DEBUG, "client %u: EAGAIN on write", i); continue; } if (r <= 0) { /* client isn't there anymore */ log(L_DEBUG, "client %u is gone (write returned:%d err:%s)", i, r, errno ? strerror(errno) : "-"); close_client(i); continue; } cinfo[i].respos += r; if (cinfo[i].respos >= resp_sz) { /* We wrote everything */ /* No point in trying to get next request, it won't come. * glibc 2.4 client closes its end after each request, * without testing for EOF from server. strace: * ... * read(3, "www.google.com\0\0", 16) = 16 * close(3) = 0 */ log(L_DEBUG, "client %u: sent answer %u/%u/%u bytes", i, r, cinfo[i].respos, resp_sz); close_client(i); continue; } log(L_DEBUG, "client %u: sent partial answer %u/%u/%u bytes", i, r, cinfo[i].respos, resp_sz); continue; } /* "Read reply from worker" case. Worker may be * already dead, revents may contain other bits too */ if ((pfd[i].revents & POLLIN) && cinfo[i].client_fd) { log(L_DEBUG, "reading response for client %u", i); handle_worker_response(i); /* We can immediately try to write a response * to client */ goto write_out; } /* POLLHUP means pfd[i].fd is closed by peer. * POLLHUP+POLLOUT[+POLLERR] is seen when we writing out * and see that pfd[i].fd is closed by peer (for example, * it happens when client's result buffer is too small * to receive a huge GETGRBYNAME result). */ if ((pfd[i].revents & ~(POLLOUT+POLLERR)) == POLLHUP) { int is_client = (cinfo[i].client_fd == 0 || cinfo[i].client_fd == pfd[i].fd); log(L_INFO, "%s %u disappeared (got POLLHUP on fd %d)", is_client ? "client" : "worker", i, pfd[i].fd ); if (is_client) close_client(i); else { /* Read worker output anyway, error handling * in that function deals with short read. * Simply closing client is wrong: it leaks * shared future entries. */ handle_worker_response(i); } continue; } /* All strange and unexpected cases */ if (pfd[i].revents != POLLIN) { /* Not just "can read", but some other bits are there */ log(L_INFO, "client %u revents is strange:0x%x", i, pfd[i].revents); close_client(i); continue; } /* "Read request from client" case */ r = safe_read(pfd[i].fd, (char*)(cinfo[i].ureq) + cinfo[i].bytecnt, MAX_USER_REQ_SIZE - cinfo[i].bytecnt); if (r < 0) { log(L_DEBUG2, "error reading from client: %s", strerror(errno)); if (errno == EAGAIN) continue; close_client(i); continue; } if (r == 0) { log(L_INFO, "premature EOF from client, dropping"); close_client(i); continue; } cinfo[i].bytecnt += r; if (cinfo[i].bytecnt >= sizeof(user_req_header)) { if (handle_client(i)) { /* Response is found in cache! */ goto write_out; } } } /* for each client[2..num_clients-1] */ skip_fd_checks: /* Age cache */ if ((g_now_ms - last_age_time) >= aging_interval_ms) { last_age_time = g_now_ms; age_cache(/*free_all:*/ 0, -1); } /* Close timed out client connections */ for (i = 2; i < num_clients; i++) { if (pfd[i].fd != 0 /* not closed yet? */ && cinfo[i].client_fd == 0 /* do we still wait for client, not worker? */ && (g_now_ms - cinfo[i].started_ms) > CLIENT_TIMEOUT_MS ) { log(L_INFO, "timed out waiting for client %u (%u ms), dropping", i, (unsigned)(g_now_ms - cinfo[i].started_ms)); close_client(i); } } if (!cnt_closed) continue; /* We closed at least one client, coalesce pfd[], cinfo[] */ if (min_closed + cnt_closed >= num_clients) { /* clients [min_closed..num_clients-1] are all closed */ /* log(L_DEBUG, "taking shortcut"); - almost always happens */ goto coalesce_done; } j = min_closed; i = min_closed + 1; while (i < num_clients) { while (1) { if (pfd[i].fd) break; if (++i >= num_clients) goto coalesce_done; } pfd[j] = pfd[i]; cinfo[j++] = cinfo[i++]; } coalesce_done: num_clients -= cnt_closed; log(L_DEBUG, "removing %d closed clients. clients:%d", cnt_closed, num_clients); min_closed = INT_MAX; cnt_closed = 0; /* start accepting new connects */ pfd[0].events = POLLIN; pfd[1].events = POLLIN; } /* while (1) */ } /* ** Initialization */ #define NSCD_PIDFILE "/var/run/nscd/nscd.pid" #define NSCD_DIR "/var/run/nscd" #define NSCD_SOCKET "/var/run/nscd/socket" #define NSCD_SOCKET_OLD "/var/run/.nscd_socket" static smallint wrote_pidfile; static void cleanup_on_signal(int sig) { if (wrote_pidfile) unlink(NSCD_PIDFILE); unlink(NSCD_SOCKET_OLD); unlink(NSCD_SOCKET); exit(0); } static void write_pid(void) { FILE *pid = fopen(NSCD_PIDFILE, "w"); if (!pid) return; fprintf(pid, "%d\n", getpid()); fclose(pid); wrote_pidfile = 1; } /* Open a listening nscd server socket */ static int open_socket(const char *name) { struct sockaddr_un sun; int sock = socket(AF_UNIX, SOCK_STREAM, 0); if (sock < 0) perror_and_die("cannot create unix domain socket"); ndelay_on(sock); close_on_exec(sock); sun.sun_family = AF_UNIX; strcpy(sun.sun_path, name); unlink(name); if (bind(sock, (struct sockaddr *) &sun, sizeof(sun)) < 0) perror_and_die("bind(%s)", name); if (chmod(name, 0666) < 0) perror_and_die("chmod(%s)", name); if (listen(sock, (max_reqnum/8) | 1) < 0) perror_and_die("listen"); return sock; } static const struct option longopt[] = { /* name, has_arg, int *flag, int val */ { "debug" , no_argument , NULL, 'd' }, { "config-file", required_argument, NULL, 'f' }, { "invalidate" , required_argument, NULL, 'i' }, { "shutdown" , no_argument , NULL, 'K' }, { "nthreads" , required_argument, NULL, 't' }, { "version" , no_argument , NULL, 'V' }, { "help" , no_argument , NULL, '?' }, { "usage" , no_argument , NULL, '?' }, /* just exit(0). TODO: "test" connect? */ { "statistic" , no_argument , NULL, 'g' }, { "secure" , no_argument , NULL, 'S' }, /* ? */ { } }; static const char *const help[] = { "Do not daemonize; log to stderr (-dd: more verbosity)", "File to read configuration from", "Invalidate cache", "Shut the server down", "Serve N requests in parallel", "Version", }; static void print_help_and_die(void) { const struct option *opt = longopt; const char *const *h = help; puts("Usage: nscd [OPTION...]\n" "Name Service Cache Daemon\n"); do { printf("\t" "-%c,--%-11s %s\n", opt->val, opt->name, *h); h++; opt++; } while (opt->val != '?'); exit(1); } static char *skip_service(int *srv, const char *s) { if (strcmp("passwd", s) == 0) { *srv = SRV_PASSWD; s++; } else if (strcmp("group", s) == 0) { *srv = SRV_GROUP; } else if (strcmp("hosts", s) == 0) { *srv = SRV_HOSTS; } else { return NULL; } return skip_whitespace(s + 6); } static void handle_null(const char *str, int srv) {} static void handle_logfile(const char *str, int srv) { config.logfile = xstrdup(str); } static void handle_debuglvl(const char *str, int srv) { debug |= (uint8_t) getnum(str); } static void handle_threads(const char *str, int srv) { unsigned n = getnum(str); if (max_reqnum < n) max_reqnum = n; } static void handle_user(const char *str, int srv) { config.user = xstrdup(str); } static void handle_enable(const char *str, int srv) { config.srv_enable[srv] = ((str[0] | 0x20) == 'y'); } static void handle_pttl(const char *str, int srv) { config.pttl[srv] = getnum(str); } static void handle_nttl(const char *str, int srv) { config.nttl[srv] = getnum(str); } static void handle_size(const char *str, int srv) { config.size[srv] = getnum(str); } static void handle_chfiles(const char *str, int srv) { config.check_files[srv] = ((str[0] | 0x20) == 'y'); } static void parse_conffile(const char *conffile, int warn) { static const struct confword { const char *str; void (*handler)(const char *, int); } conf_words[] = { { "_" "logfile" , handle_logfile }, { "_" "debug-level" , handle_debuglvl }, { "_" "threads" , handle_threads }, { "_" "max-threads" , handle_threads }, { "_" "server-user" , handle_user }, /* ignore: any user can stat */ { "_" "stat-user" , handle_null }, { "_" "paranoia" , handle_null }, /* ? */ /* ignore: design goal is to never crash/hang */ { "_" "reload-count" , handle_null }, { "_" "restart-interval" , handle_null }, { "S" "enable-cache" , handle_enable }, { "S" "positive-time-to-live" , handle_pttl }, { "S" "negative-time-to-live" , handle_nttl }, { "S" "suggested-size" , handle_size }, { "S" "check-files" , handle_chfiles }, { "S" "persistent" , handle_null }, /* ? */ { "S" "shared" , handle_null }, /* ? */ { "S" "auto-propagate" , handle_null }, /* ? */ { } }; char buf[128]; FILE *file = fopen(conffile, "r"); int lineno = 0; if (!file) { if (conffile != default_conffile) perror_and_die("cannot open %s", conffile); return; } while (fgets(buf, sizeof(buf), file) != NULL) { const struct confword *word; char *p; int len = strlen(buf); lineno++; if (len) { if (buf[len-1] != '\n') { if (len >= sizeof(buf) - 1) error_and_die("%s:%d: line is too long", conffile, lineno); len++; /* last line, not terminated by '\n' */ } buf[len-1] = '\0'; } p = strchr(buf, '#'); if (p) *p = '\0'; p = skip_whitespace(buf); if (!*p) continue; *skip_non_whitespace(p) = '\0'; word = conf_words; while (1) { if (strcmp(word->str + 1, p) == 0) { int srv = 0; p = skip_whitespace(p + strlen(p) + 1); *skip_non_whitespace(p) = '\0'; if (word->str[0] == 'S') { char *p2 = skip_service(&srv, p); if (!p2) { if (warn) error("%s:%d: ignoring unknown service name '%s'", conffile, lineno, p); break; } p = p2; *skip_non_whitespace(p) = '\0'; } word->handler(p, srv); break; } word++; if (!word->str) { if (warn) error("%s:%d: ignoring unknown directive '%s'", conffile, lineno, p); break; } } } fclose(file); } /* "XX,XX[,XX]..." -> gid_t[] */ static gid_t* env_U_to_uid_and_gids(const char *str, int *sizep) { const char *sp; gid_t *ug, *gp; int ng; sp = str; ng = 1; while (*sp) if (*sp++ == ',') ng++; ug = xmalloc(ng * sizeof(ug[0])); ng = 0; gp = ug; sp = str; errno = 0; while (1) { ng++; *gp++ = strtoul(sp, (char**)&sp, 16); if (errno || (*sp != ',' && *sp != '\0')) error_and_die("internal error"); if (*sp == '\0') break; sp++; } *sizep = ng; return ug; } static char* user_to_env_U(const char *user) { int ng; char *ug_str, *sp; gid_t *ug, *gp; struct passwd *pw; pw = getpwnam(user); if (!pw) perror_and_die("user '%s' is not known", user); ng = 64; /* 0th cell will be used for uid */ ug = xmalloc((1 + ng) * sizeof(ug[0])); if (getgrouplist(user, pw->pw_gid, &ug[1], &ng) < 0) { ug = xrealloc(ug, (1 + ng) * sizeof(ug[0])); if (getgrouplist(user, pw->pw_gid, &ug[1], &ng) < 0) perror_and_die("can't get groups of user '%s'", user); } ng++; ug[0] = pw->pw_uid; /* How much do we need for "-Uxx,xx[,xx]..." string? */ ug_str = xmalloc((sizeof(unsigned long)+1)*2 * ng + 3); gp = ug; sp = ug_str; *sp++ = 'U'; *sp++ = '='; do { sp += sprintf(sp, "%lx,", (unsigned long)(*gp++)); } while (--ng); sp[-1] = '\0'; free(ug); return ug_str; } /* not static - don't inline me, compiler! */ void readlink_self_exe(void); void readlink_self_exe(void) { char buf[PATH_MAX + 1]; ssize_t sz = readlink("/proc/self/exe", buf, sizeof(buf) - 1); if (sz < 0) perror_and_die("readlink %s failed", "/proc/self/exe"); buf[sz] = 0; self_exe_points_to = xstrdup(buf); } static void special_op(const char *arg) NORETURN; static void special_op(const char *arg) { static const user_req_header ureq = { NSCD_VERSION, SHUTDOWN, 0 }; struct sockaddr_un addr; int sock; sock = socket(PF_UNIX, SOCK_STREAM, 0); if (sock < 0) error_and_die("cannot create AF_UNIX socket"); addr.sun_family = AF_UNIX; strcpy(addr.sun_path, NSCD_SOCKET); if (connect(sock, (struct sockaddr *) &addr, sizeof(addr)) < 0) error_and_die("cannot connect to %s", NSCD_SOCKET); if (!arg) { /* shutdown */ xfull_write(sock, &ureq, sizeof(ureq)); printf("sent shutdown request, exiting\n"); } else { /* invalidate */ size_t arg_len = strlen(arg) + 1; struct { user_req_header req; char arg[arg_len]; } reqdata; reqdata.req.version = NSCD_VERSION; reqdata.req.type = INVALIDATE; reqdata.req.key_len = arg_len; memcpy(reqdata.arg, arg, arg_len); xfull_write(sock, &reqdata, arg_len + sizeof(ureq)); printf("sent invalidate(%s) request, exiting\n", arg); } exit(0); } /* Callback for glibc-2.15 */ struct traced_file; static void do_nothing(size_t dbidx, struct traced_file *finfo) { /* nscd from glibc-2.15 does something like this: if (!dbs[dbidx].enabled || !dbs[dbidx].check_file) return; add_file_to_watch_list(finfo->fname); */ } /* This internal glibc function is called to disable trying to contact nscd. * We _are_ nscd, so we need to do the lookups, and not recurse. * Until 2.14, this function was taking no parameters. * In 2.15, it takes a function pointer from hell. */ void __nss_disable_nscd(void (*hell)(size_t, struct traced_file*)); int main(int argc, char **argv) { int n; unsigned opt_d_cnt; const char *env_U; const char *conffile; /* make sure we don't get recursive calls */ __nss_disable_nscd(do_nothing); if (argv[0][0] == 'w') /* "worker_nscd" */ worker(argv[1]); setlinebuf(stdout); setlinebuf(stderr); /* Make sure stdio is not closed */ n = xopen3("/dev/null", O_RDWR, 0); while (n < 2) n = dup(n); /* Close unexpected open file descriptors */ n |= 0xff; /* start from at least fd# 255 */ do { close(n--); } while (n > 2); /* For idiotic kernels which disallow "exec /proc/self/exe" */ readlink_self_exe(); conffile = default_conffile; opt_d_cnt = 0; while ((n = getopt_long(argc, argv, "df:i:KVgt:", longopt, NULL)) != -1) { switch (n) { case 'd': opt_d_cnt++; debug &= ~D_DAEMON; break; case 'f': conffile = optarg; break; case 'i': /* invalidate */ special_op(optarg); /* exits */ case 'K': /* shutdown server */ special_op(NULL); /* exits */ case 'V': puts("unscd - nscd which does not hang, v."PROGRAM_VERSION); exit(0); case 'g': exit(0); case 't': /* N threads */ max_reqnum = getnum(optarg); break; case 'S': /* secure (?) */ break; default: print_help_and_die(); } } /* Multiple -d can bump debug regardless of nscd.conf: * no -d or -d: 0, -dd: 1, * -ddd: 3, -dddd: 7, -ddddd: 15 */ if (opt_d_cnt != 0) debug |= (((1U << opt_d_cnt) >> 1) - 1) & L_ALL; env_U = getenv("U"); /* Avoid duplicate warnings if $U exists */ parse_conffile(conffile, /* warn? */ (env_U == NULL)); /* I have a user report of (broken?) ldap nss library * opening and never closing a socket to a ldap server, * even across fork() and exec(). This messes up * worker child's operations for the reporter. * * This strenghtens my belief that nscd _must not_ trust * nss libs to be written correctly. * * Here, we need to jump through the hoops to guard against * such problems. If config file has server-user setting, we need * to setgroups + setuid. For that, we need to get uid and gid vector. * And that means possibly using buggy nss libs. * We will do it here, but then we will re-exec, passing uid+gids * in an environment variable. */ if (!env_U && config.user) { /* user_to_env_U() does getpwnam and getgrouplist */ if (putenv(user_to_env_U(config.user))) error_and_die("out of memory"); /* fds leaked by nss will be closed by execed copy */ execv(self_exe_points_to, argv); xexecve("/proc/self/exe", argv, environ); } /* Allocate dynamically sized stuff */ max_reqnum += 2; /* account for 2 first "fake" clients */ if (max_reqnum < 8) max_reqnum = 8; /* sanitize */ /* Since refcount is a byte, can't serve more than 255-2 clients * at once. The rest will block in connect() */ if (max_reqnum > 0xff) max_reqnum = 0xff; client_buf = xzalloc(max_reqnum * sizeof(client_buf[0])); busy_cbuf = xzalloc(max_reqnum * sizeof(busy_cbuf[0])); pfd = xzalloc(max_reqnum * sizeof(pfd[0])); cinfo = xzalloc(max_reqnum * sizeof(cinfo[0])); cache_size = (config.size[0] + config.size[1] + config.size[2]) / 8; if (cache_size < 8) cache_size = 8; /* 8*8 = 64 entries min */ if (cache_size > 0xffff) cache_size = 0xffff; /* 8*64k entries max */ cache_size |= 1; /* force it to be odd */ cache = xzalloc(cache_size * sizeof(cache[0])); /* Register cleanup hooks */ signal(SIGINT, cleanup_on_signal); signal(SIGTERM, cleanup_on_signal); /* Don't die if a client closes a socket on us */ signal(SIGPIPE, SIG_IGN); /* Avoid creating zombies */ signal(SIGCHLD, SIG_IGN); #if !DEBUG_BUILD /* Ensure workers don't have SIGALRM ignored */ signal(SIGALRM, SIG_DFL); #endif if (mkdir(NSCD_DIR, 0755) == 0) { /* prevent bad mode of NSCD_DIR if umask is e.g. 077 */ chmod(NSCD_DIR, 0755); } pfd[0].fd = open_socket(NSCD_SOCKET); pfd[1].fd = open_socket(NSCD_SOCKET_OLD); pfd[0].events = POLLIN; pfd[1].events = POLLIN; if (debug & D_DAEMON) { daemon(/*nochdir*/ 1, /*noclose*/ 0); if (config.logfile) { /* nochdir=1: relative paths still work as expected */ xmovefd(xopen3(config.logfile, O_WRONLY|O_CREAT|O_TRUNC, 0666), 2); debug |= D_STAMP; } else { debug = 0; /* why bother? it's /dev/null'ed anyway */ } chdir("/"); /* compat */ write_pid(); setsid(); /* ignore job control signals */ signal(SIGTTOU, SIG_IGN); signal(SIGTTIN, SIG_IGN); signal(SIGTSTP, SIG_IGN); } log(L_ALL, "unscd v" PROGRAM_VERSION ", debug level 0x%x", debug & L_ALL); log(L_DEBUG, "max %u requests in parallel", max_reqnum - 2); log(L_DEBUG, "cache size %u x 8 entries", cache_size); if (env_U) { int size; gid_t *ug = env_U_to_uid_and_gids(env_U, &size); if (size > 1) if (setgroups(size - 1, &ug[1]) || setgid(ug[1])) perror_and_die("cannot set groups for user '%s'", config.user); if (size > 0) if (setuid(ug[0])) perror_and_die("cannot set uid to %u", (unsigned)(ug[0])); free(ug); } for (n = 0; n < 3; n++) { log(L_DEBUG, "%s cache enabled:%u pttl:%u nttl:%u", srv_name[n], config.srv_enable[n], config.pttl[n], config.nttl[n]); config.pttl[n] *= 1000; config.nttl[n] *= 1000; } main_loop(); return 0; }
the_stack_data/61074325.c
#include <sys/types.h> #include <stddef.h> #ifdef NPK_DEV void tea_encode(unsigned char* c, int* k) { unsigned int y, z, sum=0, delta=0x9e3779b9, n=32; y = c[0] | c[1] << 8 | c[2] << 16 | c[3] << 24; z = c[4] | c[5] << 8 | c[6] << 16 | c[7] << 24; while (n-->0) { sum += delta; y += (z<<4)+k[0] ^ z+sum ^ (z>>5)+k[1]; z += (y<<4)+k[2] ^ y+sum ^ (y>>5)+k[3]; } c[0] = y & 0xFF; c[1] = y >> 8 & 0xFF; c[2] = y >> 16 & 0xFF; c[3] = y >> 24 & 0xFF; c[4] = z & 0xFF; c[5] = z >> 8 & 0xFF; c[6] = z >> 16 & 0xFF; c[7] = z >> 24 & 0xFF; } void tea_encode_byte(unsigned char* v, int* k, off_t p) { unsigned char y[] = "NpK!TeA"; *v = *v^y[p]^(unsigned char)(k[p%4]%0xFF); } void tea_encode_buffer(unsigned char* in_buffer, off_t in_size, int* key, int cipherRemains) { unsigned char *p; off_t remain = in_size % 8; off_t align_size = in_size - remain; for (p = in_buffer; p < in_buffer + align_size; p += 8) tea_encode(p, key); if( remain > 0 && cipherRemains ) for (p = in_buffer + align_size; p < in_buffer + in_size; p += 1) tea_encode_byte( p, key, --remain ); } #endif void tea_decode(unsigned char* c,int* k) { unsigned int n=32, sum, y, z, delta=0x9e3779b9; y = c[0] | c[1] << 8 | c[2] << 16 | c[3] << 24; z = c[4] | c[5] << 8 | c[6] << 16 | c[7] << 24; sum=delta<<5 ; /* start cycle */ while (n-->0) { z-= (y<<4)+k[2] ^ y+sum ^ (y>>5)+k[3]; y-= (z<<4)+k[0] ^ z+sum ^ (z>>5)+k[1]; sum-=delta ; } /* end cycle */ c[0] = y & 0xFF; c[1] = y >> 8 & 0xFF; c[2] = y >> 16 & 0xFF; c[3] = y >> 24 & 0xFF; c[4] = z & 0xFF; c[5] = z >> 8 & 0xFF; c[6] = z >> 16 & 0xFF; c[7] = z >> 24 & 0xFF; } void tea_decode_byte(unsigned char* v, int* k, off_t p) { unsigned char y[] = "NpK!TeA"; *v = *v^(unsigned char)(k[p%4]%0xFF)^y[p]; } void tea_decode_buffer(unsigned char* in_buffer, off_t in_size, int* key, int cipherRemains) { unsigned char *p; off_t remain = in_size % 8; off_t align_size = in_size - remain; for (p = in_buffer; p < in_buffer + align_size; p += 8) tea_decode(p, key); if( remain > 0 && cipherRemains ) for (p = in_buffer + align_size; p < in_buffer + in_size; p += 1) tea_decode_byte( p, key, --remain ); }
the_stack_data/76769.c
#include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <string.h> int main(int argc, char **argv) { int fd; //file descriptor int length; char *mapped_mem; // int pagesize = 0; pagesize = getpagesize(); // fd = open(argv[1], O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); // length = lseek(fd, 0, SEEK_END); // lseek(fd, (pagesize * 2 - length % pagesize - 1), SEEK_END); write(fd, "-1", 1); // mapped_mem = mmap(NULL, length / pagesize + 2, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); printf("\npls input info you insert(size<%d):", pagesize); char buf[pagesize]; fgets(buf, pagesize, stdin); printf("\npls input info you insert local( < filesize %d ):", length); int local = 0; scanf("%d", &local); memmove(mapped_mem + local + strlen(buf), mapped_mem + local, length - local); memcpy(mapped_mem + local, buf, strlen(buf) - 1); // msync(mapped_mem, length / pagesize + 2, MS_SYNC | MS_INVALIDATE); // munmap(mapped_mem, length / pagesize + 2); ftruncate(fd, length + strlen(buf)); // return 0; }
the_stack_data/62636754.c
void Test1(); void Test2(); void Test3(); void Test4(); void Test5(); int main(int argc,char **argv) { Test1(); Test2(); Test3(); Test4(); Test5(); }
the_stack_data/9128.c
// C program to demonstrate delete operation in binary search tree #include<stdio.h> #include<stdlib.h> struct node { int key; struct node *left, *right; }; // A utility function to create a new BST node struct node *newNode(int item) { struct node *temp = (struct node *)malloc(sizeof(struct node)); temp->key = item; temp->left = temp->right = NULL; return temp; } // A utility function to do inorder traversal of BST void inorder(struct node *root) { if (root != NULL) { inorder(root->left); printf("%d ", root->key); inorder(root->right); } } /* A utility function to insert a new node with given key in BST */ struct node* insert(struct node* node, int key) { /* If the tree is empty, return a new node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key < node->key) node->left = insert(node->left, key); else node->right = insert(node->right, key); /* return the (unchanged) node pointer */ return node; } /* Given a non-empty binary search tree, return the node with minimum key value found in that tree. Note that the entire tree does not need to be searched. */ struct node * minValueNode(struct node* node) { struct node* current = node; /* loop down to find the leftmost leaf */ while (current->left != NULL) current = current->left; return current; } /* Given a binary search tree and a key, this function deletes the key and returns the new root */ struct node* deleteNode(struct node* root, int key) { // base case if (root == NULL) return root; // If the key to be deleted is smaller than the root's key, // then it lies in left subtree if (key < root->key) root->left = deleteNode(root->left, key); // If the key to be deleted is greater than the root's key, // then it lies in right subtree else if (key > root->key) root->right = deleteNode(root->right, key); // if key is same as root's key, then This is the node // to be deleted else { // node with only one child or no child if (root->left == NULL) { struct node *temp = root->right; free(root); return temp; } else if (root->right == NULL) { struct node *temp = root->left; free(root); return temp; } // node with two children: Get the inorder successor (smallest // in the right subtree) struct node* temp = minValueNode(root->right); // Copy the inorder successor's content to this node root->key = temp->key; // Delete the inorder successor root->right = deleteNode(root->right, temp->key); } return root; } // Driver Program to test above functions int main() { /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ struct node *root = NULL; root = insert(root, 50); root = insert(root, 30); root = insert(root, 20); root = insert(root, 40); root = insert(root, 70); root = insert(root, 60); root = insert(root, 80); printf("Inorder traversal of the given tree \n"); inorder(root); printf("\nDelete 20\n"); root = deleteNode(root, 20); printf("Inorder traversal of the modified tree \n"); inorder(root); printf("\nDelete 30\n"); root = deleteNode(root, 30); printf("Inorder traversal of the modified tree \n"); inorder(root); printf("\nDelete 50\n"); root = deleteNode(root, 50); printf("Inorder traversal of the modified tree \n"); inorder(root); return 0; }
the_stack_data/1101281.c
#include <signal.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> void uchwyc_dzielenie_przez_zero(int num_sygnalu) { if (num_sygnalu == SIGFPE) { printf("Dzielenie przez zero!\n"); } else { printf("Nieoczekiwany sygnal!\n"); exit(0); } } void uchwyc_alarm(int num_sygnalu) { if (num_sygnalu == SIGALRM) { printf("Alarm zostal ugaszony!\n"); } else { printf("Nieoczekiwany sygnal!\n"); exit(0); } } int main() { // printf("Wysylam sygnal SIGSTOP!\n"); // raise(SIGSTOP); // znajdz pid sygnalu w terminalu: ps -f | grep sygnal // zatrzymaj proces: kill -STOP pid // printf("Sygnal zostal zabity!\n"); // sprobuj schwytac sygnal SIGALRM void (*rezultat_proby_schwytania_sygnalu)(int); rezultat_proby_schwytania_sygnalu = signal(SIGALRM, uchwyc_alarm); if (rezultat_proby_schwytania_sygnalu == SIG_ERR) { printf("Wystapil nieznany blad!\n"); exit(0); } // wyslij sygnal SIGALRM po 3 sekundach // jesli sygnal nie zostanie schwytany, to program zostanie zakonczony alarm(3); for (int i = 0; i < 6; i++) { printf("%d\n", i + 1); sleep(1); } rezultat_proby_schwytania_sygnalu = signal(SIGFPE, uchwyc_dzielenie_przez_zero); if (rezultat_proby_schwytania_sygnalu == SIG_ERR) { printf("Wystapil nieznany blad!\n"); exit(0); } float a = 1.0; float b = 0.0; float ulamek = a / b; printf("Wynik dzieielenia przez zero: %f\n", ulamek); return 0; }
the_stack_data/206394069.c
#include <stdio.h> int main(int argc, char *argv[]) { int p1, p2, p3, t1, t2, n, lr, l, r, e = 0; scanf("%d %d %d %d %d %d", &n, &p1, &p2, &p3, &t1, &t2); scanf("%d %d", &l, &r); e += (r - l) * p1; lr = r; while(-- n) { scanf("%d %d", &l, &r); e += (r - l) * p1; if(l - lr <= t1) e += (l - lr) * p1; else { e += t1 * p1; if(l - lr <= t1 + t2) e += (l - lr - t1) * p2; else e += t2 * p2 + (l - lr - t1 - t2) * p3; } lr = r; } printf("%d\n", e); return 0; }
the_stack_data/167331338.c
#include <stdio.h> int main() { printf("\n"); int custAge = 38; // char *legalAge }
the_stack_data/982737.c
#include <stdio.h> #include <stdlib.h> #include <sys/stat.h> // read a bmp file into an one integer per pixel double array void readBmpFile(char *bmpFileName, int **rawImgData) { struct stat stat_p; FILE *bmpFile; char *bmpData; int x, y, i, cntDown; int startOfBmpData = 0; int xSize = 0; int ySize = 0; int bitsPerPix = 0; int colorTable[256]; // does the file exist if (-1 == stat(bmpFileName, &stat_p)) return; // allocate memory for bmp file bmpData = (char *)malloc(stat_p.st_size); // open file for read bmpFile = fopen(bmpFileName,"rb"); if (!bmpFile) return; // read file data to buffer fread(bmpData, sizeof(char), stat_p.st_size, bmpFile); fclose(bmpFile); // find where the image data begins if (10 < stat_p.st_size) startOfBmpData = startOfBmpData | (bmpData[10] & 0x000000FF); if (11 < stat_p.st_size) startOfBmpData = startOfBmpData | ((bmpData[11] & 0x000000FF) << 8); if (12 < stat_p.st_size) startOfBmpData = startOfBmpData | ((bmpData[12] & 0x000000FF) << 16); if (13 < stat_p.st_size) startOfBmpData = startOfBmpData | ((bmpData[13] & 0x000000FF) << 24); //printf("startOfBmpData %i\n", startOfBmpData); // get the width of the image if (18 < stat_p.st_size) xSize = xSize | (bmpData[18] & 0x000000FF); if (19 < stat_p.st_size) xSize = xSize | ((bmpData[19] & 0x000000FF) << 8); if (20 < stat_p.st_size) xSize = xSize | ((bmpData[20] & 0x000000FF) << 16); if (21 < stat_p.st_size) xSize = abs(xSize | ((bmpData[21] & 0x000000FF) << 24)); //printf("xSize %i\n", xSize); // get the height of the image if (22 < stat_p.st_size) ySize = ySize | (bmpData[22] & 0x000000FF); if (23 < stat_p.st_size) ySize = ySize | ((bmpData[23] & 0x000000FF) << 8); if (24 < stat_p.st_size) ySize = ySize | ((bmpData[24] & 0x000000FF) << 16); if (25 < stat_p.st_size) ySize = abs(ySize | ((bmpData[25] & 0x000000FF) << 24)); //printf("ySize %i\n", ySize); // get the number of bits per pixel if (28 < stat_p.st_size) bitsPerPix = bitsPerPix | (bmpData[28] & 0x000000FF); if (29 < stat_p.st_size) bitsPerPix = bitsPerPix | ((bmpData[29] & 0x000000FF) << 8); // to use for the count down // inside the memory array cntDown = stat_p.st_size - 1; int pix16bit; int colorTableCnt = 0; int bitShift; if (bitsPerPix >= 16) { // read 24 bpp image if (bitsPerPix == 24) for (y=0; y < ySize; y++) for (x=xSize-1; x >= 0; x--) { if (x == xSize-1) cntDown = cntDown - xSize % 4;// subtract offset rawImgData[x][y] = (0xFF & bmpData[cntDown-0]) << 16 | ((0xFF & bmpData[cntDown-1]) << 8) | (0xFF & bmpData[cntDown-2]); cntDown = cntDown - 3; } // read 16 bpp image if (bitsPerPix == 16) for (y=0; y < ySize; y++) for (x=xSize-1; x >= 0; x--) { if (x == xSize-1) cntDown = cntDown - (xSize % 2) * 2;// subtract offset pix16bit = ((0xFF & bmpData[cntDown-0]) << 8) | (0xFF & bmpData[cntDown-1]); rawImgData[x][y] = ((pix16bit >> 10) & 0x1f) << (3+16) | (((pix16bit >> 5) & 0x1f) << (3+8)) | ((pix16bit & 0x1f) << 3); cntDown = cntDown - 2; } } //rawImgData[x][y] = (pix16bit >> 11) << (3+16) | (((pix16bit >> 5) & 0x3f) << (3+7)) | ((pix16bit & 0x1f) << 3); if (bitsPerPix <= 8) { // read 8 bpp image if (bitsPerPix == 8) { for (i=0; i < 256; i++) { colorTable[i] = (0xFF & bmpData[54+colorTableCnt+2]) << 16 | ((0xFF & bmpData[54+colorTableCnt+1]) << 8) | (0xFF & bmpData[54+colorTableCnt+0]); colorTableCnt = colorTableCnt + 4; } for (y=0; y < ySize; y++) for (x=xSize-1; x >= 0; x--) { // subtract offset if (x == xSize-1) cntDown = cntDown - (3-((xSize-1)%4)); rawImgData[x][y] = colorTable[0xFF & bmpData[cntDown]]; cntDown--; } } int flipFlop = 0; int offsetFlipFlop = 0; // read 4 bpp image if (bitsPerPix == 4) { for (i=0; i < 16; i++) { colorTable[i] = (0xFF & bmpData[54+colorTableCnt+2]) << 16 | ((0xFF & bmpData[54+colorTableCnt+1]) << 8) | (0xFF & bmpData[54+colorTableCnt+0]); colorTableCnt = colorTableCnt + 4; } for (y=0; y < ySize; y++) for (x=xSize-1; x >= 0; x--) { // add offset if (x == xSize-1) cntDown = cntDown - (3-(int)(((xSize-1)%8)/2));//1=2,2=3,3=3,4=0,5=0,6=1,7=1,8=2 // add extra offset if (x == xSize-1) if (xSize % 2)// if odd offsetFlipFlop = !offsetFlipFlop; if (!flipFlop) { if (!offsetFlipFlop) rawImgData[x][y] = colorTable[bmpData[cntDown] & 0xF]; else rawImgData[x][y] = colorTable[(bmpData[cntDown] >> 4) & 0xF]; if (offsetFlipFlop) cntDown--; } if (flipFlop) { if (offsetFlipFlop) rawImgData[x][y] = colorTable[bmpData[cntDown] & 0xF]; else rawImgData[x][y] = colorTable[(bmpData[cntDown] >> 4) & 0xF]; if (!offsetFlipFlop) cntDown--; } flipFlop = !flipFlop; } } // read 1 bpp image if (bitsPerPix == 1) { for (i=0; i < 2; i++) { colorTable[i] = (0xFF & bmpData[54+colorTableCnt+2]) << 16 | ((0xFF & bmpData[54+colorTableCnt+1]) << 8) | (0xFF & bmpData[54+colorTableCnt+0]); colorTableCnt = colorTableCnt + 4; } i = 0; for (y=0; y < ySize; y++) for (x=xSize-1; x >= 0; x--) { // subtract offset if (x == xSize-1) { i = i + 31-(xSize-1)%32; if (31-(xSize-1)%32 >= 8) cntDown--; if (31-(xSize-1)%32 >= 16) cntDown--; if (31-(xSize-1)%32 >= 24) cntDown--; } bitShift = i % 8; if (bitShift < 4) { if (bitShift < 2) { if (bitShift == 0) rawImgData[x][y] = colorTable[bmpData[cntDown] & 1]; if (bitShift == 1) rawImgData[x][y] = colorTable[(bmpData[cntDown] >> 1) & 1]; } else { if (bitShift == 2) rawImgData[x][y] = colorTable[(bmpData[cntDown] >> 2) & 1]; if (bitShift == 3) rawImgData[x][y] = colorTable[(bmpData[cntDown] >> 3) & 1]; } } else { if (bitShift < 6) { if (bitShift == 4) rawImgData[x][y] = colorTable[(bmpData[cntDown] >> 4) & 1]; if (bitShift == 5) rawImgData[x][y] = colorTable[(bmpData[cntDown] >> 5) & 1]; } else { if (bitShift == 6) rawImgData[x][y] = colorTable[(bmpData[cntDown] >> 6) & 1]; if (bitShift == 7) rawImgData[x][y] = colorTable[(bmpData[cntDown] >> 7) & 1]; if (bitShift == 7) cntDown--; } } i++; } } } if (bmpData) free(bmpData); } void getBmpFileDataSz(char *bmpFileName, int *xSize, int *ySize, int *bitsPerPix) { struct stat stat_p; FILE *bmpFile; int c; *xSize = 0; *ySize = 0; *bitsPerPix = 0; // does the file exist if (-1 == stat(bmpFileName, &stat_p)) return; // open file for read bmpFile = fopen(bmpFileName,"rb"); if (!bmpFile) return; // get the width of the image fseek(bmpFile, 18, SEEK_CUR); c = fgetc(bmpFile); if (c != EOF) *xSize = *xSize | (c & 0x000000FF); c = fgetc(bmpFile); if (c != EOF) *xSize = *xSize | ((c & 0x000000FF) << 8); c = fgetc(bmpFile); if (c != EOF) *xSize = *xSize | ((c & 0x000000FF) << 16); c = fgetc(bmpFile); if (c != EOF) *xSize = abs(*xSize | ((c & 0x000000FF) << 24)); // get the height of the image c = fgetc(bmpFile); if (c != EOF) *ySize = *ySize | (c & 0x000000FF); c = fgetc(bmpFile); if (c != EOF) *ySize = *ySize | ((c & 0x000000FF) << 8); c = fgetc(bmpFile); if (c != EOF) *ySize = *ySize | ((c & 0x000000FF) << 16); c = fgetc(bmpFile); if (c != EOF) *ySize = abs(*ySize | ((c & 0x000000FF) << 24)); // get the number of bits per pixel fseek(bmpFile, 2, SEEK_CUR); c = fgetc(bmpFile); if (c != EOF) *bitsPerPix = *bitsPerPix | (c & 0x000000FF); c = fgetc(bmpFile); if (c != EOF) *bitsPerPix = *bitsPerPix | ((c & 0x000000FF) << 8); fclose(bmpFile); } void writeBmpFile(char *bmpFileName, int **rawImgData, int xSize, int ySize, int bitsPerPix) { int i, x, y; int bmpDataSize; FILE *bmpFile; int colorTable[256]; int colorTableCnt; bmpFile = fopen(bmpFileName, "wb"); if (!bmpFile) return; fprintf(bmpFile, "%s", "BM"); bmpDataSize = xSize * ySize * ((float)bitsPerPix / 8); // write 24 bits per pixel bmp file if (bitsPerPix == 24) { // file size fprintf(bmpFile, "%c", (char)((bmpDataSize + 0x36) & 0xFF)); fprintf(bmpFile, "%c", (char)((bmpDataSize + 0x36) >> 8 & 0xFF)); fprintf(bmpFile, "%c", (char)((bmpDataSize + 0x36) >> 16 & 0xFF)); fprintf(bmpFile, "%c", (char)((bmpDataSize + 0x36) >> 24 & 0xFF)); // reserved1 and 2 for (i=0; i < 4; i++) fprintf(bmpFile, "%c", 0); // file offset to pixel array fprintf(bmpFile, "%c", 0x36); fprintf(bmpFile, "%c", 0); fprintf(bmpFile, "%c", 0); fprintf(bmpFile, "%c", 0); // dib header size fprintf(bmpFile, "%c", 0x28); fprintf(bmpFile, "%c", 0); fprintf(bmpFile, "%c", 0); fprintf(bmpFile, "%c", 0); // image width fprintf(bmpFile, "%c", (char)(xSize & 0xFF)); fprintf(bmpFile, "%c", (char)(xSize >> 8 & 0xFF)); fprintf(bmpFile, "%c", (char)(xSize >> 16 & 0xFF)); fprintf(bmpFile, "%c", (char)(xSize >> 24 & 0xFF)); // image height fprintf(bmpFile, "%c", (char)(ySize & 0xFF)); fprintf(bmpFile, "%c", (char)(ySize >> 8 & 0xFF)); fprintf(bmpFile, "%c", (char)(ySize >> 16 & 0xFF)); fprintf(bmpFile, "%c", (char)(ySize >> 24 & 0xFF)); // number of planes fprintf(bmpFile, "%c", 1); fprintf(bmpFile, "%c", 0); // number of bits per pixel fprintf(bmpFile, "%c", 24); fprintf(bmpFile, "%c", 0); // compression for (i=0; i < 4; i++) fprintf(bmpFile, "%c", 0); // image size fprintf(bmpFile, "%c", (char)(bmpDataSize & 0xFF)); fprintf(bmpFile, "%c", (char)(bmpDataSize >> 8 & 0xFF)); fprintf(bmpFile, "%c", (char)(bmpDataSize >> 16 & 0xFF)); fprintf(bmpFile, "%c", (char)(bmpDataSize >> 24 & 0xFF)); // x pixels per meter for (i=0; i < 4; i++) fprintf(bmpFile, "%c", 0); // y pixels per meter for (i=0; i < 4; i++) fprintf(bmpFile, "%c", 0); // colors in color table for (i=0; i < 4; i++) fprintf(bmpFile, "%c", 0); // important color count for (i=0; i < 4; i++) fprintf(bmpFile, "%c", 0); // image data for (y = ySize-1; y >= 0; y--) for (x = 0; x < xSize; x++) { fprintf(bmpFile, "%c", (char)rawImgData[x][y] & 0x0000FF); fprintf(bmpFile, "%c", (char)((rawImgData[x][y] & 0x00FF00) >> 8)); fprintf(bmpFile, "%c", (char)((rawImgData[x][y] & 0xFF0000) >> 16)); // print offset bytes if (x == xSize-1) for (i=0; i < xSize % 4; i++) fprintf(bmpFile, "%c", (char)0); } } // write 16 bits per pixel bmp file if (bitsPerPix == 16) { // file size fprintf(bmpFile, "%c", (char)((bmpDataSize + 0x36) & 0xFF)); fprintf(bmpFile, "%c", (char)((bmpDataSize + 0x36) >> 8 & 0xFF)); fprintf(bmpFile, "%c", (char)((bmpDataSize + 0x36) >> 16 & 0xFF)); fprintf(bmpFile, "%c", (char)((bmpDataSize + 0x36) >> 24 & 0xFF)); // reserved1 and 2 for (i=0; i < 4; i++) fprintf(bmpFile, "%c", 0); // file offset to pixel array fprintf(bmpFile, "%c", 0x36); fprintf(bmpFile, "%c", 0); fprintf(bmpFile, "%c", 0); fprintf(bmpFile, "%c", 0); // dib header size fprintf(bmpFile, "%c", 0x28); fprintf(bmpFile, "%c", 0); fprintf(bmpFile, "%c", 0); fprintf(bmpFile, "%c", 0); // image width fprintf(bmpFile, "%c", (char)(xSize & 0xFF)); fprintf(bmpFile, "%c", (char)(xSize >> 8 & 0xFF)); fprintf(bmpFile, "%c", (char)(xSize >> 16 & 0xFF)); fprintf(bmpFile, "%c", (char)(xSize >> 24 & 0xFF)); // image height fprintf(bmpFile, "%c", (char)(ySize & 0xFF)); fprintf(bmpFile, "%c", (char)(ySize >> 8 & 0xFF)); fprintf(bmpFile, "%c", (char)(ySize >> 16 & 0xFF)); fprintf(bmpFile, "%c", (char)(ySize >> 24 & 0xFF)); // number of planes fprintf(bmpFile, "%c", 1); fprintf(bmpFile, "%c", 0); // number of bits per pixel fprintf(bmpFile, "%c", 16); fprintf(bmpFile, "%c", 0); // compression for (i=0; i < 4; i++) fprintf(bmpFile, "%c", 0); // image size fprintf(bmpFile, "%c", (char)(bmpDataSize & 0xFF)); fprintf(bmpFile, "%c", (char)(bmpDataSize >> 8 & 0xFF)); fprintf(bmpFile, "%c", (char)(bmpDataSize >> 16 & 0xFF)); fprintf(bmpFile, "%c", (char)(bmpDataSize >> 24 & 0xFF)); // x pixels per meter for (i=0; i < 4; i++) fprintf(bmpFile, "%c", 0); // y pixels per meter for (i=0; i < 4; i++) fprintf(bmpFile, "%c", 0); // colors in color table for (i=0; i < 4; i++) fprintf(bmpFile, "%c", 0); // important color count for (i=0; i < 4; i++) fprintf(bmpFile, "%c", 0); int r, g, b; int pix16bit; // image data for (y=ySize-1; y >= 0; y--) for (x=0; x < xSize; x++) { r = (rawImgData[x][y] & 0xFF0000) >> 16; g = (rawImgData[x][y] & 0x00FF00) >> 8; b = rawImgData[x][y] & 0x0000FF; pix16bit = (r >> 3 << 10) + (g >> 3 << 5) + (b >> 3); fprintf(bmpFile, "%c", (char)(pix16bit & 0x0000FF)); fprintf(bmpFile, "%c", (char)((pix16bit & 0x00FF00) >> 8)); if (x == xSize-1) for (i=0; i < (xSize % 2) * 2; i++) fprintf(bmpFile, "%c", (char)0x0);// add offset } } // write 8 bits per pixel bmp file if (bitsPerPix == 8) { // file size fprintf(bmpFile, "%c", (char)((bmpDataSize + 0x36 + 256 * 4) & 0xFF)); fprintf(bmpFile, "%c", (char)((bmpDataSize + 0x36 + 256 * 4) >> 8 & 0xFF)); fprintf(bmpFile, "%c", (char)((bmpDataSize + 0x36 + 256 * 4) >> 16 & 0xFF)); fprintf(bmpFile, "%c", (char)((bmpDataSize + 0x36 + 256 * 4) >> 24 & 0xFF)); // reserved1 and 2 for (i=0; i < 4; i++) fprintf(bmpFile, "%c", 0); // file offset to pixel array fprintf(bmpFile, "%c", (char)((0x36 + 256 * 4) & 0xFF)); fprintf(bmpFile, "%c", (char)((0x36 + 256 * 4) >> 8 & 0xFF)); fprintf(bmpFile, "%c", (char)((0x36 + 256 * 4) >> 16 & 0xFF)); fprintf(bmpFile, "%c", (char)((0x36 + 256 * 4) >> 24 & 0xFF)); // dib header size fprintf(bmpFile, "%c", 0x28); fprintf(bmpFile, "%c", 0); fprintf(bmpFile, "%c", 0); fprintf(bmpFile, "%c", 0); // image width fprintf(bmpFile, "%c", (char)(xSize & 0xFF)); fprintf(bmpFile, "%c", (char)(xSize >> 8 & 0xFF)); fprintf(bmpFile, "%c", (char)(xSize >> 16 & 0xFF)); fprintf(bmpFile, "%c", (char)(xSize >> 24 & 0xFF)); // image height fprintf(bmpFile, "%c", (char)(ySize & 0xFF)); fprintf(bmpFile, "%c", (char)(ySize >> 8 & 0xFF)); fprintf(bmpFile, "%c", (char)(ySize >> 16 & 0xFF)); fprintf(bmpFile, "%c", (char)(ySize >> 24 & 0xFF)); // number of planes fprintf(bmpFile, "%c", 1); fprintf(bmpFile, "%c", 0); // number of bits per pixel fprintf(bmpFile, "%c", 8); fprintf(bmpFile, "%c", 0); // compression for (i=0; i < 4; i++) fprintf(bmpFile, "%c", 0); // image size fprintf(bmpFile, "%c", (char)(bmpDataSize & 0xFF)); fprintf(bmpFile, "%c", (char)(bmpDataSize >> 8 & 0xFF)); fprintf(bmpFile, "%c", (char)(bmpDataSize >> 16 & 0xFF)); fprintf(bmpFile, "%c", (char)(bmpDataSize >> 24 & 0xFF)); // x pixels per meter for (i=0; i < 4; i++) fprintf(bmpFile, "%c", 0); // y pixels per meter for (i=0; i < 4; i++) fprintf(bmpFile, "%c", 0); // colors in color table fprintf(bmpFile, "%c", (char)(256 & 0xFF)); fprintf(bmpFile, "%c", (char)(256 >> 8 & 0xFF)); fprintf(bmpFile, "%c", (char)(256 >> 16 & 0xFF)); fprintf(bmpFile, "%c", (char)(256 >> 24 & 0xFF)); // important color count fprintf(bmpFile, "%c", (char)(256 & 0xFF)); fprintf(bmpFile, "%c", (char)(256 >> 8 & 0xFF)); fprintf(bmpFile, "%c", (char)(256 >> 16 & 0xFF)); fprintf(bmpFile, "%c", (char)(256 >> 24 & 0xFF)); colorTableCnt = 0; // used for pointing to the color table for each color on an image int **colorImgData; colorImgData = (int **)malloc(xSize * sizeof(int *)); for (i = 0; i < xSize; i++) colorImgData[i] = (int *)malloc(ySize * sizeof(int)); // create color table for (y=ySize-1; y >= 0; y--) for (x=0; x < xSize; x++) { for (i=0; i < 256; i++) { if (i > colorTableCnt) break; if (i < colorTableCnt) if (colorTable[i] == rawImgData[x][y]) break; if (i == colorTableCnt) { colorTable[i] = rawImgData[x][y]; colorTableCnt++; break; } } colorImgData[x][y] = i; } // color table for (i=0; i < 256; i++) { fprintf(bmpFile, "%c", (char)colorTable[i] & 0x0000FF); fprintf(bmpFile, "%c", (char)((colorTable[i] & 0x00FF00) >> 8)); fprintf(bmpFile, "%c", (char)((colorTable[i] & 0xFF0000) >> 16)); fprintf(bmpFile, "%c", 0); } // image data for (y=ySize-1; y >= 0; y--) for (x=0; x < xSize; x++) { fprintf(bmpFile, "%c", (char)colorImgData[x][y]); if (x == xSize-1) for (i=0; i < 3-((xSize-1)%4); i++) fprintf(bmpFile, "%c", (char)0x0);// add offset } for (i = 0; i < xSize; i++) free(colorImgData[i]); free(colorImgData); } // write 4 bits per pixel bmp file if (bitsPerPix == 4) { // file size fprintf(bmpFile, "%c", (char)((bmpDataSize + 0x36 + 16 * 4) & 0xFF)); fprintf(bmpFile, "%c", (char)((bmpDataSize + 0x36 + 16 * 4) >> 8 & 0xFF)); fprintf(bmpFile, "%c", (char)((bmpDataSize + 0x36 + 16 * 4) >> 16 & 0xFF)); fprintf(bmpFile, "%c", (char)((bmpDataSize + 0x36 + 16 * 4) >> 24 & 0xFF)); // reserved1 and 2 for (i=0; i < 4; i++) fprintf(bmpFile, "%c", 0); // file offset to pixel array fprintf(bmpFile, "%c", (char)((0x36 + 16 * 4) & 0xFF)); fprintf(bmpFile, "%c", (char)((0x36 + 16 * 4) >> 8 & 0xFF)); fprintf(bmpFile, "%c", (char)((0x36 + 16 * 4) >> 16 & 0xFF)); fprintf(bmpFile, "%c", (char)((0x36 + 16 * 4) >> 24 & 0xFF)); // dib header size fprintf(bmpFile, "%c", 0x28); fprintf(bmpFile, "%c", 0); fprintf(bmpFile, "%c", 0); fprintf(bmpFile, "%c", 0); // image width fprintf(bmpFile, "%c", (char)(xSize & 0xFF)); fprintf(bmpFile, "%c", (char)(xSize >> 8 & 0xFF)); fprintf(bmpFile, "%c", (char)(xSize >> 16 & 0xFF)); fprintf(bmpFile, "%c", (char)(xSize >> 24 & 0xFF)); // image height fprintf(bmpFile, "%c", (char)(ySize & 0xFF)); fprintf(bmpFile, "%c", (char)(ySize >> 8 & 0xFF)); fprintf(bmpFile, "%c", (char)(ySize >> 16 & 0xFF)); fprintf(bmpFile, "%c", (char)(ySize >> 24 & 0xFF)); // number of planes fprintf(bmpFile, "%c", 1); fprintf(bmpFile, "%c", 0); // number of bits per pixel fprintf(bmpFile, "%c", 4); fprintf(bmpFile, "%c", 0); // compression for (i=0; i < 4; i++) fprintf(bmpFile, "%c", 0); // image size fprintf(bmpFile, "%c", (char)(bmpDataSize & 0xFF)); fprintf(bmpFile, "%c", (char)(bmpDataSize >> 8 & 0xFF)); fprintf(bmpFile, "%c", (char)(bmpDataSize >> 16 & 0xFF)); fprintf(bmpFile, "%c", (char)(bmpDataSize >> 24 & 0xFF)); // x pixels per meter for (i=0; i < 4; i++) fprintf(bmpFile, "%c", 0); // y pixels per meter for (i=0; i < 4; i++) fprintf(bmpFile, "%c", 0); // colors in color table fprintf(bmpFile, "%c", (char)(16 & 0xFF)); fprintf(bmpFile, "%c", (char)(16 >> 8 & 0xFF)); fprintf(bmpFile, "%c", (char)(16 >> 16 & 0xFF)); fprintf(bmpFile, "%c", (char)(16 >> 24 & 0xFF)); // important color count fprintf(bmpFile, "%c", (char)(16 & 0xFF)); fprintf(bmpFile, "%c", (char)(16 >> 8 & 0xFF)); fprintf(bmpFile, "%c", (char)(16 >> 16 & 0xFF)); fprintf(bmpFile, "%c", (char)(16 >> 24 & 0xFF)); colorTableCnt = 0; // create color table for (y=ySize-1; y >= 0; y--) for (x=0; x < xSize; x++) { for (i=0; i < 16; i++) { if (i > colorTableCnt) break; if (i < colorTableCnt) if (colorTable[i] == rawImgData[x][y]) break; if (i == colorTableCnt) { colorTable[i] = rawImgData[x][y]; colorTableCnt++; break; } } } // color table for (i=0; i < 16; i++) { fprintf(bmpFile, "%c", (char)colorTable[i] & 0x0000FF); fprintf(bmpFile, "%c", (char)((colorTable[i] & 0x00FF00) >> 8)); fprintf(bmpFile, "%c", (char)((colorTable[i] & 0xFF0000) >> 16)); fprintf(bmpFile, "%c", 0); } int pix4bpp1, pix4bpp2; int flipFlop = 1; int offsetFlipFlop = 0; int color; // image data for (y=ySize-1; y >= 0; y--) for (x=0; x < xSize; x++) { color = 0; for (i=0; i < 16; i++) if (rawImgData[x][y] == colorTable[i]) color = i; // add offset if (x == xSize-1) if (xSize % 2)// if odd for (i=0; i < 3-(int)(((xSize-1)%8)/2); i++)//1=2,2=3,3=3,4=0,5=0,6=1,7=1,8=2 fprintf(bmpFile, "%c", (char)color<<4); // add extra offset if (x == xSize-1) if (xSize % 2)// if odd { pix4bpp1 = 0;// load 0 pix4bpp2 = 0; offsetFlipFlop = !offsetFlipFlop; } if (!flipFlop) { pix4bpp1 = color; if (!offsetFlipFlop) fprintf(bmpFile, "%c", (char)(pix4bpp1 | (pix4bpp2 << 4))); } // add offset if (x == xSize-1) if (!(xSize % 2))// if even for (i=0; i < 3-(int)(((xSize-1)%8)/2); i++)//1=2,2=3,3=3,4=0,5=0,6=1,7=1,8=2 fprintf(bmpFile, "%c", (char)color<<4); if (flipFlop) { pix4bpp2 = color; if (offsetFlipFlop) fprintf(bmpFile, "%c", (char)(pix4bpp2 | (pix4bpp1 << 4))); } flipFlop = !flipFlop; } } // write 1 bit per pixel bmp file if (bitsPerPix == 1) { // file size fprintf(bmpFile, "%c", (char)((bmpDataSize + 0x36 + 2 * 4) & 0xFF)); fprintf(bmpFile, "%c", (char)((bmpDataSize + 0x36 + 2 * 4) >> 8 & 0xFF)); fprintf(bmpFile, "%c", (char)((bmpDataSize + 0x36 + 2 * 4) >> 16 & 0xFF)); fprintf(bmpFile, "%c", (char)((bmpDataSize + 0x36 + 2 * 4) >> 24 & 0xFF)); // reserved1 and 2 for (i=0; i < 4; i++) fprintf(bmpFile, "%c", 0); // file offset to pixel array fprintf(bmpFile, "%c", (char)((0x36 + 2 * 4) & 0xFF)); fprintf(bmpFile, "%c", (char)((0x36 + 2 * 4) >> 8 & 0xFF)); fprintf(bmpFile, "%c", (char)((0x36 + 2 * 4) >> 16 & 0xFF)); fprintf(bmpFile, "%c", (char)((0x36 + 2 * 4) >> 24 & 0xFF)); // dib header size fprintf(bmpFile, "%c", 0x28); fprintf(bmpFile, "%c", 0); fprintf(bmpFile, "%c", 0); fprintf(bmpFile, "%c", 0); // image width fprintf(bmpFile, "%c", (char)(xSize & 0xFF)); fprintf(bmpFile, "%c", (char)(xSize >> 8 & 0xFF)); fprintf(bmpFile, "%c", (char)(xSize >> 16 & 0xFF)); fprintf(bmpFile, "%c", (char)(xSize >> 24 & 0xFF)); // image height fprintf(bmpFile, "%c", (char)(ySize & 0xFF)); fprintf(bmpFile, "%c", (char)(ySize >> 8 & 0xFF)); fprintf(bmpFile, "%c", (char)(ySize >> 16 & 0xFF)); fprintf(bmpFile, "%c", (char)(ySize >> 24 & 0xFF)); // number of planes fprintf(bmpFile, "%c", 1); fprintf(bmpFile, "%c", 0); // number of bits per pixel fprintf(bmpFile, "%c", 1); fprintf(bmpFile, "%c", 0); // compression for (i=0; i < 4; i++) fprintf(bmpFile, "%c", 0); // image size fprintf(bmpFile, "%c", (char)(bmpDataSize & 0xFF)); fprintf(bmpFile, "%c", (char)(bmpDataSize >> 8 & 0xFF)); fprintf(bmpFile, "%c", (char)(bmpDataSize >> 16 & 0xFF)); fprintf(bmpFile, "%c", (char)(bmpDataSize >> 24 & 0xFF)); // x pixels per meter for (i=0; i < 4; i++) fprintf(bmpFile, "%c", 0); // y pixels per meter for (i=0; i < 4; i++) fprintf(bmpFile, "%c", 0); // colors in color table fprintf(bmpFile, "%c", (char)(2 & 0xFF)); fprintf(bmpFile, "%c", (char)(2 >> 8 & 0xFF)); fprintf(bmpFile, "%c", (char)(2 >> 16 & 0xFF)); fprintf(bmpFile, "%c", (char)(2 >> 24 & 0xFF)); // important color count fprintf(bmpFile, "%c", (char)(2 & 0xFF)); fprintf(bmpFile, "%c", (char)(2 >> 8 & 0xFF)); fprintf(bmpFile, "%c", (char)(2 >> 16 & 0xFF)); fprintf(bmpFile, "%c", (char)(2 >> 24 & 0xFF)); colorTableCnt = 0; // create color table for (y=ySize-1; y >= 0; y--) for (x=0; x < xSize; x++) { for (i=0; i < 2; i++) { if (i > colorTableCnt) break; if (i < colorTableCnt) if (colorTable[i] == rawImgData[x][y]) break; if (i == colorTableCnt) { colorTable[i] = rawImgData[x][y]; colorTableCnt++; break; } } } // color table for (i=0; i < 2; i++) { fprintf(bmpFile, "%c", (char)colorTable[i] & 0x0000FF); fprintf(bmpFile, "%c", (char)((colorTable[i] & 0x00FF00) >> 8)); fprintf(bmpFile, "%c", (char)((colorTable[i] & 0xFF0000) >> 16)); fprintf(bmpFile, "%c", 0); } int pix1bpp = 0; int bitShift; int color; i = 0; // image data for (y=ySize-1; y >= 0; y--) for (x=0; x < xSize; x++) { color = 0; if (rawImgData[x][y] == colorTable[0]) color = 0; if (rawImgData[x][y] == colorTable[1]) color = 1; // add offset if (x == xSize-1) { i = i + 31-(xSize-1)%32; pix1bpp = pix1bpp | (color << (31-(xSize-1)%32) % 8); if (31-(xSize-1)%32 >= 8) fprintf(bmpFile, "%c", (char)pix1bpp); if (31-(xSize-1)%32 >= 16) fprintf(bmpFile, "%c", (char)0); if (31-(xSize-1)%32 >= 24) fprintf(bmpFile, "%c", (char)0); } bitShift = i % 8; if (bitShift < 4) { if (bitShift < 2) { if (bitShift == 0) pix1bpp = pix1bpp | (color << 7); if (bitShift == 1) pix1bpp = pix1bpp | (color << 6); } else { if (bitShift == 2) pix1bpp = pix1bpp | (color << 5); if (bitShift == 3) pix1bpp = pix1bpp | (color << 4); } } else { if (bitShift < 6) { if (bitShift == 4) pix1bpp = pix1bpp | (color << 3); if (bitShift == 5) pix1bpp = pix1bpp | (color << 2); } else { if (bitShift == 6) pix1bpp = pix1bpp | (color << 1); if (bitShift == 7) pix1bpp = pix1bpp | color; if (bitShift == 7) { fprintf(bmpFile, "%c", (char)pix1bpp); pix1bpp = 0; } } } i++; } } fclose(bmpFile); }
the_stack_data/170453442.c
/* The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832. *see code for number* Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product? */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <locale.h> #define ADJ_DIGITS 13 unsigned long long int get_product(char *arr) { int len = strlen(arr); int value; unsigned long long int product = 1; for(int i = 0; i < len; i++) { value = arr[i] - '0'; // quick and dirty char to int conversion product *= value; } return product; } int main(void) { char largenum[] = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"; char digits[ADJ_DIGITS + 1]; unsigned long long int product; unsigned long long int maxProduct = 0; char maxDigits[ADJ_DIGITS + 1]; int sizelargenum = strlen(largenum); memset(digits, '\0', sizeof(digits)); memset(maxDigits, '\0', sizeof(maxDigits)); for(int i = 0; i <= sizelargenum; i++) { strncpy(digits, largenum + i, ADJ_DIGITS); product = get_product(digits); if (product > maxProduct) { maxProduct = product; memcpy(maxDigits, digits, strlen(digits) + 1); } } setlocale(LC_NUMERIC, ""); printf("max: %'llu\n", maxProduct); printf("adjacent digits: %s\n", maxDigits); return 0; }
the_stack_data/59513414.c
#include <stdlib.h> #include <stdio.h> int main (void) { int i = 0, j = 1, k; float *vec; float aux, media; vec = malloc (sizeof (float) * 4); scanf ("%f %f %f %f", &vec[0], &vec[1], &vec[2], &vec[3]); for (k = 0; k < 3; k++) { j = 1; i = 0; while (i < 3) { if (vec[j] < vec[i]) { aux = vec[j]; vec[j] = vec[i]; vec[i] = aux; } i++; j++; } } media = (vec[1] + vec[2] + vec[3]) / 3; printf ("%.4f\n", media); free (vec); return 0; }
the_stack_data/43887896.c
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { FILE *arq; char aux, *texto; if (argc < 2) { printf("\nErro! Não foi informado o nome do arquivo.\n\n"); return 0; } arq = fopen(argv[1], "r+"); if (arq == NULL) { printf("\nErro ao abrir o arquivo.\n\n"); return 0; } int i = 0; while (fscanf(arq, "%c", &aux) != EOF) { i++; } texto = malloc((i+1) * sizeof(char)); rewind(arq); i = 0; while (fscanf(arq, "%c", &aux) != EOF) { texto[i] = aux; i++; } texto[i] = '\0'; for (int j = 0; j < i; j++) { switch (texto[j]) { case 'a': texto[j] = 'A'; break; case 'e': texto[j] = 'E'; break; case 'i': texto[j] = 'I'; break; case 'o': texto[j] = 'O'; break; case 'u': texto[j] = 'U'; break; default: break; } } rewind(arq); fprintf(arq, "%s", texto); fclose(arq); return 0; }
the_stack_data/220454816.c
#include<stdio.h> int main(void){ int a,b,i,j=1,flag; while(scanf("%d %d",&a,&b),a,b) { flag=0; if(j!=1)printf("\n"); for(i=a;i<=b;i++){ if(i%100==0 && i%400==0){ printf("%d\n",i); flag=1; } else if(i%4==0 && i%100!=0){ printf("%d\n",i); flag=1; } } if(flag==0)printf("NA\n"); j++; } return 0; }
the_stack_data/87637198.c
#define __offsetof(type, member) __builtin_offsetof (type, member) typedef unsigned long size_t; struct list_head { struct list_head *next, *prev; }; static __inline__ void prefetch(const void *x) {;} struct range { struct list_head list; unsigned long s, e; }; struct rangeset { struct list_head rangeset_list; // struct domain *domain; struct list_head range_list; // spinlock_t lock; char name[32]; unsigned int flags; }; static struct range *find_range( struct rangeset *r, unsigned long s) { struct range *x = ((void*)0), *y; // for (y = ({ typeof( ((typeof(*y) *)0)->list ) *__mptr = ((&r->range_list)->next); (typeof(*y) *)( (char *)__mptr - __builtin_offsetof(typeof(*y),list) );}); // for (y = ({ typeof( ((typeof(*y) *)0)->list ) *__mptr = 0L; (typeof(*y) *)( (char *)__mptr - __builtin_offsetof(typeof(*y),list) );}); // for (y = ({ typeof( ((typeof(*y) *)0)->list ) *__mptr = 0L; (typeof(*y) *) ( (char *)__mptr - 0L );}); for (y = ({ typeof( ((typeof(*y) *)0)->list ) *__mptr = 0L; (typeof(*y) *)( (char *)__mptr - __builtin_offsetof(typeof(*y),list) );}); // prefetch(y->list.next), &y->list != (&r->range_list); 0; // y = ({ typeof( ((typeof(*y) *)0)->list ) *__mptr = (y->list.next); (typeof(*y) *)( (char *)__mptr - __builtin_offsetof(typeof(*y),list) );})) y++) { if ( y->s > s ) break; x = y; } return x; }
the_stack_data/114482.c
/* Exercise 6-2: deliberately broken longjmp */ #include <stdlib.h> #include <stdio.h> #include <setjmp.h> static jmp_buf jmp_env; void a (void); void b (void); void a (void) { if (setjmp(jmp_env) == 0) { printf("first time setjmp\n"); } else { printf("jumping with longjmp\n"); } } void b (void) { longjmp(jmp_env, 1); } int main (int argc, char *argv[]) { printf("before a()\n"); a(); printf("before b()\n"); b(); printf("after b()\n"); exit(EXIT_SUCCESS); }
the_stack_data/132952775.c
#include<stdio.h> int main(){ int n1,n2; printf("N1: "); scanf("%d", &n1); printf("N2: "); scanf("%d", &n2); printf("A soma é: %d", n1+n2); return 0; }
the_stack_data/64201616.c
#include <stdio.h> int main() { char **s = malloc(sizeof(char*)); // MODIFIED char foo[] = "Hello World"; *s = foo; printf("s is %p\n",s); // MODIFIED s[0] = foo; printf("s[0] is %s\n",s[0]); return(0); }
the_stack_data/6389060.c
/* Copyright 2014-2016 Free Software Foundation, Inc. This file is part of GDB. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ extern int v; asm (".hello_start: .globl .hello_start\n"); void hello (void) { asm (".hello0: .globl .hello0\n"); v++; asm (".hello1: .globl .hello1\n"); } asm (".hello_end: .globl .hello_end\n");
the_stack_data/165768898.c
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <signal.h> #include <unistd.h> #include <sys/stat.h> int main(int argc, char *argv[]) { int i; if(argc < 2){ printf("Usage: mkdir files...\n"); exit(0); } for(i = 1; i < argc; i++){ if(mkdir(argv[i], S_IRWXU|S_IRWXG|S_IRWXO) < 0){ printf("mkdir: %s failed to create\n", argv[i]); break; } } exit(0); }
the_stack_data/178264694.c
/* create_file.c This function creates the file "name" if it does not already exist. Returns 0 for success, 1 for file already exists, and -1 for an error condition. Written by Matthew Campbell. (12-15-17) */ #ifndef _CREATE_FILE_C #define _CREATE_FILE_C #include <stdio.h> int does_file_exist( const char *name ); int create_file( const char *name ) { FILE *fp; int ret; if ( name == NULL || name[ 0 ] == 0 ) { return ( -1 ); /* Invalid file name. */ } ret = does_file_exist( name ); if ( ret == ( -1 ) ) { return ( -1 ); /* Error. */ } else if ( ret == 1 ) { return 1; /* File already exists. */ } fp = fopen( name, "w" ); if ( fp == NULL ) { return ( -1 ); /* Error. */ } fclose( fp ); fp = NULL; ret = does_file_exist( name ); if ( ret != 1 ) { return ( -1 ); /* Error. */ } return 0; /* Success. */ } #endif /* _CREATE_FILE_C */ /* EOF create_file.c */
the_stack_data/24739.c
#include<stdio.h> #include<math.h> main() { float a,b,x,c,d,x1,x2; printf("Digite o valor de A:"); scanf("%f",&a); printf("Digite o valor de B:"); scanf("%f",&b); printf("Digite o valor de C:"); scanf("%f",&c); d = pow(b,2) - 4 * a * c; if (d < 0) { printf("Nao existe a raiz real\n"); } if (d == 0) { printf("Existe uma raiz real!\n"); x = (-b)/(2*a); printf("A raiz: %f",x); } if (d>0) { printf("Existem duas raizes reais\n"); x1 =((-b + sqrt(d)/(2*a) )); x2 = ((-b - sqrt(d)/(2*a))); printf("X1 = %f , x2 = % f\n",x1,x2); } }
the_stack_data/930221.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #define contSpace 8 struct arvore{ int info; struct arvore *esq; struct arvore *dir; }; typedef struct arvore Arvore; // ------------ INICIA ---------------------- // Arvore* inicializa() { return NULL; } // --------------------------------------- // // ------------ INSER��O ------------------- // Arvore* insert(int data, Arvore *left, Arvore *right) { Arvore *node = (Arvore*)malloc(sizeof(Arvore)); node->info = data; node->dir = right; node->esq = left; return node; } // --------------------------------------- // // ------------ VAZIA --------------------- // int *vazia(Arvore *a) { return a == NULL; } // --------------------------------------- // // ------------ IMPRIME ------------------- // void imprime_alt(Arvore* a) { if (!vazia(a)){ if (a->info == 6) printf("<"); printf("%d", a->info); printf("<"); imprime_alt(a->esq); printf(">"); printf("<"); imprime_alt(a->dir); printf(">"); if (a->info == 6) printf(">"); } } // --------------------------------------- // // ------------ ALTURA ------------------- // int alturaArvore(Arvore* node) { if (node == NULL) return -1; else { int alturaEsquerda = alturaArvore(node->esq); int alturaDireita = alturaArvore(node->dir); if (alturaEsquerda < alturaDireita) return alturaDireita + 1; else return alturaEsquerda + 1; } } // --------------------------------------- // // ------------ BUSCA -------------------- // int busca(Arvore* a, int c){ if (vazia(a)) return 0; else return a->info==c || busca(a->esq,c) || busca(a->dir,c); } // --------------------------------------- // // ------------ IGUAIS? ------------------ // int iguais(Arvore *a, Arvore *b) { if(!vazia(a)) { iguais(a->esq, b->esq); iguais(a->dir, b->dir); if(a->info != b->info) { printf("\nAs Árvore são diferentes"); printf("\nDiferentes: %d", a->info); printf(" %d", b->info); return 0; exit(1); } else { printf("\n%d", a->info); printf(" %d", b->info); } } } // --------------------------------------- // // ------------ Pré ordem ------------------- // Arvore* preOrdem(Arvore* a) { // pré-ordem: trata raiz, percorre sae, percorre sad if (!vazia(a)) { printf("%d ", a->info); preOrdem(a->esq); preOrdem(a->dir); } return 1; } // --------------------------------------- // // ------------ Pré ordem ------------------- // Arvore* ordemSimetrica(Arvore* a) { // ordem simétrica: percorre sae, trata raiz, percorre sad; if (!vazia(a)) { ordemSimetrica(a->esq); printf("%d ", a->info); ordemSimetrica(a->dir); } return 1; } // --------------------------------------- // // ------------ Pré ordem ------------------- // Arvore* posOrdem(Arvore* a) { // pós-ordem: percorre sae, percorre sad, trata raiz. if (!vazia(a)) { posOrdem(a->esq); posOrdem(a->dir); printf("%d ", a->info); } return 1; } // --------------------------------------- // // ------------ LIBERA ------------------- // Arvore* liberaTodosNodes(Arvore* a){ if (!vazia(a)){ liberaTodosNodes(a->esq); liberaTodosNodes(a->dir); free(a); } return NULL; } // --------------------------------------- // // ------------ IMPRIME 2D --------------- // void display_em_2D(Arvore* node, int espaco) { int i; if (node == NULL) { return; } espaco += contSpace; display_em_2D(node->dir, espaco); printf("\n"); for (i = contSpace; i < espaco; i++) { printf(" "); } printf("%d\n", node->info); display_em_2D(node->esq, espaco); } // --------------------------------------- // // ------------ IMPRIME 2D --------------- // void display_2D(Arvore* node) { display_em_2D(node, 0); } // --------------------------------------- // // ------------ FOLHAS++ ----------------- // int folhas(Arvore* a) { if(a == NULL) { return 0; } if(a->esq == a->dir) { return 1; } return folhas(a->esq) + folhas(a->dir); } // --------------------------------------- // // ------------ FOLHAS+= ----------------- // int folhasSoma(Arvore* a) { int x=0; if(a == NULL) { return 0; } if(a->esq == a->dir) { return 1; } folhasSoma(a->esq); x += a->esq->info + a->dir->info; printf("\n%d + %d: %d", a->esq->info, a->dir->info, x); folhasSoma(a->dir); return x; } // --------------------------------------- // // ------------ MAIN -------------------- // int main() { Arvore* a9 = insert(1, inicializa(), inicializa()); Arvore* a8 = insert(8, inicializa(), inicializa()); Arvore* a7 = insert(4, a8, a9); Arvore* a6 = insert(7, inicializa(), inicializa()); Arvore* a5 = insert(0, inicializa(), inicializa()); Arvore* a4 = insert(3, a6, a5); Arvore* a3 = insert(9, inicializa(), inicializa()); Arvore* a2 = insert(4, inicializa(), inicializa()); Arvore* a1 = insert(2, a3, a2); Arvore* b9 = insert(5, a4, a1); Arvore* b8 = insert(6, b9, a7); printf("========PRE-ORDEM==========\n"); preOrdem(b8); printf("\n\n========Ordem-Simetrica==========\n"); ordemSimetrica(b8); printf("\n\n========POS-ORDEM==========\n"); posOrdem(b8); printf("\n\n--------- Busca ---------------------\n"); if((busca(b8, 88))==1) { printf("Elemento encontra-se na Árvore"); } else { printf("\nElemento não encontra-se na Árvore"); } printf("\n--------- Hierarquia ----------------\n\n"); imprime_alt(b8); printf("\n\n-------------------------------------\n"); printf("\nAltura da Árvore: %d\n", alturaArvore(b8)); printf("\n\n-------------------------------------\n"); printf("\nQuantidade de folhas: %d", folhas(b8)); printf("\n\n-------------------------------------\n"); printf("\nSoma das folhas: %d", folhasSoma(b8)); printf("\n\n--------- Árvore --------------------\n"); display_2D(b8); //printf("\n\n----------- Libera -----------------\n"); //liberaTodosNodes(b8); //display_2D(b8); /* printf("------------------------------------\n"); printf("\nPrimeira Arvore\n"); Arvore *c6 = insert(1, inicializa(), inicializa()); Arvore *c5 = insert(2, inicializa(), inicializa()); Arvore *c4 = insert(3, c5, c6); Arvore *c3 = insert(4, inicializa(), inicializa()); Arvore *c2 = insert(5, inicializa(), c3); Arvore *c1 = insert(6, c2, c4); imprime_alt(c1); printf("\n"); printf("\n"); printf("Segunda Arvore\n"); Arvore *d6 = insert(1, inicializa(), inicializa()); Arvore *d5 = insert(2, inicializa(), inicializa()); Arvore *d4 = insert(7, d5, d6); Arvore *d3 = insert(4, inicializa(), inicializa()); Arvore *d2 = insert(5, inicializa(), d3); Arvore *d1 = insert(6, d2, d4); imprime_alt(d1); puts(""); iguais(c1, d1); */ } // --------------------------------------- //
the_stack_data/182954105.c
// gcc -o md5 -O3 -lm -DMAIN md5.c /* * Simple MD5 implementation * * Compile with: gcc -o md5 -O3 -lm md5.c * from: https://gist.github.com/creationix/4710780 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> // leftrotate function definition #define LEFTROTATE(x, c) (((x) << (c)) | ((x) >> (32 - (c)))) // These vars will contain the hash uint32_t h0, h1, h2, h3; void md5(uint8_t *initial_msg, size_t initial_len) { // Message (to prepare) uint8_t *msg = NULL; // Note: All variables are unsigned 32 bit and wrap modulo 2^32 when calculating // r specifies the per-round shift amounts uint32_t r[] = {7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21}; // Use binary integer part of the sines of integers (in radians) as constants// Initialize variables: uint32_t k[] = { 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391}; h0 = 0x67452301; h1 = 0xefcdab89; h2 = 0x98badcfe; h3 = 0x10325476; // Pre-processing: adding a single 1 bit //append "1" bit to message /* Notice: the input bytes are considered as bits strings, where the first bit is the most significant bit of the byte.[37] */ // Pre-processing: padding with zeros //append "0" bit until message length in bit ≡ 448 (mod 512) //append length mod (2 pow 64) to message int new_len = ((((initial_len + 8) / 64) + 1) * 64) - 8; msg = calloc(new_len + 64, 1); // also appends "0" bits // (we alloc also 64 extra bytes...) memcpy(msg, initial_msg, initial_len); msg[initial_len] = 128; // write the "1" bit uint32_t bits_len = 8*initial_len; // note, we append the len memcpy(msg + new_len, &bits_len, 4); // in bits at the end of the buffer // Process the message in successive 512-bit chunks: //for each 512-bit chunk of message: int offset; for(offset=0; offset<new_len; offset += (512/8)) { // break chunk into sixteen 32-bit words w[j], 0 ≤ j ≤ 15 uint32_t *w = (uint32_t *) (msg + offset); #ifdef DEBUG printf("offset: %d %x\n", offset, offset); int j; for(j =0; j < 64; j++) printf("%x ", ((uint8_t *) w)[j]); puts(""); #endif // Initialize hash value for this chunk: uint32_t a = h0; uint32_t b = h1; uint32_t c = h2; uint32_t d = h3; // Main loop: uint32_t i; for(i = 0; i<64; i++) { #ifdef ROUNDS uint8_t *p; printf("%i: ", i); p=(uint8_t *)&a; printf("%2.2x%2.2x%2.2x%2.2x ", p[0], p[1], p[2], p[3], a); p=(uint8_t *)&b; printf("%2.2x%2.2x%2.2x%2.2x ", p[0], p[1], p[2], p[3], b); p=(uint8_t *)&c; printf("%2.2x%2.2x%2.2x%2.2x ", p[0], p[1], p[2], p[3], c); p=(uint8_t *)&d; printf("%2.2x%2.2x%2.2x%2.2x", p[0], p[1], p[2], p[3], d); puts(""); #endif uint32_t f, g; if (i < 16) { f = (b & c) | ((~b) & d); g = i; } else if (i < 32) { f = (d & b) | ((~d) & c); g = (5*i + 1) % 16; } else if (i < 48) { f = b ^ c ^ d; g = (3*i + 5) % 16; } else { f = c ^ (b | (~d)); g = (7*i) % 16; } #ifdef ROUNDS printf("f=%x g=%d w[g]=%x\n", f, g, w[g]); #endif uint32_t temp = d; d = c; c = b; // printf("rotateLeft(%x + %x + %x + %x, %d)\n", a, f, k[i], w[g], r[i]); b = b + LEFTROTATE((a + f + k[i] + w[g]), r[i]); a = temp; } // Add this chunk's hash to result so far: h0 += a; h1 += b; h2 += c; h3 += d; } // cleanup free(msg); } char *md5str(uint8_t *msg, size_t len) { // store results as string char partial[32]; char *md5str = calloc(64, 1); md5(msg,len); uint8_t *p; p=(uint8_t *)&h0; sprintf(partial, "%2.2x%2.2x%2.2x%2.2x", p[0], p[1], p[2], p[3]); strcat(md5str, partial); p=(uint8_t *)&h1; sprintf(partial, "%2.2x%2.2x%2.2x%2.2x", p[0], p[1], p[2], p[3]); strcat(md5str, partial); p=(uint8_t *)&h2; sprintf(partial, "%2.2x%2.2x%2.2x%2.2x", p[0], p[1], p[2], p[3]); strcat(md5str, partial); p=(uint8_t *)&h3; sprintf(partial, "%2.2x%2.2x%2.2x%2.2x", p[0], p[1], p[2], p[3]); strcat(md5str, partial); // printf("%s\n", md5str); return md5str; } #ifdef MAIN int main(int argc, char **argv) { if (argc < 2) { printf("usage: %s 'string'\n", argv[0]); return 1; } char *msg = argv[1]; size_t len = strlen(msg); char* retstr = md5str(msg, len); printf("%s\n", retstr); free(retstr); return 0; } #endif
the_stack_data/915834.c
/**CFile**************************************************************** FileName [demo.c] SystemName [ABC: Logic synthesis and verification system.] PackageName [ABC as a static library.] Synopsis [A demo program illustrating the use of ABC as a static library.] Author [Alan Mishchenko] Affiliation [UC Berkeley] Date [Ver. 1.0. Started - June 20, 2005.] Revision [$Id: demo.c,v 1.00 2005/11/14 00:00:00 alanmi Exp $] ***********************************************************************/ #include <stdio.h> #include <time.h> //////////////////////////////////////////////////////////////////////// /// DECLARATIONS /// //////////////////////////////////////////////////////////////////////// // procedures to start and stop the ABC framework // (should be called before and after the ABC procedures are called) extern void Abc_Start(); extern void Abc_Stop(); // procedures to get the ABC framework and execute commands in it extern void * Abc_FrameGetGlobalFrame(); extern int Cmd_CommandExecute( void * pAbc, char * sCommand ); //////////////////////////////////////////////////////////////////////// /// FUNCTION DEFINITIONS /// //////////////////////////////////////////////////////////////////////// /**Function************************************************************* Synopsis [The main() procedure.] Description [This procedure compiles into a stand-alone program for DAG-aware rewriting of the AIGs. A BLIF or PLA file to be considered for rewriting should be given as a command-line argument. Implementation of the rewriting is inspired by the paper: Per Bjesse, Arne Boralv, "DAG-aware circuit compression for formal verification", Proc. ICCAD 2004.] SideEffects [] SeeAlso [] ***********************************************************************/ int main( int argc, char * argv[] ) { // parameters int fUseResyn2 = 0; int fPrintStats = 1; int fVerify = 1; // variables void * pAbc; char * pFileName; char Command[1000]; clock_t clkRead, clkResyn, clkVer, clk; ////////////////////////////////////////////////////////////////////////// // get the input file name if ( argc != 2 ) { printf( "Wrong number of command-line arguments.\n" ); return 1; } pFileName = argv[1]; ////////////////////////////////////////////////////////////////////////// // start the ABC framework Abc_Start(); pAbc = Abc_FrameGetGlobalFrame(); clk = clock(); ////////////////////////////////////////////////////////////////////////// // read the file sprintf( Command, "read %s", pFileName ); if ( Cmd_CommandExecute( pAbc, Command ) ) { fprintf( stdout, "Cannot execute command \"%s\".\n", Command ); return 1; } ////////////////////////////////////////////////////////////////////////// // balance sprintf( Command, "balance" ); if ( Cmd_CommandExecute( pAbc, Command ) ) { fprintf( stdout, "Cannot execute command \"%s\".\n", Command ); return 1; } clkRead = clock() - clk; ////////////////////////////////////////////////////////////////////////// // print stats if ( fPrintStats ) { sprintf( Command, "print_stats" ); if ( Cmd_CommandExecute( pAbc, Command ) ) { fprintf( stdout, "Cannot execute command \"%s\".\n", Command ); return 1; } } clk = clock(); ////////////////////////////////////////////////////////////////////////// // synthesize if ( fUseResyn2 ) { sprintf( Command, "balance; rewrite -l; refactor -l; balance; rewrite -l; rewrite -lz; balance; refactor -lz; rewrite -lz; balance" ); if ( Cmd_CommandExecute( pAbc, Command ) ) { fprintf( stdout, "Cannot execute command \"%s\".\n", Command ); return 1; } } else { sprintf( Command, "balance; rewrite -l; rewrite -lz; balance; rewrite -lz; balance" ); if ( Cmd_CommandExecute( pAbc, Command ) ) { fprintf( stdout, "Cannot execute command \"%s\".\n", Command ); return 1; } } clkResyn = clock() - clk; ////////////////////////////////////////////////////////////////////////// // print stats if ( fPrintStats ) { sprintf( Command, "print_stats" ); if ( Cmd_CommandExecute( pAbc, Command ) ) { fprintf( stdout, "Cannot execute command \"%s\".\n", Command ); return 1; } } ////////////////////////////////////////////////////////////////////////// // write the result in blif sprintf( Command, "write_blif result.blif" ); if ( Cmd_CommandExecute( pAbc, Command ) ) { fprintf( stdout, "Cannot execute command \"%s\".\n", Command ); return 1; } ////////////////////////////////////////////////////////////////////////// // perform verification clk = clock(); if ( fVerify ) { sprintf( Command, "cec %s result.blif", pFileName ); if ( Cmd_CommandExecute( pAbc, Command ) ) { fprintf( stdout, "Cannot execute command \"%s\".\n", Command ); return 1; } } clkVer = clock() - clk; printf( "Reading = %6.2f sec ", (float)(clkRead)/(float)(CLOCKS_PER_SEC) ); printf( "Rewriting = %6.2f sec ", (float)(clkResyn)/(float)(CLOCKS_PER_SEC) ); printf( "Verification = %6.2f sec\n", (float)(clkVer)/(float)(CLOCKS_PER_SEC) ); ////////////////////////////////////////////////////////////////////////// // stop the ABC framework Abc_Stop(); return 0; }
the_stack_data/31387890.c
//Program to implement binary search #include<stdio.h> int main(){ int arr[10],num,i,n,beg,end,mid; printf("\n Enter the number of elements in the array"); scanf("%d",&n); printf("\n Enter the elements: "); for(i=0;i<n;i++){ scanf("%d",&arr[i]); } printf("\n Enter the number that has to be searched: "); scanf("%d",&num); beg=0;end=n-1; while(beg<=end){ mid = (beg+end)/2; if(arr[mid]==num){ printf("\n %d is present in the array at postion %d",num,mid); break; } else if(arr[mid]>num) end=mid-1; else beg=mid+1; } if(beg>end){ printf("\n %d does not exist in the array",num); } return 0; }
the_stack_data/111079367.c
#include "stdio.h" #include "signal.h" #ifndef SIGIOT #ifdef SIGABRT #define SIGIOT SIGABRT #endif #endif #ifdef KR_headers void sig_die(s, kill) register char *s; int kill; #else #include "stdlib.h" #ifdef __cplusplus extern "C" { #endif extern void f_exit(void); void sig_die(register char *s, int kill) #endif { /* print error message, then clear buffers */ fprintf(stderr, "%s\n", s); if(kill) { fflush(stderr); f_exit(); fflush(stderr); /* now get a core */ #ifdef SIGIOT signal(SIGIOT, SIG_DFL); #endif abort(); } else { #ifdef NO_ONEXIT f_exit(); #endif exit(1); } } #ifdef __cplusplus } #endif
the_stack_data/89228.c
#include <stdio.h> #define MAX (26) #define TRUE (1) #define FALSE (0) #define INVALID (-1) int queue[2][(MAX + 1) * (MAX + 1)]; int push_queue, queue_index; int prev_length[MAX + 1]; int prev[MAX + 1][MAX + 1]; int next[MAX + 1][MAX + 1]; int visit[MAX + 1]; int N; char answer[MAX + 1]; char buffer[2][MAX + 1]; #define push(X) do { \ queue[push_queue][queue_index] = (X);\ ++queue_index;\ } while(0) int main(void) { int tc, T; int i, j, k; int input_buffer; int before_buffer; int pop_queue, queue_size; int answer_index; int t; // freopen("sample_input.txt", "r", stdin); setbuf(stdout, NULL); scanf("%d", &T); for (tc = 0; tc < T; ++tc) { scanf("%d\n", &N); input_buffer = 0; for (i = 0; i <= MAX; ++i) { for (j = 0; j <= MAX; ++j) { prev[i][j] = FALSE; next[i][j] = FALSE; } prev_length[i] = 0; answer[i] = 'a' + i; visit[i] = FALSE; } scanf("%s\n", &buffer[input_buffer][0]); if (N > 1) { answer_index = 0; push_queue = 0; queue_index = 0; for (k = 1; k < N; ++k) { before_buffer = input_buffer; input_buffer = !input_buffer; scanf("%s\n", &buffer[input_buffer][0]); for (i = 0; (buffer[input_buffer][i] != '\0') && (buffer[before_buffer][i] != '\0') && (buffer[input_buffer][i] == buffer[before_buffer][i]); ++i); if ((buffer[before_buffer][i] != '\0') && (buffer[input_buffer][i] == '\0')) { answer_index = INVALID; } else if ((buffer[before_buffer][i] != '\0') && (buffer[input_buffer][i] != '\0')) { if (prev[buffer[input_buffer][i] - 'a'][buffer[before_buffer][i] - 'a'] == FALSE) { prev[buffer[input_buffer][i] - 'a'][buffer[before_buffer][i] - 'a'] = TRUE; ++prev_length[buffer[input_buffer][i] - 'a']; } next[buffer[before_buffer][i] - 'a'][buffer[input_buffer][i] - 'a'] = TRUE; } } if (answer_index == 0) { for (i = 0; i < MAX; ++i) { if ((prev_length[i] == 0) && (visit[i] == FALSE)) push(i); } for (queue_size = queue_index; queue_size > 0; queue_size = queue_index) { pop_queue = push_queue; push_queue = !push_queue; queue_index = 0; for (i = 0; i < queue_size; ++i) { t = queue[pop_queue][i]; if (visit[t] == FALSE) { visit[t] = TRUE; answer[answer_index++] = 'a' + t; if (t == 14) t = 14; for (j = 0; j < MAX; ++j) { if (next[t][j] == TRUE) { prev[j][t] = FALSE; --prev_length[j]; } } } } for (i = 0; i < MAX; ++i) { if ((prev_length[i] == 0) && (visit[i] == FALSE)) push(i); } } } } else { answer_index = MAX; } if (answer_index < MAX) { printf("INVALID HYPOTHESIS"); } else { for (i = 0; i < MAX; ++i) printf("%c", answer[i]); } printf("\n"); } return 0; }
the_stack_data/147611.c
#ifndef DDEBUG #define DDEBUG 0 #endif #define _GNU_SOURCE #include <sys/types.h> #include <sys/socket.h> #include <sys/poll.h> #include <sys/uio.h> #include <sys/time.h> #include <dlfcn.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <errno.h> #if __linux__ #include <sys/eventfd.h> #include <sys/signalfd.h> #endif #if DDEBUG # define dd(...) \ fprintf(stderr, "mockeagain: "); \ fprintf(stderr, __VA_ARGS__); \ fprintf(stderr, " at %s line %d.\n", __FILE__, __LINE__) #else # define dd(...) #endif #define MAX_FD 1024 static void *libc_handle = NULL; static short active_fds[MAX_FD + 1]; static char polled_fds[MAX_FD + 1]; static char written_fds[MAX_FD + 1]; static char weird_fds[MAX_FD + 1]; static char blacklist_fds[MAX_FD + 1]; static char snd_timeout_fds[MAX_FD + 1]; static char **matchbufs = NULL; static size_t matchbuf_len = 0; static const char *pattern = NULL; static int verbose = -1; static int mocking_type = -1; enum { MOCKING_READS = 0x01, MOCKING_WRITES = 0x02 }; # define init_libc_handle() \ if (libc_handle == NULL) { \ libc_handle = RTLD_NEXT; \ } typedef int (*socket_handle) (int domain, int type, int protocol); typedef int (*poll_handle) (struct pollfd *ufds, unsigned int nfds, int timeout); typedef ssize_t (*writev_handle) (int fildes, const struct iovec *iov, int iovcnt); typedef int (*close_handle) (int fd); typedef ssize_t (*send_handle) (int sockfd, const void *buf, size_t len, int flags); typedef ssize_t (*read_handle) (int fd, void *buf, size_t count); typedef ssize_t (*recv_handle) (int sockfd, void *buf, size_t len, int flags); typedef ssize_t (*recvfrom_handle) (int sockfd, void *buf, size_t len, int flags, struct sockaddr *src_addr, socklen_t *addrlen); #if __linux__ typedef int (*accept4_handle) (int socket, struct sockaddr *address, socklen_t *address_len, int flags); typedef int (*signalfd_handle) (int fd, const sigset_t *mask, int flags); #if (defined(__GLIBC__) && __GLIBC__ <= 2) && \ (defined(__GLIBC_MINOR__) && __GLIBC_MINOR__ < 21) /* glibc < 2.21 used different signature */ typedef int (*eventfd_handle) (int initval, int flags); #else typedef int (*eventfd_handle) (unsigned int initval, int flags); #endif #endif static int get_verbose_level(); static void init_matchbufs(); static int now(); static int get_mocking_type(); #if __linux__ int accept4(int socket, struct sockaddr *address, socklen_t *address_len, int flags) { int fd; static accept4_handle orig_accept4 = NULL; init_libc_handle(); if (orig_accept4 == NULL) { orig_accept4 = dlsym(libc_handle, "accept4"); if (orig_accept4 == NULL) { fprintf(stderr, "mockeagain: could not find the underlying accept4: " "%s\n", dlerror()); exit(1); } } fd = orig_accept4(socket, address, address_len, flags); if (fd < 0) { return fd; } if (flags & SOCK_NONBLOCK) { if (matchbufs && matchbufs[fd]) { free(matchbufs[fd]); matchbufs[fd] = NULL; } active_fds[fd] = 0; polled_fds[fd] = 1; snd_timeout_fds[fd] = 0; } return fd; } int signalfd(int fd, const sigset_t *mask, int flags) { static signalfd_handle orig_signalfd = NULL; init_libc_handle(); if (orig_signalfd == NULL) { orig_signalfd = dlsym(libc_handle, "signalfd"); if (orig_signalfd == NULL) { fprintf(stderr, "mockeagain: could not find the underlying" " signalfd: %s\n", dlerror()); exit(1); } } fd = orig_signalfd(fd, mask, flags); if (fd < 0) { return fd; } if (get_verbose_level()) { fprintf(stderr, "mockeagain: signalfd: blacklist fd %d\n", fd); } blacklist_fds[fd] = 1; return fd; } #if (defined(__GLIBC__) && __GLIBC__ <= 2) && \ (defined(__GLIBC_MINOR__) && __GLIBC_MINOR__ < 21) /* glibc < 2.21 used different signature */ int eventfd(int initval, int flags) #else int eventfd(unsigned int initval, int flags) #endif { int fd; static eventfd_handle orig_eventfd = NULL; init_libc_handle(); if (orig_eventfd == NULL) { orig_eventfd = dlsym(libc_handle, "eventfd"); if (orig_eventfd == NULL) { fprintf(stderr, "mockeagain: could not find the underlying" " eventfd: %s\n", dlerror()); exit(1); } } fd = orig_eventfd(initval, flags); if (fd < 0) { return fd; } if (get_verbose_level()) { fprintf(stderr, "mockeagain: eventfd: blacklist fd %d\n", fd); } blacklist_fds[fd] = 1; return fd; } #endif int socket(int domain, int type, int protocol) { int fd; static socket_handle orig_socket = NULL; dd("calling my socket"); init_libc_handle(); if (orig_socket == NULL) { orig_socket = dlsym(libc_handle, "socket"); if (orig_socket == NULL) { fprintf(stderr, "mockeagain: could not find the underlying socket: " "%s\n", dlerror()); exit(1); } } init_matchbufs(); fd = (*orig_socket)(domain, type, protocol); dd("socket with type %d (SOCK_STREAM %d, SOCK_DGRAM %d)", type, SOCK_STREAM, SOCK_DGRAM); if (fd <= MAX_FD) { if (!(type & SOCK_STREAM)) { dd("socket: the current fd is weird: %d", fd); weird_fds[fd] = 1; } else { weird_fds[fd] = 0; } #if 1 if (matchbufs && matchbufs[fd]) { free(matchbufs[fd]); matchbufs[fd] = NULL; } #endif active_fds[fd] = 0; polled_fds[fd] = 0; snd_timeout_fds[fd] = 0; } dd("socket returning %d", fd); return fd; } int poll(struct pollfd *ufds, nfds_t nfds, int timeout) { static void *libc_handle; int retval; static poll_handle orig_poll = NULL; struct pollfd *p; int i; int fd = -1; int begin = 0; int elapsed = 0; dd("calling my poll"); init_libc_handle(); if (orig_poll == NULL) { orig_poll = dlsym(libc_handle, "poll"); if (orig_poll == NULL) { fprintf(stderr, "mockeagain: could not find the underlying poll: " "%s\n", dlerror()); exit(1); } } init_matchbufs(); dd("calling the original poll"); if (pattern) { begin = now(); } retval = (*orig_poll)(ufds, nfds, timeout); if (pattern) { elapsed = now() - begin; } if (retval > 0) { struct timeval tm; p = ufds; for (i = 0; i < nfds; i++, p++) { fd = p->fd; if (fd > MAX_FD || weird_fds[fd]) { dd("skipping fd %d", fd); continue; } if (pattern && (p->revents & POLLOUT) && snd_timeout_fds[fd]) { if (get_verbose_level()) { fprintf(stderr, "mockeagain: poll: should suppress write " "event on fd %d.\n", fd); } p->revents &= ~POLLOUT; if (p->revents == 0) { retval--; continue; } } if (blacklist_fds[fd]) { if (get_verbose_level()) { fprintf(stderr, "mockeagain: poll: skip fd %d because it " "is in blacklist\n", fd); } continue; } active_fds[fd] = p->revents; polled_fds[fd] = 1; if (get_verbose_level()) { fprintf(stderr, "mockeagain: poll: fd %d polled with events " "%d\n", fd, p->revents); } } if (retval == 0) { if (get_verbose_level()) { fprintf(stderr, "mockeagain: poll: emulating timeout on " "fd %d.\n", fd); } if (timeout < 0) { tm.tv_sec = 3600 * 24; tm.tv_usec = 0; if (get_verbose_level()) { fprintf(stderr, "mockeagain: poll: sleeping 1 day " "on fd %d.\n", fd); } select(0, NULL, NULL, NULL, &tm); } else { if (elapsed < timeout) { int diff; diff = timeout - elapsed; tm.tv_sec = diff / 1000; tm.tv_usec = diff % 1000 * 1000; if (get_verbose_level()) { fprintf(stderr, "mockeagain: poll: sleeping %d ms " "on fd %d.\n", diff, fd); } select(0, NULL, NULL, NULL, &tm); } } } } return retval; } ssize_t writev(int fd, const struct iovec *iov, int iovcnt) { ssize_t retval; static writev_handle orig_writev = NULL; struct iovec new_iov[1] = { {NULL, 0} }; const struct iovec *p; int i; size_t len = 0; if ((get_mocking_type() & MOCKING_WRITES) && get_verbose_level() && fd <= MAX_FD) { fprintf(stderr, "mockeagain: writev(%d): polled=%d, written=%d, " "active=%d\n", fd, (int) polled_fds[fd], (int) written_fds[fd], (int) active_fds[fd]); } if ((get_mocking_type() & MOCKING_WRITES) && fd <= MAX_FD && polled_fds[fd] && written_fds[fd] && !(active_fds[fd] & POLLOUT)) { if (get_verbose_level()) { fprintf(stderr, "mockeagain: mocking \"writev\" on fd %d to " "signal EAGAIN.\n", fd); } errno = EAGAIN; return -1; } written_fds[fd] = 1; init_libc_handle(); if (orig_writev == NULL) { orig_writev = dlsym(libc_handle, "writev"); if (orig_writev == NULL) { fprintf(stderr, "mockeagain: could not find the underlying writev: " "%s\n", dlerror()); exit(1); } } if (!(get_mocking_type() & MOCKING_WRITES)) { return (*orig_writev)(fd, iov, iovcnt); } if (fd <= MAX_FD && polled_fds[fd]) { p = iov; for (i = 0; i < iovcnt; i++, p++) { if (p->iov_base == NULL || p->iov_len == 0) { continue; } new_iov[0].iov_base = p->iov_base; new_iov[0].iov_len = 1; break; } len = 0; p = iov; for (i = 0; i < iovcnt; i++, p++) { len += p->iov_len; } } if (new_iov[0].iov_base == NULL) { retval = (*orig_writev)(fd, iov, iovcnt); } else { if (get_verbose_level()) { fprintf(stderr, "mockeagain: mocking \"writev\" on fd %d to emit " "1 of %llu bytes.\n", fd, (unsigned long long) len); } if (pattern && new_iov[0].iov_len) { char *p; size_t len; char c; c = *(char *) new_iov[0].iov_base; if (matchbufs[fd] == NULL) { matchbufs[fd] = malloc(matchbuf_len); if (matchbufs[fd] == NULL) { fprintf(stderr, "mockeagain: ERROR: failed to allocate memory.\n"); } p = matchbufs[fd]; memset(p, 0, matchbuf_len); p[0] = c; len = 1; } else { p = matchbufs[fd]; len = strlen(p); if (len < matchbuf_len - 1) { p[len] = c; len++; } else { memmove(p, p + 1, matchbuf_len - 2); p[matchbuf_len - 2] = c; } } /* test if the pattern matches the matchbuf */ dd("matchbuf: %.*s (len: %d)", (int) len, p, (int) matchbuf_len - 1); if (len == matchbuf_len - 1 && strncmp(p, pattern, len) == 0) { if (get_verbose_level()) { fprintf(stderr, "mockeagain: \"writev\" has found a match for " "the timeout pattern \"%s\" on fd %d.\n", pattern, fd); } snd_timeout_fds[fd] = 1; } } dd("calling the original writev on fd %d", fd); retval = (*orig_writev)(fd, new_iov, 1); active_fds[fd] &= ~POLLOUT; } return retval; } int close(int fd) { int retval; static close_handle orig_close = NULL; init_libc_handle(); if (orig_close == NULL) { orig_close = dlsym(libc_handle, "close"); if (orig_close == NULL) { fprintf(stderr, "mockeagain: could not find the underlying close: " "%s\n", dlerror()); exit(1); } } if (fd <= MAX_FD) { #if (DDEBUG) if (polled_fds[fd]) { dd("calling the original close on fd %d", fd); } #endif if (matchbufs && matchbufs[fd]) { free(matchbufs[fd]); matchbufs[fd] = NULL; } active_fds[fd] = 0; polled_fds[fd] = 0; written_fds[fd] = 0; snd_timeout_fds[fd] = 0; weird_fds[fd] = 0; blacklist_fds[fd] = 0; } retval = (*orig_close)(fd); return retval; } ssize_t send(int fd, const void *buf, size_t len, int flags) { ssize_t retval; static send_handle orig_send = NULL; dd("calling my send"); if ((get_mocking_type() & MOCKING_WRITES) && fd <= MAX_FD && polled_fds[fd] && written_fds[fd] && !(active_fds[fd] & POLLOUT)) { if (get_verbose_level()) { fprintf(stderr, "mockeagain: mocking \"send\" on fd %d to " "signal EAGAIN\n", fd); } errno = EAGAIN; return -1; } written_fds[fd] = 1; init_libc_handle(); if (orig_send == NULL) { orig_send = dlsym(libc_handle, "send"); if (orig_send == NULL) { fprintf(stderr, "mockeagain: could not find the underlying send: " "%s\n", dlerror()); exit(1); } } if ((get_mocking_type() & MOCKING_WRITES) && fd <= MAX_FD && polled_fds[fd] && len) { if (get_verbose_level()) { fprintf(stderr, "mockeagain: mocking \"send\" on fd %d to emit " "1 byte data only\n", fd); } if (pattern && len) { char *p; size_t len; char c; c = *(char *) buf; if (matchbufs[fd] == NULL) { matchbufs[fd] = malloc(matchbuf_len); if (matchbufs[fd] == NULL) { fprintf(stderr, "mockeagain: ERROR: failed to allocate memory.\n"); } p = matchbufs[fd]; memset(p, 0, matchbuf_len); p[0] = c; len = 1; } else { p = matchbufs[fd]; len = strlen(p); if (len < matchbuf_len - 1) { p[len] = c; len++; } else { memmove(p, p + 1, matchbuf_len - 2); p[matchbuf_len - 2] = c; } } /* test if the pattern matches the matchbuf */ dd("matchbuf: %.*s (len: %d)", (int) len, p, (int) matchbuf_len - 1); if (len == matchbuf_len - 1 && strncmp(p, pattern, len) == 0) { if (get_verbose_level()) { fprintf(stderr, "mockeagain: \"writev\" has found a match for " "the timeout pattern \"%s\" on fd %d.\n", pattern, fd); } snd_timeout_fds[fd] = 1; } } retval = (*orig_send)(fd, buf, 1, flags); active_fds[fd] &= ~POLLOUT; } else { dd("calling the original send on fd %d", fd); retval = (*orig_send)(fd, buf, len, flags); } return retval; } ssize_t read(int fd, void *buf, size_t len) { ssize_t retval; static read_handle orig_read = NULL; dd("calling my read"); if ((get_mocking_type() & MOCKING_READS) && fd <= MAX_FD && polled_fds[fd] && !(active_fds[fd] & (POLLIN | POLLHUP))) { if (get_verbose_level()) { fprintf(stderr, "mockeagain: mocking \"read\" on fd %d to " "signal EAGAIN\n", fd); } errno = EAGAIN; return -1; } init_libc_handle(); if (orig_read == NULL) { orig_read = dlsym(libc_handle, "read"); if (orig_read == NULL) { fprintf(stderr, "mockeagain: could not find the underlying read: " "%s\n", dlerror()); exit(1); } } if ((get_mocking_type() & MOCKING_READS) && fd <= MAX_FD && polled_fds[fd] && len) { if (get_verbose_level()) { fprintf(stderr, "mockeagain: mocking \"read\" on fd %d to read " "1 byte only\n", fd); } dd("calling the original read on fd %d", fd); retval = (*orig_read)(fd, buf, 1); active_fds[fd] &= ~POLLIN; } else { retval = (*orig_read)(fd, buf, len); } return retval; } ssize_t recv(int fd, void *buf, size_t len, int flags) { ssize_t retval; static recv_handle orig_recv = NULL; dd("calling my recv"); if ((get_mocking_type() & MOCKING_READS) && fd <= MAX_FD && polled_fds[fd] && !(active_fds[fd] & POLLIN)) { if (get_verbose_level()) { fprintf(stderr, "mockeagain: mocking \"recv\" on fd %d to " "signal EAGAIN\n", fd); } errno = EAGAIN; return -1; } init_libc_handle(); if (orig_recv == NULL) { orig_recv = dlsym(libc_handle, "recv"); if (orig_recv == NULL) { fprintf(stderr, "mockeagain: could not find the underlying recv: " "%s\n", dlerror()); exit(1); } } if ((get_mocking_type() & MOCKING_READS) && fd <= MAX_FD && polled_fds[fd] && len) { if (get_verbose_level()) { fprintf(stderr, "mockeagain: mocking \"recv\" on fd %d to read " "1 byte only\n", fd); } dd("calling the original recv on fd %d", fd); retval = (*orig_recv)(fd, buf, 1, flags); active_fds[fd] &= ~POLLIN; } else { retval = (*orig_recv)(fd, buf, len, flags); } return retval; } ssize_t recvfrom(int fd, void *buf, size_t len, int flags, struct sockaddr *src_addr, socklen_t *addrlen) { ssize_t retval; static recvfrom_handle orig_recvfrom = NULL; dd("calling my recvfrom"); if ((get_mocking_type() & MOCKING_READS) && fd <= MAX_FD && polled_fds[fd] && !(active_fds[fd] & POLLIN)) { if (get_verbose_level()) { fprintf(stderr, "mockeagain: mocking \"recvfrom\" on fd %d to " "signal EAGAIN\n", fd); } errno = EAGAIN; return -1; } init_libc_handle(); if (orig_recvfrom == NULL) { orig_recvfrom = dlsym(libc_handle, "recvfrom"); if (orig_recvfrom == NULL) { fprintf(stderr, "mockeagain: could not find the underlying recvfrom: " "%s\n", dlerror()); exit(1); } } if ((get_mocking_type() & MOCKING_READS) && fd <= MAX_FD && polled_fds[fd] && len) { if (get_verbose_level()) { fprintf(stderr, "mockeagain: mocking \"recvfrom\" on fd %d to read " "1 byte only\n", fd); } dd("calling the original recvfrom on fd %d", fd); retval = (*orig_recvfrom)(fd, buf, 1, flags, src_addr, addrlen); active_fds[fd] &= ~POLLIN; } else { retval = (*orig_recvfrom)(fd, buf, len, flags, src_addr, addrlen); } return retval; } static int get_mocking_type() { const char *p; #if 1 if (mocking_type >= 0) { return mocking_type; } #endif mocking_type = 0; p = getenv("MOCKEAGAIN"); if (p == NULL || *p == '\0') { dd("MOCKEAGAIN env empty"); /* mocking_type = MOCKING_WRITES; */ return mocking_type; } while (*p) { if (*p == 'r' || *p == 'R') { mocking_type |= MOCKING_READS; } else if (*p == 'w' || *p == 'W') { mocking_type |= MOCKING_WRITES; } p++; } if (mocking_type == 0) { mocking_type = MOCKING_WRITES; } dd("mocking_type %d", mocking_type); return mocking_type; } static int get_verbose_level() { const char *p; if (verbose >= 0) { return verbose; } p = getenv("MOCKEAGAIN_VERBOSE"); if (p == NULL || *p == '\0') { dd("MOCKEAGAIN_VERBOSE env empty"); verbose = 0; return verbose; } if (*p >= '0' && *p <= '9') { dd("MOCKEAGAIN_VERBOSE env value: %s", p); verbose = *p - '0'; return verbose; } dd("bad verbose env value: %s", p); verbose = 0; return verbose; } static void init_matchbufs() { const char *p; int len; if (matchbufs != NULL) { return; } p = getenv("MOCKEAGAIN_WRITE_TIMEOUT_PATTERN"); if (p == NULL || *p == '\0') { dd("write_timeout env empty"); matchbuf_len = 0; return; } len = strlen(p); matchbufs = malloc((MAX_FD + 1) * sizeof(char *)); if (matchbufs == NULL) { fprintf(stderr, "mockeagain: ERROR: failed to allocate memory.\n"); return; } memset(matchbufs, 0, (MAX_FD + 1) * sizeof(char *)); matchbuf_len = len + 1; pattern = p; if (get_verbose_level()) { fprintf(stderr, "mockeagain: reading write timeout pattern: %s\n", pattern); } } /* returns a time in milliseconds */ static int now() { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec % (3600 * 24) + tv.tv_usec/1000; }
the_stack_data/20450614.c
/** * Exercise 1-16. * Revise the main routine of the longest-line program * so it will correctly print the length of arbitrary long input lines, * and as much as possible of the text. */ #include <stdio.h> #define MAXLINE 1000 int gline(char line[], int maxline); void copy(char from[], char to[]); int main() { int len; // the length of current line int max; // the length of longest line char line[MAXLINE]; // store the current line char longest[MAXLINE]; // store the longest line max = 0; while ((len = gline(line, MAXLINE)) > 0) { if (len > max) { max = len; copy(line, longest); } } if (max > 0) { printf("Line length is %d\nLongest string is %s\n", max, longest); } return 0; } int gline(char s[], int lim) { int c, i; for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) { s[i] = c; } if (c == '\n') { s[i] = c; ++i; } s[i] = '\0'; return i; } void copy(char from[], char to[]) { int i; i = 0; while ((to[i] = from[i]) != '\0') ++i; }
the_stack_data/153268862.c
/* Copyright (c) 2021 SoulHarsh007 (Harsh Peshwani) * Contact: [email protected] or [email protected] * GitHub: https://github.com/SoulHarsh007/ */ #include <stdio.h> int main() { int arr[10], n, i, j, extra; printf("Enter number of elements in the array: "); scanf("%d", &n); for (i = 0; i < n; i++) { printf("Enter the values for element no. %d: ", i + 1); scanf("%d", &arr[i]); } for (i = 0; i < n - 1; i++) { for (j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { extra = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = extra; } } } printf("Array in ascending order: "); for (i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); return 0; }
the_stack_data/25137978.c
//Program to display a hollow right triangle pattern #include<stdio.h> int main() { int n,i,j; printf("Enter the number of rows\n"); scanf("%d",&n); printf("The desired pattern is:\n\n"); for(i=1;i<=n;i++) { for(j=1;j<=i;j++) { if(j==1 || j==i || i==n) { printf("*"); } else { printf(" "); } } printf("\n"); } }
the_stack_data/146599.c
#include <stdio.h> int main(void){ int sample[5] = {1,4,3,4,5}; for(int i =0; i<5; i++){ printf("%d\n", sample[i]); } return 0; }
the_stack_data/853545.c
/* Test for -Wtraditional warnings on automatic aggregate initialization. Note, gcc should omit these warnings in system header files. By Kaveh R. Ghazi <[email protected]> 8/22/2000. */ /* { dg-do compile } */ /* { dg-options "-Wtraditional" } */ struct foo { int i; long l; }; struct foo f0 = { 0, 0 }; static struct foo f1 = { 0, 0 }; void testfunc1 () { struct foo f3 = { 0, 0 }; /* { dg-warning "traditional C rejects automatic" "automatic aggregate initialization" } */ static struct foo f4 = { 0, 0 }; f3 = f4; __extension__ ({ struct foo f5 = { 0, 0 }; /* { dg-bogus "traditional C rejects automatic" "__extension__ disables warnings" } */ f5.i = 0; }); { struct foo f6 = { 0, 0 }; /* { dg-warning "traditional C rejects automatic" "__extension__ reenables warnings" } */ f6.i = 0; } } # 35 "sys-header.h" 3 /* We are in system headers now, no -Wtraditional warnings should issue. */ struct foo f7 = { 0, 0 }; static struct foo f8 = { 0, 0 }; void testfunc2 () { struct foo f9 = { 0, 0 }; static struct foo f10 = { 0, 0 }; f9 = f10; }
the_stack_data/1127704.c
long a[100]; long *b; void main() { long c[10]; long *d; long i; i = a[8]; a[9] = i; i = b[10]; b[11] = i; i = c[12]; c[13] = i; i = d[14]; d[15] = i; return; }
the_stack_data/430542.c
#include <math.h> double pow(double x, double y) { for (int i = 0; i < y - 1; i++) x *= x; return x; }
the_stack_data/96364.c
#include<stdio.h> #define INF 1000000000 void MST(int); int edge[101][101],v[101],d[101],sum=0,n; int main(void){ int m,a,b,i,j, cost; while(1){ scanf("%d",&n); if(n==0)break; scanf("%d",&m); for(i=0;i<101;i++){ for(j=0;j<101;j++){ edge[i][j]=INF; } } for(i=0;i<m;i++){ scanf("%d,%d,%d",&a,&b,&cost); edge[a][b]=cost; edge[b][a]=cost; } for(i=0;i<101;i++){ d[i]=INF; v[i]=0; } d[0]=0; sum = 0; MST(0); printf("%d\n",sum); } return 0; } void MST(int u){ int x=0,i; while(1){ int minv=INF; for(i=0;i<n;i++){ if(v[i]==0 && d[i]<minv){ x=i; minv=d[i]; } } if(minv==INF)break; v[x]=1; if ( x != u ) sum+=(d[x]/100-1); for(i=0;i<n;i++){ if ( v[i] ) continue; d[i]=min(d[i],edge[x][i]); } } } int min(int x,int y){ return x < y ? x : y; }
the_stack_data/62637597.c
#define CRT_SECURE_NO_WARNINGS #include <stdio.h> // Recursion in programming is a term used to describe when a function makes an internal call to itself. // This leads to the function repeating within itself. // This functionality must be controlled to avoid infinitely running code, which can lead to system crashes. // When implemented correctly, recursion can be extremely useful in reducing code repetition. // Below is an example of recursion being implemented to calculate a factorial of a number. // (Factorial is the value found for f(n) where f() is n * n-1 *n-2 ... * 1) // (i.e. the value is multiplied by one less each time until finally multiplied by 1) // Unsigned long long is used due to the exponential growth in size of values when calculating factorial values // In this case, factorial(15) would return an incorrect answer due to data type overflow if int or long it was used // Overflow is still possible in this system, however, this is a prof of concept for how recursion can be used unsigned long long factorial(unsigned long int inputVal) { // Verify that the input value is positive if (inputVal < 0) { printf("Cannot calculate factorial of a negative value"); return 0; } // If the value is larger than 0 if (inputVal > 0) { // Return the input value * the return from the recursive call using value - 1 return inputVal * factorial(inputVal - 1); } else { // Factorial of 0 is 1 return 1; } } // Driver program for testing the factorial function int main() { printf("%llu\n\r", factorial(0)); printf("%llu\n\r", factorial(5)); printf("%llu\n\r", factorial(10)); printf("%llu\n\r", factorial(15)); return 0; }
the_stack_data/170453509.c
/* URI Online Judge | 1098 Sequence IJ 4 Adapted by Neilor Tonin, URI Brazil https://www.urionlinejudge.com.br/judge/en/problems/view/1098 Timelimit: 1 Make a program that prints the sequence like the following example. Input This problem doesn't have input. Output Print the sequence like the example below. @author Marcos Lima @profile https://www.urionlinejudge.com.br/judge/pt/profile/242402 @status Accepted @language C (gcc 4.8.5, -O2 -lm) [+0s] @time 0.000s @size 451 Bytes @submission 12/8/19, 9:27:12 AM */ #include <stdio.h> int main(void) { unsigned int z=0, i = 0, j = 1; for (; z < 3; z++) { for (; i < 10; i += 2) { for (;j<4; j++) if (i) printf("I=%d.%d J=%d.%d\n",z,i,(j+z),i); else printf("I=%d J=%d\n",z,(z+j)); j = 1; if (z == 2) break; } i = 0; } return 0; }
the_stack_data/220456545.c
/* * POK header * * The following file is a part of the POK project. Any modification should * made according to the POK licence. You CANNOT use this file or a part of * this file is this part of a file for your own project * * For more information on the POK licence, please see our LICENCE FILE * * Please follow the coding guidelines described in doc/CODING_GUIDELINES * * Copyright (c) 2007-2009 POK team * * Created by julien on Fri Jan 30 14:41:34 2009 */ /* s_log1pf.c -- float version of s_log1p.c. * Conversion to float by Ian Lance Taylor, Cygnus Support, [email protected]. */ /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== */ #ifdef POK_NEEDS_LIBMATH #include <types.h> #include "math_private.h" static const float ln2_hi = 6.9313812256e-01, /* 0x3f317180 */ ln2_lo = 9.0580006145e-06, /* 0x3717f7d1 */ two25 = 3.355443200e+07, /* 0x4c000000 */ Lp1 = 6.6666668653e-01, /* 3F2AAAAB */ Lp2 = 4.0000000596e-01, /* 3ECCCCCD */ Lp3 = 2.8571429849e-01, /* 3E924925 */ Lp4 = 2.2222198546e-01, /* 3E638E29 */ Lp5 = 1.8183572590e-01, /* 3E3A3325 */ Lp6 = 1.5313838422e-01, /* 3E1CD04F */ Lp7 = 1.4798198640e-01; /* 3E178897 */ static const float zero = 0.0; float log1pf(float x) { float hfsq, f, c, s, z, R, u; int32_t k, hx, hu, ax; f = c = 0; hu = 0; GET_FLOAT_WORD(hx, x); ax = hx & 0x7fffffff; k = 1; if (hx < 0x3ed413d7) { /* x < 0.41422 */ if (ax >= 0x3f800000) { /* x <= -1.0 */ if (x == (float)-1.0) return -two25 / zero; /* log1p(-1)=+inf */ else return (x - x) / (x - x); /* log1p(x<-1)=NaN */ } if (ax < 0x31000000) { /* |x| < 2**-29 */ if (two25 + x > zero /* raise inexact */ && ax < 0x24800000) /* |x| < 2**-54 */ return x; else return x - x * x * (float)0.5; } if (hx > 0 || hx <= ((int32_t)0xbe95f61f)) { k = 0; f = x; hu = 1; } /* -0.2929<x<0.41422 */ } if (hx >= 0x7f800000) return x + x; if (k != 0) { if (hx < 0x5a000000) { u = (float)1.0 + x; GET_FLOAT_WORD(hu, u); k = (hu >> 23) - 127; /* correction term */ c = (k > 0) ? (float)1.0 - (u - x) : x - (u - (float)1.0); c /= u; } else { u = x; GET_FLOAT_WORD(hu, u); k = (hu >> 23) - 127; c = 0; } hu &= 0x007fffff; if (hu < 0x3504f7) { SET_FLOAT_WORD(u, hu | 0x3f800000); /* normalize u */ } else { k += 1; SET_FLOAT_WORD(u, hu | 0x3f000000); /* normalize u/2 */ hu = (0x00800000 - hu) >> 2; } f = u - (float)1.0; } hfsq = (float)0.5 * f * f; if (hu == 0) { /* |f| < 2**-20 */ if (f == zero) { if (k == 0) return zero; else { c += k * ln2_lo; return k * ln2_hi + c; } } R = hfsq * ((float)1.0 - (float)0.66666666666666666 * f); if (k == 0) return f - R; else return k * ln2_hi - ((R - (k * ln2_lo + c)) - f); } s = f / ((float)2.0 + f); z = s * s; R = z * (Lp1 + z * (Lp2 + z * (Lp3 + z * (Lp4 + z * (Lp5 + z * (Lp6 + z * Lp7)))))); if (k == 0) return f - (hfsq - s * (hfsq + R)); else return k * ln2_hi - ((hfsq - (s * (hfsq + R) + (k * ln2_lo + c))) - f); } #endif