file
stringlengths
18
26
data
stringlengths
2
1.05M
the_stack_data/154828441.c
// 8. perform to subtract Two Float number #include <stdio.h> int main() { float var1 , var2 ; scanf("%f%f", &var1, &var2); printf("%f",var2 - var1); return 0; }
the_stack_data/751294.c
/* Program: test-while.c */ #include <stdio.h> #include <stdbool.h> bool beg_for_mercy() { char ch; printf("Beg for mercy? [y/N]: "); scanf(" %c", &ch); return ch == 'y' || ch == 'Y'; } int main() { bool mercy = false; printf("Before you stands a 12 foot tall Knight...\n"); printf("\"We are the Knights who say 'Ni'.\"\n"); printf("\"I will say Ni to you again if you do not appease us!\"\n"); mercy = beg_for_mercy(); while( !mercy ) { printf("\"Ni!\"\n"); mercy = beg_for_mercy(); } printf("\"Bring us a Shrubbery!\"\n"); return 0; }
the_stack_data/62638720.c
#include <stdio.h> #include <stdlib.h> void scilab_rt_interp1_d2d2d0_d0(int sin00, int sin01, double in0[sin00][sin01], int sin10, int sin11, double in1[sin10][sin11], double in2, double* out0) { int i; int j; double val0 = 0; double val1 = 0; for (i = 0; i < sin00; ++i) { for (j = 0; j < sin01; ++j) { val0 += in0[i][j]; } } for (i = 0; i < sin10; ++i) { for (j = 0; j < sin11; ++j) { val1 += in1[i][j]; } } *out0 = val0 + val1 + in2; }
the_stack_data/36991.c
#include <stdio.h> void function1(int u, int v); void function2(int *pu, int *pv); int main(void) { int u = 1; int v = 3; printf("\nBefore calling function 1: u = %d and v = %d\n\n", u, v); function1(u, v); printf("\nAfter calling function1: u = %d and v = %d\n\n", u, v); printf("\nBefore calling function2: u = %d and v = %d\n\n", u, v); function2(&u, &v); printf("\nAfter calling function2: u = %d and v = %d\n\n", u, v); } void function1(int u, int v) { u = 0; v = 0; printf("\nWithin function1: u = %d and v = %d\n\n", u, v); return 0; } void function2(int *pu, int *pv) { *pu = 0; *pv = 0; printf("\nWithin function2: *pu = %d and *pv = %d\n\n", *pu, *pv); return 0; }
the_stack_data/200509.c
// RUN: %clang_cc1 -triple x86_64-pc-windows-msvc18.0.0 -fcoroutines-ts -emit-llvm %s -o - -verify void f(void) { __builtin_coro_alloc(); // expected-error {{this builtin expect that __builtin_coro_id}} __builtin_coro_begin(0); // expected-error {{this builtin expect that __builtin_coro_id}} __builtin_coro_free(0); // expected-error {{this builtin expect that __builtin_coro_id}} __builtin_coro_id(32, 0, 0, 0); __builtin_coro_id(32, 0, 0, 0); // expected-error {{only one __builtin_coro_id}} }
the_stack_data/87317.c
#include <stdio.h> #define MAX 12 int main(void) { int c, i, j, aux; float Matriz[MAX][MAX], N, SOMA; char O; SOMA=0; scanf("%c", &O); for (i = 0; i < MAX; i++) { for (j = 0; j < MAX; j++) { scanf("%f", &N); Matriz[i][j] = N; //preenchimento de acordo com o valor de entrada colocado } } for (i =0; i< MAX; i++) { for (j=0; j<i; j++) { SOMA+=Matriz[i][j]; //Os valores vão se somando desde que a coluna seja menor que a linha } } if(O=='S') printf("%.1f\n", SOMA); else printf("%.1f\n", (SOMA/(MAX*MAX/2-(MAX/2)))); //média return 0; }
the_stack_data/111077258.c
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ____ ___ __ _ // / __// o |,'_/ .' \ // / _/ / _,'/ /_n / o / _ __ _ ___ _ _ __ // /_/ /_/ |__,'/_n_/ / \,' /.' \ ,' _/,' \ / |/ / // / \,' // o /_\ `./ o // || / // /_/ /_//_n_//___,'|_,'/_/|_/ // //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Author : Wesley Taylor-Rendal (WTR) // Design history : Review git logs. // Description : Copying Characters from Standard Input to Standard Output // Concepts : Understanding how a eof terminator for a file works. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #include <stdio.h> int main(void) { int c; while ( ( c = getchar() ) != EOF ) putchar(c); return 0; }
the_stack_data/955787.c
#include <stdio.h> #include <sys/stat.h> #include <sys/types.h> int main(int argc, char *argv[]) { struct stat statbuf; char *mode; int i; for (i = 1; i < argc; i++) { // argv 에 있는 파일 수 만큼 반복. printf("%s: ", argv[i]); if (lstat(argv[i], &statbuf)) { // lstat으로 파일의 정보를 perror("lstat"); // stat구조체로 받음. continue; } // 구조체에 받은 정보 디스플레이. // 파일 종류. if (S_ISREG(statbuf.st_mode)) mode = "regular"; else if (S_ISDIR(statbuf.st_mode)) mode = "directory"; else if (S_ISCHR(statbuf.st_mode)) mode = "character special"; else if (S_ISBLK(statbuf.st_mode)) mode = "block special"; else if (S_ISFIFO(statbuf.st_mode)) mode = "FIFO"; else if (S_ISLNK(statbuf.st_mode)) mode = "symbolic link"; else if (S_ISSOCK(statbuf.st_mode)) mode = "socket"; printf("%s\n", mode); printf("\tst_mode = %d\n", statbuf.st_mode); printf("\tst_ino = %d\n", statbuf.st_ino); printf("\tst_dev = %d\n", statbuf.st_dev); printf("\tst_rdev = %d\n", statbuf.st_rdev); printf("\tst_nlink = %d\n", statbuf.st_nlink); printf("\tst_uid = %d\n", statbuf.st_uid); printf("\tst_gid = %d\n", statbuf.st_gid); printf("\tst_size = %d\n", statbuf.st_size); printf("\tst_atime = %d\n", statbuf.st_atime); printf("\tst_mtime = %d\n", statbuf.st_mtime); printf("\tst_ctime = %d\n", statbuf.st_ctime); printf("\tst_blksize = %d\n", statbuf.st_blksize); printf("\tst_blocks = %d\n", statbuf.st_blocks); } }
the_stack_data/168892751.c
/* Copyright (C) 1992, 1996, 1999, 2002 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #include <string.h> #include <stdlib.h> #include <time.h> #include <unistd.h> char * strfry (char *string) { static int init; static struct random_data rdata; size_t len, i; if (!init) { static char state[32]; rdata.state = NULL; __initstate_r (time ((time_t *) NULL) ^ getpid (), state, sizeof (state), &rdata); init = 1; } len = strlen (string); for (i = 0; i < len; ++i) { int32_t j; char c; __random_r (&rdata, &j); j %= len; c = string[i]; string[i] = string[j]; string[j] = c; } return string; }
the_stack_data/40117.c
#include <stdio.h> #include <setjmp.h> static jmp_buf jmpenv; void jumpjump(int label) { goto printer; jumper: longjmp(jmpenv, label); printer: printf("jumpjump(%d)\n", label); goto jumper; } int main() { int counter = 0; goto begin; end: puts("end this madness"); return 0; begin: puts("begin jumping"); switch(setjmp(jmpenv)) { case 0: // Initial jump puts("patient zero"); jumpjump(counter++); break; case 1: // First return jumpjump(counter++); break; case 2: goto begin; break; case 3: goto end; } goto end; }
the_stack_data/67651.c
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #define NUM_RANKS 13 #define NUM_SUITS 4 #define NUM_CARDS 5 /* external variables */ int hand[NUM_CARDS][2]; bool straight, flush, four, three; int pairs; /* can be 0, 1, or 2 */ /* prototypes */ void read_cards(void); void analyze_hand(void); void print_result(void); int card_exists(int rank, int suit); int main(void) { for (;;) { read_cards(); analyze_hand(); print_result(); } } void read_cards(void) { char ch, rank_ch, suit_ch; bool bad_card; int rank, suit; int cards_read = 0; while (cards_read < NUM_CARDS) { bad_card = false; printf("Enter a card: "); rank_ch = getchar(); switch (rank_ch) { case '0': exit(EXIT_SUCCESS); case '2': rank = 0; break; case '3': rank = 1; break; case '4': rank = 2; break; case '5': rank = 3; break; case '6': rank = 4; break; case '7': rank = 5; break; case '8': rank = 6; break; case '9': rank = 7; break; case 't': case 'T': rank = 8; break; case 'j': case 'J': rank = 9; break; case 'q': case 'Q': rank = 10; break; case 'k': case 'K': rank = 11; break; case 'a': case 'A': rank = 12; break; default: bad_card = true; } suit_ch = getchar(); switch (suit_ch) { case 'c': case 'C': suit = 0; break; case 'd': case 'D': suit = 1; break; case 'h': case 'H': suit = 2; break; case 's': case 'S': suit = 3; break; default: bad_card = true; } while ((ch = getchar() != '\n')) if (ch != ' ') bad_card = true; if (bad_card) printf("Bad card; ignored.\n"); else if (card_exists(rank, suit)) printf("Duplicate card; ignored.\n"); else { hand[cards_read][0] = rank; hand[cards_read][1] = suit; cards_read++; } } } int card_exists(int rank, int suit) { for (int i = 0; i < NUM_CARDS; i++) { if (hand[i][0] == rank && hand[i][1] == suit) return true; } return false; } void analyze_hand(void) { int num_consec = 0; int card, count, t_rank, t_suit, small, temp; straight = false; flush = false; four = false; three = false; pairs = 0; // Sorting hat for (int i = 0; i < NUM_CARDS; i++) { small = i; for (int j = 0; j < NUM_CARDS; j++) { if (hand[j][0] < hand[small][0]) small = j; } t_rank = hand[i][0]; t_suit = hand [i][1]; hand[i][0] = hand[small][0]; hand[i][1] = hand [small][1]; hand[small][0] = t_rank; hand[small][1] = t_suit; } // check for flush -- same SUIT count = 0; temp = hand[0][1]; for (int i = 0; i <= NUM_SUITS; i++) (temp == hand[i][1]) ? count++ : count ; if (count == NUM_CARDS) flush = true; //check for straight -- ascending RANK! for (int i = 1; i < NUM_CARDS; i++) { if (hand[i][0] - hand[card-1][0] != 1) break; if (card == NUM_CARDS -1) straight = true; } // check for 4-of-a-kind, 3-of-a-kind, and pairs for (int i = 0; i < NUM_CARDS; i++) { temp = 0; for (int j = i + 1; j < NUM_CARDS; j++) { (hand[j][0] == hand[i][0]) ? temp++ : temp; } if (temp == 1) pairs++ ; if (temp == 2) three = true; if (temp == 3) four = true; } } void print_result(void) { if (straight && flush) printf("Straight flush"); else if (four) printf("Four of a kind"); else if (three && pairs == 1) printf("Full house"); else if (flush) printf("Flush"); else if (straight) printf("Straight"); else if (three) printf("Three of a kind"); else if (pairs == 2) printf("Two pairs"); else if (pairs == 1) printf("Pair"); else printf("High card"); printf("\n\n"); }
the_stack_data/90766872.c
#include <stdio.h> int main(){ int robotLocation[][3] = { {34, 54,0},{75, 9,0},{1,2,0} }; printf("The robot is at x = %d, y = %d, z = %d\n", robotLocation[1][0], robotLocation[1][1], robotLocation[1][2]); }
the_stack_data/184518950.c
/* * ECMA objects: * class PeridotServo { * constructor(pin) { * } * * static enableAll() { * } * * static disableAll() { * } * * get rawValue() { return <uint>; } * set rawValue(<uint>){} * * get pin() { return <uint>; } * } * global.Peridot.Servo = PeridotServo; */ #if defined(DUX_USE_BOARD_PERIDOT) #if !defined(DUX_OPT_NO_HARDWARE_MODULES) && !defined(DUX_OPT_NO_SERVO) #include "../dux_internal.h" #include <system.h> #include <peridot_servo.h> /* * Constants */ DUK_LOCAL const char DUX_IPK_PERIDOT_SERVO_PIN[] = DUX_IPK("bSrvPin"); DUK_LOCAL const char DUX_IPK_PERIDOT_SERVO_CFG[] = DUX_IPK("bSrvCfg"); enum { SERVO_CFG_FLOATMODE = 0, SERVO_CFG_MINVALUE, SERVO_CFG_MAXVALUE, SERVO_CFG_MINRAWVALUE, SERVO_CFG_MAXRAWVALUE, SERVO_CFG_SATURATED, SERVO_CFG_VALUE, }; /* * Entry of PeridotServo.enableAll() */ DUK_LOCAL duk_ret_t servo_enableAll(duk_context *ctx) { /* [ ] */ peridot_servo_enable_all(); return 0; /* return undefined; */ } /* * Entry of PeridotServo.disableAll() */ DUK_LOCAL duk_ret_t servo_disableAll(duk_context *ctx) { /* [ ] */ peridot_servo_disable_all(); return 0; /* return undefined; */ } #if 0 /* * Getter of PeridotServo.prototype.floatMode */ DUK_LOCAL duk_ret_t servo_proto_floatMode_getter(duk_context *ctx) { /* [ ] */ duk_push_this(ctx); /* [ this ] */ if (!duk_get_prop_string(ctx, 0, DUK_IPK_PERIDOT_SERVO_CFG)) { return DUK_ERR_TYPE_ERROR; } /* [ this arr ] */ duk_get_prop_index(ctx, 1, SERVO_CFG_FLOATMODE); return 1; /* return <bool>; */ } /* * Setter of PeridotServo.prototype.floatMode */ DUK_LOCAL duk_ret_t servo_proto_floatMode_setter(duk_context *ctx) { /* [ bool ] */ duk_push_this(ctx); /* [ bool this ] */ if (!duk_get_prop_string(ctx, 1, DUK_IPK_PERIDOT_SERVO_CFG)) { return DUK_ERR_TYPE_ERROR; } /* [ bool this arr ] */ duk_push_boolean(ctx, duk_require_boolean(ctx, 0)); duk_get_prop_index(ctx, 2, SERVO_CFG_FLOATMODE); return 0; /* return undefined; */ } /* * Getter of PeridotServo.prototype.maxRawValue */ DUK_LOCAL duk_ret_t servo_proto_maxRawValue_getter(duk_context *ctx) { /* [ ] */ duk_push_this(ctx); /* [ this ] */ if (!duk_get_prop_string(ctx, 0, DUK_IPK_PERIDOT_SERVO_CFG)) { return DUK_ERR_TYPE_ERROR; } /* [ this arr ] */ duk_get_prop_index(ctx, 1, SERVO_CFG_MAXRAWVALUE); return 1; /* return <int>; */ } /* * Setter of PeridotServo.prototype.maxRawValue */ DUK_LOCAL duk_ret_t servo_proto_maxRawValue_setter(duk_context *ctx) { /* [ int ] */ duk_push_this(ctx); /* [ int this ] */ if (!duk_get_prop_string(ctx, 1, DUK_IPK_PERIDOT_SERVO_CFG)) { return DUK_ERR_TYPE_ERROR; } /* [ int this arr ] */ duk_push_int(ctx, duk_require_int(ctx, 0)); duk_get_prop_index(ctx, 2, SERVO_CFG_MAXRAWVALUE); return 0; /* return undefined; */ } /* * Getter of PeridotServo.prototype.minRawValue */ DUK_LOCAL duk_ret_t servo_proto_minRawValue_getter(duk_context *ctx) { /* [ ] */ duk_push_this(ctx); /* [ this ] */ if (!duk_get_prop_string(ctx, 0, DUK_IPK_PERIDOT_SERVO_CFG)) { return DUK_ERR_TYPE_ERROR; } /* [ this arr ] */ duk_get_prop_index(ctx, 1, SERVO_CFG_MINRAWVALUE); return 1; /* return <int>; */ } /* * Setter of PeridotServo.prototype.minRawValue */ DUK_LOCAL duk_ret_t servo_proto_minRawValue_setter(duk_context *ctx) { /* [ int ] */ duk_push_this(ctx); /* [ int this ] */ if (!duk_get_prop_string(ctx, 1, DUK_IPK_PERIDOT_SERVO_CFG)) { return DUK_ERR_TYPE_ERROR; } /* [ int this arr ] */ duk_push_int(ctx, duk_require_int(ctx, 0)); duk_get_prop_index(ctx, 2, SERVO_CFG_MINRAWVALUE); return 0; /* return undefined; */ } /* * Getter of PeridotServo.prototype.maxValue */ DUK_LOCAL duk_ret_t servo_proto_maxValue_getter(duk_context *ctx) { /* [ ] */ duk_push_this(ctx); /* [ this ] */ if (!duk_get_prop_string(ctx, 0, DUK_IPK_PERIDOT_SERVO_CFG)) { return DUK_ERR_TYPE_ERROR; } /* [ this arr ] */ duk_get_prop_index(ctx, 1, SERVO_CFG_MAXVALUE); return 1; /* return <number>; */ } /* * Setter of PeridotServo.prototype.maxValue */ DUK_LOCAL duk_ret_t servo_proto_maxValue_setter(duk_context *ctx) { /* [ number ] */ duk_push_this(ctx); /* [ number this ] */ if (!duk_get_prop_string(ctx, 1, DUK_IPK_PERIDOT_SERVO_CFG)) { return DUK_ERR_TYPE_ERROR; } /* [ number this arr ] */ duk_push_number(ctx, duk_require_number(ctx, 0)); duk_get_prop_index(ctx, 2, SERVO_CFG_MAXVALUE); return 0; /* return undefined; */ } /* * Getter of PeridotServo.prototype.minValue */ DUK_LOCAL duk_ret_t servo_proto_minValue_getter(duk_context *ctx) { /* [ ] */ duk_push_this(ctx); /* [ this ] */ if (!duk_get_prop_string(ctx, 0, DUK_IPK_PERIDOT_SERVO_CFG)) { return DUK_ERR_TYPE_ERROR; } /* [ this arr ] */ duk_get_prop_index(ctx, 1, SERVO_CFG_MINVALUE); return 1; /* return <number>; */ } /* * Setter of PeridotServo.prototype.minValue */ DUK_LOCAL duk_ret_t servo_proto_minValue_setter(duk_context *ctx) { /* [ number ] */ duk_push_this(ctx); /* [ number this ] */ if (!duk_get_prop_string(ctx, 1, DUK_IPK_PERIDOT_SERVO_CFG)) { return DUK_ERR_TYPE_ERROR; } /* [ number this arr ] */ duk_push_number(ctx, duk_require_number(ctx, 0)); duk_get_prop_index(ctx, 2, SERVO_CFG_MINVALUE); return 0; /* return undefined; */ } #endif /* * Getter of PeridotServo.prototype.pin */ DUK_LOCAL duk_ret_t servo_proto_pin_getter(duk_context *ctx) { /* [ ] */ duk_push_this(ctx); /* [ this ] */ if (!duk_get_prop_string(ctx, 0, DUX_IPK_PERIDOT_SERVO_PIN)) { return DUK_ERR_TYPE_ERROR; } /* [ this int ] */ return 1; /* return <int>; */ } /* * Getter of PeridotServo.prototype.rawValue */ DUK_LOCAL duk_ret_t servo_proto_rawValue_getter(duk_context *ctx) { duk_int_t pin; duk_int_t value; /* [ ] */ duk_push_this(ctx); /* [ this ] */ if (!duk_get_prop_string(ctx, 0, DUX_IPK_PERIDOT_SERVO_PIN)) { return DUK_RET_TYPE_ERROR; } /* [ this int ] */ pin = duk_require_int(ctx, 1); value = peridot_servo_get_value(pin); if (value < 0) { return DUK_RET_ERROR; } duk_push_int(ctx, value); return 1; /* return <int>; */ } /* * Setter of PeridotServo.prototype.rawValue */ DUK_LOCAL duk_ret_t servo_proto_rawValue_setter(duk_context *ctx) { duk_int_t pin; duk_int_t value; /* [ int(value) ] */ duk_push_this(ctx); /* [ int(value) this ] */ if (!duk_get_prop_string(ctx, 1, DUX_IPK_PERIDOT_SERVO_PIN)) { return DUK_RET_TYPE_ERROR; } /* [ int(value) this int ] */ pin = duk_require_int(ctx, 2); value = duk_require_int(ctx, 0); if (value < 0) { value = 0; } else if (value > 255) { value = 255; } if (peridot_servo_set_value(pin, value) < 0) { return DUK_RET_ERROR; } return 0; /* return undefined; */ } #if 0 /* * Getter of PeridotServo.prototype.saturated */ DUK_LOCAL duk_ret_t servo_proto_saturated_getter(duk_context *ctx) { /* [ ] */ duk_push_this(ctx); /* [ this ] */ if (!duk_get_prop_string(ctx, 0, DUK_IPK_PERIDOT_SERVO_CFG)) { return DUK_ERR_TYPE_ERROR; } /* [ this arr ] */ duk_get_prop_index(ctx, 1, SERVO_CFG_SATURATED); return 1; /* return <bool>; */ } /* * Getter of PeridotServo.prototype.value */ DUK_LOCAL duk_ret_t servo_proto_value_getter(duk_context *ctx) { /* [ ] */ duk_push_this(ctx); /* [ this ] */ if (!duk_get_prop_string(ctx, 0, DUK_IPK_PERIDOT_SERVO_CFG)) { return DUK_ERR_TYPE_ERROR; } /* [ this arr ] */ duk_get_prop_index(ctx, 1, SERVO_CFG_VALUE); return 1; /* return <number>; */ } /* * Setter of PeridotServo.prototype.value */ DUK_LOCAL duk_ret_t servo_proto_value_setter(duk_context *ctx) { duk_int_t maxR, minR, newR; /* [ number ] */ duk_push_this(ctx); /* [ number this ] */ if (!duk_get_prop_string(ctx, 1, DUK_IPK_PERIDOT_SERVO_CFG)) { return DUK_ERR_TYPE_ERROR; } /* [ number this arr ] */ duk_get_prop_index(ctx, 2, SERVO_CFG_FLOATMODE); duk_get_prop_index(ctx, 2, SERVO_CFG_MAXVALUE); duk_get_prop_index(ctx, 2, SERVO_CFG_MINVALUE); duk_get_prop_index(ctx, 2, SERVO_CFG_MAXRAWVALUE); duk_get_prop_index(ctx, 2, SERVO_CFG_MINRAWVALUE); /* [ number this arr bool:3 number:4 number:5 int:6 int:7 ] */ maxR = duk_require_int(ctx, 6); minR = duk_require_int(ctx, 7); #define CALC(type, getter) \ type curV, maxV, minV; \ curV = getter(ctx, 0); \ maxV = getter(ctx, 4); \ minV = getter(ctx, 5); \ if (curV < minV) { \ curV = minV; \ } else if (curV > maxV) { \ curV = maxV; \ } \ if (duk_require_boolean(ctx, 3)) { CALC(double, duk_require_number); } else { CALC(duk_int_t, duk_require_int); } return 0; /* return undefined; */ } #endif /* * Entry of PeridotServo constructor */ DUK_LOCAL duk_ret_t servo_constructor(duk_context *ctx) { duk_int_t pin; int result; /* [ obj(pin) ] */ if (!duk_is_constructor_call(ctx)) { return DUK_RET_TYPE_ERROR; } pin = dux_get_peridot_pin(ctx, 0); if (pin < 0) { return pin; } result = peridot_servo_configure_pwm(pin, 0); if (result < 0) { return DUK_RET_ERROR; } duk_push_this(ctx); duk_push_int(ctx, pin); /* [ obj(pin) this int ] */ duk_put_prop_string(ctx, 1, DUX_IPK_PERIDOT_SERVO_PIN); /* [ obj(pin) this ] */ return 0; /* return this; */ } /* * List of class methods */ DUK_LOCAL const duk_function_list_entry servo_funcs[] = { { "enableAll", servo_enableAll, 0 }, { "disableAll", servo_disableAll, 0 }, { NULL, NULL, 0 } }; /* * List of prototype properties */ DUK_LOCAL const dux_property_list_entry servo_proto_props[] = { // { "floatMode", servo_proto_floatMode_getter, servo_proto_floatMode_setter }, // { "maxRawValue", servo_proto_maxRawValue_getter, servo_proto_maxRawValue_setter }, // { "minRawValue", servo_proto_minRawValue_getter, servo_proto_minRawValue_setter }, // { "maxValue", servo_proto_maxValue_getter, servo_proto_maxValue_setter }, // { "minValue", servo_proto_minValue_getter, servo_proto_minValue_setter }, { "pin", servo_proto_pin_getter, NULL }, { "rawValue", servo_proto_rawValue_getter, servo_proto_rawValue_setter }, // { "saturated", servo_proto_saturated_getter, NULL }, // { "value", servo_proto_value_getter, servo_proto_value_setter }, { NULL, NULL, NULL } }; /* * Initialize PeridotServo module */ DUK_INTERNAL duk_errcode_t dux_peridot_servo_init(duk_context *ctx) { /* [ ... obj ] */ dux_push_named_c_constructor( ctx, "PeridotServo", servo_constructor, 1, servo_funcs, NULL, NULL, servo_proto_props); /* [ ... obj constructor ] */ duk_put_prop_string(ctx, -2, "Servo"); /* [ ... obj ] */ return DUK_ERR_NONE; } #endif /* !DUX_OPT_NO_HARDWARE_MODULES && !DUX_OPT_NO_SERVO */ #endif /* DUX_USE_BOARD_PERIDOT */
the_stack_data/90764521.c
#include <stdio.h> #define QUEUE_SIZE 5 int q[QUEUE_SIZE], front = -1, rear = -1, next; void enq(int n){ if(front == -1){ front = rear = 0; q[rear] = n; }else{ next = (rear + 1)%QUEUE_SIZE; if(next == front){ printf("Queue is full\n"); }else{ rear = next; q[rear] = n; } } } void deq(){ if(front == -1){ printf("Queue is Empty\n"); }else{ printf("%d\n", q[front]); if(front == rear){ front = rear = -1; }else{ front = (front + 1)%QUEUE_SIZE; } } } void status(){ if(front == -1){ printf("Queue is Empty\n"); }else if((rear + 1)%QUEUE_SIZE == front){ printf("Queue is full\n"); }else{ if(front == rear){ printf("1 Element\n"); }else if(front < rear){ printf("%d elements\n", (rear-front+1)); }else{ printf("%d elements\n", (front+ QUEUE_SIZE-rear)); } } } void main(){ int c, n; do{ printf("1. Enuqeue\n2. Dequeue\n3. Status\n0. Exit\n: "); scanf("%d", &c); switch(c){ case 1:printf("Enter element:"); scanf("%d", &n); enq(n); break; case 2:deq(); break; case 3:status(); break; case 0:; break; default:printf("Invalid\n"); } }while(c != 0); }
the_stack_data/104779.c
// memory leak in sctp_stream_init // https://syzkaller.appspot.com/bug?id=c61c7e57b46f3eb46e5712f4750ca475fb98526e // status:open // autogenerated by syzkaller (https://github.com/google/syzkaller) #define _GNU_SOURCE #include <arpa/inet.h> #include <dirent.h> #include <endian.h> #include <errno.h> #include <fcntl.h> #include <net/if.h> #include <netinet/in.h> #include <signal.h> #include <stdarg.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/prctl.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/types.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> #include <linux/genetlink.h> #include <linux/if_addr.h> #include <linux/if_link.h> #include <linux/in6.h> #include <linux/neighbour.h> #include <linux/net.h> #include <linux/netlink.h> #include <linux/rtnetlink.h> #include <linux/veth.h> static void sleep_ms(uint64_t ms) { usleep(ms * 1000); } static uint64_t current_time_ms(void) { struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts)) exit(1); return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000; } static bool write_file(const char* file, const char* what, ...) { char buf[1024]; va_list args; va_start(args, what); vsnprintf(buf, sizeof(buf), what, args); va_end(args); buf[sizeof(buf) - 1] = 0; int len = strlen(buf); int fd = open(file, O_WRONLY | O_CLOEXEC); if (fd == -1) return false; if (write(fd, buf, len) != len) { int err = errno; close(fd); errno = err; return false; } close(fd); return true; } struct nlmsg { char* pos; int nesting; struct nlattr* nested[8]; char buf[1024]; }; static struct nlmsg nlmsg; static void netlink_init(struct nlmsg* nlmsg, int typ, int flags, const void* data, int size) { memset(nlmsg, 0, sizeof(*nlmsg)); struct nlmsghdr* hdr = (struct nlmsghdr*)nlmsg->buf; hdr->nlmsg_type = typ; hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | flags; memcpy(hdr + 1, data, size); nlmsg->pos = (char*)(hdr + 1) + NLMSG_ALIGN(size); } static void netlink_attr(struct nlmsg* nlmsg, int typ, const void* data, int size) { struct nlattr* attr = (struct nlattr*)nlmsg->pos; attr->nla_len = sizeof(*attr) + size; attr->nla_type = typ; memcpy(attr + 1, data, size); nlmsg->pos += NLMSG_ALIGN(attr->nla_len); } static int netlink_send_ext(struct nlmsg* nlmsg, int sock, uint16_t reply_type, int* reply_len) { if (nlmsg->pos > nlmsg->buf + sizeof(nlmsg->buf) || nlmsg->nesting) exit(1); struct nlmsghdr* hdr = (struct nlmsghdr*)nlmsg->buf; hdr->nlmsg_len = nlmsg->pos - nlmsg->buf; struct sockaddr_nl addr; memset(&addr, 0, sizeof(addr)); addr.nl_family = AF_NETLINK; unsigned n = sendto(sock, nlmsg->buf, hdr->nlmsg_len, 0, (struct sockaddr*)&addr, sizeof(addr)); if (n != hdr->nlmsg_len) exit(1); n = recv(sock, nlmsg->buf, sizeof(nlmsg->buf), 0); if (hdr->nlmsg_type == NLMSG_DONE) { *reply_len = 0; return 0; } if (n < sizeof(struct nlmsghdr)) exit(1); if (reply_len && hdr->nlmsg_type == reply_type) { *reply_len = n; return 0; } if (n < sizeof(struct nlmsghdr) + sizeof(struct nlmsgerr)) exit(1); if (hdr->nlmsg_type != NLMSG_ERROR) exit(1); return -((struct nlmsgerr*)(hdr + 1))->error; } static int netlink_send(struct nlmsg* nlmsg, int sock) { return netlink_send_ext(nlmsg, sock, 0, NULL); } static int netlink_next_msg(struct nlmsg* nlmsg, unsigned int offset, unsigned int total_len) { struct nlmsghdr* hdr = (struct nlmsghdr*)(nlmsg->buf + offset); if (offset == total_len || offset + hdr->nlmsg_len > total_len) return -1; return hdr->nlmsg_len; } static void netlink_device_change(struct nlmsg* nlmsg, int sock, const char* name, bool up, const char* master, const void* mac, int macsize, const char* new_name) { struct ifinfomsg hdr; memset(&hdr, 0, sizeof(hdr)); if (up) hdr.ifi_flags = hdr.ifi_change = IFF_UP; hdr.ifi_index = if_nametoindex(name); netlink_init(nlmsg, RTM_NEWLINK, 0, &hdr, sizeof(hdr)); if (new_name) netlink_attr(nlmsg, IFLA_IFNAME, new_name, strlen(new_name)); if (master) { int ifindex = if_nametoindex(master); netlink_attr(nlmsg, IFLA_MASTER, &ifindex, sizeof(ifindex)); } if (macsize) netlink_attr(nlmsg, IFLA_ADDRESS, mac, macsize); int err = netlink_send(nlmsg, sock); (void)err; } const int kInitNetNsFd = 239; #define DEVLINK_FAMILY_NAME "devlink" #define DEVLINK_CMD_PORT_GET 5 #define DEVLINK_CMD_RELOAD 37 #define DEVLINK_ATTR_BUS_NAME 1 #define DEVLINK_ATTR_DEV_NAME 2 #define DEVLINK_ATTR_NETDEV_NAME 7 #define DEVLINK_ATTR_NETNS_FD 138 static int netlink_devlink_id_get(struct nlmsg* nlmsg, int sock) { struct genlmsghdr genlhdr; struct nlattr* attr; int err, n; uint16_t id = 0; memset(&genlhdr, 0, sizeof(genlhdr)); genlhdr.cmd = CTRL_CMD_GETFAMILY; netlink_init(nlmsg, GENL_ID_CTRL, 0, &genlhdr, sizeof(genlhdr)); netlink_attr(nlmsg, CTRL_ATTR_FAMILY_NAME, DEVLINK_FAMILY_NAME, strlen(DEVLINK_FAMILY_NAME) + 1); err = netlink_send_ext(nlmsg, sock, GENL_ID_CTRL, &n); if (err) { return -1; } attr = (struct nlattr*)(nlmsg->buf + NLMSG_HDRLEN + NLMSG_ALIGN(sizeof(genlhdr))); for (; (char*)attr < nlmsg->buf + n; attr = (struct nlattr*)((char*)attr + NLMSG_ALIGN(attr->nla_len))) { if (attr->nla_type == CTRL_ATTR_FAMILY_ID) { id = *(uint16_t*)(attr + 1); break; } } if (!id) { return -1; } recv(sock, nlmsg->buf, sizeof(nlmsg->buf), 0); /* recv ack */ return id; } static void netlink_devlink_netns_move(const char* bus_name, const char* dev_name, int netns_fd) { struct genlmsghdr genlhdr; int sock; int id, err; sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_GENERIC); if (sock == -1) exit(1); id = netlink_devlink_id_get(&nlmsg, sock); if (id == -1) goto error; memset(&genlhdr, 0, sizeof(genlhdr)); genlhdr.cmd = DEVLINK_CMD_RELOAD; netlink_init(&nlmsg, id, 0, &genlhdr, sizeof(genlhdr)); netlink_attr(&nlmsg, DEVLINK_ATTR_BUS_NAME, bus_name, strlen(bus_name) + 1); netlink_attr(&nlmsg, DEVLINK_ATTR_DEV_NAME, dev_name, strlen(dev_name) + 1); netlink_attr(&nlmsg, DEVLINK_ATTR_NETNS_FD, &netns_fd, sizeof(netns_fd)); err = netlink_send(&nlmsg, sock); if (err) { } error: close(sock); } static struct nlmsg nlmsg2; static void initialize_devlink_ports(const char* bus_name, const char* dev_name, const char* netdev_prefix) { struct genlmsghdr genlhdr; int len, total_len, id, err, offset; uint16_t netdev_index; int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_GENERIC); if (sock == -1) exit(1); int rtsock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (rtsock == -1) exit(1); id = netlink_devlink_id_get(&nlmsg, sock); if (id == -1) goto error; memset(&genlhdr, 0, sizeof(genlhdr)); genlhdr.cmd = DEVLINK_CMD_PORT_GET; netlink_init(&nlmsg, id, NLM_F_DUMP, &genlhdr, sizeof(genlhdr)); netlink_attr(&nlmsg, DEVLINK_ATTR_BUS_NAME, bus_name, strlen(bus_name) + 1); netlink_attr(&nlmsg, DEVLINK_ATTR_DEV_NAME, dev_name, strlen(dev_name) + 1); err = netlink_send_ext(&nlmsg, sock, id, &total_len); if (err) { goto error; } offset = 0; netdev_index = 0; while ((len = netlink_next_msg(&nlmsg, offset, total_len)) != -1) { struct nlattr* attr = (struct nlattr*)(nlmsg.buf + offset + NLMSG_HDRLEN + NLMSG_ALIGN(sizeof(genlhdr))); for (; (char*)attr < nlmsg.buf + offset + len; attr = (struct nlattr*)((char*)attr + NLMSG_ALIGN(attr->nla_len))) { if (attr->nla_type == DEVLINK_ATTR_NETDEV_NAME) { char* port_name; char netdev_name[IFNAMSIZ]; port_name = (char*)(attr + 1); snprintf(netdev_name, sizeof(netdev_name), "%s%d", netdev_prefix, netdev_index); netlink_device_change(&nlmsg2, rtsock, port_name, true, 0, 0, 0, netdev_name); break; } } offset += len; netdev_index++; } error: close(rtsock); close(sock); } static void initialize_devlink_pci(void) { int netns = open("/proc/self/ns/net", O_RDONLY); if (netns == -1) exit(1); int ret = setns(kInitNetNsFd, 0); if (ret == -1) exit(1); netlink_devlink_netns_move("pci", "0000:00:10.0", netns); ret = setns(netns, 0); if (ret == -1) exit(1); close(netns); initialize_devlink_ports("pci", "0000:00:10.0", "netpci"); } static int inject_fault(int nth) { int fd; fd = open("/proc/thread-self/fail-nth", O_RDWR); if (fd == -1) exit(1); char buf[16]; sprintf(buf, "%d", nth + 1); if (write(fd, buf, strlen(buf)) != (ssize_t)strlen(buf)) exit(1); return fd; } static void kill_and_wait(int pid, int* status) { kill(-pid, SIGKILL); kill(pid, SIGKILL); int i; for (i = 0; i < 100; i++) { if (waitpid(-1, status, WNOHANG | __WALL) == pid) return; usleep(1000); } DIR* dir = opendir("/sys/fs/fuse/connections"); if (dir) { for (;;) { struct dirent* ent = readdir(dir); if (!ent) break; if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue; char abort[300]; snprintf(abort, sizeof(abort), "/sys/fs/fuse/connections/%s/abort", ent->d_name); int fd = open(abort, O_WRONLY); if (fd == -1) { continue; } if (write(fd, abort, 1) < 0) { } close(fd); } closedir(dir); } else { } while (waitpid(-1, status, __WALL) != pid) { } } static void setup_test() { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); setpgrp(); write_file("/proc/self/oom_score_adj", "1000"); } static void setup_fault() { static struct { const char* file; const char* val; bool fatal; } files[] = { {"/sys/kernel/debug/failslab/ignore-gfp-wait", "N", true}, {"/sys/kernel/debug/fail_futex/ignore-private", "N", false}, {"/sys/kernel/debug/fail_page_alloc/ignore-gfp-highmem", "N", false}, {"/sys/kernel/debug/fail_page_alloc/ignore-gfp-wait", "N", false}, {"/sys/kernel/debug/fail_page_alloc/min-order", "0", false}, }; unsigned i; for (i = 0; i < sizeof(files) / sizeof(files[0]); i++) { if (!write_file(files[i].file, files[i].val)) { if (files[i].fatal) exit(1); } } } #define KMEMLEAK_FILE "/sys/kernel/debug/kmemleak" static void setup_leak() { if (!write_file(KMEMLEAK_FILE, "scan")) exit(1); sleep(5); if (!write_file(KMEMLEAK_FILE, "scan")) exit(1); if (!write_file(KMEMLEAK_FILE, "clear")) exit(1); } static void check_leaks(void) { int fd = open(KMEMLEAK_FILE, O_RDWR); if (fd == -1) exit(1); uint64_t start = current_time_ms(); if (write(fd, "scan", 4) != 4) exit(1); sleep(1); while (current_time_ms() - start < 4 * 1000) sleep(1); if (write(fd, "scan", 4) != 4) exit(1); static char buf[128 << 10]; ssize_t n = read(fd, buf, sizeof(buf) - 1); if (n < 0) exit(1); int nleaks = 0; if (n != 0) { sleep(1); if (write(fd, "scan", 4) != 4) exit(1); if (lseek(fd, 0, SEEK_SET) < 0) exit(1); n = read(fd, buf, sizeof(buf) - 1); if (n < 0) exit(1); buf[n] = 0; char* pos = buf; char* end = buf + n; while (pos < end) { char* next = strstr(pos + 1, "unreferenced object"); if (!next) next = end; char prev = *next; *next = 0; fprintf(stderr, "BUG: memory leak\n%s\n", pos); *next = prev; pos = next; nleaks++; } } if (write(fd, "clear", 5) != 5) exit(1); close(fd); if (nleaks) exit(1); } static void execute_one(void); #define WAIT_FLAGS __WALL static void loop(void) { int iter; for (iter = 0;; iter++) { int pid = fork(); if (pid < 0) exit(1); if (pid == 0) { setup_test(); execute_one(); exit(0); } int status = 0; uint64_t start = current_time_ms(); for (;;) { if (waitpid(-1, &status, WNOHANG | WAIT_FLAGS) == pid) break; sleep_ms(1); if (current_time_ms() - start < 5 * 1000) continue; kill_and_wait(pid, &status); break; } check_leaks(); } } uint64_t r[1] = {0xffffffffffffffff}; void execute_one(void) { intptr_t res = 0; syscall(__NR_perf_event_open, 0ul, 0, 0ul, -1, 0ul); res = syscall(__NR_socket, 2ul, 0x2000080001ul, 0x84); if (res != -1) r[0] = res; syscall(__NR_setsockopt, r[0], 0x84ul, 0x7bul, 0ul, 0ul); *(uint16_t*)0x20000000 = 0xfff; *(uint16_t*)0x20000002 = 0; *(uint16_t*)0x20000004 = 0; *(uint16_t*)0x20000006 = 0; syscall(__NR_setsockopt, r[0], 0x84ul, 2ul, 0x20000000ul, 8ul); *(uint32_t*)0x20000140 = 0; *(uint32_t*)0x20000144 = 0x10; *(uint64_t*)0x20000148 = 0x20000080; *(uint16_t*)0x20000080 = 2; *(uint16_t*)0x20000082 = htobe16(0); *(uint8_t*)0x20000084 = 0xac; *(uint8_t*)0x20000085 = 0x14; *(uint8_t*)0x20000086 = 0x14; *(uint8_t*)0x20000087 = 0xaa; *(uint32_t*)0x20000180 = 0x10; inject_fault(10); syscall(__NR_getsockopt, r[0], 0x84ul, 0x6ful, 0x20000140ul, 0x20000180ul); } int main(void) { syscall(__NR_mmap, 0x20000000ul, 0x1000000ul, 3ul, 0x32ul, -1, 0); setup_leak(); setup_fault(); loop(); return 0; }
the_stack_data/48574622.c
/* */ #include <limits.h> int main(void){return 0;}
the_stack_data/231393569.c
// Should save and read back the assembly from a file // RUN: %clang -target arm-none-linux-gnueabi -integrated-as -via-file-asm %s -### 2>&1 | FileCheck %s // CHECK: "-cc1" // CHECK: "-o" "[[TMP:[^"]*]]" // CHECK: -cc1as // CHECK: [[TMP]] // Should not force using the integrated assembler // RUN: %clang -target arm-none-linux-gnueabi -no-integrated-as -via-file-asm %s -### 2>&1 | FileCheck --check-prefix=NO_IAS %s // NO_IAS-NOT: "-cc1as"
the_stack_data/140766548.c
#include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <sys/wait.h> #include <string.h> void trata_alarma(int s) { } int main(int argc,char *argv[]) { int pid,res; char buff[256]; int contador = 0; int hijos=0; for (hijos=0;hijos<10;hijos++) { sprintf(buff, "Creando el hijo numero %d\n", hijos); write(1, buff, strlen(buff)); pid=fork(); if (pid==0) /* Esta linea la ejecutan tanto el padre como el hijo */ { signal (SIGALRM, trata_alarma); /* Escribe aqui el codigo del proceso hijo */ sprintf(buff,"Hola, soy %d\n",getpid()); write(1, buff, strlen(buff)); alarm(1); pause(); /* Termina su ejecución */ exit(0); }else if (pid<0) { /* Se ha producido un error */ perror("Error en el fork"); } } /* Esperamos que acaben los hijos */ while (hijos > 0) { pid=waitpid(-1,&res,0); if (WIFEXITED(res) != 0 ) { sprintf(buff,"Termina el proceso %d con un exit. Exit status:%d \n",pid, WEXITSTATUS(res)); write(1, buff, strlen(buff)); } else { sprintf(buff,"Termina el proceso %d con un signal. Signal code:%d \n",pid, WIFSIGNALED(res)); write(1, buff, strlen(buff)); } hijos --; contador++; } sprintf(buff,"Valor del contador %d\n", contador); write(1, buff, strlen(buff)); return 0; }
the_stack_data/13384.c
#include <stdio.h> int main(void) { int num; printf("Enter the number of rows and columns for the square: "); scanf("%d", &num); for (int i = 1; i <= num; i++) { for (int j = 1; j <= num; j++) { printf("%d ", j); } printf("\n"); } return 0; }
the_stack_data/68886984.c
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ typedef struct TYPE_12__ TYPE_6__ ; typedef struct TYPE_11__ TYPE_5__ ; typedef struct TYPE_10__ TYPE_4__ ; typedef struct TYPE_9__ TYPE_3__ ; typedef struct TYPE_8__ TYPE_2__ ; typedef struct TYPE_7__ TYPE_1__ ; /* Type definitions */ struct TYPE_12__ {int pkey_index; int sched_queue; int ackto; } ; struct mlx4_qp_context {int mtu_msgmax; TYPE_6__ alt_path; int /*<<< orphan*/ params1; TYPE_6__ pri_path; int /*<<< orphan*/ rnr_nextrecvpsn; int /*<<< orphan*/ params2; int /*<<< orphan*/ remote_qpn; int /*<<< orphan*/ next_send_psn; int /*<<< orphan*/ qkey; int /*<<< orphan*/ flags; } ; struct TYPE_9__ {int /*<<< orphan*/ max_gs; int /*<<< orphan*/ wqe_cnt; } ; struct TYPE_8__ {int /*<<< orphan*/ max_gs; int /*<<< orphan*/ wqe_cnt; } ; struct TYPE_7__ {scalar_t__ qp_type; } ; struct mlx4_ib_qp {scalar_t__ state; int port; int flags; scalar_t__ sq_signal_bits; int /*<<< orphan*/ mutex; TYPE_3__ sq; TYPE_2__ rq; TYPE_1__ ibqp; int /*<<< orphan*/ mqp; } ; struct mlx4_ib_dev {int /*<<< orphan*/ dev; } ; struct TYPE_10__ {scalar_t__ max_inline_data; int /*<<< orphan*/ max_send_sge; int /*<<< orphan*/ max_send_wr; int /*<<< orphan*/ max_recv_sge; int /*<<< orphan*/ max_recv_wr; } ; struct ib_qp_init_attr {int /*<<< orphan*/ sq_sig_type; int /*<<< orphan*/ create_flags; TYPE_4__ cap; } ; struct TYPE_11__ {int /*<<< orphan*/ port_num; } ; struct ib_qp_attr {scalar_t__ qp_state; int path_mtu; int qkey; int rq_psn; int sq_psn; int dest_qp_num; int alt_pkey_index; int pkey_index; int port_num; int sq_draining; int max_rd_atomic; int max_dest_rd_atomic; int min_rnr_timer; int timeout; int retry_cnt; int rnr_retry; int alt_timeout; scalar_t__ cur_qp_state; TYPE_4__ cap; TYPE_5__ alt_ah_attr; int /*<<< orphan*/ alt_port_num; TYPE_5__ ah_attr; int /*<<< orphan*/ qp_access_flags; int /*<<< orphan*/ path_mig_state; } ; struct ib_qp {int /*<<< orphan*/ uobject; int /*<<< orphan*/ device; } ; /* Variables and functions */ int EINVAL ; scalar_t__ IB_QPS_INIT ; scalar_t__ IB_QPS_RESET ; scalar_t__ IB_QPT_RC ; scalar_t__ IB_QPT_UC ; int /*<<< orphan*/ IB_QP_CREATE_BLOCK_MULTICAST_LOOPBACK ; int /*<<< orphan*/ IB_QP_CREATE_IPOIB_UD_LSO ; int /*<<< orphan*/ IB_QP_CREATE_NETIF_QP ; int /*<<< orphan*/ IB_SIGNAL_ALL_WR ; int /*<<< orphan*/ IB_SIGNAL_REQ_WR ; int MLX4_IB_QP_BLOCK_MULTICAST_LOOPBACK ; int MLX4_IB_QP_LSO ; int MLX4_IB_QP_NETIF ; int MLX4_QP_STATE_SQ_DRAINING ; int /*<<< orphan*/ MLX4_WQE_CTRL_CQ_UPDATE ; int be32_to_cpu (int /*<<< orphan*/ ) ; scalar_t__ cpu_to_be32 (int /*<<< orphan*/ ) ; int mlx4_qp_query (int /*<<< orphan*/ ,int /*<<< orphan*/ *,struct mlx4_qp_context*) ; int /*<<< orphan*/ mutex_lock (int /*<<< orphan*/ *) ; int /*<<< orphan*/ mutex_unlock (int /*<<< orphan*/ *) ; int /*<<< orphan*/ to_ib_ah_attr (struct mlx4_ib_dev*,TYPE_5__*,TYPE_6__*) ; int /*<<< orphan*/ to_ib_mig_state (int) ; int /*<<< orphan*/ to_ib_qp_access_flags (int) ; scalar_t__ to_ib_qp_state (int) ; struct mlx4_ib_dev* to_mdev (int /*<<< orphan*/ ) ; struct mlx4_ib_qp* to_mqp (struct ib_qp*) ; int mlx4_ib_query_qp(struct ib_qp *ibqp, struct ib_qp_attr *qp_attr, int qp_attr_mask, struct ib_qp_init_attr *qp_init_attr) { struct mlx4_ib_dev *dev = to_mdev(ibqp->device); struct mlx4_ib_qp *qp = to_mqp(ibqp); struct mlx4_qp_context context; int mlx4_state; int err = 0; mutex_lock(&qp->mutex); if (qp->state == IB_QPS_RESET) { qp_attr->qp_state = IB_QPS_RESET; goto done; } err = mlx4_qp_query(dev->dev, &qp->mqp, &context); if (err) { err = -EINVAL; goto out; } mlx4_state = be32_to_cpu(context.flags) >> 28; qp->state = to_ib_qp_state(mlx4_state); qp_attr->qp_state = qp->state; qp_attr->path_mtu = context.mtu_msgmax >> 5; qp_attr->path_mig_state = to_ib_mig_state((be32_to_cpu(context.flags) >> 11) & 0x3); qp_attr->qkey = be32_to_cpu(context.qkey); qp_attr->rq_psn = be32_to_cpu(context.rnr_nextrecvpsn) & 0xffffff; qp_attr->sq_psn = be32_to_cpu(context.next_send_psn) & 0xffffff; qp_attr->dest_qp_num = be32_to_cpu(context.remote_qpn) & 0xffffff; qp_attr->qp_access_flags = to_ib_qp_access_flags(be32_to_cpu(context.params2)); if (qp->ibqp.qp_type == IB_QPT_RC || qp->ibqp.qp_type == IB_QPT_UC) { to_ib_ah_attr(dev, &qp_attr->ah_attr, &context.pri_path); to_ib_ah_attr(dev, &qp_attr->alt_ah_attr, &context.alt_path); qp_attr->alt_pkey_index = context.alt_path.pkey_index & 0x7f; qp_attr->alt_port_num = qp_attr->alt_ah_attr.port_num; } qp_attr->pkey_index = context.pri_path.pkey_index & 0x7f; if (qp_attr->qp_state == IB_QPS_INIT) qp_attr->port_num = qp->port; else qp_attr->port_num = context.pri_path.sched_queue & 0x40 ? 2 : 1; /* qp_attr->en_sqd_async_notify is only applicable in modify qp */ qp_attr->sq_draining = mlx4_state == MLX4_QP_STATE_SQ_DRAINING; qp_attr->max_rd_atomic = 1 << ((be32_to_cpu(context.params1) >> 21) & 0x7); qp_attr->max_dest_rd_atomic = 1 << ((be32_to_cpu(context.params2) >> 21) & 0x7); qp_attr->min_rnr_timer = (be32_to_cpu(context.rnr_nextrecvpsn) >> 24) & 0x1f; qp_attr->timeout = context.pri_path.ackto >> 3; qp_attr->retry_cnt = (be32_to_cpu(context.params1) >> 16) & 0x7; qp_attr->rnr_retry = (be32_to_cpu(context.params1) >> 13) & 0x7; qp_attr->alt_timeout = context.alt_path.ackto >> 3; done: qp_attr->cur_qp_state = qp_attr->qp_state; qp_attr->cap.max_recv_wr = qp->rq.wqe_cnt; qp_attr->cap.max_recv_sge = qp->rq.max_gs; if (!ibqp->uobject) { qp_attr->cap.max_send_wr = qp->sq.wqe_cnt; qp_attr->cap.max_send_sge = qp->sq.max_gs; } else { qp_attr->cap.max_send_wr = 0; qp_attr->cap.max_send_sge = 0; } /* * We don't support inline sends for kernel QPs (yet), and we * don't know what userspace's value should be. */ qp_attr->cap.max_inline_data = 0; qp_init_attr->cap = qp_attr->cap; qp_init_attr->create_flags = 0; if (qp->flags & MLX4_IB_QP_BLOCK_MULTICAST_LOOPBACK) qp_init_attr->create_flags |= IB_QP_CREATE_BLOCK_MULTICAST_LOOPBACK; if (qp->flags & MLX4_IB_QP_LSO) qp_init_attr->create_flags |= IB_QP_CREATE_IPOIB_UD_LSO; if (qp->flags & MLX4_IB_QP_NETIF) qp_init_attr->create_flags |= IB_QP_CREATE_NETIF_QP; qp_init_attr->sq_sig_type = qp->sq_signal_bits == cpu_to_be32(MLX4_WQE_CTRL_CQ_UPDATE) ? IB_SIGNAL_ALL_WR : IB_SIGNAL_REQ_WR; out: mutex_unlock(&qp->mutex); return err; }
the_stack_data/159515469.c
// RUN: %clang -target i686-pc-linux-gnu -### -nodefaultlibs %s 2> %t // RUN: FileCheck < %t %s // // CHECK-NOT: start-group // CHECK-NOT: "-lgcc" // CHECK-NOT: "-lc" // CHECK: crtbegin // CHECK: crtend
the_stack_data/78656.c
int main() { int a[1005]; int n, i, max, x, br; for(i = 1; i <= 1005; i = i + 1) { a[i] = 0; } scanf("%d", &n); for(i = 1; i <= n; i = i + 1) { scanf("%d", &x); a[x] = a[x] + 1; } max = -1; for(i = 1; i <= 1005; i = i + 1) { if(max < a[i]) { max = a[i]; br = i; } } printf("%d %d", br, max); return 0; }
the_stack_data/191529.c
// // main.c // returnStatements // // Created by Rodrigo Weber on 04/07/20. // Copyright © 2020 Rodrigo Weber. All rights reserved. // #include <stdio.h> void cube(int number); int main(int argc, const char * argv[]) { cube(5); return 0; } void cube(int number){ int cubeNumber = number * number * number; printf("The cube of the %d is %d\n", number, cubeNumber); }
the_stack_data/99098.c
#define _GNU_SOURCE 1 #include <sys/mman.h> #include "syscall.h" int mlock2(const void *addr, size_t len, unsigned flags) { #ifdef PS4 return mlock(addr, len); #else if (flags == 0) return mlock(addr, len); return syscall(SYS_mlock2, addr, len, flags); #endif }
the_stack_data/3263507.c
#include <signal.h> #include <stdio.h> #include <string.h> #include <unistd.h> void handler(int signo) { _exit(signo); } int main (int argc, char *argv[]) { #ifndef __APPLE__ // Real time signals not supported on apple platforms. if (signal(SIGRTMIN, handler) == SIG_ERR) { perror("signal(SIGRTMIN)"); return 1; } #endif if (argc < 2) { puts("Please specify a signal to raise"); return 1; } if (strcmp(argv[1], "SIGSTOP") == 0) raise(SIGSTOP); #ifndef __APPLE__ else if (strcmp(argv[1], "SIGRTMIN") == 0) raise(SIGRTMIN); #endif else { printf("Unknown signal: %s\n", argv[1]); return 1; } return 0; }
the_stack_data/7017.c
/* * POK header * * The following file is a part of the POK project. Any modification should * be made according to the POK licence. You CANNOT use this file or a 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-2021 POK team */ #ifdef POK_NEEDS_DEBUG #include <arch.h> #include <core/cons.h> #include <core/debug.h> #include <core/multiprocessing.h> #include <core/partition.h> #include <core/sched.h> #include <core/thread.h> #include <errno.h> int debug_strlen(const char *str) { int i = 0; while (*str != '\0') { str++; i++; } return i; } void pok_debug_print_current_state() { uint32_t i; uint8_t current_proc = pok_get_proc_id(); printf("\nCurrent state\n"); printf("-------------\n"); printf("Processor : %d\n", current_proc); printf("Kernel thread : %d\n", KERNEL_THREAD); printf("Idle thread : %d\n", IDLE_THREAD); printf("Current partition : %d\n", POK_SCHED_CURRENT_PARTITION); printf("Thread index : %d\n", POK_CURRENT_PARTITION.thread_index); printf("Thread low : %d\n", POK_CURRENT_PARTITION.thread_index_low); printf("Thread high : %d\n", POK_CURRENT_PARTITION.thread_index_high); printf("Thread capacity : %d\n", POK_CURRENT_PARTITION.nthreads); printf("Base addr : 0x%x\n", POK_CURRENT_PARTITION.base_addr); printf("Base vaddr : 0x%x\n", POK_CURRENT_PARTITION.base_vaddr); printf("Size : %d\n", POK_CURRENT_PARTITION.size); printf("Current thread : %d\n", CURRENT_THREAD(POK_CURRENT_PARTITION)); printf("Prev current thread : %d\n", PREV_THREAD(POK_CURRENT_PARTITION)); printf("Main thread : %d\n", POK_CURRENT_PARTITION.thread_main); printf("Main thread entry : 0x%x\n", POK_CURRENT_PARTITION.thread_main_entry); printf("Partition threads sp :"); for (i = POK_CURRENT_PARTITION.thread_index_low; i < POK_CURRENT_PARTITION.thread_index_low + POK_CURRENT_PARTITION.thread_index; i++) { printf(" 0x%x", pok_threads[i].sp); } printf("\n"); printf("-------------\n"); printf("Current thread : %d\n", POK_SCHED_CURRENT_THREAD); printf("Period : %lld\n", POK_CURRENT_THREAD.period); printf("Deadline : %lld\n", POK_CURRENT_THREAD.deadline); printf("Partition : %d\n", POK_CURRENT_THREAD.partition); printf("sp : 0x%x\n", POK_CURRENT_THREAD.sp); printf("init_stack_addr : 0x%x\n", POK_CURRENT_THREAD.init_stack_addr); printf("entry : 0x%lx\n", (unsigned long int)POK_CURRENT_THREAD.entry); } void pok_fatal(const char *message) { pok_write("FATAL ERROR: \n", 13); pok_write(message, debug_strlen(message)); POK_DEBUG_PRINT_CURRENT_STATE pok_arch_idle(); } #endif /* POK_CONFIG_NEEDS_DEBUG */
the_stack_data/243893424.c
#include <arpa/inet.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> /* linux help manual open a terminal then type the following command man tcp man send man recv compile command gcc -o server raw_server.c */ #define SERVER_IP "127.0.0.1" #define SERVER_PORT 8000 #define BUFFER_SIZE 1024 struct sockaddr_in createServerInfo(const char *ip, int port) { struct sockaddr_in server_addr; memset(&server_addr, 0, sizeof(server_addr)); // Filling server information server_addr.sin_family = AF_INET; server_addr.sin_port = htons(port); //server_addr.sin_addr.s_addr = INADDR_ANY; server_addr.sin_addr.s_addr = inet_addr(ip); return server_addr; } int main() { char buffer[BUFFER_SIZE]; char msg[BUFFER_SIZE]; //create socket file descriptor int sock_fd = socket(AF_INET, SOCK_STREAM, 0); if (sock_fd < 0) { printf("socket creation failed\n"); return 0; } //init server address information struct sockaddr_in server_addr = createServerInfo(SERVER_IP, SERVER_PORT); //bind to address int res = bind(sock_fd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr_in)); if (res < 0) { printf("bind failed,may be port %d already in use\n", SERVER_PORT); return 0; } //listen res = listen(sock_fd, 1); if (res < 0) { printf("Error while listening\n"); return 0; } //accept struct sockaddr_in client_addr; socklen_t client_addr_len = sizeof(struct sockaddr_in); //if set to 0,we won't get client_addr int client_fd = accept(sock_fd, (struct sockaddr *)&client_addr, &client_addr_len); //receive msg from client int recv_buffer_size = recv(client_fd, buffer, BUFFER_SIZE, 0); buffer[recv_buffer_size] = '\0'; sprintf(msg, "receive msg from client\n IP: %s Port: %d", inet_ntoa(client_addr.sin_addr), htons(client_addr.sin_port)); printf("%s\n%s\n", msg, buffer); //send msg to clinet int send_buffer_size = send(client_fd, msg, strlen(msg), 0); //close socket close(sock_fd); return 0; }
the_stack_data/578847.c
/* ipvalid - validate an IP address via inet_pton(3) and emit via * inet_ntop(3) */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <err.h> #include <errno.h> #include <getopt.h> #include <limits.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sysexits.h> #include <unistd.h> void emit_help(void); bool Flag_Quiet = false; char addr[INET6_ADDRSTRLEN]; struct in_addr v4addr; struct in6_addr v6addr; int main(int argc, char *argv[]) { int ch, ipret; #ifdef __OpenBSD__ if (pledge("stdio", NULL) == -1) err(1, "pledge failed"); #endif while ((ch = getopt(argc, argv, "q")) != -1) { switch (ch) { case 'q': Flag_Quiet = true; break; case 'h': default: emit_help(); /* NOTREACHED */ } } argc -= optind; argv += optind; if (argc == 0) emit_help(); // may be necessary if IPv6 addresses mis-parsed by inet_ntop(AF_INET, //if (!strchr(*argv, ':')) { ipret = inet_pton(AF_INET, *argv, &v4addr); switch (ipret) { case 1: if (!Flag_Quiet) { if (!inet_ntop(AF_INET, &v4addr, (char *) &addr, INET_ADDRSTRLEN)) err(EX_OSERR, "inet_ntop() for IPv4 failed"); puts(addr); } exit(EXIT_SUCCESS); case 0: // not parseable, perhaps IPv6? break; case -1: err(EX_OSERR, "inet_pton() for IPv4 failed"); default: errx(EX_OSERR, "unexpected return from inet_pton() for IPv4: %d", ipret); } //} else { ipret = inet_pton(AF_INET6, *argv, &v6addr); switch (ipret) { case 1: if (!Flag_Quiet) { if (!inet_ntop(AF_INET6, &v6addr, (char *) &addr, INET6_ADDRSTRLEN)) err(EX_OSERR, "inet_ntop() for IPv6 failed"); puts(addr); } exit(EXIT_SUCCESS); case 0: /* not parseable */ break; case -1: err(EX_OSERR, "inet_pton() for IPv6 failed"); default: errx(EX_OSERR, "unexpected return from inet_pton() for IPv6: %d", ipret); } //} exit(1); } void emit_help(void) { fputs("Usage: ipvalid [-q] ipaddress\n", stderr); exit(EX_USAGE); }
the_stack_data/98310.c
#include <stdio.h> int assembly (void); extern int var; int main (void) { assembly(); printf("Value: %i\n", var); return 0; }
the_stack_data/1260557.c
//LINKED_QUEUE //https://github.com/L-F-Z/ADT_Code //Developed by UCAS ADT_Code Group //!警告:为了使用方便, 链队列的数据定义与严蔚敏<数据结构>上的有微小差异, 使用时请注意! #ifndef LINKED_QUEUE_C #define LINKED_QUEUE_C #include <stdio.h> #include <stdlib.h> #include <malloc.h> //----------|Status|----------- typedef int Status; #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASIBLE -1 #define OVERFLOW -2 //----------------------------- //---------|Typedef|----------- typedef int ElemType; //存储的数据类型 typedef struct QNode //链式队列节点 { ElemType data; //数据域 struct QNode *next; //指针域,指向下一个节点 } QNode, *QNodeptr; typedef struct _LinkQueue_struct //链式队列头 { QNodeptr front; QNodeptr rear; } * LinkQueue;//链式队列头节点指针 //----------------------------- //定义的新的变量类型首字母大写 //---------|FuncList|---------- Status InitQueue(LinkQueue* Q); //生成一个新的链式队列 Status DestoryQueue(LinkQueue Q); //销毁一个链式队列 Status ClearQueue(LinkQueue Q); //清空链式队列, 保留队列头 Status QueueEmpty(LinkQueue Q); //返回队列是否为空, 若为空返回TRUE int QueueLength(LinkQueue Q); //返回链式队列长度 Status GetHead(LinkQueue Q, ElemType *E); //返回队列头元素值 Status EnQueue(LinkQueue Q, ElemType E); //将新元素进入队列尾 Status DeQueue(LinkQueue Q, ElemType *E); //将首元素离开队列 Status QueueTraverse(LinkQueue Q, void visit(ElemType e)); //对队列的每个元素应用函数visit //----------------------------- Status InitQueue(LinkQueue* Q) //生成一个新的链式队列 { if(!(*Q = (LinkQueue)malloc(sizeof(struct _LinkQueue_struct))))return ERROR; (*Q)->front = (*Q)->rear = (QNodeptr)malloc(sizeof(QNode)); if (!(*Q)->front) exit(OVERFLOW); (*Q)->front->next = NULL; return OK; } Status DestoryQueue(LinkQueue Q) //销毁一个链式队列 { while (Q->front) { Q->rear = Q->front->next; free(Q->front); Q->front = Q->rear; } return OK; } Status ClearQueue(LinkQueue Q) //清空链式队列, 保留队列头 { if (!Q) return OVERFLOW; QNodeptr t = Q->front; QNodeptr p = Q->front->next; while (p != 0) { t = p->next; free(p); p = t; } Q->rear = Q->front; Q->front->next = 0; return OK; } Status QueueEmpty(LinkQueue Q) //返回队列是否为空, 若为空返回TRUE { return Q->rear == Q->front; } int QueueLength(LinkQueue Q) //返回链式队列长度 { if (!Q) return -1; QNodeptr t = Q->front; int cnt = 0; while (t != Q->rear) { t = t->next; cnt++; } return cnt; } Status GetHead(LinkQueue Q, ElemType *E) //返回队列头元素值 { if (!Q || Q->rear == Q->front) return OVERFLOW; *E = Q->front->next->data; return OK; } Status EnQueue(LinkQueue Q, ElemType E) //将新元素进入队列尾 { QNodeptr p = (QNodeptr)malloc(sizeof(QNode)); if (!p) exit(OVERFLOW); p->data = E; p->next = NULL; Q->rear->next = p; Q->rear = p; return OK; } Status DeQueue(LinkQueue Q, ElemType *E) //将首元素离开队列 { if (Q->front == Q->rear) return ERROR; QNodeptr p = Q->front->next; *E = p->data; Q->front->next = p->next; if (Q->rear == p) Q->rear = Q->front; free(p); return OK; } Status QueueTraverse(LinkQueue Q, void (*visit)(ElemType e)) //对队列的每个元素应用函数visit { if ((!Q) || (Q->front == Q->rear)) return ERROR; QNodeptr p = Q->front->next; while (p != Q->rear) { visit(p->data); p = p->next; } return OK; } void _test(int i) { printf("%d ", i); } // 单元测试, 处理注释时删去 // #include"lazy.h" // int main() // { // LinkQueue Q; // InitQueue(&Q); // CK(QueueEmpty(Q)); // ClearQueue(Q); // CK(QueueLength(Q)); // EnQueue(Q, 1); // EnQueue(Q, 2); // EnQueue(Q, 3); // EnQueue(Q, 4); // int a; // GetHead(Q,&a); // CK(a); // DeQueue( Q, &a); // DeQueue( Q, &a); // CK(a); // QueueTraverse(Q, _test); // DestoryQueue(Q); // return 0; // } #endif
the_stack_data/154829682.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_TOKEN_SIZE 32 #define MAX_INPUT_SIZE 255 int makearg(char *s,char ***args); int main() { // define variables char str[MAX_INPUT_SIZE+1]; int i; int argc; char **argv; printf("Input string to Parse (max input %i chars, max token %i chars):\n>",MAX_INPUT_SIZE,MAX_TOKEN_SIZE); fgets(str,(int)sizeof(str),stdin); if( strlen(str) > MAX_INPUT_SIZE ) { printf("Error: Max input size exceeded\n"); return 0; } // run parser function argc = makearg(str,&argv); // output if( argc > 0 ) { printf("makearg() Returned Successfully!\n"); printf("Num of Args:%i\n",argc); for(i=0;i<argc;i++) { printf("Arg #%i:%s\n",i+1,argv[i]); } } else if( argc == 0 ) printf("Error: Input string empty\n"); else if( argc == -1 ) printf("Error: Max token size exceeded\n"); else printf("Error: Unrecognized error. What have you done?\n"); return 0; } int makearg( char *s , char ***args ) { // don't waste time if empty if(strlen(s)==0) return 0; char tokenbuf[MAX_TOKEN_SIZE]; char **argv; char *temp; int i; int j = 0; int argc = 0; // get argc on the first pass to mallocate the array for(i=0;i<strlen(s)+1;i++) { if(s[i] == ' ' || s[i] == '\0') argc++; } argv = (char **) malloc(argc*sizeof(char **)); // second pass to make strings argc = 0; for(i=0;i<strlen(s)+1;i++) { // if printable character if(s[i] >= '!' && s[i] <= '~') { if(j<MAX_TOKEN_SIZE) { tokenbuf[j] = s[i]; // add char to buffer j++; // increment buffer index } else return -1; } // else if delimiter or end of line else if(s[i] == ' ' || s[i] == '\n' ) { tokenbuf[j] = '\0'; // give end of str to buffer temp = (char *) malloc(strlen(tokenbuf)+1); // allocate the str argv[argc] = temp; // give the str ptr to the value at the ptr to char strcpy(argv[argc],tokenbuf); // fill the allocated string with the buffer argc++; // increment the item count j=0; // reset the buffer index } // if we hit a null, we're done else if (s[i] == '\0') break; // some other char (unexpected) is being parsed else return -2; } // output *args = argv; return argc; }
the_stack_data/140764950.c
#include <stdio.h> #include <stdlib.h> typedef struct end { int cpf[11]; int nro_candidato; struct end *prox; } eleitor; eleitor *cria_lista(void) { eleitor *cell = NULL; cell = (eleitor *)(malloc(sizeof(eleitor))); if (cell == NULL) { printf("\nErro ao alocar memoria!"); exit(1); } cell->prox = NULL; return cell; } int menu(void) { int c = 0; do { printf("-- MENU:\n"); printf("\t 1. Votar\n"); printf("\t 2. Excluir voto\n"); printf("\t 3. Imprimir relatório final\n"); printf("\t 4. Sair\n"); printf("-- Digite sua escolha: "); scanf("%d", &c); } while (c <= 0 || c > 4); getchar(); return c; } int procurar_cpf(int *cpf, eleitor *ini) { eleitor *p = NULL; for (p = ini->prox; p != NULL; p = p->prox) { if(*p->cpf == *cpf) return 0; } return -1; } void votar(eleitor *ini) { eleitor *nova = NULL; nova = (eleitor *)(malloc(sizeof(eleitor))); if (nova == NULL) { printf("\nErro ao alocar memoria!"); exit(1); } printf("Digite seu CPF: "); scanf("%lu", &nova->cpf); if(procurar_cpf(nova->cpf, ini)) { printf("-- MENU DE VOTAÇÃO:\n"); printf("\t 1. Fulano\n"); printf("\t 2. Ciclano\n"); printf("\t 3. Branco\n"); printf("-- Digite sua escolha: "); scanf("%d", &nova->nro_candidato); } else { printf("Esse CPF já possui um voto cadastrado!\n"); } nova->prox = ini->prox; ini->prox = nova; } void imprimir(eleitor *ini) { eleitor *p = NULL; int opcao1 = 0, opcao2 = 0; for (p = ini->prox; p != NULL; p = p->prox) { if(p->nro_candidato == 1) opcao1++; if(p->nro_candidato == 2) opcao2++; } printf("Numero de votos para o candidato Fulano: %d\n", opcao1); printf("Numero de votos para o candidato Ciclano: %d\n", opcao2); } void apagar(eleitor *ini) { eleitor *p = NULL, *j = NULL; int cpf[11]; printf("Digite seu CPF: "); scanf("%lu", &cpf); for (p = ini->prox; p != NULL; p = p->prox) { if(*p->cpf == *cpf) { for (j = ini; j != NULL; j = j->prox) { if(j->prox == p) j->prox = p->prox; } } } } int main() { int escolha; eleitor *cell = NULL; cell = cria_lista(); for (;;) { escolha = menu(); switch (escolha) { case 1: votar(cell); break; case 2: apagar(cell); break; case 3: imprimir(cell); break; case 4: exit(0); break; } } free(cell); return 0; }
the_stack_data/973202.c
/* Print a string on serial port 0 */ #define UART0_BASE 0x101f1000 #define UART0_FR (UART0_BASE + 0x18) #define UART0_DR (UART0_BASE + 0x00) void print_uart0 ( const char *s ) { volatile unsigned int *uart_dr = (unsigned int *) UART0_DR; volatile unsigned int *uart_fr = (unsigned int *) UART0_FR; while ( *s != '\0' ) /* Loop until end of string */ { /* Wait for UART to become ready to transmit */ while ( (*uart_fr) & (1 << 5) ) ; /* Transmit char */ *uart_dr = (unsigned int) (*s); s++; /* Next char */ } } void print_hello() { print_uart0 ( "Hello world!\n" ); }
the_stack_data/76698999.c
#include <stdio.h> int max3(int a, int b, int c) { int max = a; if (b > max) max = b; if (c > max) max = c; return max; } int main(void) { printf("max3(%d, %d, %d) = %d\n", 3, 2, 1, max3(3, 2, 1)); printf("max3(%d, %d, %d) = %d\n", 3, 2, 2, max3(3, 2, 2)); printf("max3(%d, %d, %d) = %d\n", 3, 1, 2, max3(3, 1, 2)); printf("max3(%d, %d, %d) = %d\n", 3, 2, 3, max3(3, 2, 3)); printf("max3(%d, %d, %d) = %d\n", 2, 1, 3, max3(2, 1, 3)); printf("max3(%d, %d, %d) = %d\n", 3, 3, 2, max3(3, 3, 2)); printf("max3(%d, %d, %d) = %d\n", 3, 3, 3, max3(3, 3, 3)); printf("max3(%d, %d, %d) = %d\n", 2, 2, 3, max3(2, 2, 3)); printf("max3(%d, %d, %d) = %d\n", 2, 3, 1, max3(2, 3, 1)); printf("max3(%d, %d, %d) = %d\n", 2, 3, 2, max3(2, 3, 2)); printf("max3(%d, %d, %d) = %d\n", 1, 3, 2, max3(1, 3, 2)); printf("max3(%d, %d, %d) = %d\n", 2, 3, 3, max3(2, 3, 3)); printf("max3(%d, %d, %d) = %d\n", 1, 2, 3, max3(1, 2, 3)); printf("max3(%d, %d, %d) = %d\n", 1, 3, 2, max3(1, 3, 2)); }
the_stack_data/90766939.c
#include <stdio.h> #include <stdlib.h> typedef struct node *node_ptr; struct node { int element; node_ptr next; }; typedef node_ptr LIST; typedef node_ptr position; void create_list(LIST L) { position p = L; int num; printf("\nplease input a natural number with 0 to quit"); scanf("%d", &num); while (num != 0) { p->next = (position)malloc(sizeof(struct node)); p->next->element = num; p->next->next = NULL; p = p->next; printf("\nplease input a natural number and use 0 to quit"); scanf("%d", &num); } } void print_list(LIST L) { if (L->next == NULL) printf("\nno node in this list"); position p = L->next; while (p != NULL) { printf("%d\t", p->element); p = p->next; } } void swap_list(LIST L, int a) { position p = L, q = NULL; int i; if (a <= 0 || L->next == NULL || L->next->next == NULL) { printf("\nwrong"); return; } for (i = 0; i < a - 1; i++) { p = p->next; if (p->next->next == NULL) { printf("\noverflow"); return; } } q = p->next; p->next = p->next->next; q->next = p->next->next; p->next->next = q; } int main() { int a; LIST L = (position)malloc(sizeof(struct node)); L->element = 0; L->next = NULL; create_list(L); print_list(L); printf("\nplease input a number to determine the position you want to swap,-1 to exit"); scanf("%d", &a); while (a != -1) { swap_list(L, a); print_list(L); printf("\nplease input a number to determine the position you want to swap,-1 to exit"); scanf("%d", &a); } }
the_stack_data/29996.c
#include <stdio.h> int main() { int f; int numero1, numero2, numero3; printf("Escolha uma opção\n"); printf("1-Soma de dois numeros\n"); printf("2-Verificador se e maior que 100\n"); scanf("%d",&f ); switch (f) { case 1: printf("Insira o primeiro numero:"); scanf("%d", &numero1); printf("Insira o segundo numero:"); scanf("%d", &numero2); printf("%d + %d = %d", numero1, numero2, numero1+numero2 ); break; case 2: printf("Maior que 100\n"); printf("Intruduz 3 numeros\n"); scanf("%d%d%d",&numero1,&numero2,&numero3); //end_inputs if (numero1+numero2+numero3>= 100) { printf("A soma e maior que 100\n"); } else printf("A soma e menor que 100\n"); break; } }
the_stack_data/231391971.c
/*** * This code is a part of EvoApproxLib library (ehw.fit.vutbr.cz/approxlib) distributed under The MIT License. * When used, please cite the following article(s): V. Mrazek, Z. Vasicek and R. Hrbacek, "Role of circuit representation in evolutionary design of energy-efficient approximate circuits" in IET Computers & Digital Techniques, vol. 12, no. 4, pp. 139-149, 7 2018. doi: 10.1049/iet-cdt.2017.0188 * This file contains a circuit from a sub-set of pareto optimal circuits with respect to the pwr and wce parameters ***/ // MAE% = 0.88 % // MAE = 4.5 // WCE% = 2.34 % // WCE = 12 // WCRE% = 1100.00 % // EP% = 93.75 % // MRE% = 2.54 % // MSE = 30 // PDK45_PWR = 0.016 mW // PDK45_AREA = 53.0 um2 // PDK45_DELAY = 0.42 ns #include <stdint.h> #include <stdlib.h> uint64_t add8u_1DK(uint64_t a, uint64_t b) { uint64_t o = 0; int n_304=0, n_411=0, n_410=0, n_23=0, n_22=0, n_21=0, n_20=0, n_27=0, n_26=0, n_25=0; int n_24=0, n_262=0, n_29=0, n_28=0, n_263=0, n_240=0, n_82=0, n_346=0, n_389=0, n_388=0; int n_284=0, n_285=0, n_326=0, n_38=0, n_127=0, n_126=0, n_220=0, n_241=0, n_347=0, n_221=0; int n_8=0, n_9=0, n_368=0, n_159=0, n_4=0, n_5=0, n_6=0, n_7=0, n_0=0, n_1=0; int n_2=0, n_3=0, n_30=0, n_31=0, n_117=0, n_18=0, n_19=0, n_16=0, n_17=0, n_14=0; int n_15=0, n_12=0, n_13=0, n_10=0, n_11=0, n_158=0, n_45=0, n_94=0, n_95=0, n_44=0; int n_178=0, n_179=0, n_136=0, n_137=0, n_305=0, n_116=0; n_0 = (a >> 0) & 0x1; n_1 = (a >> 0) & 0x1; n_2 = (a >> 1) & 0x1; n_3 = (a >> 1) & 0x1; n_4 = (a >> 2) & 0x1; n_5 = (a >> 2) & 0x1; n_6 = (a >> 3) & 0x1; n_7 = (a >> 3) & 0x1; n_8 = (a >> 4) & 0x1; n_9 = (a >> 4) & 0x1; n_10 = (a >> 5) & 0x1; n_11 = (a >> 5) & 0x1; n_12 = (a >> 6) & 0x1; n_13 = (a >> 6) & 0x1; n_14 = (a >> 7) & 0x1; n_15 = (a >> 7) & 0x1; n_16 = (b >> 0) & 0x1; n_17 = (b >> 0) & 0x1; n_18 = (b >> 1) & 0x1; n_19 = (b >> 1) & 0x1; n_20 = (b >> 2) & 0x1; n_21 = (b >> 2) & 0x1; n_22 = (b >> 3) & 0x1; n_23 = (b >> 3) & 0x1; n_24 = (b >> 4) & 0x1; n_25 = (b >> 4) & 0x1; n_26 = (b >> 5) & 0x1; n_27 = (b >> 5) & 0x1; n_28 = (b >> 6) & 0x1; n_29 = (b >> 6) & 0x1; n_30 = (b >> 7) & 0x1; n_31 = (b >> 7) & 0x1; n_38 = n_6 & n_4; n_44 = n_22 ^ n_22; n_45 = n_22 & n_22; n_82 = n_38 & n_22; n_94 = n_20 & n_82; n_95 = n_94; n_116 = n_8 ^ n_24; n_117 = n_8 & n_24; n_126 = ~n_44; n_127 = n_126; n_136 = n_10 ^ n_26 ^n_117; n_137 = (n_10 & n_26) | (n_26 & n_117) | (n_10 & n_117); n_158 = n_12 ^ n_28 ^n_137; n_159 = (n_12 & n_28) | (n_28 & n_137) | (n_12 & n_137); n_178 = n_14 ^ n_30 ^n_159; n_179 = (n_14 & n_30) | (n_30 & n_159) | (n_14 & n_159); n_220 = ~(n_116 & n_95); n_221 = n_220; n_240 = ~n_221; n_241 = n_240; n_262 = n_10 ^ n_26 ^n_127; n_263 = (n_10 & n_26) | (n_26 & n_127) | (n_10 & n_127); n_284 = n_12 ^ n_28 ^n_263; n_285 = (n_12 & n_28) | (n_28 & n_263) | (n_12 & n_263); n_304 = n_14 ^ n_30 ^n_285; n_305 = (n_14 & n_30) | (n_30 & n_285) | (n_14 & n_285); n_326 = (n_116 & ~n_95) | (n_220 & n_95); n_346 = (n_136 & ~n_240) | (n_262 & n_240); n_347 = n_346; n_368 = (n_158 & ~n_240) | (n_284 & n_240); n_388 = (n_178 & ~n_241) | (n_304 & n_241); n_389 = n_388; n_410 = (n_179 & ~n_241) | (n_305 & n_241); n_411 = n_410; o |= (n_6 & 0x01) << 0; o |= (n_18 & 0x01) << 1; o |= (n_126 & 0x01) << 2; o |= (n_127 & 0x01) << 3; o |= (n_326 & 0x01) << 4; o |= (n_347 & 0x01) << 5; o |= (n_368 & 0x01) << 6; o |= (n_389 & 0x01) << 7; o |= (n_411 & 0x01) << 8; return o; }
the_stack_data/165765637.c
#if defined(HAVE_FMA3) && defined(HAVE_AVX2) #define HAVE_DROT_KERNEL 1 #include <immintrin.h> #include <stdint.h> static void drot_kernel(BLASLONG n, FLOAT *x, FLOAT *y, FLOAT c, FLOAT s) { BLASLONG i = 0; BLASLONG tail_index_4 = n&(~3); BLASLONG tail_index_16 = n&(~15); __m256d c_256, s_256; if (n >= 4) { c_256 = _mm256_set1_pd(c); s_256 = _mm256_set1_pd(s); } __m256d x0, x1, x2, x3; __m256d y0, y1, y2, y3; __m256d t0, t1, t2, t3; for (i = 0; i < tail_index_16; i += 16) { x0 = _mm256_loadu_pd(&x[i + 0]); x1 = _mm256_loadu_pd(&x[i + 4]); x2 = _mm256_loadu_pd(&x[i + 8]); x3 = _mm256_loadu_pd(&x[i +12]); y0 = _mm256_loadu_pd(&y[i + 0]); y1 = _mm256_loadu_pd(&y[i + 4]); y2 = _mm256_loadu_pd(&y[i + 8]); y3 = _mm256_loadu_pd(&y[i +12]); t0 = _mm256_mul_pd(s_256, y0); t1 = _mm256_mul_pd(s_256, y1); t2 = _mm256_mul_pd(s_256, y2); t3 = _mm256_mul_pd(s_256, y3); t0 = _mm256_fmadd_pd(c_256, x0, t0); t1 = _mm256_fmadd_pd(c_256, x1, t1); t2 = _mm256_fmadd_pd(c_256, x2, t2); t3 = _mm256_fmadd_pd(c_256, x3, t3); _mm256_storeu_pd(&x[i + 0], t0); _mm256_storeu_pd(&x[i + 4], t1); _mm256_storeu_pd(&x[i + 8], t2); _mm256_storeu_pd(&x[i +12], t3); t0 = _mm256_mul_pd(s_256, x0); t1 = _mm256_mul_pd(s_256, x1); t2 = _mm256_mul_pd(s_256, x2); t3 = _mm256_mul_pd(s_256, x3); t0 = _mm256_fmsub_pd(c_256, y0, t0); t1 = _mm256_fmsub_pd(c_256, y1, t1); t2 = _mm256_fmsub_pd(c_256, y2, t2); t3 = _mm256_fmsub_pd(c_256, y3, t3); _mm256_storeu_pd(&y[i + 0], t0); _mm256_storeu_pd(&y[i + 4], t1); _mm256_storeu_pd(&y[i + 8], t2); _mm256_storeu_pd(&y[i +12], t3); } for (i = tail_index_16; i < tail_index_4; i += 4) { x0 = _mm256_loadu_pd(&x[i]); y0 = _mm256_loadu_pd(&y[i]); t0 = _mm256_mul_pd(s_256, y0); t0 = _mm256_fmadd_pd(c_256, x0, t0); _mm256_storeu_pd(&x[i], t0); t0 = _mm256_mul_pd(s_256, x0); t0 = _mm256_fmsub_pd(c_256, y0, t0); _mm256_storeu_pd(&y[i], t0); } for (i = tail_index_4; i < n; ++i) { FLOAT temp = c * x[i] + s * y[i]; y[i] = c * y[i] - s * x[i]; x[i] = temp; } } #endif
the_stack_data/111077313.c
/* Enable a variable CVSUSER for cvs. */ /* See cvs/subr.c: getcaller(). */ #include <stdlib.h> #include <string.h> #include <pwd.h> int getuid (void) { return 0; } char * getlogin (void) { char *s; s = getenv ("CVSUSER"); if (s && *s) return s; s = getenv ("USER"); if (s && *s) return s; return NULL; } struct passwd * getpwnam (const char *name) { static struct passwd pw; static char namebuf[100]; pw.pw_name = strcpy (namebuf, name); pw.pw_passwd = "*"; pw.pw_uid = 100; pw.pw_gid = 100; pw.pw_gecos = ""; pw.pw_dir = "/"; pw.pw_shell = "/bin/sh"; return &pw; }
the_stack_data/9512560.c
#include <stdio.h> #define N 10 void invertiarray(int[],int); int main(void) { int i; int a[N]; for(i=0;i<N;i++) scanf("%d", &a[i]); for(i=0;i<N;i++) printf("%d ", a[i]); printf("\n"); invertiarray(a,N); for(i=0;i<N;i++) printf("%d ", a[i]); printf("\n"); return 0; } void invertiarray(int vett[], int dim) { int i, temp; for(i=0;i<dim/2;i++) { temp = vett[i]; vett[i] = vett[dim-1-i]; vett[dim-1-i] = temp; } }
the_stack_data/14198999.c
void rank(unsigned long n, unsigned long indx[], unsigned long irank[]) { unsigned long j; for (j=1;j<=n;j++) irank[indx[j]]=j; } /* (C) Copr. 1986-92 Numerical Recipes Software 9.1-5i. */
the_stack_data/66492.c
#include <stdio.h> int main() { int frequency[100] = {0}; int size; int i; printf("Enter the size of the array = "); scanf("%d", &size); int array[size]; printf("Enter the elements of the array = "); for(i = 0; i < size; i++){ scanf("%d", &array[i]); } for(i = 0; i < size; i++){ ++frequency[array[i]]; } for(i = 0; i < 100; i++){ if(frequency[i] != 0){ printf("%d occurs %d times\n",i,frequency[i]); } } return 0; }
the_stack_data/149665.c
/* { dg-do run { target openacc_nvidia_accel_selected } } */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <openacc.h> int main (int argc, char **argv) { const int N = 256; int i; unsigned char *h; void *d; h = (unsigned char *) malloc (N); for (i = 0; i < N; i++) { h[i] = i; } d = acc_malloc (N); acc_memcpy_to_device (d, h, N); memset (&h[0], 0, N); fprintf (stderr, "CheCKpOInT\n"); acc_memcpy_from_device (h, 0, N); for (i = 0; i < N; i++) { if (h[i] != i) abort (); } acc_free (d); free (h); return 0; } /* { dg-output "CheCKpOInT(\n|\r\n|\r).*" } */ /* { dg-output "invalid device address" } */ /* { dg-shouldfail "" } */
the_stack_data/168893592.c
/* board.c */ #include <stdlib.h> #include <stdio.h> #define ALIVE 'x' #define DEAD 'o' unsigned int getNeighbors(unsigned nr, unsigned nc, unsigned x, unsigned y, char *b[]) { return ((y > 0 && x > 0) ? (b[x - 1][y - 1] == ALIVE) : 0) + // top left ((y > 0) ? (b[x][y - 1] == ALIVE) : 0) + // top ((y > 0 && x < nc - 1) ? (b[x + 1][y - 1] == ALIVE) : 0) + // top right ((x < nc - 1) ? (b[x + 1][y] == ALIVE) : 0) + // right ((y < nr - 1 && x < nc - 1) ? (b[x + 1][y + 1] == ALIVE) : 0) + // bot right ((y < nr - 1) ? (b[x][y + 1] == ALIVE) : 0) + // bottom ((y < nr - 1 && x > 0) ? (b[x - 1][y + 1] == ALIVE) : 0) + // bot left ((x > 0) ? (b[x - 1][y] == ALIVE) : 0); // left } void playOne(unsigned int nr, unsigned int nc, char *old[], char *new[]) { unsigned int i, j, neighbors; for (j = 0; j < nr; j++) { for (i = 0; i < nc; i++) { if (((neighbors = getNeighbors(nr, nc, i, j, old)) == 3) || (neighbors == 2 && old[i][j] == ALIVE)) { new[i][j] = ALIVE; } else { new[i][j] = DEAD; } } } } void printBoard(unsigned int nr, unsigned int nc, char *board[], long iteration) { unsigned int i, j; // clear the screen printf("\e[1;1H\e[2J"); printf("==== ITERATION %li ====\n", iteration); for (j = 0; j < nr; j++) { for (i = 0; i < nc; i++) { if (board[i][j] == ALIVE) printf("\x1B[32mX\x1B[0m"); else printf(" "); } printf("\n"); } } // returns 1 if equal, 0 otherwise int arrayEquals(unsigned nr, unsigned nc, char *A[], char *B[]) { unsigned int i, j; for (j = 0; j < nr; j++) { for (i = 0; i < nc; i++) { if (A[i][j] != B[i][j]) return 0; } } return 1; } // returns 0 for not done, 1 for loop, 2 for oscillate int checkDone(unsigned nr, unsigned nc, char *A[], char *B[], char *C[]) { if (arrayEquals(nr, nc, A, B)) return 1; else if (arrayEquals(nr, nc, C, B)) return 2; else return 0; }
the_stack_data/812835.c
int main(void){ return ((int[]){1, 2, 3, 4, 5})[4]; }
the_stack_data/789093.c
#include <stdio.h> #include <stdlib.h> #include <time.h> void boardfill(int **board,int size,int available_flags,double percentage){ double number; int i,j; while(available_flags>0){ for(i=0;i<size;i++){ for(j=0;j<size;j++){ if(available_flags>0){ number=(((double)rand())/((double) RAND_MAX)); if(number<=percentage && board[i][j]!='*'){ board[i][j]='*'; available_flags=available_flags-1; } } } } } for(i=0;i<size;i++){ for(j=0;j<size;j++){ if(board[i][j]!='*'){ board[i][j]=0; } } } for(i=0;i<size;i++){ for(j=0;j<size;j++){ if(board[i][j]>='*'){ if(i==0 && j==0){ board[1][0]+=1; board[0][1]+=1; board[1][1]+=1; } if(i==0 && j==size-1){ board[0][size-2]+=1; board[1][size-2]+=1; board[1][size-1]+=1; } if(i==size-1 && j==0){ board[size-2][0]+=1; board[size-2][1]+=1; board[size-1][1]+=1; } if(i==size-1 && j==size-1){ board[size-1][size-2]+=1; board[size-2][size-2]+=1; board[size-2][size-1]+=1; } if(i>0 && i<size-1 && j==0){ board[i-1][j]+=1; board[i-1][j+1]+=1; board[i][j+1]+=1; board[i+1][j+1]+=1; board[i+1][j]+=1; } if(j>0 && j<size-1 && i==0){ board[i][j-1]+=1; board[i+1][j-1]+=1; board[i+1][j]+=1; board[i+1][j+1]+=1; board[i][j+1]+=1; } if(j>0 && j<size-1 && i==size-1){ board[i][j-1]+=1; board[i-1][j-1]+=1; board[i-1][j]+=1; board[i-1][j+1]+=1; board[i][j+1]+=1; } if(i>0 && i<size-1 && j==size-1){ board[i-1][j]+=1; board[i-1][j-1]+=1; board[i][j-1]+=1; board[i+1][j-1]+=1; board[i+1][j]+=1; } if((i>0 && i<size-1) && (j>0 && j<size-1)){ board[i-1][j-1]+=1; board[i-1][j]+=1; board[i-1][j+1]+=1; board[i][j+1]+=1; board[i+1][j+1]+=1; board[i+1][j]+=1; board[i+1][j-1]+=1; board[i][j-1]+=1; } } } } }
the_stack_data/231393422.c
#include <stdarg.h> #include <unistd.h> int execlp(const char* file, const char* argv0, ...) { int argc; va_list ap; va_start(ap, argv0); for (argc = 1; va_arg(ap, const char*); argc++) ; va_end(ap); { int i; char* argv[argc + 1]; va_start(ap, argv0); argv[0] = (char*)argv0; for (i = 1; i < argc; i++) argv[i] = va_arg(ap, char*); argv[i] = NULL; va_end(ap); return execvp(file, argv); } }
the_stack_data/123174.c
/*$$HEADER*/ /******************************************************************************/ /* */ /* H E A D E R I N F O R M A T I O N */ /* */ /******************************************************************************/ // Project Name : ORPSoC v2 // File Name : bin2hex.c // Prepared By : // Project Start : /*$$COPYRIGHT NOTICE*/ /******************************************************************************/ /* */ /* C O P Y R I G H T N O T I C E */ /* */ /******************************************************************************/ /* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; version 2.1 of the License, a copy of which is available from http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /*$$DESCRIPTION*/ /******************************************************************************/ /* */ /* D E S C R I P T I O N */ /* */ /******************************************************************************/ // // Generates basic ASCII hex output to stdout from binary file input // Compile and run the program with no options for usage. // #include <stdio.h> #include <stdlib.h> #include <string.h> /* Number of bytes before line is broken For example if target flash is 8 bits wide, define BREAK as 1. If it is 16 bits wide, define it as 2 etc. */ #define BREAK 1 int main(int argc, char **argv) { FILE *fd; int c; int i = 0; int write_size_word=0; // Disabled by default int filename_index=1; int bytes_per_line=1; int bytes_per_line_index=2; unsigned int image_size; if(argc < 3) { fprintf(stderr,"\n\tInsufficient options.\n"); fprintf(stderr,"\tPlease specify, in this order: a binary file to\n"); fprintf(stderr,"\tconvert and the number of bytes of data to putput\n"); fprintf(stderr,"\tper line.\n"); fprintf(stderr,"\tOptionally specify the option -size_word to output,\n"); fprintf(stderr,"\tthe size of the image in the first 4 bytes. This is\n"); fprintf(stderr,"\tused by some of the new OR1k bootloaders.\n\n"); exit(1); } if(argc == 4) { if (strcmp("-size_word", argv[3]) == 0) // We will calculate the number of bytes first write_size_word=1; } fd = fopen( argv[filename_index], "r" ); bytes_per_line = atoi(argv[bytes_per_line_index]); if ((bytes_per_line == 0) || (bytes_per_line > 8)) { fprintf(stderr,"bytes per line incorrect or missing: %s\n",argv[bytes_per_line_index]); exit(1); } // Now subtract 1 from bytes_per_line //if (bytes_per_line == 2) // bytes_per_line--; if (fd == NULL) { fprintf(stderr,"failed to open input file: %s\n",argv[1]); exit(1); } if (write_size_word) { // or1200 startup method of determining size of boot image we're copying by reading out // the very first word in flash is used. Determine the length of this file fseek(fd, 0, SEEK_END); image_size = ftell(fd); fseek(fd,0,SEEK_SET); // Now we should have the size of the file in bytes. Let's ensure it's a word multiple image_size+=3; image_size &= 0xfffffffc; // Sanity check on image size if (image_size < 8){ fprintf(stderr, "Bad binary image. Size too small\n"); return 1; } // Now write out the image size i=0; printf("%.2x",(image_size >> 24) & 0xff); if(++i==bytes_per_line){ printf("\n"); i=0; } printf("%.2x",(image_size >> 16) & 0xff); if(++i==bytes_per_line){ printf("\n"); i=0; } printf("%.2x",(image_size >> 8) & 0xff); if(++i==bytes_per_line){ printf("\n"); i=0; } printf("%.2x",(image_size) & 0xff); if(++i==bytes_per_line){ printf("\n"); i=0; } } // Fix for the current bootloader software! Skip the first 4 bytes of application data. Hopefully it's not important. 030509 -- jb for(i=0;i<4;i++) c=fgetc(fd); i=0; // Now write out the binary data to hex format while ((c = fgetc(fd)) != EOF) { printf("%.2x", (unsigned int) c); if (++i == bytes_per_line) { printf("\n"); i = 0; } } return 0; }
the_stack_data/48574769.c
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> char* trim_string(char* s) { size_t len = strlen(s); while (len && isspace(s[len-1])) s[--len] = '\0'; return s; } size_t look_say_inner(char* dest, char* src) { size_t len = 0; while (*src) { int count = 0; char* c = src; for ( ; *c == *src; ++c) { ++count; } *dest++ = count + '0'; // count is only ever 1-3 *dest++ = *src; len += 2; src = c; } *dest = '\0'; return len; } char* look_say(char* input, size_t n) { static const double scale = 1.5; size_t len = strlen(input) * scale; while (n--) { char* next = malloc(len); next[0] = '\0'; len = look_say_inner(next, input) * scale; free(input); input = next; } return input; } int main() { puts("Advent of Code 2015"); puts("Day 10: Elves Look, Elves Say"); size_t len = 16; // enough for input char* input = malloc(len); if (!fgets(input, len, stdin)) return EXIT_FAILURE; trim_string(input); input = look_say(input, 40); size_t part1 = strlen(input); printf("Part 1: %zu\n", part1); input = look_say(input, 10); size_t part2 = strlen(input); printf("Part 2: %zu\n", part2); free(input); return EXIT_SUCCESS; }
the_stack_data/104632.c
/* * test.c * * Created on: 1/09/2021 * Author: Fran */
the_stack_data/1073596.c
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <stdlib.h> int main(int argc, char* argv[]) { return 42; }
the_stack_data/150139825.c
int main() { /** * The following test is an interesting composition of loops. * First the _do-while_ runs through all of its iterations. * Then the _while_ loop runs, but with each of its iterations, a "do" is * forced, so we see a _do-while_ iteration along with each _while_ iteration. * Finally, the _for_ is allowed to progress without additional _while_ iterations. * This is further discussed in the comments on each line */ int i = 0; int j = 10; int k = 15; // test for loop for( i = 0; i <= 5; i ++ ) { // test while loops while( j <= 15 ) { // test do while loops do{ // expect to see 15-20, then 21-25 interspersed with numbers from js print_char('k'); print_char(':'); print_char(' '); print_int(k); print_char('\n'); k++; } while( k <= 20 ); // expect to see 10-15 interspersed with the numbers from the ks do print_char('j'); print_char(':'); print_char(' '); print_int(j); print_char('\n'); j++; } // expect to see 0-5 print_char('i'); print_char(':'); print_char(' '); print_int(i); print_char('\n'); } return 0; }
the_stack_data/243891977.c
#include <math.h> float expdev(long *idum) { float ran1(long *idum); float dum; do dum=ran1(idum); while (dum == 0.0); return -log(dum); } /* (C) Copr. 1986-92 Numerical Recipes Software 7&X*. */
the_stack_data/159515522.c
#include<stdio.h> #define N 16 #define L 256 int line=0; int finalres[L][N]; int res[N]; int scanNum=0; //深度比较 int arrcmp(int *a,int *b){ if (*a>*b) { return 1; } if (*a<*b) { return -1; } return arrcmp(a-1,b-1); } //排序算法 void BubbleSort(int* arr[],int n){ int flag=1;//标识是否进行交换 int* t=NULL; while(flag){ flag=0;//默认不存在交换 并扫描一次 //扫描 for(int i=0;i<n-1;i++){ int a=arr[i][0]; int b=arr[i+1][0]; if(arrcmp(&(arr[i][a]),&(arr[i+1][b]))==-1)//如果前项大于后项怎后移 { //交换 t=arr[i+1]; arr[i+1]=arr[i]; arr[i]=t; //标记存在交换 flag=1; } } } } //主要题解函数 /* 将一个数完全展开,然后从后面逐渐缩叠 5=1+1+1+1+1 5=1+1+1+2 5=1+1+3 ... */ void resolve(int k, int num) { int rest = 0; for (int i = 1; i <= num; i++) { // 避免重复 if (i < res[k - 1]) continue; // 去掉6=6这种情况 if (i == scanNum) continue; res[k] = i; rest = num - i; // 递归终止条件 拆分结束 if (rest == 0) { for (int j = k; j > 1; j--) { finalres[line][j]=res[j]; } finalres[line][1]=res[1]; finalres[line][0]=k; line++; continue; } resolve(k + 1, rest); } } int main(int argc, char const *argv[]) { scanf("%d",&scanNum); resolve(1,scanNum); if(scanNum==1){ printf("1=1\n"); } //对fianlres数组进行排序 int *arr[L]={NULL}; for (int i = 0; i < line; i++) { arr[i]=finalres[i]; } BubbleSort(arr,line); for (int i = 0; i < line; i++) { printf("%d=",scanNum); for (int j = arr[i][0]; j >1; j--) { printf("%d+",arr[i][j]); } printf("%d\n",arr[i][1]); } return 0; }
the_stack_data/87638264.c
/* *Name: Nikhil Ranjan Nayak *Regd No: 1641012040 *Desc: Check output */ #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> #include <sys/wait.h> void forkexample() { if(fork() == 0) printf("Hello from Child\n"); else { wait(NULL); printf("Helo from Parent\n"); } } int main() { forkexample(); }
the_stack_data/34589.c
/* * Copyright (c) 2014 Jonas 'Sortie' Termansen. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * wchar/wcscasecmp.c * Compares two strings ignoring case. */ #include <stdbool.h> #include <wchar.h> #include <wctype.h> int wcscasecmp(const wchar_t* a, const wchar_t* b) { for ( size_t i = 0; true; i++ ) { wint_t ac = towlower((wint_t) a[i]); wint_t bc = towlower((wint_t) b[i]); if ( ac == L'\0' && bc == L'\0' ) return 0; if ( ac < bc ) return -1; if ( ac > bc ) return 1; } }
the_stack_data/3261854.c
/* * BK Id: SCCS/s.mknote.c 1.7 05/18/01 15:17:23 cort */ /* * Copyright (C) Cort Dougan 1999. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Generate a note section as per the CHRP specification. * */ #include <stdio.h> #define PL(x) printf("%c%c%c%c", ((x)>>24)&0xff, ((x)>>16)&0xff, ((x)>>8)&0xff, (x)&0xff ); int main(void) { /* header */ /* namesz */ PL(strlen("PowerPC")+1); /* descrsz */ PL(6*4); /* type */ PL(0x1275); /* name */ printf("PowerPC"); printf("%c", 0); /* descriptor */ /* real-mode */ PL(0xffffffff); /* real-base */ PL(0x00c00000); /* real-size */ PL(0xffffffff); /* virt-base */ PL(0xffffffff); /* virt-size */ PL(0xffffffff); /* load-base */ PL(0x4000); return 0; }
the_stack_data/6387014.c
#include <stdio.h> #define moo(type, str) \ fprintf(stderr, " abc " # type " cde %s\n", str); #define moo2(type, str) \ fprintf(stderr, " abc " STR_HELPER(type) " cde %s\n", str); #define too 2 #define two(str,a) \ moo( a, str); //src: https://stackoverflow.com/questions/5459868/c-preprocessor-concatenate-int-to-string //The extra level of indirection will allow the preprocessor to expand the macros before they are converted to strings. #define STR_HELPER(x) #x #define three(str) \ moo2( too, str ) #define one(str) \ moo(one, str); void main() { one("wonder"); two("wonder", a); three("wonder"); }
the_stack_data/51699875.c
/* Date: Thu, 05 Aug 1993 20:28:03 +0200 From: "Tom R.Hageman" <[email protected]> Subject: more etags torture;-) [etags 7.3 patch#3] To: [email protected] Hi, This test file illustrates some more problems with etags (7.3): 1. parentheses are confusing, 2. preprocessor directives can disrupt other state machines. */ /* A small torture test for etags. */ /* The classic parenthesis nightmare, based on signal(). */ void (*tag1 (sig, handler)) () int sig; void (*handler) (); { (*handler)(sig); return handler; } #define notag2 void /* The classic, with user-defined return type. */ notag2 (*tag2 (sig, handler)) () int sig; void (*handler) (); { (*handler)(sig); return handler; } /* The classic, in ANSI C style. */ void (*tag3 (int sig, void (*handler) (int))) (int) { (*handler)(sig); return handler; } #define notag4 void /* The classic, with user-defined return type, in ANSI C style. */ notag4 (*tag4 (int sig, void (*handler) (int))) (int) { (*handler)(sig); return handler; } /* A less tortuous example. */ void tag5 (handler, arg) void (*handler)(); void *arg; { (*handler)(arg); } /* A less tortuous example, in ANSI C style. */ void tag6 (void (*handler) (void *), void *arg) { (*handler)(arg); } /* Interfering preprocessing torture */ int pp1( #if (__STDC__) int #endif bar) #if (!__STDC__) int bar; #endif { return bar; } int pp2 #if __STDC__ (int bar) #else (bar) int bar; #endif { return bar; } int #if __STDC__ pp3(int bar) #else pp3(bar) int bar; #endif { return bar; }
the_stack_data/535810.c
#include <assert.h> int main() { int x; const char *c = "Hello world"; _Bool dummy; __CPROVER_assume(dummy); int *p = (dummy ? &x : (int *)c); *p = 1; assert(*p == 1); return 0; }
the_stack_data/140766403.c
/* * Copyright (C) 2015-2018 Alibaba Group Holding Limited */ /* * The SSL 3.0 specification was drafted by Netscape in 1996, * and became an IETF standard in 1999. * * http://wp.netscape.com/eng/ssl3/ * http://www.ietf.org/rfc/rfc2246.txt * http://www.ietf.org/rfc/rfc4346.txt */ #ifdef SUPPORT_TLS #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #if defined(MBEDTLS_SSL_TLS_C) #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else #include <stdlib.h> #define mbedtls_calloc calloc #define mbedtls_free free #endif #include "mbedtls/debug.h" #include "mbedtls/ssl.h" #include "mbedtls/ssl_internal.h" #include <string.h> #if defined(MBEDTLS_X509_CRT_PARSE_C) #include "mbedtls/oid.h" #endif /* Implementation that should never be optimized out by the compiler */ static void mbedtls_zeroize( void *v, size_t n ) { volatile unsigned char *p = v; while( n-- ) *p++ = 0; } /* Length of the "epoch" field in the record header */ static inline size_t ssl_ep_len( const mbedtls_ssl_context *ssl ) { #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) return( 2 ); #else ((void) ssl); #endif return( 0 ); } /* * Start a timer. * Passing millisecs = 0 cancels a running timer. */ static void ssl_set_timer( mbedtls_ssl_context *ssl, uint32_t millisecs ) { if( ssl->f_set_timer == NULL ) return; MBEDTLS_SSL_DEBUG_MSG( 3, ( "set_timer to %d ms", (int) millisecs ) ); ssl->f_set_timer( ssl->p_timer, millisecs / 4, millisecs ); } /* * Return -1 is timer is expired, 0 if it isn't. */ static int ssl_check_timer( mbedtls_ssl_context *ssl ) { if( ssl->f_get_timer == NULL ) return( 0 ); if( ssl->f_get_timer( ssl->p_timer ) == 2 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "timer expired" ) ); return( -1 ); } return( 0 ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) /* * Double the retransmit timeout value, within the allowed range, * returning -1 if the maximum value has already been reached. */ static int ssl_double_retransmit_timeout( mbedtls_ssl_context *ssl ) { uint32_t new_timeout; if( ssl->handshake->retransmit_timeout >= ssl->conf->hs_timeout_max ) return( -1 ); new_timeout = 2 * ssl->handshake->retransmit_timeout; /* Avoid arithmetic overflow and range overflow */ if( new_timeout < ssl->handshake->retransmit_timeout || new_timeout > ssl->conf->hs_timeout_max ) { new_timeout = ssl->conf->hs_timeout_max; } ssl->handshake->retransmit_timeout = new_timeout; MBEDTLS_SSL_DEBUG_MSG( 3, ( "update timeout value to %d millisecs", ssl->handshake->retransmit_timeout ) ); return( 0 ); } static void ssl_reset_retransmit_timeout( mbedtls_ssl_context *ssl ) { ssl->handshake->retransmit_timeout = ssl->conf->hs_timeout_min; MBEDTLS_SSL_DEBUG_MSG( 3, ( "update timeout value to %d millisecs", ssl->handshake->retransmit_timeout ) ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) /* * Convert max_fragment_length codes to length. * RFC 6066 says: * enum{ * 2^9(1), 2^10(2), 2^11(3), 2^12(4), (255) * } MaxFragmentLength; * and we add 0 -> extension unused */ static unsigned int mfl_code_to_length[MBEDTLS_SSL_MAX_FRAG_LEN_INVALID] = { MBEDTLS_SSL_MAX_CONTENT_LEN, /* MBEDTLS_SSL_MAX_FRAG_LEN_NONE */ 512, /* MBEDTLS_SSL_MAX_FRAG_LEN_512 */ 1024, /* MBEDTLS_SSL_MAX_FRAG_LEN_1024 */ 2048, /* MBEDTLS_SSL_MAX_FRAG_LEN_2048 */ 4096, /* MBEDTLS_SSL_MAX_FRAG_LEN_4096 */ }; #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ #if defined(MBEDTLS_SSL_CLI_C) static int ssl_session_copy( mbedtls_ssl_session *dst, const mbedtls_ssl_session *src ) { mbedtls_ssl_session_free( dst ); memcpy( dst, src, sizeof( mbedtls_ssl_session ) ); #if defined(MBEDTLS_X509_CRT_PARSE_C) if( src->peer_cert != NULL ) { int ret; dst->peer_cert = mbedtls_calloc( 1, sizeof(mbedtls_x509_crt) ); if( dst->peer_cert == NULL ) return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); mbedtls_x509_crt_init( dst->peer_cert ); if( ( ret = mbedtls_x509_crt_parse_der( dst->peer_cert, src->peer_cert->raw.p, src->peer_cert->raw.len ) ) != 0 ) { mbedtls_free( dst->peer_cert ); dst->peer_cert = NULL; return( ret ); } } #endif /* MBEDTLS_X509_CRT_PARSE_C */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C) if( src->ticket != NULL ) { dst->ticket = mbedtls_calloc( 1, src->ticket_len ); if( dst->ticket == NULL ) return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); memcpy( dst->ticket, src->ticket, src->ticket_len ); } #endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */ return( 0 ); } #endif /* MBEDTLS_SSL_CLI_C */ #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) int (*mbedtls_ssl_hw_record_init)( mbedtls_ssl_context *ssl, const unsigned char *key_enc, const unsigned char *key_dec, size_t keylen, const unsigned char *iv_enc, const unsigned char *iv_dec, size_t ivlen, const unsigned char *mac_enc, const unsigned char *mac_dec, size_t maclen ) = NULL; int (*mbedtls_ssl_hw_record_activate)( mbedtls_ssl_context *ssl, int direction) = NULL; int (*mbedtls_ssl_hw_record_reset)( mbedtls_ssl_context *ssl ) = NULL; int (*mbedtls_ssl_hw_record_write)( mbedtls_ssl_context *ssl ) = NULL; int (*mbedtls_ssl_hw_record_read)( mbedtls_ssl_context *ssl ) = NULL; int (*mbedtls_ssl_hw_record_finish)( mbedtls_ssl_context *ssl ) = NULL; #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */ /* * Key material generation */ #if defined(MBEDTLS_SSL_PROTO_SSL3) static int ssl3_prf( const unsigned char *secret, size_t slen, const char *label, const unsigned char *random, size_t rlen, unsigned char *dstbuf, size_t dlen ) { size_t i; mbedtls_md5_context md5; mbedtls_sha1_context sha1; unsigned char padding[16]; unsigned char sha1sum[20]; ((void)label); mbedtls_md5_init( &md5 ); mbedtls_sha1_init( &sha1 ); /* * SSLv3: * block = * MD5( secret + SHA1( 'A' + secret + random ) ) + * MD5( secret + SHA1( 'BB' + secret + random ) ) + * MD5( secret + SHA1( 'CCC' + secret + random ) ) + * ... */ for( i = 0; i < dlen / 16; i++ ) { memset( padding, (unsigned char) ('A' + i), 1 + i ); mbedtls_sha1_starts( &sha1 ); mbedtls_sha1_update( &sha1, padding, 1 + i ); mbedtls_sha1_update( &sha1, secret, slen ); mbedtls_sha1_update( &sha1, random, rlen ); mbedtls_sha1_finish( &sha1, sha1sum ); mbedtls_md5_starts( &md5 ); mbedtls_md5_update( &md5, secret, slen ); mbedtls_md5_update( &md5, sha1sum, 20 ); mbedtls_md5_finish( &md5, dstbuf + i * 16 ); } mbedtls_md5_free( &md5 ); mbedtls_sha1_free( &sha1 ); mbedtls_zeroize( padding, sizeof( padding ) ); mbedtls_zeroize( sha1sum, sizeof( sha1sum ) ); return( 0 ); } #endif /* MBEDTLS_SSL_PROTO_SSL3 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) static int tls1_prf( const unsigned char *secret, size_t slen, const char *label, const unsigned char *random, size_t rlen, unsigned char *dstbuf, size_t dlen ) { size_t nb, hs; size_t i, j, k; const unsigned char *S1, *S2; unsigned char tmp[128]; unsigned char h_i[20]; const mbedtls_md_info_t *md_info; mbedtls_md_context_t md_ctx; int ret; mbedtls_md_init( &md_ctx ); if( sizeof( tmp ) < 20 + strlen( label ) + rlen ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); hs = ( slen + 1 ) / 2; S1 = secret; S2 = secret + slen - hs; nb = strlen( label ); memcpy( tmp + 20, label, nb ); memcpy( tmp + 20 + nb, random, rlen ); nb += rlen; /* * First compute P_md5(secret,label+random)[0..dlen] */ if( ( md_info = mbedtls_md_info_from_type( MBEDTLS_MD_MD5 ) ) == NULL ) return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 ) return( ret ); mbedtls_md_hmac_starts( &md_ctx, S1, hs ); mbedtls_md_hmac_update( &md_ctx, tmp + 20, nb ); mbedtls_md_hmac_finish( &md_ctx, 4 + tmp ); for( i = 0; i < dlen; i += 16 ) { mbedtls_md_hmac_reset ( &md_ctx ); mbedtls_md_hmac_update( &md_ctx, 4 + tmp, 16 + nb ); mbedtls_md_hmac_finish( &md_ctx, h_i ); mbedtls_md_hmac_reset ( &md_ctx ); mbedtls_md_hmac_update( &md_ctx, 4 + tmp, 16 ); mbedtls_md_hmac_finish( &md_ctx, 4 + tmp ); k = ( i + 16 > dlen ) ? dlen % 16 : 16; for( j = 0; j < k; j++ ) dstbuf[i + j] = h_i[j]; } mbedtls_md_free( &md_ctx ); /* * XOR out with P_sha1(secret,label+random)[0..dlen] */ if( ( md_info = mbedtls_md_info_from_type( MBEDTLS_MD_SHA1 ) ) == NULL ) return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 ) return( ret ); mbedtls_md_hmac_starts( &md_ctx, S2, hs ); mbedtls_md_hmac_update( &md_ctx, tmp + 20, nb ); mbedtls_md_hmac_finish( &md_ctx, tmp ); for( i = 0; i < dlen; i += 20 ) { mbedtls_md_hmac_reset ( &md_ctx ); mbedtls_md_hmac_update( &md_ctx, tmp, 20 + nb ); mbedtls_md_hmac_finish( &md_ctx, h_i ); mbedtls_md_hmac_reset ( &md_ctx ); mbedtls_md_hmac_update( &md_ctx, tmp, 20 ); mbedtls_md_hmac_finish( &md_ctx, tmp ); k = ( i + 20 > dlen ) ? dlen % 20 : 20; for( j = 0; j < k; j++ ) dstbuf[i + j] = (unsigned char)( dstbuf[i + j] ^ h_i[j] ); } mbedtls_md_free( &md_ctx ); mbedtls_zeroize( tmp, sizeof( tmp ) ); mbedtls_zeroize( h_i, sizeof( h_i ) ); return( 0 ); } #endif /* MBEDTLS_SSL_PROTO_TLS1) || MBEDTLS_SSL_PROTO_TLS1_1 */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) static int tls_prf_generic( mbedtls_md_type_t md_type, const unsigned char *secret, size_t slen, const char *label, const unsigned char *random, size_t rlen, unsigned char *dstbuf, size_t dlen ) { size_t nb; size_t i, j, k, md_len; unsigned char tmp[128]; unsigned char h_i[MBEDTLS_MD_MAX_SIZE]; const mbedtls_md_info_t *md_info; mbedtls_md_context_t md_ctx; int ret; mbedtls_md_init( &md_ctx ); if( ( md_info = mbedtls_md_info_from_type( md_type ) ) == NULL ) return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); md_len = mbedtls_md_get_size( md_info ); if( sizeof( tmp ) < md_len + strlen( label ) + rlen ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); nb = strlen( label ); memcpy( tmp + md_len, label, nb ); memcpy( tmp + md_len + nb, random, rlen ); nb += rlen; /* * Compute P_<hash>(secret, label + random)[0..dlen] */ if ( ( ret = mbedtls_md_setup( &md_ctx, md_info, 1 ) ) != 0 ) return( ret ); mbedtls_md_hmac_starts( &md_ctx, secret, slen ); mbedtls_md_hmac_update( &md_ctx, tmp + md_len, nb ); mbedtls_md_hmac_finish( &md_ctx, tmp ); for( i = 0; i < dlen; i += md_len ) { mbedtls_md_hmac_reset ( &md_ctx ); mbedtls_md_hmac_update( &md_ctx, tmp, md_len + nb ); mbedtls_md_hmac_finish( &md_ctx, h_i ); mbedtls_md_hmac_reset ( &md_ctx ); mbedtls_md_hmac_update( &md_ctx, tmp, md_len ); mbedtls_md_hmac_finish( &md_ctx, tmp ); k = ( i + md_len > dlen ) ? dlen % md_len : md_len; for( j = 0; j < k; j++ ) dstbuf[i + j] = h_i[j]; } mbedtls_md_free( &md_ctx ); mbedtls_zeroize( tmp, sizeof( tmp ) ); mbedtls_zeroize( h_i, sizeof( h_i ) ); return( 0 ); } #if defined(MBEDTLS_SHA256_C) static int tls_prf_sha256( const unsigned char *secret, size_t slen, const char *label, const unsigned char *random, size_t rlen, unsigned char *dstbuf, size_t dlen ) { return( tls_prf_generic( MBEDTLS_MD_SHA256, secret, slen, label, random, rlen, dstbuf, dlen ) ); } #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) static int tls_prf_sha384( const unsigned char *secret, size_t slen, const char *label, const unsigned char *random, size_t rlen, unsigned char *dstbuf, size_t dlen ) { return( tls_prf_generic( MBEDTLS_MD_SHA384, secret, slen, label, random, rlen, dstbuf, dlen ) ); } #endif /* MBEDTLS_SHA512_C */ #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ static void ssl_update_checksum_start( mbedtls_ssl_context *, const unsigned char *, size_t ); #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) static void ssl_update_checksum_md5sha1( mbedtls_ssl_context *, const unsigned char *, size_t ); #endif #if defined(MBEDTLS_SSL_PROTO_SSL3) static void ssl_calc_verify_ssl( mbedtls_ssl_context *, unsigned char * ); static void ssl_calc_finished_ssl( mbedtls_ssl_context *, unsigned char *, int ); #endif #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) static void ssl_calc_verify_tls( mbedtls_ssl_context *, unsigned char * ); static void ssl_calc_finished_tls( mbedtls_ssl_context *, unsigned char *, int ); #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_SHA256_C) static void ssl_update_checksum_sha256( mbedtls_ssl_context *, const unsigned char *, size_t ); static void ssl_calc_verify_tls_sha256( mbedtls_ssl_context *,unsigned char * ); static void ssl_calc_finished_tls_sha256( mbedtls_ssl_context *,unsigned char *, int ); #endif #if defined(MBEDTLS_SHA512_C) static void ssl_update_checksum_sha384( mbedtls_ssl_context *, const unsigned char *, size_t ); static void ssl_calc_verify_tls_sha384( mbedtls_ssl_context *, unsigned char * ); static void ssl_calc_finished_tls_sha384( mbedtls_ssl_context *, unsigned char *, int ); #endif #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl ) { int ret = 0; unsigned char tmp[64]; unsigned char keyblk[256]; unsigned char *key1; unsigned char *key2; unsigned char *mac_enc; unsigned char *mac_dec; size_t iv_copy_len; const mbedtls_cipher_info_t *cipher_info; const mbedtls_md_info_t *md_info; mbedtls_ssl_session *session = ssl->session_negotiate; mbedtls_ssl_transform *transform = ssl->transform_negotiate; mbedtls_ssl_handshake_params *handshake = ssl->handshake; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> derive keys" ) ); cipher_info = mbedtls_cipher_info_from_type( transform->ciphersuite_info->cipher ); if( cipher_info == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "cipher info for %d not found", transform->ciphersuite_info->cipher ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } md_info = mbedtls_md_info_from_type( transform->ciphersuite_info->mac ); if( md_info == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "mbedtls_md info for %d not found", transform->ciphersuite_info->mac ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } /* * Set appropriate PRF function and other SSL / TLS / TLS1.2 functions */ #if defined(MBEDTLS_SSL_PROTO_SSL3) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) { handshake->tls_prf = ssl3_prf; handshake->calc_verify = ssl_calc_verify_ssl; handshake->calc_finished = ssl_calc_finished_ssl; } else #endif #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 ) { handshake->tls_prf = tls1_prf; handshake->calc_verify = ssl_calc_verify_tls; handshake->calc_finished = ssl_calc_finished_tls; } else #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_SHA512_C) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 && transform->ciphersuite_info->mac == MBEDTLS_MD_SHA384 ) { handshake->tls_prf = tls_prf_sha384; handshake->calc_verify = ssl_calc_verify_tls_sha384; handshake->calc_finished = ssl_calc_finished_tls_sha384; } else #endif #if defined(MBEDTLS_SHA256_C) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { handshake->tls_prf = tls_prf_sha256; handshake->calc_verify = ssl_calc_verify_tls_sha256; handshake->calc_finished = ssl_calc_finished_tls_sha256; } else #endif #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } /* * SSLv3: * master = * MD5( premaster + SHA1( 'A' + premaster + randbytes ) ) + * MD5( premaster + SHA1( 'BB' + premaster + randbytes ) ) + * MD5( premaster + SHA1( 'CCC' + premaster + randbytes ) ) * * TLSv1+: * master = PRF( premaster, "master secret", randbytes )[0..47] */ if( handshake->resume == 0 ) { MBEDTLS_SSL_DEBUG_BUF( 3, "premaster secret", handshake->premaster, handshake->pmslen ); #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) if( ssl->handshake->extended_ms == MBEDTLS_SSL_EXTENDED_MS_ENABLED ) { unsigned char session_hash[48]; size_t hash_len; MBEDTLS_SSL_DEBUG_MSG( 3, ( "using extended master secret" ) ); ssl->handshake->calc_verify( ssl, session_hash ); #if defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { #if defined(MBEDTLS_SHA512_C) if( ssl->transform_negotiate->ciphersuite_info->mac == MBEDTLS_MD_SHA384 ) { hash_len = 48; } else #endif hash_len = 32; } else #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ hash_len = 36; MBEDTLS_SSL_DEBUG_BUF( 3, "session hash", session_hash, hash_len ); ret = handshake->tls_prf( handshake->premaster, handshake->pmslen, "extended master secret", session_hash, hash_len, session->master, 48 ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret ); return( ret ); } } else #endif ret = handshake->tls_prf( handshake->premaster, handshake->pmslen, "master secret", handshake->randbytes, 64, session->master, 48 ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret ); return( ret ); } mbedtls_zeroize( handshake->premaster, sizeof(handshake->premaster) ); } else MBEDTLS_SSL_DEBUG_MSG( 3, ( "no premaster (session resumed)" ) ); /* * Swap the client and server random values. */ memcpy( tmp, handshake->randbytes, 64 ); memcpy( handshake->randbytes, tmp + 32, 32 ); memcpy( handshake->randbytes + 32, tmp, 32 ); mbedtls_zeroize( tmp, sizeof( tmp ) ); /* * SSLv3: * key block = * MD5( master + SHA1( 'A' + master + randbytes ) ) + * MD5( master + SHA1( 'BB' + master + randbytes ) ) + * MD5( master + SHA1( 'CCC' + master + randbytes ) ) + * MD5( master + SHA1( 'DDDD' + master + randbytes ) ) + * ... * * TLSv1: * key block = PRF( master, "key expansion", randbytes ) */ ret = handshake->tls_prf( session->master, 48, "key expansion", handshake->randbytes, 64, keyblk, 256 ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "prf", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite = %s", mbedtls_ssl_get_ciphersuite_name( session->ciphersuite ) ) ); MBEDTLS_SSL_DEBUG_BUF( 3, "master secret", session->master, 48 ); MBEDTLS_SSL_DEBUG_BUF( 4, "random bytes", handshake->randbytes, 64 ); MBEDTLS_SSL_DEBUG_BUF( 4, "key block", keyblk, 256 ); mbedtls_zeroize( handshake->randbytes, sizeof( handshake->randbytes ) ); /* * Determine the appropriate key, IV and MAC length. */ transform->keylen = cipher_info->key_bitlen / 8; if( cipher_info->mode == MBEDTLS_MODE_GCM || cipher_info->mode == MBEDTLS_MODE_CCM ) { transform->maclen = 0; transform->ivlen = 12; transform->fixed_ivlen = 4; /* Minimum length is expicit IV + tag */ transform->minlen = transform->ivlen - transform->fixed_ivlen + ( transform->ciphersuite_info->flags & MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16 ); } else { /* Initialize HMAC contexts */ if( ( ret = mbedtls_md_setup( &transform->md_ctx_enc, md_info, 1 ) ) != 0 || ( ret = mbedtls_md_setup( &transform->md_ctx_dec, md_info, 1 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_setup", ret ); return( ret ); } /* Get MAC length */ transform->maclen = mbedtls_md_get_size( md_info ); #if defined(MBEDTLS_SSL_TRUNCATED_HMAC) /* * If HMAC is to be truncated, we shall keep the leftmost bytes, * (rfc 6066 page 13 or rfc 2104 section 4), * so we only need to adjust the length here. */ if( session->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_ENABLED ) transform->maclen = MBEDTLS_SSL_TRUNCATED_HMAC_LEN; #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */ /* IV length */ transform->ivlen = cipher_info->iv_size; /* Minimum length */ if( cipher_info->mode == MBEDTLS_MODE_STREAM ) transform->minlen = transform->maclen; else { /* * GenericBlockCipher: * 1. if EtM is in use: one block plus MAC * otherwise: * first multiple of blocklen greater than maclen * 2. IV except for SSL3 and TLS 1.0 */ #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) if( session->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED ) { transform->minlen = transform->maclen + cipher_info->block_size; } else #endif { transform->minlen = transform->maclen + cipher_info->block_size - transform->maclen % cipher_info->block_size; } #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 || ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_1 ) ; /* No need to adjust minlen */ else #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_2 || ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { transform->minlen += transform->ivlen; } else #endif { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } } } MBEDTLS_SSL_DEBUG_MSG( 3, ( "keylen: %d, minlen: %d, ivlen: %d, maclen: %d", transform->keylen, transform->minlen, transform->ivlen, transform->maclen ) ); /* * Finally setup the cipher contexts, IVs and MAC secrets. */ #if defined(MBEDTLS_SSL_CLI_C) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) { key1 = keyblk + transform->maclen * 2; key2 = keyblk + transform->maclen * 2 + transform->keylen; mac_enc = keyblk; mac_dec = keyblk + transform->maclen; /* * This is not used in TLS v1.1. */ iv_copy_len = ( transform->fixed_ivlen ) ? transform->fixed_ivlen : transform->ivlen; memcpy( transform->iv_enc, key2 + transform->keylen, iv_copy_len ); memcpy( transform->iv_dec, key2 + transform->keylen + iv_copy_len, iv_copy_len ); } else #endif /* MBEDTLS_SSL_CLI_C */ #if defined(MBEDTLS_SSL_SRV_C) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER ) { key1 = keyblk + transform->maclen * 2 + transform->keylen; key2 = keyblk + transform->maclen * 2; mac_enc = keyblk + transform->maclen; mac_dec = keyblk; /* * This is not used in TLS v1.1. */ iv_copy_len = ( transform->fixed_ivlen ) ? transform->fixed_ivlen : transform->ivlen; memcpy( transform->iv_dec, key1 + transform->keylen, iv_copy_len ); memcpy( transform->iv_enc, key1 + transform->keylen + iv_copy_len, iv_copy_len ); } else #endif /* MBEDTLS_SSL_SRV_C */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #if defined(MBEDTLS_SSL_PROTO_SSL3) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) { if( transform->maclen > sizeof transform->mac_enc ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } memcpy( transform->mac_enc, mac_enc, transform->maclen ); memcpy( transform->mac_dec, mac_dec, transform->maclen ); } else #endif /* MBEDTLS_SSL_PROTO_SSL3 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 ) { mbedtls_md_hmac_starts( &transform->md_ctx_enc, mac_enc, transform->maclen ); mbedtls_md_hmac_starts( &transform->md_ctx_dec, mac_dec, transform->maclen ); } else #endif { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) if( mbedtls_ssl_hw_record_init != NULL ) { int ret = 0; MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_init()" ) ); if( ( ret = mbedtls_ssl_hw_record_init( ssl, key1, key2, transform->keylen, transform->iv_enc, transform->iv_dec, iv_copy_len, mac_enc, mac_dec, transform->maclen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_init", ret ); return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); } } #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */ #if defined(MBEDTLS_SSL_EXPORT_KEYS) if( ssl->conf->f_export_keys != NULL ) { ssl->conf->f_export_keys( ssl->conf->p_export_keys, session->master, keyblk, transform->maclen, transform->keylen, iv_copy_len ); } #endif if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_enc, cipher_info ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup", ret ); return( ret ); } if( ( ret = mbedtls_cipher_setup( &transform->cipher_ctx_dec, cipher_info ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setup", ret ); return( ret ); } if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_enc, key1, cipher_info->key_bitlen, MBEDTLS_ENCRYPT ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setkey", ret ); return( ret ); } if( ( ret = mbedtls_cipher_setkey( &transform->cipher_ctx_dec, key2, cipher_info->key_bitlen, MBEDTLS_DECRYPT ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_setkey", ret ); return( ret ); } #if defined(MBEDTLS_CIPHER_MODE_CBC) if( cipher_info->mode == MBEDTLS_MODE_CBC ) { if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_enc, MBEDTLS_PADDING_NONE ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_set_padding_mode", ret ); return( ret ); } if( ( ret = mbedtls_cipher_set_padding_mode( &transform->cipher_ctx_dec, MBEDTLS_PADDING_NONE ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_set_padding_mode", ret ); return( ret ); } } #endif /* MBEDTLS_CIPHER_MODE_CBC */ mbedtls_zeroize( keyblk, sizeof( keyblk ) ); #if defined(MBEDTLS_ZLIB_SUPPORT) // Initialize compression // if( session->compression == MBEDTLS_SSL_COMPRESS_DEFLATE ) { if( ssl->compress_buf == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "Allocating compression buffer" ) ); ssl->compress_buf = mbedtls_calloc( 1, MBEDTLS_SSL_BUFFER_LEN ); if( ssl->compress_buf == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed", MBEDTLS_SSL_BUFFER_LEN ) ); return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); } } MBEDTLS_SSL_DEBUG_MSG( 3, ( "Initializing zlib states" ) ); memset( &transform->ctx_deflate, 0, sizeof( transform->ctx_deflate ) ); memset( &transform->ctx_inflate, 0, sizeof( transform->ctx_inflate ) ); if( deflateInit( &transform->ctx_deflate, Z_DEFAULT_COMPRESSION ) != Z_OK || inflateInit( &transform->ctx_inflate ) != Z_OK ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Failed to initialize compression" ) ); return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED ); } } #endif /* MBEDTLS_ZLIB_SUPPORT */ MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= derive keys" ) ); return( 0 ); } #if defined(MBEDTLS_SSL_PROTO_SSL3) void ssl_calc_verify_ssl( mbedtls_ssl_context *ssl, unsigned char hash[36] ) { mbedtls_md5_context md5; mbedtls_sha1_context sha1; unsigned char pad_1[48]; unsigned char pad_2[48]; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify ssl" ) ); mbedtls_md5_init( &md5 ); mbedtls_sha1_init( &sha1 ); mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 ); mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 ); memset( pad_1, 0x36, 48 ); memset( pad_2, 0x5C, 48 ); mbedtls_md5_update( &md5, ssl->session_negotiate->master, 48 ); mbedtls_md5_update( &md5, pad_1, 48 ); mbedtls_md5_finish( &md5, hash ); mbedtls_md5_starts( &md5 ); mbedtls_md5_update( &md5, ssl->session_negotiate->master, 48 ); mbedtls_md5_update( &md5, pad_2, 48 ); mbedtls_md5_update( &md5, hash, 16 ); mbedtls_md5_finish( &md5, hash ); mbedtls_sha1_update( &sha1, ssl->session_negotiate->master, 48 ); mbedtls_sha1_update( &sha1, pad_1, 40 ); mbedtls_sha1_finish( &sha1, hash + 16 ); mbedtls_sha1_starts( &sha1 ); mbedtls_sha1_update( &sha1, ssl->session_negotiate->master, 48 ); mbedtls_sha1_update( &sha1, pad_2, 40 ); mbedtls_sha1_update( &sha1, hash + 16, 20 ); mbedtls_sha1_finish( &sha1, hash + 16 ); MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 36 ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) ); mbedtls_md5_free( &md5 ); mbedtls_sha1_free( &sha1 ); return; } #endif /* MBEDTLS_SSL_PROTO_SSL3 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) void ssl_calc_verify_tls( mbedtls_ssl_context *ssl, unsigned char hash[36] ) { mbedtls_md5_context md5; mbedtls_sha1_context sha1; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify tls" ) ); mbedtls_md5_init( &md5 ); mbedtls_sha1_init( &sha1 ); mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 ); mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 ); mbedtls_md5_finish( &md5, hash ); mbedtls_sha1_finish( &sha1, hash + 16 ); MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 36 ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) ); mbedtls_md5_free( &md5 ); mbedtls_sha1_free( &sha1 ); return; } #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_SHA256_C) void ssl_calc_verify_tls_sha256( mbedtls_ssl_context *ssl, unsigned char hash[32] ) { mbedtls_sha256_context sha256; mbedtls_sha256_init( &sha256 ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify sha256" ) ); mbedtls_sha256_clone( &sha256, &ssl->handshake->fin_sha256 ); mbedtls_sha256_finish( &sha256, hash ); MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 32 ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) ); mbedtls_sha256_free( &sha256 ); return; } #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) void ssl_calc_verify_tls_sha384( mbedtls_ssl_context *ssl, unsigned char hash[48] ) { mbedtls_sha512_context sha512; mbedtls_sha512_init( &sha512 ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc verify sha384" ) ); mbedtls_sha512_clone( &sha512, &ssl->handshake->fin_sha512 ); mbedtls_sha512_finish( &sha512, hash ); MBEDTLS_SSL_DEBUG_BUF( 3, "calculated verify result", hash, 48 ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc verify" ) ); mbedtls_sha512_free( &sha512 ); return; } #endif /* MBEDTLS_SHA512_C */ #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) int mbedtls_ssl_psk_derive_premaster( mbedtls_ssl_context *ssl, mbedtls_key_exchange_type_t key_ex ) { unsigned char *p = ssl->handshake->premaster; unsigned char *end = p + sizeof( ssl->handshake->premaster ); const unsigned char *psk = ssl->conf->psk; size_t psk_len = ssl->conf->psk_len; /* If the psk callback was called, use its result */ if( ssl->handshake->psk != NULL ) { psk = ssl->handshake->psk; psk_len = ssl->handshake->psk_len; } /* * PMS = struct { * opaque other_secret<0..2^16-1>; * opaque psk<0..2^16-1>; * }; * with "other_secret" depending on the particular key exchange */ #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) if( key_ex == MBEDTLS_KEY_EXCHANGE_PSK ) { if( end - p < 2 ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); *(p++) = (unsigned char)( psk_len >> 8 ); *(p++) = (unsigned char)( psk_len ); if( end < p || (size_t)( end - p ) < psk_len ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); memset( p, 0, psk_len ); p += psk_len; } else #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) if( key_ex == MBEDTLS_KEY_EXCHANGE_RSA_PSK ) { /* * other_secret already set by the ClientKeyExchange message, * and is 48 bytes long */ *p++ = 0; *p++ = 48; p += 48; } else #endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) if( key_ex == MBEDTLS_KEY_EXCHANGE_DHE_PSK ) { int ret; size_t len; /* Write length only when we know the actual value */ if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx, p + 2, end - ( p + 2 ), &len, ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret ); return( ret ); } *(p++) = (unsigned char)( len >> 8 ); *(p++) = (unsigned char)( len ); p += len; MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K ); } else #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) if( key_ex == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ) { int ret; size_t zlen; if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx, &zlen, p + 2, end - ( p + 2 ), ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret ); return( ret ); } *(p++) = (unsigned char)( zlen >> 8 ); *(p++) = (unsigned char)( zlen ); p += zlen; MBEDTLS_SSL_DEBUG_MPI( 3, "ECDH: z", &ssl->handshake->ecdh_ctx.z ); } else #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } /* opaque psk<0..2^16-1>; */ if( end - p < 2 ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); *(p++) = (unsigned char)( psk_len >> 8 ); *(p++) = (unsigned char)( psk_len ); if( end < p || (size_t)( end - p ) < psk_len ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); memcpy( p, psk, psk_len ); p += psk_len; ssl->handshake->pmslen = p - ssl->handshake->premaster; return( 0 ); } #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */ #if defined(MBEDTLS_SSL_PROTO_SSL3) /* * SSLv3.0 MAC functions */ static void ssl_mac( mbedtls_md_context_t *md_ctx, unsigned char *secret, unsigned char *buf, size_t len, unsigned char *ctr, int type ) { unsigned char header[11]; unsigned char padding[48]; int padlen; int md_size = mbedtls_md_get_size( md_ctx->md_info ); int md_type = mbedtls_md_get_type( md_ctx->md_info ); /* Only MD5 and SHA-1 supported */ if( md_type == MBEDTLS_MD_MD5 ) padlen = 48; else padlen = 40; memcpy( header, ctr, 8 ); header[ 8] = (unsigned char) type; header[ 9] = (unsigned char)( len >> 8 ); header[10] = (unsigned char)( len ); memset( padding, 0x36, padlen ); mbedtls_md_starts( md_ctx ); mbedtls_md_update( md_ctx, secret, md_size ); mbedtls_md_update( md_ctx, padding, padlen ); mbedtls_md_update( md_ctx, header, 11 ); mbedtls_md_update( md_ctx, buf, len ); mbedtls_md_finish( md_ctx, buf + len ); memset( padding, 0x5C, padlen ); mbedtls_md_starts( md_ctx ); mbedtls_md_update( md_ctx, secret, md_size ); mbedtls_md_update( md_ctx, padding, padlen ); mbedtls_md_update( md_ctx, buf + len, md_size ); mbedtls_md_finish( md_ctx, buf + len ); } #endif /* MBEDTLS_SSL_PROTO_SSL3 */ #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER) || \ ( defined(MBEDTLS_CIPHER_MODE_CBC) && \ ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) ) ) #define SSL_SOME_MODES_USE_MAC #endif /* * Encryption/decryption functions */ static int ssl_encrypt_buf( mbedtls_ssl_context *ssl ) { mbedtls_cipher_mode_t mode; int auth_done = 0; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> encrypt buf" ) ); if( ssl->session_out == NULL || ssl->transform_out == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } mode = mbedtls_cipher_get_cipher_mode( &ssl->transform_out->cipher_ctx_enc ); MBEDTLS_SSL_DEBUG_BUF( 4, "before encrypt: output payload", ssl->out_msg, ssl->out_msglen ); /* * Add MAC before if needed */ #if defined(SSL_SOME_MODES_USE_MAC) if( mode == MBEDTLS_MODE_STREAM || ( mode == MBEDTLS_MODE_CBC #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) && ssl->session_out->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED #endif ) ) { #if defined(MBEDTLS_SSL_PROTO_SSL3) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) { ssl_mac( &ssl->transform_out->md_ctx_enc, ssl->transform_out->mac_enc, ssl->out_msg, ssl->out_msglen, ssl->out_ctr, ssl->out_msgtype ); } else #endif #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 ) { mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_ctr, 8 ); mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_hdr, 3 ); mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_len, 2 ); mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_msg, ssl->out_msglen ); mbedtls_md_hmac_finish( &ssl->transform_out->md_ctx_enc, ssl->out_msg + ssl->out_msglen ); mbedtls_md_hmac_reset( &ssl->transform_out->md_ctx_enc ); } else #endif { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } MBEDTLS_SSL_DEBUG_BUF( 4, "computed mac", ssl->out_msg + ssl->out_msglen, ssl->transform_out->maclen ); ssl->out_msglen += ssl->transform_out->maclen; auth_done++; } #endif /* AEAD not the only option */ /* * Encrypt */ #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER) if( mode == MBEDTLS_MODE_STREAM ) { int ret; size_t olen = 0; MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, " "including %d bytes of padding", ssl->out_msglen, 0 ) ); if( ( ret = mbedtls_cipher_crypt( &ssl->transform_out->cipher_ctx_enc, ssl->transform_out->iv_enc, ssl->transform_out->ivlen, ssl->out_msg, ssl->out_msglen, ssl->out_msg, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret ); return( ret ); } if( ssl->out_msglen != olen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } } else #endif /* MBEDTLS_ARC4_C || MBEDTLS_CIPHER_NULL_CIPHER */ #if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CCM_C) if( mode == MBEDTLS_MODE_GCM || mode == MBEDTLS_MODE_CCM ) { int ret; size_t enc_msglen, olen; unsigned char *enc_msg; unsigned char add_data[13]; unsigned char taglen = ssl->transform_out->ciphersuite_info->flags & MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16; memcpy( add_data, ssl->out_ctr, 8 ); add_data[8] = ssl->out_msgtype; mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver, ssl->conf->transport, add_data + 9 ); add_data[11] = ( ssl->out_msglen >> 8 ) & 0xFF; add_data[12] = ssl->out_msglen & 0xFF; MBEDTLS_SSL_DEBUG_BUF( 4, "additional data used for AEAD", add_data, 13 ); /* * Generate IV */ if( ssl->transform_out->ivlen - ssl->transform_out->fixed_ivlen != 8 ) { /* Reminder if we ever add an AEAD mode with a different size */ MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } memcpy( ssl->transform_out->iv_enc + ssl->transform_out->fixed_ivlen, ssl->out_ctr, 8 ); memcpy( ssl->out_iv, ssl->out_ctr, 8 ); MBEDTLS_SSL_DEBUG_BUF( 4, "IV used", ssl->out_iv, ssl->transform_out->ivlen - ssl->transform_out->fixed_ivlen ); /* * Fix pointer positions and message length with added IV */ enc_msg = ssl->out_msg; enc_msglen = ssl->out_msglen; ssl->out_msglen += ssl->transform_out->ivlen - ssl->transform_out->fixed_ivlen; MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, " "including %d bytes of padding", ssl->out_msglen, 0 ) ); /* * Encrypt and authenticate */ if( ( ret = mbedtls_cipher_auth_encrypt( &ssl->transform_out->cipher_ctx_enc, ssl->transform_out->iv_enc, ssl->transform_out->ivlen, add_data, 13, enc_msg, enc_msglen, enc_msg, &olen, enc_msg + enc_msglen, taglen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_auth_encrypt", ret ); return( ret ); } if( olen != enc_msglen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } ssl->out_msglen += taglen; auth_done++; MBEDTLS_SSL_DEBUG_BUF( 4, "after encrypt: tag", enc_msg + enc_msglen, taglen ); } else #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */ #if defined(MBEDTLS_CIPHER_MODE_CBC) && \ ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) ) if( mode == MBEDTLS_MODE_CBC ) { int ret; unsigned char *enc_msg; size_t enc_msglen, padlen, olen = 0, i; padlen = ssl->transform_out->ivlen - ( ssl->out_msglen + 1 ) % ssl->transform_out->ivlen; if( padlen == ssl->transform_out->ivlen ) padlen = 0; for( i = 0; i <= padlen; i++ ) ssl->out_msg[ssl->out_msglen + i] = (unsigned char) padlen; ssl->out_msglen += padlen + 1; enc_msglen = ssl->out_msglen; enc_msg = ssl->out_msg; #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2) /* * Prepend per-record IV for block cipher in TLS v1.1 and up as per * Method 1 (6.2.3.2. in RFC4346 and RFC5246) */ if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 ) { /* * Generate IV */ ret = ssl->conf->f_rng( ssl->conf->p_rng, ssl->transform_out->iv_enc, ssl->transform_out->ivlen ); if( ret != 0 ) return( ret ); memcpy( ssl->out_iv, ssl->transform_out->iv_enc, ssl->transform_out->ivlen ); /* * Fix pointer positions and message length with added IV */ enc_msg = ssl->out_msg; enc_msglen = ssl->out_msglen; ssl->out_msglen += ssl->transform_out->ivlen; } #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, " "including %d bytes of IV and %d bytes of padding", ssl->out_msglen, ssl->transform_out->ivlen, padlen + 1 ) ); if( ( ret = mbedtls_cipher_crypt( &ssl->transform_out->cipher_ctx_enc, ssl->transform_out->iv_enc, ssl->transform_out->ivlen, enc_msg, enc_msglen, enc_msg, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret ); return( ret ); } if( enc_msglen != olen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 ) { /* * Save IV in SSL3 and TLS1 */ memcpy( ssl->transform_out->iv_enc, ssl->transform_out->cipher_ctx_enc.iv, ssl->transform_out->ivlen ); } #endif #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) if( auth_done == 0 ) { /* * MAC(MAC_write_key, seq_num + * TLSCipherText.type + * TLSCipherText.version + * length_of( (IV +) ENC(...) ) + * IV + // except for TLS 1.0 * ENC(content + padding + padding_length)); */ unsigned char pseudo_hdr[13]; MBEDTLS_SSL_DEBUG_MSG( 3, ( "using encrypt then mac" ) ); memcpy( pseudo_hdr + 0, ssl->out_ctr, 8 ); memcpy( pseudo_hdr + 8, ssl->out_hdr, 3 ); pseudo_hdr[11] = (unsigned char)( ( ssl->out_msglen >> 8 ) & 0xFF ); pseudo_hdr[12] = (unsigned char)( ( ssl->out_msglen ) & 0xFF ); MBEDTLS_SSL_DEBUG_BUF( 4, "MAC'd meta-data", pseudo_hdr, 13 ); mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, pseudo_hdr, 13 ); mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, ssl->out_iv, ssl->out_msglen ); mbedtls_md_hmac_finish( &ssl->transform_out->md_ctx_enc, ssl->out_iv + ssl->out_msglen ); mbedtls_md_hmac_reset( &ssl->transform_out->md_ctx_enc ); ssl->out_msglen += ssl->transform_out->maclen; auth_done++; } #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ } else #endif /* MBEDTLS_CIPHER_MODE_CBC && ( MBEDTLS_AES_C || MBEDTLS_CAMELLIA_C ) */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } /* Make extra sure authentication was performed, exactly once */ if( auth_done != 1 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= encrypt buf" ) ); return( 0 ); } #define SSL_MAX_MAC_SIZE 48 static int ssl_decrypt_buf( mbedtls_ssl_context *ssl ) { size_t i; mbedtls_cipher_mode_t mode; int auth_done = 0; #if defined(SSL_SOME_MODES_USE_MAC) size_t padlen = 0, correct = 1; #endif MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> decrypt buf" ) ); if( ssl->session_in == NULL || ssl->transform_in == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } mode = mbedtls_cipher_get_cipher_mode( &ssl->transform_in->cipher_ctx_dec ); if( ssl->in_msglen < ssl->transform_in->minlen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "in_msglen (%d) < minlen (%d)", ssl->in_msglen, ssl->transform_in->minlen ) ); return( MBEDTLS_ERR_SSL_INVALID_MAC ); } #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER) if( mode == MBEDTLS_MODE_STREAM ) { int ret; size_t olen = 0; padlen = 0; if( ( ret = mbedtls_cipher_crypt( &ssl->transform_in->cipher_ctx_dec, ssl->transform_in->iv_dec, ssl->transform_in->ivlen, ssl->in_msg, ssl->in_msglen, ssl->in_msg, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret ); return( ret ); } if( ssl->in_msglen != olen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } } else #endif /* MBEDTLS_ARC4_C || MBEDTLS_CIPHER_NULL_CIPHER */ #if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CCM_C) if( mode == MBEDTLS_MODE_GCM || mode == MBEDTLS_MODE_CCM ) { int ret; size_t dec_msglen, olen; unsigned char *dec_msg; unsigned char *dec_msg_result; unsigned char add_data[13]; unsigned char taglen = ssl->transform_in->ciphersuite_info->flags & MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16; size_t explicit_iv_len = ssl->transform_in->ivlen - ssl->transform_in->fixed_ivlen; if( ssl->in_msglen < explicit_iv_len + taglen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < explicit_iv_len (%d) " "+ taglen (%d)", ssl->in_msglen, explicit_iv_len, taglen ) ); return( MBEDTLS_ERR_SSL_INVALID_MAC ); } dec_msglen = ssl->in_msglen - explicit_iv_len - taglen; dec_msg = ssl->in_msg; dec_msg_result = ssl->in_msg; ssl->in_msglen = dec_msglen; memcpy( add_data, ssl->in_ctr, 8 ); add_data[8] = ssl->in_msgtype; mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver, ssl->conf->transport, add_data + 9 ); add_data[11] = ( ssl->in_msglen >> 8 ) & 0xFF; add_data[12] = ssl->in_msglen & 0xFF; MBEDTLS_SSL_DEBUG_BUF( 4, "additional data used for AEAD", add_data, 13 ); memcpy( ssl->transform_in->iv_dec + ssl->transform_in->fixed_ivlen, ssl->in_iv, ssl->transform_in->ivlen - ssl->transform_in->fixed_ivlen ); MBEDTLS_SSL_DEBUG_BUF( 4, "IV used", ssl->transform_in->iv_dec, ssl->transform_in->ivlen ); MBEDTLS_SSL_DEBUG_BUF( 4, "TAG used", dec_msg + dec_msglen, taglen ); /* * Decrypt and authenticate */ if( ( ret = mbedtls_cipher_auth_decrypt( &ssl->transform_in->cipher_ctx_dec, ssl->transform_in->iv_dec, ssl->transform_in->ivlen, add_data, 13, dec_msg, dec_msglen, dec_msg_result, &olen, dec_msg + dec_msglen, taglen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_auth_decrypt", ret ); if( ret == MBEDTLS_ERR_CIPHER_AUTH_FAILED ) return( MBEDTLS_ERR_SSL_INVALID_MAC ); return( ret ); } auth_done++; if( olen != dec_msglen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } } else #endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C */ #if defined(MBEDTLS_CIPHER_MODE_CBC) && \ ( defined(MBEDTLS_AES_C) || defined(MBEDTLS_CAMELLIA_C) ) if( mode == MBEDTLS_MODE_CBC ) { /* * Decrypt and check the padding */ int ret; unsigned char *dec_msg; unsigned char *dec_msg_result; size_t dec_msglen; size_t minlen = 0; size_t olen = 0; /* * Check immediate ciphertext sanity */ #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 ) minlen += ssl->transform_in->ivlen; #endif if( ssl->in_msglen < minlen + ssl->transform_in->ivlen || ssl->in_msglen < minlen + ssl->transform_in->maclen + 1 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < max( ivlen(%d), maclen (%d) " "+ 1 ) ( + expl IV )", ssl->in_msglen, ssl->transform_in->ivlen, ssl->transform_in->maclen ) ); return( MBEDTLS_ERR_SSL_INVALID_MAC ); } dec_msglen = ssl->in_msglen; dec_msg = ssl->in_msg; dec_msg_result = ssl->in_msg; /* * Authenticate before decrypt if enabled */ #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) if( ssl->session_in->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED ) { unsigned char computed_mac[SSL_MAX_MAC_SIZE]; unsigned char pseudo_hdr[13]; MBEDTLS_SSL_DEBUG_MSG( 3, ( "using encrypt then mac" ) ); dec_msglen -= ssl->transform_in->maclen; ssl->in_msglen -= ssl->transform_in->maclen; memcpy( pseudo_hdr + 0, ssl->in_ctr, 8 ); memcpy( pseudo_hdr + 8, ssl->in_hdr, 3 ); pseudo_hdr[11] = (unsigned char)( ( ssl->in_msglen >> 8 ) & 0xFF ); pseudo_hdr[12] = (unsigned char)( ( ssl->in_msglen ) & 0xFF ); MBEDTLS_SSL_DEBUG_BUF( 4, "MAC'd meta-data", pseudo_hdr, 13 ); mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, pseudo_hdr, 13 ); mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_iv, ssl->in_msglen ); mbedtls_md_hmac_finish( &ssl->transform_in->md_ctx_dec, computed_mac ); mbedtls_md_hmac_reset( &ssl->transform_in->md_ctx_dec ); MBEDTLS_SSL_DEBUG_BUF( 4, "message mac", ssl->in_iv + ssl->in_msglen, ssl->transform_in->maclen ); MBEDTLS_SSL_DEBUG_BUF( 4, "computed mac", computed_mac, ssl->transform_in->maclen ); if( mbedtls_ssl_safer_memcmp( ssl->in_iv + ssl->in_msglen, computed_mac, ssl->transform_in->maclen ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "message mac does not match" ) ); return( MBEDTLS_ERR_SSL_INVALID_MAC ); } auth_done++; } #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ /* * Check length sanity */ if( ssl->in_msglen % ssl->transform_in->ivlen != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) %% ivlen (%d) != 0", ssl->in_msglen, ssl->transform_in->ivlen ) ); return( MBEDTLS_ERR_SSL_INVALID_MAC ); } #if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2) /* * Initialize for prepended IV for block cipher in TLS v1.1 and up */ if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 ) { dec_msglen -= ssl->transform_in->ivlen; ssl->in_msglen -= ssl->transform_in->ivlen; for( i = 0; i < ssl->transform_in->ivlen; i++ ) ssl->transform_in->iv_dec[i] = ssl->in_iv[i]; } #endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */ if( ( ret = mbedtls_cipher_crypt( &ssl->transform_in->cipher_ctx_dec, ssl->transform_in->iv_dec, ssl->transform_in->ivlen, dec_msg, dec_msglen, dec_msg_result, &olen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret ); return( ret ); } if( dec_msglen != olen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 ) { /* * Save IV in SSL3 and TLS1 */ memcpy( ssl->transform_in->iv_dec, ssl->transform_in->cipher_ctx_dec.iv, ssl->transform_in->ivlen ); } #endif padlen = 1 + ssl->in_msg[ssl->in_msglen - 1]; if( ssl->in_msglen < ssl->transform_in->maclen + padlen && auth_done == 0 ) { #if defined(MBEDTLS_SSL_DEBUG_ALL) MBEDTLS_SSL_DEBUG_MSG( 1, ( "msglen (%d) < maclen (%d) + padlen (%d)", ssl->in_msglen, ssl->transform_in->maclen, padlen ) ); #endif padlen = 0; correct = 0; } #if defined(MBEDTLS_SSL_PROTO_SSL3) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) { if( padlen > ssl->transform_in->ivlen ) { #if defined(MBEDTLS_SSL_DEBUG_ALL) MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad padding length: is %d, " "should be no more than %d", padlen, ssl->transform_in->ivlen ) ); #endif correct = 0; } } else #endif /* MBEDTLS_SSL_PROTO_SSL3 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_0 ) { /* * TLSv1+: always check the padding up to the first failure * and fake check up to 256 bytes of padding */ size_t pad_count = 0, real_count = 1; size_t padding_idx = ssl->in_msglen - padlen - 1; /* * Padding is guaranteed to be incorrect if: * 1. padlen >= ssl->in_msglen * * 2. padding_idx >= MBEDTLS_SSL_MAX_CONTENT_LEN + * ssl->transform_in->maclen * * In both cases we reset padding_idx to a safe value (0) to * prevent out-of-buffer reads. */ correct &= ( ssl->in_msglen >= padlen + 1 ); correct &= ( padding_idx < MBEDTLS_SSL_MAX_CONTENT_LEN + ssl->transform_in->maclen ); padding_idx *= correct; for( i = 1; i <= 256; i++ ) { real_count &= ( i <= padlen ); pad_count += real_count * ( ssl->in_msg[padding_idx + i] == padlen - 1 ); } correct &= ( pad_count == padlen ); /* Only 1 on correct padding */ #if defined(MBEDTLS_SSL_DEBUG_ALL) if( padlen > 0 && correct == 0 ) MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad padding byte detected" ) ); #endif padlen &= correct * 0x1FF; } else #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \ MBEDTLS_SSL_PROTO_TLS1_2 */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } ssl->in_msglen -= padlen; } else #endif /* MBEDTLS_CIPHER_MODE_CBC && ( MBEDTLS_AES_C || MBEDTLS_CAMELLIA_C ) */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } MBEDTLS_SSL_DEBUG_BUF( 4, "raw buffer after decryption", ssl->in_msg, ssl->in_msglen ); /* * Authenticate if not done yet. * Compute the MAC regardless of the padding result (RFC4346, CBCTIME). */ #if defined(SSL_SOME_MODES_USE_MAC) if( auth_done == 0 ) { unsigned char tmp[SSL_MAX_MAC_SIZE]; ssl->in_msglen -= ssl->transform_in->maclen; ssl->in_len[0] = (unsigned char)( ssl->in_msglen >> 8 ); ssl->in_len[1] = (unsigned char)( ssl->in_msglen ); memcpy( tmp, ssl->in_msg + ssl->in_msglen, ssl->transform_in->maclen ); #if defined(MBEDTLS_SSL_PROTO_SSL3) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) { ssl_mac( &ssl->transform_in->md_ctx_dec, ssl->transform_in->mac_dec, ssl->in_msg, ssl->in_msglen, ssl->in_ctr, ssl->in_msgtype ); } else #endif /* MBEDTLS_SSL_PROTO_SSL3 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_0 ) { /* * Process MAC and always update for padlen afterwards to make * total time independent of padlen * * extra_run compensates MAC check for padlen * * Known timing attacks: * - Lucky Thirteen (http://www.isg.rhul.ac.uk/tls/TLStiming.pdf) * * We use ( ( Lx + 8 ) / 64 ) to handle 'negative Lx' values * correctly. (We round down instead of up, so -56 is the correct * value for our calculations instead of -55) */ size_t j, extra_run = 0; extra_run = ( 13 + ssl->in_msglen + padlen + 8 ) / 64 - ( 13 + ssl->in_msglen + 8 ) / 64; extra_run &= correct * 0xFF; mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_ctr, 8 ); mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_hdr, 3 ); mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_len, 2 ); mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_msg, ssl->in_msglen ); mbedtls_md_hmac_finish( &ssl->transform_in->md_ctx_dec, ssl->in_msg + ssl->in_msglen ); /* Call mbedtls_md_process at least once due to cache attacks */ for( j = 0; j < extra_run + 1; j++ ) mbedtls_md_process( &ssl->transform_in->md_ctx_dec, ssl->in_msg ); mbedtls_md_hmac_reset( &ssl->transform_in->md_ctx_dec ); } else #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \ MBEDTLS_SSL_PROTO_TLS1_2 */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } MBEDTLS_SSL_DEBUG_BUF( 4, "message mac", tmp, ssl->transform_in->maclen ); MBEDTLS_SSL_DEBUG_BUF( 4, "computed mac", ssl->in_msg + ssl->in_msglen, ssl->transform_in->maclen ); if( mbedtls_ssl_safer_memcmp( tmp, ssl->in_msg + ssl->in_msglen, ssl->transform_in->maclen ) != 0 ) { #if defined(MBEDTLS_SSL_DEBUG_ALL) MBEDTLS_SSL_DEBUG_MSG( 1, ( "message mac does not match" ) ); #endif correct = 0; } auth_done++; /* * Finally check the correct flag */ if( correct == 0 ) return( MBEDTLS_ERR_SSL_INVALID_MAC ); } #endif /* SSL_SOME_MODES_USE_MAC */ /* Make extra sure authentication was performed, exactly once */ if( auth_done != 1 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } if( ssl->in_msglen == 0 ) { ssl->nb_zero++; /* * Three or more empty messages may be a DoS attack * (excessive CPU consumption). */ if( ssl->nb_zero > 3 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "received four consecutive empty " "messages, possible DoS attack" ) ); return( MBEDTLS_ERR_SSL_INVALID_MAC ); } } else ssl->nb_zero = 0; #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { ; /* in_ctr read from peer, not maintained internally */ } else #endif { for( i = 8; i > ssl_ep_len( ssl ); i-- ) if( ++ssl->in_ctr[i - 1] != 0 ) break; /* The loop goes to its end iff the counter is wrapping */ if( i == ssl_ep_len( ssl ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "incoming message counter would wrap" ) ); return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING ); } } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= decrypt buf" ) ); return( 0 ); } #undef MAC_NONE #undef MAC_PLAINTEXT #undef MAC_CIPHERTEXT #if defined(MBEDTLS_ZLIB_SUPPORT) /* * Compression/decompression functions */ static int ssl_compress_buf( mbedtls_ssl_context *ssl ) { int ret; unsigned char *msg_post = ssl->out_msg; size_t len_pre = ssl->out_msglen; unsigned char *msg_pre = ssl->compress_buf; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> compress buf" ) ); if( len_pre == 0 ) return( 0 ); memcpy( msg_pre, ssl->out_msg, len_pre ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "before compression: msglen = %d, ", ssl->out_msglen ) ); MBEDTLS_SSL_DEBUG_BUF( 4, "before compression: output payload", ssl->out_msg, ssl->out_msglen ); ssl->transform_out->ctx_deflate.next_in = msg_pre; ssl->transform_out->ctx_deflate.avail_in = len_pre; ssl->transform_out->ctx_deflate.next_out = msg_post; ssl->transform_out->ctx_deflate.avail_out = MBEDTLS_SSL_BUFFER_LEN; ret = deflate( &ssl->transform_out->ctx_deflate, Z_SYNC_FLUSH ); if( ret != Z_OK ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "failed to perform compression (%d)", ret ) ); return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED ); } ssl->out_msglen = MBEDTLS_SSL_BUFFER_LEN - ssl->transform_out->ctx_deflate.avail_out; MBEDTLS_SSL_DEBUG_MSG( 3, ( "after compression: msglen = %d, ", ssl->out_msglen ) ); MBEDTLS_SSL_DEBUG_BUF( 4, "after compression: output payload", ssl->out_msg, ssl->out_msglen ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= compress buf" ) ); return( 0 ); } static int ssl_decompress_buf( mbedtls_ssl_context *ssl ) { int ret; unsigned char *msg_post = ssl->in_msg; size_t len_pre = ssl->in_msglen; unsigned char *msg_pre = ssl->compress_buf; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> decompress buf" ) ); if( len_pre == 0 ) return( 0 ); memcpy( msg_pre, ssl->in_msg, len_pre ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "before decompression: msglen = %d, ", ssl->in_msglen ) ); MBEDTLS_SSL_DEBUG_BUF( 4, "before decompression: input payload", ssl->in_msg, ssl->in_msglen ); ssl->transform_in->ctx_inflate.next_in = msg_pre; ssl->transform_in->ctx_inflate.avail_in = len_pre; ssl->transform_in->ctx_inflate.next_out = msg_post; ssl->transform_in->ctx_inflate.avail_out = MBEDTLS_SSL_MAX_CONTENT_LEN; ret = inflate( &ssl->transform_in->ctx_inflate, Z_SYNC_FLUSH ); if( ret != Z_OK ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "failed to perform decompression (%d)", ret ) ); return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED ); } ssl->in_msglen = MBEDTLS_SSL_MAX_CONTENT_LEN - ssl->transform_in->ctx_inflate.avail_out; MBEDTLS_SSL_DEBUG_MSG( 3, ( "after decompression: msglen = %d, ", ssl->in_msglen ) ); MBEDTLS_SSL_DEBUG_BUF( 4, "after decompression: input payload", ssl->in_msg, ssl->in_msglen ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= decompress buf" ) ); return( 0 ); } #endif /* MBEDTLS_ZLIB_SUPPORT */ #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION) static int ssl_write_hello_request( mbedtls_ssl_context *ssl ); #if defined(MBEDTLS_SSL_PROTO_DTLS) static int ssl_resend_hello_request( mbedtls_ssl_context *ssl ) { /* If renegotiation is not enforced, retransmit until we would reach max * timeout if we were using the usual handshake doubling scheme */ if( ssl->conf->renego_max_records < 0 ) { uint32_t ratio = ssl->conf->hs_timeout_max / ssl->conf->hs_timeout_min + 1; unsigned char doublings = 1; while( ratio != 0 ) { ++doublings; ratio >>= 1; } if( ++ssl->renego_records_seen > doublings ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "no longer retransmitting hello request" ) ); return( 0 ); } } return( ssl_write_hello_request( ssl ) ); } #endif #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */ /* * Fill the input message buffer by appending data to it. * The amount of data already fetched is in ssl->in_left. * * If we return 0, is it guaranteed that (at least) nb_want bytes are * available (from this read and/or a previous one). Otherwise, an error code * is returned (possibly EOF or WANT_READ). * * With stream transport (TLS) on success ssl->in_left == nb_want, but * with datagram transport (DTLS) on success ssl->in_left >= nb_want, * since we always read a whole datagram at once. * * For DTLS, it is up to the caller to set ssl->next_record_offset when * they're done reading a record. */ int mbedtls_ssl_fetch_input( mbedtls_ssl_context *ssl, size_t nb_want ) { int ret; size_t len; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> fetch input" ) ); if( ssl->f_recv == NULL && ssl->f_recv_timeout == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() " "or mbedtls_ssl_set_bio()" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } if( nb_want > MBEDTLS_SSL_BUFFER_LEN - (size_t)( ssl->in_hdr - ssl->in_buf ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "requesting more data than fits" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { uint32_t timeout; /* Just to be sure */ if( ssl->f_set_timer == NULL || ssl->f_get_timer == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "You must use " "mbedtls_ssl_set_timer_cb() for DTLS" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } /* * The point is, we need to always read a full datagram at once, so we * sometimes read more then requested, and handle the additional data. * It could be the rest of the current record (while fetching the * header) and/or some other records in the same datagram. */ /* * Move to the next record in the already read datagram if applicable */ if( ssl->next_record_offset != 0 ) { if( ssl->in_left < ssl->next_record_offset ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } ssl->in_left -= ssl->next_record_offset; if( ssl->in_left != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "next record in same datagram, offset: %d", ssl->next_record_offset ) ); memmove( ssl->in_hdr, ssl->in_hdr + ssl->next_record_offset, ssl->in_left ); } ssl->next_record_offset = 0; } MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d", ssl->in_left, nb_want ) ); /* * Done if we already have enough data. */ if( nb_want <= ssl->in_left) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= fetch input" ) ); return( 0 ); } /* * A record can't be split accross datagrams. If we need to read but * are not at the beginning of a new record, the caller did something * wrong. */ if( ssl->in_left != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } /* * Don't even try to read if time's out already. * This avoids by-passing the timer when repeatedly receiving messages * that will end up being dropped. */ if( ssl_check_timer( ssl ) != 0 ) ret = MBEDTLS_ERR_SSL_TIMEOUT; else { len = MBEDTLS_SSL_BUFFER_LEN - ( ssl->in_hdr - ssl->in_buf ); if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) timeout = ssl->handshake->retransmit_timeout; else timeout = ssl->conf->read_timeout; MBEDTLS_SSL_DEBUG_MSG( 3, ( "f_recv_timeout: %u ms", timeout ) ); if( ssl->f_recv_timeout != NULL ) ret = ssl->f_recv_timeout( ssl->p_bio, ssl->in_hdr, len, timeout ); else ret = ssl->f_recv( ssl->p_bio, ssl->in_hdr, len ); MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_recv(_timeout)", ret ); if( ret == 0 ) return( MBEDTLS_ERR_SSL_CONN_EOF ); } if( ret == MBEDTLS_ERR_SSL_TIMEOUT ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "timeout" ) ); ssl_set_timer( ssl, 0 ); if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) { if( ssl_double_retransmit_timeout( ssl ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake timeout" ) ); return( MBEDTLS_ERR_SSL_TIMEOUT ); } if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret ); return( ret ); } return( MBEDTLS_ERR_SSL_WANT_READ ); } #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION) else if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ) { if( ( ret = ssl_resend_hello_request( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_resend_hello_request", ret ); return( ret ); } return( MBEDTLS_ERR_SSL_WANT_READ ); } #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */ } if( ret < 0 ) return( ret ); ssl->in_left = ret; } else #endif { MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d", ssl->in_left, nb_want ) ); while( ssl->in_left < nb_want ) { len = nb_want - ssl->in_left; if( ssl_check_timer( ssl ) != 0 ) ret = MBEDTLS_ERR_SSL_TIMEOUT; else { if( ssl->f_recv_timeout != NULL ) { ret = ssl->f_recv_timeout( ssl->p_bio, ssl->in_hdr + ssl->in_left, len, ssl->conf->read_timeout ); } else { ret = ssl->f_recv( ssl->p_bio, ssl->in_hdr + ssl->in_left, len ); } } MBEDTLS_SSL_DEBUG_MSG( 2, ( "in_left: %d, nb_want: %d", ssl->in_left, nb_want ) ); MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_recv(_timeout)", ret ); if( ret == 0 ) return( MBEDTLS_ERR_SSL_CONN_EOF ); if( ret < 0 ) return( ret ); ssl->in_left += ret; } } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= fetch input" ) ); return( 0 ); } /* * Flush any data not yet written */ int mbedtls_ssl_flush_output( mbedtls_ssl_context *ssl ) { int ret; unsigned char *buf, i; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> flush output" ) ); if( ssl->f_send == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "Bad usage of mbedtls_ssl_set_bio() " "or mbedtls_ssl_set_bio()" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } /* Avoid incrementing counter if data is flushed */ if( ssl->out_left == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= flush output" ) ); return( 0 ); } while( ssl->out_left > 0 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "message length: %d, out_left: %d", mbedtls_ssl_hdr_len( ssl ) + ssl->out_msglen, ssl->out_left ) ); buf = ssl->out_hdr + mbedtls_ssl_hdr_len( ssl ) + ssl->out_msglen - ssl->out_left; ret = ssl->f_send( ssl->p_bio, buf, ssl->out_left ); MBEDTLS_SSL_DEBUG_RET( 2, "ssl->f_send", ret ); if( ret <= 0 ) return( ret ); ssl->out_left -= ret; } for( i = 8; i > ssl_ep_len( ssl ); i-- ) if( ++ssl->out_ctr[i - 1] != 0 ) break; /* The loop goes to its end iff the counter is wrapping */ if( i == ssl_ep_len( ssl ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "outgoing message counter would wrap" ) ); return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= flush output" ) ); return( 0 ); } /* * Functions to handle the DTLS retransmission state machine */ #if defined(MBEDTLS_SSL_PROTO_DTLS) /* * Append current handshake message to current outgoing flight */ static int ssl_flight_append( mbedtls_ssl_context *ssl ) { mbedtls_ssl_flight_item *msg; /* Allocate space for current message */ if( ( msg = mbedtls_calloc( 1, sizeof( mbedtls_ssl_flight_item ) ) ) == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc %d bytes failed", sizeof( mbedtls_ssl_flight_item ) ) ); return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); } if( ( msg->p = mbedtls_calloc( 1, ssl->out_msglen ) ) == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc %d bytes failed", ssl->out_msglen ) ); mbedtls_free( msg ); return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); } /* Copy current handshake message with headers */ memcpy( msg->p, ssl->out_msg, ssl->out_msglen ); msg->len = ssl->out_msglen; msg->type = ssl->out_msgtype; msg->next = NULL; /* Append to the current flight */ if( ssl->handshake->flight == NULL ) ssl->handshake->flight = msg; else { mbedtls_ssl_flight_item *cur = ssl->handshake->flight; while( cur->next != NULL ) cur = cur->next; cur->next = msg; } return( 0 ); } /* * Free the current flight of handshake messages */ static void ssl_flight_free( mbedtls_ssl_flight_item *flight ) { mbedtls_ssl_flight_item *cur = flight; mbedtls_ssl_flight_item *next; while( cur != NULL ) { next = cur->next; mbedtls_free( cur->p ); mbedtls_free( cur ); cur = next; } } #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) static void ssl_dtls_replay_reset( mbedtls_ssl_context *ssl ); #endif /* * Swap transform_out and out_ctr with the alternative ones */ static void ssl_swap_epochs( mbedtls_ssl_context *ssl ) { mbedtls_ssl_transform *tmp_transform; unsigned char tmp_out_ctr[8]; if( ssl->transform_out == ssl->handshake->alt_transform_out ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip swap epochs" ) ); return; } MBEDTLS_SSL_DEBUG_MSG( 3, ( "swap epochs" ) ); /* Swap transforms */ tmp_transform = ssl->transform_out; ssl->transform_out = ssl->handshake->alt_transform_out; ssl->handshake->alt_transform_out = tmp_transform; /* Swap epoch + sequence_number */ memcpy( tmp_out_ctr, ssl->out_ctr, 8 ); memcpy( ssl->out_ctr, ssl->handshake->alt_out_ctr, 8 ); memcpy( ssl->handshake->alt_out_ctr, tmp_out_ctr, 8 ); /* Adjust to the newly activated transform */ if( ssl->transform_out != NULL && ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 ) { ssl->out_msg = ssl->out_iv + ssl->transform_out->ivlen - ssl->transform_out->fixed_ivlen; } else ssl->out_msg = ssl->out_iv; #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) if( mbedtls_ssl_hw_record_activate != NULL ) { if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_OUTBOUND ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret ); return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); } } #endif } /* * Retransmit the current flight of messages. * * Need to remember the current message in case flush_output returns * WANT_WRITE, causing us to exit this function and come back later. * This function must be called until state is no longer SENDING. */ int mbedtls_ssl_resend( mbedtls_ssl_context *ssl ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> mbedtls_ssl_resend" ) ); if( ssl->handshake->retransmit_state != MBEDTLS_SSL_RETRANS_SENDING ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "initialise resending" ) ); ssl->handshake->cur_msg = ssl->handshake->flight; ssl_swap_epochs( ssl ); ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_SENDING; } while( ssl->handshake->cur_msg != NULL ) { int ret; mbedtls_ssl_flight_item *cur = ssl->handshake->cur_msg; /* Swap epochs before sending Finished: we can't do it after * sending ChangeCipherSpec, in case write returns WANT_READ. * Must be done before copying, may change out_msg pointer */ if( cur->type == MBEDTLS_SSL_MSG_HANDSHAKE && cur->p[0] == MBEDTLS_SSL_HS_FINISHED ) { ssl_swap_epochs( ssl ); } memcpy( ssl->out_msg, cur->p, cur->len ); ssl->out_msglen = cur->len; ssl->out_msgtype = cur->type; ssl->handshake->cur_msg = cur->next; MBEDTLS_SSL_DEBUG_BUF( 3, "resent handshake message header", ssl->out_msg, 12 ); if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret ); return( ret ); } } if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER ) ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED; else { ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING; ssl_set_timer( ssl, ssl->handshake->retransmit_timeout ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= mbedtls_ssl_resend" ) ); return( 0 ); } /* * To be called when the last message of an incoming flight is received. */ void mbedtls_ssl_recv_flight_completed( mbedtls_ssl_context *ssl ) { /* We won't need to resend that one any more */ ssl_flight_free( ssl->handshake->flight ); ssl->handshake->flight = NULL; ssl->handshake->cur_msg = NULL; /* The next incoming flight will start with this msg_seq */ ssl->handshake->in_flight_start_seq = ssl->handshake->in_msg_seq; /* Cancel timer */ ssl_set_timer( ssl, 0 ); if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE && ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED ) { ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED; } else ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING; } /* * To be called when the last message of an outgoing flight is send. */ void mbedtls_ssl_send_flight_completed( mbedtls_ssl_context *ssl ) { ssl_reset_retransmit_timeout( ssl ); ssl_set_timer( ssl, ssl->handshake->retransmit_timeout ); if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE && ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED ) { ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_FINISHED; } else ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING; } #endif /* MBEDTLS_SSL_PROTO_DTLS */ /* * Record layer functions */ /* * Write current record. * Uses ssl->out_msgtype, ssl->out_msglen and bytes at ssl->out_msg. */ int mbedtls_ssl_write_record( mbedtls_ssl_context *ssl ) { int ret, done = 0, out_msg_type; size_t len = ssl->out_msglen; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write record" ) ); #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl->handshake != NULL && ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING ) { ; /* Skip special handshake treatment when resending */ } else #endif if( ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE ) { out_msg_type = ssl->out_msg[0]; if( out_msg_type != MBEDTLS_SSL_HS_HELLO_REQUEST && ssl->handshake == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } ssl->out_msg[1] = (unsigned char)( ( len - 4 ) >> 16 ); ssl->out_msg[2] = (unsigned char)( ( len - 4 ) >> 8 ); ssl->out_msg[3] = (unsigned char)( ( len - 4 ) ); /* * DTLS has additional fields in the Handshake layer, * between the length field and the actual payload: * uint16 message_seq; * uint24 fragment_offset; * uint24 fragment_length; */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { /* Make room for the additional DTLS fields */ memmove( ssl->out_msg + 12, ssl->out_msg + 4, len - 4 ); ssl->out_msglen += 8; len += 8; /* Write message_seq and update it, except for HelloRequest */ if( out_msg_type != MBEDTLS_SSL_HS_HELLO_REQUEST ) { ssl->out_msg[4] = ( ssl->handshake->out_msg_seq >> 8 ) & 0xFF; ssl->out_msg[5] = ( ssl->handshake->out_msg_seq ) & 0xFF; ++( ssl->handshake->out_msg_seq ); } else { ssl->out_msg[4] = 0; ssl->out_msg[5] = 0; } /* We don't fragment, so frag_offset = 0 and frag_len = len */ memset( ssl->out_msg + 6, 0x00, 3 ); memcpy( ssl->out_msg + 9, ssl->out_msg + 1, 3 ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ if( out_msg_type != MBEDTLS_SSL_HS_HELLO_REQUEST ) ssl->handshake->update_checksum( ssl, ssl->out_msg, len ); } /* Save handshake and CCS messages for resending */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl->handshake != NULL && ssl->handshake->retransmit_state != MBEDTLS_SSL_RETRANS_SENDING && ( ssl->out_msgtype == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC || ssl->out_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE ) ) { if( ( ret = ssl_flight_append( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_flight_append", ret ); return( ret ); } } #endif #if defined(MBEDTLS_ZLIB_SUPPORT) if( ssl->transform_out != NULL && ssl->session_out->compression == MBEDTLS_SSL_COMPRESS_DEFLATE ) { if( ( ret = ssl_compress_buf( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_compress_buf", ret ); return( ret ); } len = ssl->out_msglen; } #endif /*MBEDTLS_ZLIB_SUPPORT */ #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) if( mbedtls_ssl_hw_record_write != NULL ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_write()" ) ); ret = mbedtls_ssl_hw_record_write( ssl ); if( ret != 0 && ret != MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_write", ret ); return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); } if( ret == 0 ) done = 1; } #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */ if( !done ) { ssl->out_hdr[0] = (unsigned char) ssl->out_msgtype; mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver, ssl->conf->transport, ssl->out_hdr + 1 ); ssl->out_len[0] = (unsigned char)( len >> 8 ); ssl->out_len[1] = (unsigned char)( len ); if( ssl->transform_out != NULL ) { if( ( ret = ssl_encrypt_buf( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_encrypt_buf", ret ); return( ret ); } len = ssl->out_msglen; ssl->out_len[0] = (unsigned char)( len >> 8 ); ssl->out_len[1] = (unsigned char)( len ); } ssl->out_left = mbedtls_ssl_hdr_len( ssl ) + ssl->out_msglen; MBEDTLS_SSL_DEBUG_MSG( 3, ( "output record: msgtype = %d, " "version = [%d:%d], msglen = %d", ssl->out_hdr[0], ssl->out_hdr[1], ssl->out_hdr[2], ( ssl->out_len[0] << 8 ) | ssl->out_len[1] ) ); MBEDTLS_SSL_DEBUG_BUF( 4, "output record sent to network", ssl->out_hdr, mbedtls_ssl_hdr_len( ssl ) + ssl->out_msglen ); } if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flush_output", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write record" ) ); return( 0 ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) /* * Mark bits in bitmask (used for DTLS HS reassembly) */ static void ssl_bitmask_set( unsigned char *mask, size_t offset, size_t len ) { unsigned int start_bits, end_bits; start_bits = 8 - ( offset % 8 ); if( start_bits != 8 ) { size_t first_byte_idx = offset / 8; /* Special case */ if( len <= start_bits ) { for( ; len != 0; len-- ) mask[first_byte_idx] |= 1 << ( start_bits - len ); /* Avoid potential issues with offset or len becoming invalid */ return; } offset += start_bits; /* Now offset % 8 == 0 */ len -= start_bits; for( ; start_bits != 0; start_bits-- ) mask[first_byte_idx] |= 1 << ( start_bits - 1 ); } end_bits = len % 8; if( end_bits != 0 ) { size_t last_byte_idx = ( offset + len ) / 8; len -= end_bits; /* Now len % 8 == 0 */ for( ; end_bits != 0; end_bits-- ) mask[last_byte_idx] |= 1 << ( 8 - end_bits ); } memset( mask + offset / 8, 0xFF, len / 8 ); } /* * Check that bitmask is full */ static int ssl_bitmask_check( unsigned char *mask, size_t len ) { size_t i; for( i = 0; i < len / 8; i++ ) if( mask[i] != 0xFF ) return( -1 ); for( i = 0; i < len % 8; i++ ) if( ( mask[len / 8] & ( 1 << ( 7 - i ) ) ) == 0 ) return( -1 ); return( 0 ); } /* * Reassemble fragmented DTLS handshake messages. * * Use a temporary buffer for reassembly, divided in two parts: * - the first holds the reassembled message (including handshake header), * - the second holds a bitmask indicating which parts of the message * (excluding headers) have been received so far. */ static int ssl_reassemble_dtls_handshake( mbedtls_ssl_context *ssl ) { unsigned char *msg, *bitmask; size_t frag_len, frag_off; size_t msg_len = ssl->in_hslen - 12; /* Without headers */ if( ssl->handshake == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "not supported outside handshake (for now)" ) ); return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); } /* * For first fragment, check size and allocate buffer */ if( ssl->handshake->hs_msg == NULL ) { size_t alloc_len; MBEDTLS_SSL_DEBUG_MSG( 2, ( "initialize reassembly, total length = %d", msg_len ) ); if( ssl->in_hslen > MBEDTLS_SSL_MAX_CONTENT_LEN ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake message too large" ) ); return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); } /* The bitmask needs one bit per byte of message excluding header */ alloc_len = 12 + msg_len + msg_len / 8 + ( msg_len % 8 != 0 ); ssl->handshake->hs_msg = mbedtls_calloc( 1, alloc_len ); if( ssl->handshake->hs_msg == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc failed (%d bytes)", alloc_len ) ); return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); } /* Prepare final header: copy msg_type, length and message_seq, * then add standardised fragment_offset and fragment_length */ memcpy( ssl->handshake->hs_msg, ssl->in_msg, 6 ); memset( ssl->handshake->hs_msg + 6, 0, 3 ); memcpy( ssl->handshake->hs_msg + 9, ssl->handshake->hs_msg + 1, 3 ); } else { /* Make sure msg_type and length are consistent */ if( memcmp( ssl->handshake->hs_msg, ssl->in_msg, 4 ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "fragment header mismatch" ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } } msg = ssl->handshake->hs_msg + 12; bitmask = msg + msg_len; /* * Check and copy current fragment */ frag_off = ( ssl->in_msg[6] << 16 ) | ( ssl->in_msg[7] << 8 ) | ssl->in_msg[8]; frag_len = ( ssl->in_msg[9] << 16 ) | ( ssl->in_msg[10] << 8 ) | ssl->in_msg[11]; if( frag_off + frag_len > msg_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid fragment offset/len: %d + %d > %d", frag_off, frag_len, msg_len ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } if( frag_len + 12 > ssl->in_msglen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid fragment length: %d + 12 > %d", frag_len, ssl->in_msglen ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "adding fragment, offset = %d, length = %d", frag_off, frag_len ) ); memcpy( msg + frag_off, ssl->in_msg + 12, frag_len ); ssl_bitmask_set( bitmask, frag_off, frag_len ); /* * Do we have the complete message by now? * If yes, finalize it, else ask to read the next record. */ if( ssl_bitmask_check( bitmask, msg_len ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "message is not complete yet" ) ); return( MBEDTLS_ERR_SSL_WANT_READ ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "handshake message completed" ) ); if( frag_len + 12 < ssl->in_msglen ) { /* * We'got more handshake messages in the same record. * This case is not handled now because no know implementation does * that and it's hard to test, so we prefer to fail cleanly for now. */ MBEDTLS_SSL_DEBUG_MSG( 1, ( "last fragment not alone in its record" ) ); return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); } if( ssl->in_left > ssl->next_record_offset ) { /* * We've got more data in the buffer after the current record, * that we don't want to overwrite. Move it before writing the * reassembled message, and adjust in_left and next_record_offset. */ unsigned char *cur_remain = ssl->in_hdr + ssl->next_record_offset; unsigned char *new_remain = ssl->in_msg + ssl->in_hslen; size_t remain_len = ssl->in_left - ssl->next_record_offset; /* First compute and check new lengths */ ssl->next_record_offset = new_remain - ssl->in_hdr; ssl->in_left = ssl->next_record_offset + remain_len; if( ssl->in_left > MBEDTLS_SSL_BUFFER_LEN - (size_t)( ssl->in_hdr - ssl->in_buf ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "reassembled message too large for buffer" ) ); return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); } memmove( new_remain, cur_remain, remain_len ); } memcpy( ssl->in_msg, ssl->handshake->hs_msg, ssl->in_hslen ); mbedtls_free( ssl->handshake->hs_msg ); ssl->handshake->hs_msg = NULL; MBEDTLS_SSL_DEBUG_BUF( 3, "reassembled handshake message", ssl->in_msg, ssl->in_hslen ); return( 0 ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ int mbedtls_ssl_prepare_handshake_record( mbedtls_ssl_context *ssl ) { if( ssl->in_msglen < mbedtls_ssl_hs_hdr_len( ssl ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake message too short: %d", ssl->in_msglen ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } ssl->in_hslen = mbedtls_ssl_hs_hdr_len( ssl ) + ( ( ssl->in_msg[1] << 16 ) | ( ssl->in_msg[2] << 8 ) | ssl->in_msg[3] ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "handshake message: msglen =" " %d, type = %d, hslen = %d", ssl->in_msglen, ssl->in_msg[0], ssl->in_hslen ) ); #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { int ret; unsigned int recv_msg_seq = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5]; /* ssl->handshake is NULL when receiving ClientHello for renego */ if( ssl->handshake != NULL && recv_msg_seq != ssl->handshake->in_msg_seq ) { /* Retransmit only on last message from previous flight, to avoid * too many retransmissions. * Besides, No sane server ever retransmits HelloVerifyRequest */ if( recv_msg_seq == ssl->handshake->in_flight_start_seq - 1 && ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "received message from last flight, " "message_seq = %d, start_of_flight = %d", recv_msg_seq, ssl->handshake->in_flight_start_seq ) ); if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret ); return( ret ); } } else { MBEDTLS_SSL_DEBUG_MSG( 2, ( "dropping out-of-sequence message: " "message_seq = %d, expected = %d", recv_msg_seq, ssl->handshake->in_msg_seq ) ); } return( MBEDTLS_ERR_SSL_WANT_READ ); } /* Wait until message completion to increment in_msg_seq */ /* Reassemble if current message is fragmented or reassembly is * already in progress */ if( ssl->in_msglen < ssl->in_hslen || memcmp( ssl->in_msg + 6, "\0\0\0", 3 ) != 0 || memcmp( ssl->in_msg + 9, ssl->in_msg + 1, 3 ) != 0 || ( ssl->handshake != NULL && ssl->handshake->hs_msg != NULL ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "found fragmented DTLS handshake message" ) ); if( ( ret = ssl_reassemble_dtls_handshake( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_reassemble_dtls_handshake", ret ); return( ret ); } } } else #endif /* MBEDTLS_SSL_PROTO_DTLS */ /* With TLS we don't handle fragmentation (for now) */ if( ssl->in_msglen < ssl->in_hslen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "TLS handshake fragmentation not supported" ) ); return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); } return( 0 ); } void mbedtls_ssl_update_handshake_status( mbedtls_ssl_context *ssl ) { if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER && ssl->handshake != NULL ) { ssl->handshake->update_checksum( ssl, ssl->in_msg, ssl->in_hslen ); } /* Handshake message is complete, increment counter */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl->handshake != NULL ) { ssl->handshake->in_msg_seq++; } #endif } /* * DTLS anti-replay: RFC 6347 4.1.2.6 * * in_window is a field of bits numbered from 0 (lsb) to 63 (msb). * Bit n is set iff record number in_window_top - n has been seen. * * Usually, in_window_top is the last record number seen and the lsb of * in_window is set. The only exception is the initial state (record number 0 * not seen yet). */ #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) static void ssl_dtls_replay_reset( mbedtls_ssl_context *ssl ) { ssl->in_window_top = 0; ssl->in_window = 0; } static inline uint64_t ssl_load_six_bytes( unsigned char *buf ) { return( ( (uint64_t) buf[0] << 40 ) | ( (uint64_t) buf[1] << 32 ) | ( (uint64_t) buf[2] << 24 ) | ( (uint64_t) buf[3] << 16 ) | ( (uint64_t) buf[4] << 8 ) | ( (uint64_t) buf[5] ) ); } /* * Return 0 if sequence number is acceptable, -1 otherwise */ int mbedtls_ssl_dtls_replay_check( mbedtls_ssl_context *ssl ) { uint64_t rec_seqnum = ssl_load_six_bytes( ssl->in_ctr + 2 ); uint64_t bit; if( ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED ) return( 0 ); if( rec_seqnum > ssl->in_window_top ) return( 0 ); bit = ssl->in_window_top - rec_seqnum; if( bit >= 64 ) return( -1 ); if( ( ssl->in_window & ( (uint64_t) 1 << bit ) ) != 0 ) return( -1 ); return( 0 ); } /* * Update replay window on new validated record */ void mbedtls_ssl_dtls_replay_update( mbedtls_ssl_context *ssl ) { uint64_t rec_seqnum = ssl_load_six_bytes( ssl->in_ctr + 2 ); if( ssl->conf->anti_replay == MBEDTLS_SSL_ANTI_REPLAY_DISABLED ) return; if( rec_seqnum > ssl->in_window_top ) { /* Update window_top and the contents of the window */ uint64_t shift = rec_seqnum - ssl->in_window_top; if( shift >= 64 ) ssl->in_window = 1; else { ssl->in_window <<= shift; ssl->in_window |= 1; } ssl->in_window_top = rec_seqnum; } else { /* Mark that number as seen in the current window */ uint64_t bit = ssl->in_window_top - rec_seqnum; if( bit < 64 ) /* Always true, but be extra sure */ ssl->in_window |= (uint64_t) 1 << bit; } } #endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */ #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C) /* Forward declaration */ static int ssl_session_reset_int( mbedtls_ssl_context *ssl, int partial ); /* * Without any SSL context, check if a datagram looks like a ClientHello with * a valid cookie, and if it doesn't, generate a HelloVerifyRequest message. * Both input and output include full DTLS headers. * * - if cookie is valid, return 0 * - if ClientHello looks superficially valid but cookie is not, * fill obuf and set olen, then * return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED * - otherwise return a specific error code */ static int ssl_check_dtls_clihlo_cookie( mbedtls_ssl_cookie_write_t *f_cookie_write, mbedtls_ssl_cookie_check_t *f_cookie_check, void *p_cookie, const unsigned char *cli_id, size_t cli_id_len, const unsigned char *in, size_t in_len, unsigned char *obuf, size_t buf_len, size_t *olen ) { size_t sid_len, cookie_len; unsigned char *p; if( f_cookie_write == NULL || f_cookie_check == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); /* * Structure of ClientHello with record and handshake headers, * and expected values. We don't need to check a lot, more checks will be * done when actually parsing the ClientHello - skipping those checks * avoids code duplication and does not make cookie forging any easier. * * 0-0 ContentType type; copied, must be handshake * 1-2 ProtocolVersion version; copied * 3-4 uint16 epoch; copied, must be 0 * 5-10 uint48 sequence_number; copied * 11-12 uint16 length; (ignored) * * 13-13 HandshakeType msg_type; (ignored) * 14-16 uint24 length; (ignored) * 17-18 uint16 message_seq; copied * 19-21 uint24 fragment_offset; copied, must be 0 * 22-24 uint24 fragment_length; (ignored) * * 25-26 ProtocolVersion client_version; (ignored) * 27-58 Random random; (ignored) * 59-xx SessionID session_id; 1 byte len + sid_len content * 60+ opaque cookie<0..2^8-1>; 1 byte len + content * ... * * Minimum length is 61 bytes. */ if( in_len < 61 || in[0] != MBEDTLS_SSL_MSG_HANDSHAKE || in[3] != 0 || in[4] != 0 || in[19] != 0 || in[20] != 0 || in[21] != 0 ) { return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } sid_len = in[59]; if( sid_len > in_len - 61 ) return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); cookie_len = in[60 + sid_len]; if( cookie_len > in_len - 60 ) return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); if( f_cookie_check( p_cookie, in + sid_len + 61, cookie_len, cli_id, cli_id_len ) == 0 ) { /* Valid cookie */ return( 0 ); } /* * If we get here, we've got an invalid cookie, let's prepare HVR. * * 0-0 ContentType type; copied * 1-2 ProtocolVersion version; copied * 3-4 uint16 epoch; copied * 5-10 uint48 sequence_number; copied * 11-12 uint16 length; olen - 13 * * 13-13 HandshakeType msg_type; hello_verify_request * 14-16 uint24 length; olen - 25 * 17-18 uint16 message_seq; copied * 19-21 uint24 fragment_offset; copied * 22-24 uint24 fragment_length; olen - 25 * * 25-26 ProtocolVersion server_version; 0xfe 0xff * 27-27 opaque cookie<0..2^8-1>; cookie_len = olen - 27, cookie * * Minimum length is 28. */ if( buf_len < 28 ) return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); /* Copy most fields and adapt others */ memcpy( obuf, in, 25 ); obuf[13] = MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST; obuf[25] = 0xfe; obuf[26] = 0xff; /* Generate and write actual cookie */ p = obuf + 28; if( f_cookie_write( p_cookie, &p, obuf + buf_len, cli_id, cli_id_len ) != 0 ) { return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } *olen = p - obuf; /* Go back and fill length fields */ obuf[27] = (unsigned char)( *olen - 28 ); obuf[14] = obuf[22] = (unsigned char)( ( *olen - 25 ) >> 16 ); obuf[15] = obuf[23] = (unsigned char)( ( *olen - 25 ) >> 8 ); obuf[16] = obuf[24] = (unsigned char)( ( *olen - 25 ) ); obuf[11] = (unsigned char)( ( *olen - 13 ) >> 8 ); obuf[12] = (unsigned char)( ( *olen - 13 ) ); return( MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED ); } /* * Handle possible client reconnect with the same UDP quadruplet * (RFC 6347 Section 4.2.8). * * Called by ssl_parse_record_header() in case we receive an epoch 0 record * that looks like a ClientHello. * * - if the input looks like a ClientHello without cookies, * send back HelloVerifyRequest, then * return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED * - if the input looks like a ClientHello with a valid cookie, * reset the session of the current context, and * return MBEDTLS_ERR_SSL_CLIENT_RECONNECT * - if anything goes wrong, return a specific error code * * mbedtls_ssl_read_record() will ignore the record if anything else than * MBEDTLS_ERR_SSL_CLIENT_RECONNECT or 0 is returned, although this function * cannot not return 0. */ static int ssl_handle_possible_reconnect( mbedtls_ssl_context *ssl ) { int ret; size_t len; ret = ssl_check_dtls_clihlo_cookie( ssl->conf->f_cookie_write, ssl->conf->f_cookie_check, ssl->conf->p_cookie, ssl->cli_id, ssl->cli_id_len, ssl->in_buf, ssl->in_left, ssl->out_buf, MBEDTLS_SSL_MAX_CONTENT_LEN, &len ); MBEDTLS_SSL_DEBUG_RET( 2, "ssl_check_dtls_clihlo_cookie", ret ); if( ret == MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED ) { /* Don't check write errors as we can't do anything here. * If the error is permanent we'll catch it later, * if it's not, then hopefully it'll work next time. */ (void) ssl->f_send( ssl->p_bio, ssl->out_buf, len ); return( MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED ); } if( ret == 0 ) { /* Got a valid cookie, partially reset context */ if( ( ret = ssl_session_reset_int( ssl, 1 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "reset", ret ); return( ret ); } return( MBEDTLS_ERR_SSL_CLIENT_RECONNECT ); } return( ret ); } #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */ /* * ContentType type; * ProtocolVersion version; * uint16 epoch; // DTLS only * uint48 sequence_number; // DTLS only * uint16 length; * * Return 0 if header looks sane (and, for DTLS, the record is expected) * MBEDTLS_ERR_SSL_INVALID_RECORD if the header looks bad, * MBEDTLS_ERR_SSL_UNEXPECTED_RECORD (DTLS only) if sane but unexpected. * * With DTLS, mbedtls_ssl_read_record() will: * 1. proceed with the record if this function returns 0 * 2. drop only the current record if this function returns UNEXPECTED_RECORD * 3. return CLIENT_RECONNECT if this function return that value * 4. drop the whole datagram if this function returns anything else. * Point 2 is needed when the peer is resending, and we have already received * the first record from a datagram but are still waiting for the others. */ static int ssl_parse_record_header( mbedtls_ssl_context *ssl ) { int ret; int major_ver, minor_ver; MBEDTLS_SSL_DEBUG_BUF( 4, "input record header", ssl->in_hdr, mbedtls_ssl_hdr_len( ssl ) ); ssl->in_msgtype = ssl->in_hdr[0]; ssl->in_msglen = ( ssl->in_len[0] << 8 ) | ssl->in_len[1]; mbedtls_ssl_read_version( &major_ver, &minor_ver, ssl->conf->transport, ssl->in_hdr + 1 ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "input record: msgtype = %d, " "version = [%d:%d], msglen = %d", ssl->in_msgtype, major_ver, minor_ver, ssl->in_msglen ) ); /* Check record type */ if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE && ssl->in_msgtype != MBEDTLS_SSL_MSG_ALERT && ssl->in_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC && ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "unknown record type" ) ); if( ( ret = mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE ) ) != 0 ) { return( ret ); } return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } /* Check version */ if( major_ver != ssl->major_ver ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "major version mismatch" ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } if( minor_ver > ssl->conf->max_minor_ver ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "minor version mismatch" ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } /* Check length against the size of our buffer */ if( ssl->in_msglen > MBEDTLS_SSL_BUFFER_LEN - (size_t)( ssl->in_msg - ssl->in_buf ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } /* Check length against bounds of the current transform and version */ if( ssl->transform_in == NULL ) { if( ssl->in_msglen < 1 || ssl->in_msglen > MBEDTLS_SSL_MAX_CONTENT_LEN ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } } else { if( ssl->in_msglen < ssl->transform_in->minlen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } #if defined(MBEDTLS_SSL_PROTO_SSL3) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 && ssl->in_msglen > ssl->transform_in->minlen + MBEDTLS_SSL_MAX_CONTENT_LEN ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } #endif #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) /* * TLS encrypted messages can have up to 256 bytes of padding */ if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 && ssl->in_msglen > ssl->transform_in->minlen + MBEDTLS_SSL_MAX_CONTENT_LEN + 256 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } #endif } /* * DTLS-related tests done last, because most of them may result in * silently dropping the record (but not the whole datagram), and we only * want to consider that after ensuring that the "basic" fields (type, * version, length) are sane. */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { unsigned int rec_epoch = ( ssl->in_ctr[0] << 8 ) | ssl->in_ctr[1]; /* Drop unexpected ChangeCipherSpec messages */ if( ssl->in_msgtype == MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC && ssl->state != MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC && ssl->state != MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "dropping unexpected ChangeCipherSpec" ) ); return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD ); } /* Drop unexpected ApplicationData records, * except at the beginning of renegotiations */ if( ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA && ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER #if defined(MBEDTLS_SSL_RENEGOTIATION) && ! ( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS && ssl->state == MBEDTLS_SSL_SERVER_HELLO ) #endif ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "dropping unexpected ApplicationData" ) ); return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD ); } /* Check epoch (and sequence number) with DTLS */ if( rec_epoch != ssl->in_epoch ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "record from another epoch: " "expected %d, received %d", ssl->in_epoch, rec_epoch ) ); #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C) /* * Check for an epoch 0 ClientHello. We can't use in_msg here to * access the first byte of record content (handshake type), as we * have an active transform (possibly iv_len != 0), so use the * fact that the record header len is 13 instead. */ if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER && rec_epoch == 0 && ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE && ssl->in_left > 13 && ssl->in_buf[13] == MBEDTLS_SSL_HS_CLIENT_HELLO ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "possible client reconnect " "from the same port" ) ); return( ssl_handle_possible_reconnect( ssl ) ); } else #endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */ return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD ); } #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) /* Replay detection only works for the current epoch */ if( rec_epoch == ssl->in_epoch && mbedtls_ssl_dtls_replay_check( ssl ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "replayed record" ) ); return( MBEDTLS_ERR_SSL_UNEXPECTED_RECORD ); } #endif } #endif /* MBEDTLS_SSL_PROTO_DTLS */ return( 0 ); } /* * If applicable, decrypt (and decompress) record content */ static int ssl_prepare_record_content( mbedtls_ssl_context *ssl ) { int ret, done = 0; MBEDTLS_SSL_DEBUG_BUF( 4, "input record from network", ssl->in_hdr, mbedtls_ssl_hdr_len( ssl ) + ssl->in_msglen ); #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) if( mbedtls_ssl_hw_record_read != NULL ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_read()" ) ); ret = mbedtls_ssl_hw_record_read( ssl ); if( ret != 0 && ret != MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_read", ret ); return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); } if( ret == 0 ) done = 1; } #endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */ if( !done && ssl->transform_in != NULL ) { if( ( ret = ssl_decrypt_buf( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_decrypt_buf", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_BUF( 4, "input payload after decrypt", ssl->in_msg, ssl->in_msglen ); if( ssl->in_msglen > MBEDTLS_SSL_MAX_CONTENT_LEN ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad message length" ) ); return( MBEDTLS_ERR_SSL_INVALID_RECORD ); } } #if defined(MBEDTLS_ZLIB_SUPPORT) if( ssl->transform_in != NULL && ssl->session_in->compression == MBEDTLS_SSL_COMPRESS_DEFLATE ) { if( ( ret = ssl_decompress_buf( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_decompress_buf", ret ); return( ret ); } } #endif /* MBEDTLS_ZLIB_SUPPORT */ #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { mbedtls_ssl_dtls_replay_update( ssl ); } #endif return( 0 ); } static void ssl_handshake_wrapup_free_hs_transform( mbedtls_ssl_context *ssl ); /* * Read a record. * * Silently ignore non-fatal alert (and for DTLS, invalid records as well, * RFC 6347 4.1.2.7) and continue reading until a valid record is found. * */ int mbedtls_ssl_read_record( mbedtls_ssl_context *ssl ) { int ret; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> read record" ) ); do { if( ( ret = mbedtls_ssl_read_record_layer( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ssl_read_record_layer" ), ret ); return( ret ); } ret = mbedtls_ssl_handle_message_type( ssl ); } while( MBEDTLS_ERR_SSL_NON_FATAL == ret ); if( 0 != ret ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ssl_handle_message_type" ), ret ); return( ret ); } if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE ) { mbedtls_ssl_update_handshake_status( ssl ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= read record" ) ); return( 0 ); } int mbedtls_ssl_read_record_layer( mbedtls_ssl_context *ssl ) { int ret; if( ssl->in_hslen != 0 && ssl->in_hslen < ssl->in_msglen ) { /* * Get next Handshake message in the current record */ ssl->in_msglen -= ssl->in_hslen; memmove( ssl->in_msg, ssl->in_msg + ssl->in_hslen, ssl->in_msglen ); MBEDTLS_SSL_DEBUG_BUF( 4, "remaining content in record", ssl->in_msg, ssl->in_msglen ); return( 0 ); } ssl->in_hslen = 0; /* * Read the record header and parse it */ #if defined(MBEDTLS_SSL_PROTO_DTLS) read_record_header: #endif if( ( ret = mbedtls_ssl_fetch_input( ssl, mbedtls_ssl_hdr_len( ssl ) ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret ); return( ret ); } if( ( ret = ssl_parse_record_header( ssl ) ) != 0 ) { #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ret != MBEDTLS_ERR_SSL_CLIENT_RECONNECT ) { if( ret == MBEDTLS_ERR_SSL_UNEXPECTED_RECORD ) { /* Skip unexpected record (but not whole datagram) */ ssl->next_record_offset = ssl->in_msglen + mbedtls_ssl_hdr_len( ssl ); MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding unexpected record " "(header)" ) ); } else { /* Skip invalid record and the rest of the datagram */ ssl->next_record_offset = 0; ssl->in_left = 0; MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding invalid record " "(header)" ) ); } /* Get next record */ goto read_record_header; } #endif return( ret ); } /* * Read and optionally decrypt the message contents */ if( ( ret = mbedtls_ssl_fetch_input( ssl, mbedtls_ssl_hdr_len( ssl ) + ssl->in_msglen ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret ); return( ret ); } /* Done reading this record, get ready for the next one */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) ssl->next_record_offset = ssl->in_msglen + mbedtls_ssl_hdr_len( ssl ); else #endif ssl->in_left = 0; if( ( ret = ssl_prepare_record_content( ssl ) ) != 0 ) { #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { /* Silently discard invalid records */ if( ret == MBEDTLS_ERR_SSL_INVALID_RECORD || ret == MBEDTLS_ERR_SSL_INVALID_MAC ) { /* Except when waiting for Finished as a bad mac here * probably means something went wrong in the handshake * (eg wrong psk used, mitm downgrade attempt, etc.) */ if( ssl->state == MBEDTLS_SSL_CLIENT_FINISHED || ssl->state == MBEDTLS_SSL_SERVER_FINISHED ) { #if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES) if( ret == MBEDTLS_ERR_SSL_INVALID_MAC ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC ); } #endif return( ret ); } #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT) if( ssl->conf->badmac_limit != 0 && ++ssl->badmac_seen >= ssl->conf->badmac_limit ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "too many records with bad MAC" ) ); return( MBEDTLS_ERR_SSL_INVALID_MAC ); } #endif MBEDTLS_SSL_DEBUG_MSG( 1, ( "discarding invalid record (mac)" ) ); goto read_record_header; } return( ret ); } else #endif { /* Error out (and send alert) on invalid records */ #if defined(MBEDTLS_SSL_ALL_ALERT_MESSAGES) if( ret == MBEDTLS_ERR_SSL_INVALID_MAC ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC ); } #endif return( ret ); } } /* * When we sent the last flight of the handshake, we MUST respond to a * retransmit of the peer's previous flight with a retransmit. (In * practice, only the Finished message will make it, other messages * including CCS use the old transform so they're dropped as invalid.) * * If the record we received is not a handshake message, however, it * means the peer received our last flight so we can clean up * handshake info. * * This check needs to be done before prepare_handshake() due to an edge * case: if the client immediately requests renegotiation, this * finishes the current handshake first, avoiding the new ClientHello * being mistaken for an ancient message in the current handshake. */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl->handshake != NULL && ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER ) { if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE && ssl->in_msg[0] == MBEDTLS_SSL_HS_FINISHED ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "received retransmit of last flight" ) ); if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_resend", ret ); return( ret ); } return( MBEDTLS_ERR_SSL_WANT_READ ); } else { ssl_handshake_wrapup_free_hs_transform( ssl ); } } #endif return( 0 ); } int mbedtls_ssl_handle_message_type( mbedtls_ssl_context *ssl ) { int ret; /* * Handle particular types of records */ if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE ) { if( ( ret = mbedtls_ssl_prepare_handshake_record( ssl ) ) != 0 ) { return( ret ); } } if( ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "got an alert message, type: [%d:%d]", ssl->in_msg[0], ssl->in_msg[1] ) ); /* * Ignore non-fatal alerts, except close_notify and no_renegotiation */ if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_FATAL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "is a fatal alert message (msg %d)", ssl->in_msg[1] ) ); return( MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE ); } if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING && ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a close notify message" ) ); return( MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY ); } #if defined(MBEDTLS_SSL_RENEGOTIATION_ENABLED) if( ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING && ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a SSLv3 no_cert" ) ); /* Will be handled when trying to parse ServerHello */ return( 0 ); } #endif #if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_SRV_C) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 && ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING && ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_CERT ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "is a SSLv3 no_cert" ) ); /* Will be handled in mbedtls_ssl_parse_certificate() */ return( 0 ); } #endif /* MBEDTLS_SSL_PROTO_SSL3 && MBEDTLS_SSL_SRV_C */ /* Silently ignore: fetch new message */ return MBEDTLS_ERR_SSL_NON_FATAL; } return( 0 ); } int mbedtls_ssl_send_fatal_handshake_failure( mbedtls_ssl_context *ssl ) { int ret; if( ( ret = mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ) ) != 0 ) { return( ret ); } return( 0 ); } int mbedtls_ssl_send_alert_message( mbedtls_ssl_context *ssl, unsigned char level, unsigned char message ) { int ret; if( ssl == NULL || ssl->conf == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> send alert message" ) ); ssl->out_msgtype = MBEDTLS_SSL_MSG_ALERT; ssl->out_msglen = 2; ssl->out_msg[0] = level; ssl->out_msg[1] = message; if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= send alert message" ) ); return( 0 ); } /* * Handshake functions */ #if !defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) && \ !defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) && \ !defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) && \ !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) && \ !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) && \ !defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) && \ !defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) int mbedtls_ssl_write_certificate( mbedtls_ssl_context *ssl ) { const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate" ) ); if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) ); ssl->state++; return( 0 ); } MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl ) { const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) ); if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) ); ssl->state++; return( 0 ); } MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #else int mbedtls_ssl_write_certificate( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; size_t i, n; const mbedtls_x509_crt *crt; const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate" ) ); if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) ); ssl->state++; return( 0 ); } #if defined(MBEDTLS_SSL_CLI_C) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) { if( ssl->client_auth == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate" ) ); ssl->state++; return( 0 ); } #if defined(MBEDTLS_SSL_PROTO_SSL3) /* * If using SSLv3 and got no cert, send an Alert message * (otherwise an empty Certificate message will be sent). */ if( mbedtls_ssl_own_cert( ssl ) == NULL && ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) { ssl->out_msglen = 2; ssl->out_msgtype = MBEDTLS_SSL_MSG_ALERT; ssl->out_msg[0] = MBEDTLS_SSL_ALERT_LEVEL_WARNING; ssl->out_msg[1] = MBEDTLS_SSL_ALERT_MSG_NO_CERT; MBEDTLS_SSL_DEBUG_MSG( 2, ( "got no certificate to send" ) ); goto write_msg; } #endif /* MBEDTLS_SSL_PROTO_SSL3 */ } #endif /* MBEDTLS_SSL_CLI_C */ #if defined(MBEDTLS_SSL_SRV_C) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER ) { if( mbedtls_ssl_own_cert( ssl ) == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no certificate to send" ) ); return( MBEDTLS_ERR_SSL_CERTIFICATE_REQUIRED ); } } #endif MBEDTLS_SSL_DEBUG_CRT( 3, "own certificate", mbedtls_ssl_own_cert( ssl ) ); /* * 0 . 0 handshake type * 1 . 3 handshake length * 4 . 6 length of all certs * 7 . 9 length of cert. 1 * 10 . n-1 peer certificate * n . n+2 length of cert. 2 * n+3 . ... upper level cert, etc. */ i = 7; crt = mbedtls_ssl_own_cert( ssl ); while( crt != NULL ) { n = crt->raw.len; if( n > MBEDTLS_SSL_MAX_CONTENT_LEN - 3 - i ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "certificate too large, %d > %d", i + 3 + n, MBEDTLS_SSL_MAX_CONTENT_LEN ) ); return( MBEDTLS_ERR_SSL_CERTIFICATE_TOO_LARGE ); } ssl->out_msg[i ] = (unsigned char)( n >> 16 ); ssl->out_msg[i + 1] = (unsigned char)( n >> 8 ); ssl->out_msg[i + 2] = (unsigned char)( n ); i += 3; memcpy( ssl->out_msg + i, crt->raw.p, n ); i += n; crt = crt->next; } ssl->out_msg[4] = (unsigned char)( ( i - 7 ) >> 16 ); ssl->out_msg[5] = (unsigned char)( ( i - 7 ) >> 8 ); ssl->out_msg[6] = (unsigned char)( ( i - 7 ) ); ssl->out_msglen = i; ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_CERTIFICATE; #if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_CLI_C) write_msg: #endif ssl->state++; if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write certificate" ) ); return( ret ); } int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; size_t i, n; const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info; int authmode = ssl->conf->authmode; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) ); if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) ); ssl->state++; return( 0 ); } #if defined(MBEDTLS_SSL_SRV_C) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) ); ssl->state++; return( 0 ); } #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) if( ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET ) authmode = ssl->handshake->sni_authmode; #endif if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && authmode == MBEDTLS_SSL_VERIFY_NONE ) { ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_SKIP_VERIFY; MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) ); ssl->state++; return( 0 ); } #endif if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); return( ret ); } ssl->state++; #if defined(MBEDTLS_SSL_SRV_C) #if defined(MBEDTLS_SSL_PROTO_SSL3) /* * Check if the client sent an empty certificate */ if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) { if( ssl->in_msglen == 2 && ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT && ssl->in_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_WARNING && ssl->in_msg[1] == MBEDTLS_SSL_ALERT_MSG_NO_CERT ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "SSLv3 client has no certificate" ) ); ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_MISSING; if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL ) return( 0 ); else return( MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE ); } } #endif /* MBEDTLS_SSL_PROTO_SSL3 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0 ) { if( ssl->in_hslen == 3 + mbedtls_ssl_hs_hdr_len( ssl ) && ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE && ssl->in_msg[0] == MBEDTLS_SSL_HS_CERTIFICATE && memcmp( ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ), "\0\0\0", 3 ) == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "TLSv1 client has no certificate" ) ); ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_MISSING; if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL ) return( 0 ); else return( MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE ); } } #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \ MBEDTLS_SSL_PROTO_TLS1_2 */ #endif /* MBEDTLS_SSL_SRV_C */ if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } if( ssl->in_msg[0] != MBEDTLS_SSL_HS_CERTIFICATE || ssl->in_hslen < mbedtls_ssl_hs_hdr_len( ssl ) + 3 + 3 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ); } i = mbedtls_ssl_hs_hdr_len( ssl ); /* * Same message structure as in mbedtls_ssl_write_certificate() */ n = ( ssl->in_msg[i+1] << 8 ) | ssl->in_msg[i+2]; if( ssl->in_msg[i] != 0 || ssl->in_hslen != n + 3 + mbedtls_ssl_hs_hdr_len( ssl ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ); } /* In case we tried to reuse a session but it failed */ if( ssl->session_negotiate->peer_cert != NULL ) { mbedtls_x509_crt_free( ssl->session_negotiate->peer_cert ); mbedtls_free( ssl->session_negotiate->peer_cert ); } if( ( ssl->session_negotiate->peer_cert = mbedtls_calloc( 1, sizeof( mbedtls_x509_crt ) ) ) == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed", sizeof( mbedtls_x509_crt ) ) ); return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); } mbedtls_x509_crt_init( ssl->session_negotiate->peer_cert ); i += 3; while( i < ssl->in_hslen ) { if( ssl->in_msg[i] != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ); } n = ( (unsigned int) ssl->in_msg[i + 1] << 8 ) | (unsigned int) ssl->in_msg[i + 2]; i += 3; if( n < 128 || i + n > ssl->in_hslen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ); } ret = mbedtls_x509_crt_parse_der( ssl->session_negotiate->peer_cert, ssl->in_msg + i, n ); if( 0 != ret && ( MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG + MBEDTLS_ERR_OID_NOT_FOUND ) != ret ) { MBEDTLS_SSL_DEBUG_RET( 1, " mbedtls_x509_crt_parse_der", ret ); return( ret ); } i += n; } MBEDTLS_SSL_DEBUG_CRT( 3, "peer certificate", ssl->session_negotiate->peer_cert ); /* * On client, make sure the server cert doesn't change during renego to * avoid "triple handshake" attack: https://secure-resumption.com/ */ #if defined(MBEDTLS_SSL_RENEGOTIATION) && defined(MBEDTLS_SSL_CLI_C) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT && ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS ) { if( ssl->session->peer_cert == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "new server cert during renegotiation" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ); } if( ssl->session->peer_cert->raw.len != ssl->session_negotiate->peer_cert->raw.len || memcmp( ssl->session->peer_cert->raw.p, ssl->session_negotiate->peer_cert->raw.p, ssl->session->peer_cert->raw.len ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "server cert changed during renegotiation" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE ); } } #endif /* MBEDTLS_SSL_RENEGOTIATION && MBEDTLS_SSL_CLI_C */ if( authmode != MBEDTLS_SSL_VERIFY_NONE ) { mbedtls_x509_crt *ca_chain; mbedtls_x509_crl *ca_crl; #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) if( ssl->handshake->sni_ca_chain != NULL ) { ca_chain = ssl->handshake->sni_ca_chain; ca_crl = ssl->handshake->sni_ca_crl; } else #endif { ca_chain = ssl->conf->ca_chain; ca_crl = ssl->conf->ca_crl; } if( ca_chain == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no CA chain" ) ); return( MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED ); } /* * Main check: verify certificate */ ret = mbedtls_x509_crt_verify_with_profile( ssl->session_negotiate->peer_cert, ca_chain, ca_crl, ssl->conf->cert_profile, ssl->hostname, &ssl->session_negotiate->verify_result, ssl->conf->f_vrfy, ssl->conf->p_vrfy ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "x509_verify_cert", ret ); } /* * Secondary checks: always done, but change 'ret' only if it was 0 */ #if defined(MBEDTLS_ECP_C) { const mbedtls_pk_context *pk = &ssl->session_negotiate->peer_cert->pk; /* If certificate uses an EC key, make sure the curve is OK */ if( mbedtls_pk_can_do( pk, MBEDTLS_PK_ECKEY ) && mbedtls_ssl_check_curve( ssl, mbedtls_pk_ec( *pk )->grp.id ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate (EC key curve)" ) ); if( ret == 0 ) ret = MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE; } } #endif /* MBEDTLS_ECP_C */ if( mbedtls_ssl_check_cert_usage( ssl->session_negotiate->peer_cert, ciphersuite_info, ! ssl->conf->endpoint, &ssl->session_negotiate->verify_result ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate (usage extensions)" ) ); if( ret == 0 ) ret = MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE; } if( authmode == MBEDTLS_SSL_VERIFY_OPTIONAL ) ret = 0; } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate" ) ); return( ret ); } #endif /* !MBEDTLS_KEY_EXCHANGE_RSA_ENABLED !MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED !MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED !MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED !MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED !MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED !MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */ int mbedtls_ssl_write_change_cipher_spec( mbedtls_ssl_context *ssl ) { int ret; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write change cipher spec" ) ); ssl->out_msgtype = MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC; ssl->out_msglen = 1; ssl->out_msg[0] = 1; ssl->state++; if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write change cipher spec" ) ); return( 0 ); } int mbedtls_ssl_parse_change_cipher_spec( mbedtls_ssl_context *ssl ) { int ret; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse change cipher spec" ) ); if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); return( ret ); } if( ssl->in_msgtype != MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad change cipher spec message" ) ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } if( ssl->in_msglen != 1 || ssl->in_msg[0] != 1 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad change cipher spec message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CHANGE_CIPHER_SPEC ); } /* * Switch to our negotiated transform and session parameters for inbound * data. */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "switching to new transform spec for inbound data" ) ); ssl->transform_in = ssl->transform_negotiate; ssl->session_in = ssl->session_negotiate; #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) ssl_dtls_replay_reset( ssl ); #endif /* Increment epoch */ if( ++ssl->in_epoch == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS epoch would wrap" ) ); return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING ); } } else #endif /* MBEDTLS_SSL_PROTO_DTLS */ memset( ssl->in_ctr, 0, 8 ); /* * Set the in_msg pointer to the correct location based on IV length */ if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 ) { ssl->in_msg = ssl->in_iv + ssl->transform_negotiate->ivlen - ssl->transform_negotiate->fixed_ivlen; } else ssl->in_msg = ssl->in_iv; #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) if( mbedtls_ssl_hw_record_activate != NULL ) { if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_INBOUND ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret ); return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); } } #endif ssl->state++; MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse change cipher spec" ) ); return( 0 ); } void mbedtls_ssl_optimize_checksum( mbedtls_ssl_context *ssl, const mbedtls_ssl_ciphersuite_t *ciphersuite_info ) { ((void) ciphersuite_info); #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 ) ssl->handshake->update_checksum = ssl_update_checksum_md5sha1; else #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_SHA512_C) if( ciphersuite_info->mac == MBEDTLS_MD_SHA384 ) ssl->handshake->update_checksum = ssl_update_checksum_sha384; else #endif #if defined(MBEDTLS_SHA256_C) if( ciphersuite_info->mac != MBEDTLS_MD_SHA384 ) ssl->handshake->update_checksum = ssl_update_checksum_sha256; else #endif #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return; } } void mbedtls_ssl_reset_checksum( mbedtls_ssl_context *ssl ) { #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) mbedtls_md5_starts( &ssl->handshake->fin_md5 ); mbedtls_sha1_starts( &ssl->handshake->fin_sha1 ); #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_SHA256_C) mbedtls_sha256_starts( &ssl->handshake->fin_sha256, 0 ); #endif #if defined(MBEDTLS_SHA512_C) mbedtls_sha512_starts( &ssl->handshake->fin_sha512, 1 ); #endif #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ } static void ssl_update_checksum_start( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) mbedtls_md5_update( &ssl->handshake->fin_md5 , buf, len ); mbedtls_sha1_update( &ssl->handshake->fin_sha1, buf, len ); #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_SHA256_C) mbedtls_sha256_update( &ssl->handshake->fin_sha256, buf, len ); #endif #if defined(MBEDTLS_SHA512_C) mbedtls_sha512_update( &ssl->handshake->fin_sha512, buf, len ); #endif #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ } #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) static void ssl_update_checksum_md5sha1( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { mbedtls_md5_update( &ssl->handshake->fin_md5 , buf, len ); mbedtls_sha1_update( &ssl->handshake->fin_sha1, buf, len ); } #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_SHA256_C) static void ssl_update_checksum_sha256( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { mbedtls_sha256_update( &ssl->handshake->fin_sha256, buf, len ); } #endif #if defined(MBEDTLS_SHA512_C) static void ssl_update_checksum_sha384( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { mbedtls_sha512_update( &ssl->handshake->fin_sha512, buf, len ); } #endif #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ #if defined(MBEDTLS_SSL_PROTO_SSL3) static void ssl_calc_finished_ssl( mbedtls_ssl_context *ssl, unsigned char *buf, int from ) { const char *sender; mbedtls_md5_context md5; mbedtls_sha1_context sha1; unsigned char padbuf[48]; unsigned char md5sum[16]; unsigned char sha1sum[20]; mbedtls_ssl_session *session = ssl->session_negotiate; if( !session ) session = ssl->session; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc finished ssl" ) ); mbedtls_md5_init( &md5 ); mbedtls_sha1_init( &sha1 ); mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 ); mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 ); /* * SSLv3: * hash = * MD5( master + pad2 + * MD5( handshake + sender + master + pad1 ) ) * + SHA1( master + pad2 + * SHA1( handshake + sender + master + pad1 ) ) */ #if !defined(MBEDTLS_MD5_ALT) MBEDTLS_SSL_DEBUG_BUF( 4, "finished md5 state", (unsigned char *) md5.state, sizeof( md5.state ) ); #endif #if !defined(MBEDTLS_SHA1_ALT) MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *) sha1.state, sizeof( sha1.state ) ); #endif sender = ( from == MBEDTLS_SSL_IS_CLIENT ) ? "CLNT" : "SRVR"; memset( padbuf, 0x36, 48 ); mbedtls_md5_update( &md5, (const unsigned char *) sender, 4 ); mbedtls_md5_update( &md5, session->master, 48 ); mbedtls_md5_update( &md5, padbuf, 48 ); mbedtls_md5_finish( &md5, md5sum ); mbedtls_sha1_update( &sha1, (const unsigned char *) sender, 4 ); mbedtls_sha1_update( &sha1, session->master, 48 ); mbedtls_sha1_update( &sha1, padbuf, 40 ); mbedtls_sha1_finish( &sha1, sha1sum ); memset( padbuf, 0x5C, 48 ); mbedtls_md5_starts( &md5 ); mbedtls_md5_update( &md5, session->master, 48 ); mbedtls_md5_update( &md5, padbuf, 48 ); mbedtls_md5_update( &md5, md5sum, 16 ); mbedtls_md5_finish( &md5, buf ); mbedtls_sha1_starts( &sha1 ); mbedtls_sha1_update( &sha1, session->master, 48 ); mbedtls_sha1_update( &sha1, padbuf , 40 ); mbedtls_sha1_update( &sha1, sha1sum, 20 ); mbedtls_sha1_finish( &sha1, buf + 16 ); MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, 36 ); mbedtls_md5_free( &md5 ); mbedtls_sha1_free( &sha1 ); mbedtls_zeroize( padbuf, sizeof( padbuf ) ); mbedtls_zeroize( md5sum, sizeof( md5sum ) ); mbedtls_zeroize( sha1sum, sizeof( sha1sum ) ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) ); } #endif /* MBEDTLS_SSL_PROTO_SSL3 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) static void ssl_calc_finished_tls( mbedtls_ssl_context *ssl, unsigned char *buf, int from ) { int len = 12; const char *sender; mbedtls_md5_context md5; mbedtls_sha1_context sha1; unsigned char padbuf[36]; mbedtls_ssl_session *session = ssl->session_negotiate; if( !session ) session = ssl->session; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc finished tls" ) ); mbedtls_md5_init( &md5 ); mbedtls_sha1_init( &sha1 ); mbedtls_md5_clone( &md5, &ssl->handshake->fin_md5 ); mbedtls_sha1_clone( &sha1, &ssl->handshake->fin_sha1 ); /* * TLSv1: * hash = PRF( master, finished_label, * MD5( handshake ) + SHA1( handshake ) )[0..11] */ #if !defined(MBEDTLS_MD5_ALT) MBEDTLS_SSL_DEBUG_BUF( 4, "finished md5 state", (unsigned char *) md5.state, sizeof( md5.state ) ); #endif #if !defined(MBEDTLS_SHA1_ALT) MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha1 state", (unsigned char *) sha1.state, sizeof( sha1.state ) ); #endif sender = ( from == MBEDTLS_SSL_IS_CLIENT ) ? "client finished" : "server finished"; mbedtls_md5_finish( &md5, padbuf ); mbedtls_sha1_finish( &sha1, padbuf + 16 ); ssl->handshake->tls_prf( session->master, 48, sender, padbuf, 36, buf, len ); MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len ); mbedtls_md5_free( &md5 ); mbedtls_sha1_free( &sha1 ); mbedtls_zeroize( padbuf, sizeof( padbuf ) ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) ); } #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_SHA256_C) static void ssl_calc_finished_tls_sha256( mbedtls_ssl_context *ssl, unsigned char *buf, int from ) { int len = 12; const char *sender; mbedtls_sha256_context sha256; unsigned char padbuf[32]; mbedtls_ssl_session *session = ssl->session_negotiate; if( !session ) session = ssl->session; mbedtls_sha256_init( &sha256 ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc finished tls sha256" ) ); mbedtls_sha256_clone( &sha256, &ssl->handshake->fin_sha256 ); /* * TLSv1.2: * hash = PRF( master, finished_label, * Hash( handshake ) )[0.11] */ #if !defined(MBEDTLS_SHA256_ALT) MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha2 state", (unsigned char *) sha256.state, sizeof( sha256.state ) ); #endif sender = ( from == MBEDTLS_SSL_IS_CLIENT ) ? "client finished" : "server finished"; mbedtls_sha256_finish( &sha256, padbuf ); ssl->handshake->tls_prf( session->master, 48, sender, padbuf, 32, buf, len ); MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len ); mbedtls_sha256_free( &sha256 ); mbedtls_zeroize( padbuf, sizeof( padbuf ) ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) ); } #endif /* MBEDTLS_SHA256_C */ #if defined(MBEDTLS_SHA512_C) static void ssl_calc_finished_tls_sha384( mbedtls_ssl_context *ssl, unsigned char *buf, int from ) { int len = 12; const char *sender; mbedtls_sha512_context sha512; unsigned char padbuf[48]; mbedtls_ssl_session *session = ssl->session_negotiate; if( !session ) session = ssl->session; mbedtls_sha512_init( &sha512 ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> calc finished tls sha384" ) ); mbedtls_sha512_clone( &sha512, &ssl->handshake->fin_sha512 ); /* * TLSv1.2: * hash = PRF( master, finished_label, * Hash( handshake ) )[0.11] */ #if !defined(MBEDTLS_SHA512_ALT) MBEDTLS_SSL_DEBUG_BUF( 4, "finished sha512 state", (unsigned char *) sha512.state, sizeof( sha512.state ) ); #endif sender = ( from == MBEDTLS_SSL_IS_CLIENT ) ? "client finished" : "server finished"; mbedtls_sha512_finish( &sha512, padbuf ); ssl->handshake->tls_prf( session->master, 48, sender, padbuf, 48, buf, len ); MBEDTLS_SSL_DEBUG_BUF( 3, "calc finished result", buf, len ); mbedtls_sha512_free( &sha512 ); mbedtls_zeroize( padbuf, sizeof( padbuf ) ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= calc finished" ) ); } #endif /* MBEDTLS_SHA512_C */ #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ static void ssl_handshake_wrapup_free_hs_transform( mbedtls_ssl_context *ssl ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "=> handshake wrapup: final free" ) ); /* * Free our handshake params */ mbedtls_ssl_handshake_free( ssl->handshake ); mbedtls_free( ssl->handshake ); ssl->handshake = NULL; /* * Free the previous transform and swith in the current one */ if( ssl->transform ) { mbedtls_ssl_transform_free( ssl->transform ); mbedtls_free( ssl->transform ); } ssl->transform = ssl->transform_negotiate; ssl->transform_negotiate = NULL; MBEDTLS_SSL_DEBUG_MSG( 3, ( "<= handshake wrapup: final free" ) ); } void mbedtls_ssl_handshake_wrapup( mbedtls_ssl_context *ssl ) { int resume = ssl->handshake->resume; MBEDTLS_SSL_DEBUG_MSG( 3, ( "=> handshake wrapup" ) ); #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS ) { ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_DONE; ssl->renego_records_seen = 0; } #endif /* * Free the previous session and switch in the current one */ if( ssl->session ) { #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) /* RFC 7366 3.1: keep the EtM state */ ssl->session_negotiate->encrypt_then_mac = ssl->session->encrypt_then_mac; #endif mbedtls_ssl_session_free( ssl->session ); mbedtls_free( ssl->session ); } ssl->session = ssl->session_negotiate; ssl->session_negotiate = NULL; /* * Add cache entry */ if( ssl->conf->f_set_cache != NULL && ssl->session->id_len != 0 && resume == 0 ) { if( ssl->conf->f_set_cache( ssl->conf->p_cache, ssl->session ) != 0 ) MBEDTLS_SSL_DEBUG_MSG( 1, ( "cache did not store session" ) ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl->handshake->flight != NULL ) { /* Cancel handshake timer */ ssl_set_timer( ssl, 0 ); /* Keep last flight around in case we need to resend it: * we need the handshake and transform structures for that */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip freeing handshake and transform" ) ); } else #endif ssl_handshake_wrapup_free_hs_transform( ssl ); ssl->state++; MBEDTLS_SSL_DEBUG_MSG( 3, ( "<= handshake wrapup" ) ); } int mbedtls_ssl_write_finished( mbedtls_ssl_context *ssl ) { int ret, hash_len; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write finished" ) ); /* * Set the out_msg pointer to the correct location based on IV length */ if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 ) { ssl->out_msg = ssl->out_iv + ssl->transform_negotiate->ivlen - ssl->transform_negotiate->fixed_ivlen; } else ssl->out_msg = ssl->out_iv; ssl->handshake->calc_finished( ssl, ssl->out_msg + 4, ssl->conf->endpoint ); /* * RFC 5246 7.4.9 (Page 63) says 12 is the default length and ciphersuites * may define some other value. Currently (early 2016), no defined * ciphersuite does this (and this is unlikely to change as activity has * moved to TLS 1.3 now) so we can keep the hardcoded 12 here. */ hash_len = ( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) ? 36 : 12; #if defined(MBEDTLS_SSL_RENEGOTIATION) ssl->verify_data_len = hash_len; memcpy( ssl->own_verify_data, ssl->out_msg + 4, hash_len ); #endif ssl->out_msglen = 4 + hash_len; ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_FINISHED; /* * In case of session resuming, invert the client and server * ChangeCipherSpec messages order. */ if( ssl->handshake->resume != 0 ) { #if defined(MBEDTLS_SSL_CLI_C) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP; #endif #if defined(MBEDTLS_SSL_SRV_C) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER ) ssl->state = MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC; #endif } else ssl->state++; /* * Switch to our negotiated transform and session parameters for outbound * data. */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "switching to new transform spec for outbound data" ) ); #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { unsigned char i; /* Remember current epoch settings for resending */ ssl->handshake->alt_transform_out = ssl->transform_out; memcpy( ssl->handshake->alt_out_ctr, ssl->out_ctr, 8 ); /* Set sequence_number to zero */ memset( ssl->out_ctr + 2, 0, 6 ); /* Increment epoch */ for( i = 2; i > 0; i-- ) if( ++ssl->out_ctr[i - 1] != 0 ) break; /* The loop goes to its end iff the counter is wrapping */ if( i == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "DTLS epoch would wrap" ) ); return( MBEDTLS_ERR_SSL_COUNTER_WRAPPING ); } } else #endif /* MBEDTLS_SSL_PROTO_DTLS */ memset( ssl->out_ctr, 0, 8 ); ssl->transform_out = ssl->transform_negotiate; ssl->session_out = ssl->session_negotiate; #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) if( mbedtls_ssl_hw_record_activate != NULL ) { if( ( ret = mbedtls_ssl_hw_record_activate( ssl, MBEDTLS_SSL_CHANNEL_OUTBOUND ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_activate", ret ); return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); } } #endif #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) mbedtls_ssl_send_flight_completed( ssl ); #endif if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write finished" ) ); return( 0 ); } #if defined(MBEDTLS_SSL_PROTO_SSL3) #define SSL_MAX_HASH_LEN 36 #else #define SSL_MAX_HASH_LEN 12 #endif int mbedtls_ssl_parse_finished( mbedtls_ssl_context *ssl ) { int ret; unsigned int hash_len; unsigned char buf[SSL_MAX_HASH_LEN]; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse finished" ) ); ssl->handshake->calc_finished( ssl, buf, ssl->conf->endpoint ^ 1 ); if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); return( ret ); } if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } /* There is currently no ciphersuite using another length with TLS 1.2 */ #if defined(MBEDTLS_SSL_PROTO_SSL3) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) hash_len = 36; else #endif hash_len = 12; if( ssl->in_msg[0] != MBEDTLS_SSL_HS_FINISHED || ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) + hash_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_FINISHED ); } if( mbedtls_ssl_safer_memcmp( ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ), buf, hash_len ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad finished message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_FINISHED ); } #if defined(MBEDTLS_SSL_RENEGOTIATION) ssl->verify_data_len = hash_len; memcpy( ssl->peer_verify_data, buf, hash_len ); #endif if( ssl->handshake->resume != 0 ) { #if defined(MBEDTLS_SSL_CLI_C) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) ssl->state = MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC; #endif #if defined(MBEDTLS_SSL_SRV_C) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER ) ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP; #endif } else ssl->state++; #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) mbedtls_ssl_recv_flight_completed( ssl ); #endif MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse finished" ) ); return( 0 ); } static void ssl_handshake_params_init( mbedtls_ssl_handshake_params *handshake ) { memset( handshake, 0, sizeof( mbedtls_ssl_handshake_params ) ); #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) mbedtls_md5_init( &handshake->fin_md5 ); mbedtls_sha1_init( &handshake->fin_sha1 ); mbedtls_md5_starts( &handshake->fin_md5 ); mbedtls_sha1_starts( &handshake->fin_sha1 ); #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_SHA256_C) mbedtls_sha256_init( &handshake->fin_sha256 ); mbedtls_sha256_starts( &handshake->fin_sha256, 0 ); #endif #if defined(MBEDTLS_SHA512_C) mbedtls_sha512_init( &handshake->fin_sha512 ); mbedtls_sha512_starts( &handshake->fin_sha512, 1 ); #endif #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ handshake->update_checksum = ssl_update_checksum_start; handshake->sig_alg = MBEDTLS_SSL_HASH_SHA1; #if defined(MBEDTLS_DHM_C) mbedtls_dhm_init( &handshake->dhm_ctx ); #endif #if defined(MBEDTLS_ECDH_C) mbedtls_ecdh_init( &handshake->ecdh_ctx ); #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) mbedtls_ecjpake_init( &handshake->ecjpake_ctx ); #if defined(MBEDTLS_SSL_CLI_C) handshake->ecjpake_cache = NULL; handshake->ecjpake_cache_len = 0; #endif #endif #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) handshake->sni_authmode = MBEDTLS_SSL_VERIFY_UNSET; #endif } static void ssl_transform_init( mbedtls_ssl_transform *transform ) { memset( transform, 0, sizeof(mbedtls_ssl_transform) ); mbedtls_cipher_init( &transform->cipher_ctx_enc ); mbedtls_cipher_init( &transform->cipher_ctx_dec ); mbedtls_md_init( &transform->md_ctx_enc ); mbedtls_md_init( &transform->md_ctx_dec ); } void mbedtls_ssl_session_init( mbedtls_ssl_session *session ) { memset( session, 0, sizeof(mbedtls_ssl_session) ); } static int ssl_handshake_init( mbedtls_ssl_context *ssl ) { /* Clear old handshake information if present */ if( ssl->transform_negotiate ) mbedtls_ssl_transform_free( ssl->transform_negotiate ); if( ssl->session_negotiate ) mbedtls_ssl_session_free( ssl->session_negotiate ); if( ssl->handshake ) mbedtls_ssl_handshake_free( ssl->handshake ); /* * Either the pointers are now NULL or cleared properly and can be freed. * Now allocate missing structures. */ if( ssl->transform_negotiate == NULL ) { ssl->transform_negotiate = mbedtls_calloc( 1, sizeof(mbedtls_ssl_transform) ); } if( ssl->session_negotiate == NULL ) { ssl->session_negotiate = mbedtls_calloc( 1, sizeof(mbedtls_ssl_session) ); } if( ssl->handshake == NULL ) { ssl->handshake = mbedtls_calloc( 1, sizeof(mbedtls_ssl_handshake_params) ); } /* All pointers should exist and can be directly freed without issue */ if( ssl->handshake == NULL || ssl->transform_negotiate == NULL || ssl->session_negotiate == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc() of ssl sub-contexts failed" ) ); mbedtls_free( ssl->handshake ); mbedtls_free( ssl->transform_negotiate ); mbedtls_free( ssl->session_negotiate ); ssl->handshake = NULL; ssl->transform_negotiate = NULL; ssl->session_negotiate = NULL; return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); } /* Initialize structures */ mbedtls_ssl_session_init( ssl->session_negotiate ); ssl_transform_init( ssl->transform_negotiate ); ssl_handshake_params_init( ssl->handshake ); #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { ssl->handshake->alt_transform_out = ssl->transform_out; if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING; else ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING; ssl_set_timer( ssl, 0 ); } #endif return( 0 ); } #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C) /* Dummy cookie callbacks for defaults */ static int ssl_cookie_write_dummy( void *ctx, unsigned char **p, unsigned char *end, const unsigned char *cli_id, size_t cli_id_len ) { ((void) ctx); ((void) p); ((void) end); ((void) cli_id); ((void) cli_id_len); return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); } static int ssl_cookie_check_dummy( void *ctx, const unsigned char *cookie, size_t cookie_len, const unsigned char *cli_id, size_t cli_id_len ) { ((void) ctx); ((void) cookie); ((void) cookie_len); ((void) cli_id); ((void) cli_id_len); return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); } #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY && MBEDTLS_SSL_SRV_C */ /* * Initialize an SSL context */ void mbedtls_ssl_init( mbedtls_ssl_context *ssl ) { memset( ssl, 0, sizeof( mbedtls_ssl_context ) ); } /* * Setup an SSL context */ int mbedtls_ssl_setup( mbedtls_ssl_context *ssl, const mbedtls_ssl_config *conf ) { int ret; const size_t len = MBEDTLS_SSL_BUFFER_LEN; ssl->conf = conf; /* * Prepare base structures */ if( ( ssl-> in_buf = mbedtls_calloc( 1, len ) ) == NULL || ( ssl->out_buf = mbedtls_calloc( 1, len ) ) == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed", len ) ); mbedtls_free( ssl->in_buf ); ssl->in_buf = NULL; return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { ssl->out_hdr = ssl->out_buf; ssl->out_ctr = ssl->out_buf + 3; ssl->out_len = ssl->out_buf + 11; ssl->out_iv = ssl->out_buf + 13; ssl->out_msg = ssl->out_buf + 13; ssl->in_hdr = ssl->in_buf; ssl->in_ctr = ssl->in_buf + 3; ssl->in_len = ssl->in_buf + 11; ssl->in_iv = ssl->in_buf + 13; ssl->in_msg = ssl->in_buf + 13; } else #endif { ssl->out_ctr = ssl->out_buf; ssl->out_hdr = ssl->out_buf + 8; ssl->out_len = ssl->out_buf + 11; ssl->out_iv = ssl->out_buf + 13; ssl->out_msg = ssl->out_buf + 13; ssl->in_ctr = ssl->in_buf; ssl->in_hdr = ssl->in_buf + 8; ssl->in_len = ssl->in_buf + 11; ssl->in_iv = ssl->in_buf + 13; ssl->in_msg = ssl->in_buf + 13; } if( ( ret = ssl_handshake_init( ssl ) ) != 0 ) return( ret ); return( 0 ); } /* * Reset an initialized and used SSL context for re-use while retaining * all application-set variables, function pointers and data. * * If partial is non-zero, keep data in the input buffer and client ID. * (Use when a DTLS client reconnects from the same port.) */ static int ssl_session_reset_int( mbedtls_ssl_context *ssl, int partial ) { int ret; ssl->state = MBEDTLS_SSL_HELLO_REQUEST; /* Cancel any possibly running timer */ ssl_set_timer( ssl, 0 ); #if defined(MBEDTLS_SSL_RENEGOTIATION) ssl->renego_status = MBEDTLS_SSL_INITIAL_HANDSHAKE; ssl->renego_records_seen = 0; ssl->verify_data_len = 0; memset( ssl->own_verify_data, 0, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN ); memset( ssl->peer_verify_data, 0, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN ); #endif ssl->secure_renegotiation = MBEDTLS_SSL_LEGACY_RENEGOTIATION; ssl->in_offt = NULL; ssl->in_msg = ssl->in_buf + 13; ssl->in_msgtype = 0; ssl->in_msglen = 0; if( partial == 0 ) ssl->in_left = 0; #if defined(MBEDTLS_SSL_PROTO_DTLS) ssl->next_record_offset = 0; ssl->in_epoch = 0; #endif #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) ssl_dtls_replay_reset( ssl ); #endif ssl->in_hslen = 0; ssl->nb_zero = 0; ssl->record_read = 0; ssl->out_msg = ssl->out_buf + 13; ssl->out_msgtype = 0; ssl->out_msglen = 0; ssl->out_left = 0; #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING) if( ssl->split_done != MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED ) ssl->split_done = 0; #endif ssl->transform_in = NULL; ssl->transform_out = NULL; memset( ssl->out_buf, 0, MBEDTLS_SSL_BUFFER_LEN ); if( partial == 0 ) memset( ssl->in_buf, 0, MBEDTLS_SSL_BUFFER_LEN ); #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) if( mbedtls_ssl_hw_record_reset != NULL ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_reset()" ) ); if( ( ret = mbedtls_ssl_hw_record_reset( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_reset", ret ); return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED ); } } #endif if( ssl->transform ) { mbedtls_ssl_transform_free( ssl->transform ); mbedtls_free( ssl->transform ); ssl->transform = NULL; } if( ssl->session ) { mbedtls_ssl_session_free( ssl->session ); mbedtls_free( ssl->session ); ssl->session = NULL; } #if defined(MBEDTLS_SSL_ALPN) ssl->alpn_chosen = NULL; #endif #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C) if( partial == 0 ) { mbedtls_free( ssl->cli_id ); ssl->cli_id = NULL; ssl->cli_id_len = 0; } #endif if( ( ret = ssl_handshake_init( ssl ) ) != 0 ) return( ret ); return( 0 ); } /* * Reset an initialized and used SSL context for re-use while retaining * all application-set variables, function pointers and data. */ int mbedtls_ssl_session_reset( mbedtls_ssl_context *ssl ) { return( ssl_session_reset_int( ssl, 0 ) ); } /* * SSL set accessors */ void mbedtls_ssl_conf_endpoint( mbedtls_ssl_config *conf, int endpoint ) { conf->endpoint = endpoint; } void mbedtls_ssl_conf_transport( mbedtls_ssl_config *conf, int transport ) { conf->transport = transport; } #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) void mbedtls_ssl_conf_dtls_anti_replay( mbedtls_ssl_config *conf, char mode ) { conf->anti_replay = mode; } #endif #if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT) void mbedtls_ssl_conf_dtls_badmac_limit( mbedtls_ssl_config *conf, unsigned limit ) { conf->badmac_limit = limit; } #endif #if defined(MBEDTLS_SSL_PROTO_DTLS) void mbedtls_ssl_conf_handshake_timeout( mbedtls_ssl_config *conf, uint32_t min, uint32_t max ) { conf->hs_timeout_min = min; conf->hs_timeout_max = max; } #endif void mbedtls_ssl_conf_authmode( mbedtls_ssl_config *conf, int authmode ) { conf->authmode = authmode; } #if defined(MBEDTLS_X509_CRT_PARSE_C) void mbedtls_ssl_conf_verify( mbedtls_ssl_config *conf, int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), void *p_vrfy ) { conf->f_vrfy = f_vrfy; conf->p_vrfy = p_vrfy; } #endif /* MBEDTLS_X509_CRT_PARSE_C */ void mbedtls_ssl_conf_rng( mbedtls_ssl_config *conf, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { conf->f_rng = f_rng; conf->p_rng = p_rng; } void mbedtls_ssl_conf_dbg( mbedtls_ssl_config *conf, void (*f_dbg)(void *, int, const char *, int, const char *), void *p_dbg ) { conf->f_dbg = f_dbg; conf->p_dbg = p_dbg; } void mbedtls_ssl_set_bio( mbedtls_ssl_context *ssl, void *p_bio, mbedtls_ssl_send_t *f_send, mbedtls_ssl_recv_t *f_recv, mbedtls_ssl_recv_timeout_t *f_recv_timeout ) { ssl->p_bio = p_bio; ssl->f_send = f_send; ssl->f_recv = f_recv; ssl->f_recv_timeout = f_recv_timeout; } void mbedtls_ssl_conf_read_timeout( mbedtls_ssl_config *conf, uint32_t timeout ) { conf->read_timeout = timeout; } void mbedtls_ssl_set_timer_cb( mbedtls_ssl_context *ssl, void *p_timer, mbedtls_ssl_set_timer_t *f_set_timer, mbedtls_ssl_get_timer_t *f_get_timer ) { ssl->p_timer = p_timer; ssl->f_set_timer = f_set_timer; ssl->f_get_timer = f_get_timer; /* Make sure we start with no timer running */ ssl_set_timer( ssl, 0 ); } #if defined(MBEDTLS_SSL_SRV_C) void mbedtls_ssl_conf_session_cache( mbedtls_ssl_config *conf, void *p_cache, int (*f_get_cache)(void *, mbedtls_ssl_session *), int (*f_set_cache)(void *, const mbedtls_ssl_session *) ) { conf->p_cache = p_cache; conf->f_get_cache = f_get_cache; conf->f_set_cache = f_set_cache; } #endif /* MBEDTLS_SSL_SRV_C */ #if defined(MBEDTLS_SSL_CLI_C) int mbedtls_ssl_set_session( mbedtls_ssl_context *ssl, const mbedtls_ssl_session *session ) { int ret; if( ssl == NULL || session == NULL || ssl->session_negotiate == NULL || ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT ) { return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } if( ( ret = ssl_session_copy( ssl->session_negotiate, session ) ) != 0 ) return( ret ); ssl->handshake->resume = 1; return( 0 ); } #endif /* MBEDTLS_SSL_CLI_C */ void mbedtls_ssl_conf_ciphersuites( mbedtls_ssl_config *conf, const int *ciphersuites ) { conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] = ciphersuites; conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] = ciphersuites; conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] = ciphersuites; conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] = ciphersuites; } void mbedtls_ssl_conf_ciphersuites_for_version( mbedtls_ssl_config *conf, const int *ciphersuites, int major, int minor ) { if( major != MBEDTLS_SSL_MAJOR_VERSION_3 ) return; if( minor < MBEDTLS_SSL_MINOR_VERSION_0 || minor > MBEDTLS_SSL_MINOR_VERSION_3 ) return; conf->ciphersuite_list[minor] = ciphersuites; } #if defined(MBEDTLS_X509_CRT_PARSE_C) void mbedtls_ssl_conf_cert_profile( mbedtls_ssl_config *conf, const mbedtls_x509_crt_profile *profile ) { conf->cert_profile = profile; } /* Append a new keycert entry to a (possibly empty) list */ static int ssl_append_key_cert( mbedtls_ssl_key_cert **head, mbedtls_x509_crt *cert, mbedtls_pk_context *key ) { mbedtls_ssl_key_cert *new; new = mbedtls_calloc( 1, sizeof( mbedtls_ssl_key_cert ) ); if( new == NULL ) return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); new->cert = cert; new->key = key; new->next = NULL; /* Update head is the list was null, else add to the end */ if( *head == NULL ) { *head = new; } else { mbedtls_ssl_key_cert *cur = *head; while( cur->next != NULL ) cur = cur->next; cur->next = new; } return( 0 ); } int mbedtls_ssl_conf_own_cert( mbedtls_ssl_config *conf, mbedtls_x509_crt *own_cert, mbedtls_pk_context *pk_key ) { return( ssl_append_key_cert( &conf->key_cert, own_cert, pk_key ) ); } void mbedtls_ssl_conf_ca_chain( mbedtls_ssl_config *conf, mbedtls_x509_crt *ca_chain, mbedtls_x509_crl *ca_crl ) { conf->ca_chain = ca_chain; conf->ca_crl = ca_crl; } #endif /* MBEDTLS_X509_CRT_PARSE_C */ #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) int mbedtls_ssl_set_hs_own_cert( mbedtls_ssl_context *ssl, mbedtls_x509_crt *own_cert, mbedtls_pk_context *pk_key ) { return( ssl_append_key_cert( &ssl->handshake->sni_key_cert, own_cert, pk_key ) ); } void mbedtls_ssl_set_hs_ca_chain( mbedtls_ssl_context *ssl, mbedtls_x509_crt *ca_chain, mbedtls_x509_crl *ca_crl ) { ssl->handshake->sni_ca_chain = ca_chain; ssl->handshake->sni_ca_crl = ca_crl; } void mbedtls_ssl_set_hs_authmode( mbedtls_ssl_context *ssl, int authmode ) { ssl->handshake->sni_authmode = authmode; } #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) /* * Set EC J-PAKE password for current handshake */ int mbedtls_ssl_set_hs_ecjpake_password( mbedtls_ssl_context *ssl, const unsigned char *pw, size_t pw_len ) { mbedtls_ecjpake_role role; if( ssl->handshake == NULL || ssl->conf == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER ) role = MBEDTLS_ECJPAKE_SERVER; else role = MBEDTLS_ECJPAKE_CLIENT; return( mbedtls_ecjpake_setup( &ssl->handshake->ecjpake_ctx, role, MBEDTLS_MD_SHA256, MBEDTLS_ECP_DP_SECP256R1, pw, pw_len ) ); } #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) int mbedtls_ssl_conf_psk( mbedtls_ssl_config *conf, const unsigned char *psk, size_t psk_len, const unsigned char *psk_identity, size_t psk_identity_len ) { if( psk == NULL || psk_identity == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); if( psk_len > MBEDTLS_PSK_MAX_LEN ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); /* Identity len will be encoded on two bytes */ if( ( psk_identity_len >> 16 ) != 0 || psk_identity_len > MBEDTLS_SSL_MAX_CONTENT_LEN ) { return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } if( conf->psk != NULL || conf->psk_identity != NULL ) { mbedtls_free( conf->psk ); mbedtls_free( conf->psk_identity ); conf->psk = NULL; conf->psk_identity = NULL; } if( ( conf->psk = mbedtls_calloc( 1, psk_len ) ) == NULL || ( conf->psk_identity = mbedtls_calloc( 1, psk_identity_len ) ) == NULL ) { mbedtls_free( conf->psk ); mbedtls_free( conf->psk_identity ); conf->psk = NULL; conf->psk_identity = NULL; return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); } conf->psk_len = psk_len; conf->psk_identity_len = psk_identity_len; memcpy( conf->psk, psk, conf->psk_len ); memcpy( conf->psk_identity, psk_identity, conf->psk_identity_len ); return( 0 ); } int mbedtls_ssl_set_hs_psk( mbedtls_ssl_context *ssl, const unsigned char *psk, size_t psk_len ) { if( psk == NULL || ssl->handshake == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); if( psk_len > MBEDTLS_PSK_MAX_LEN ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); if( ssl->handshake->psk != NULL ) mbedtls_free( ssl->handshake->psk ); if( ( ssl->handshake->psk = mbedtls_calloc( 1, psk_len ) ) == NULL ) return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); ssl->handshake->psk_len = psk_len; memcpy( ssl->handshake->psk, psk, ssl->handshake->psk_len ); return( 0 ); } void mbedtls_ssl_conf_psk_cb( mbedtls_ssl_config *conf, int (*f_psk)(void *, mbedtls_ssl_context *, const unsigned char *, size_t), void *p_psk ) { conf->f_psk = f_psk; conf->p_psk = p_psk; } #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */ #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C) int mbedtls_ssl_conf_dh_param( mbedtls_ssl_config *conf, const char *dhm_P, const char *dhm_G ) { int ret; if( ( ret = mbedtls_mpi_read_string( &conf->dhm_P, 16, dhm_P ) ) != 0 || ( ret = mbedtls_mpi_read_string( &conf->dhm_G, 16, dhm_G ) ) != 0 ) { mbedtls_mpi_free( &conf->dhm_P ); mbedtls_mpi_free( &conf->dhm_G ); return( ret ); } return( 0 ); } int mbedtls_ssl_conf_dh_param_ctx( mbedtls_ssl_config *conf, mbedtls_dhm_context *dhm_ctx ) { int ret; if( ( ret = mbedtls_mpi_copy( &conf->dhm_P, &dhm_ctx->P ) ) != 0 || ( ret = mbedtls_mpi_copy( &conf->dhm_G, &dhm_ctx->G ) ) != 0 ) { mbedtls_mpi_free( &conf->dhm_P ); mbedtls_mpi_free( &conf->dhm_G ); return( ret ); } return( 0 ); } #endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_SRV_C */ #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C) /* * Set the minimum length for Diffie-Hellman parameters */ void mbedtls_ssl_conf_dhm_min_bitlen( mbedtls_ssl_config *conf, unsigned int bitlen ) { conf->dhm_min_bitlen = bitlen; } #endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_CLI_C */ #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED) /* * Set allowed/preferred hashes for handshake signatures */ void mbedtls_ssl_conf_sig_hashes( mbedtls_ssl_config *conf, const int *hashes ) { conf->sig_hashes = hashes; } #endif #if defined(MBEDTLS_ECP_C) /* * Set the allowed elliptic curves */ void mbedtls_ssl_conf_curves( mbedtls_ssl_config *conf, const mbedtls_ecp_group_id *curve_list ) { conf->curve_list = curve_list; } #endif #if defined(MBEDTLS_X509_CRT_PARSE_C) int mbedtls_ssl_set_hostname( mbedtls_ssl_context *ssl, const char *hostname ) { size_t hostname_len; if( hostname == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); hostname_len = strlen( hostname ); if( hostname_len + 1 == 0 ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); if( hostname_len > MBEDTLS_SSL_MAX_HOST_NAME_LEN ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); ssl->hostname = mbedtls_calloc( 1, hostname_len + 1 ); if( ssl->hostname == NULL ) return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); memcpy( ssl->hostname, hostname, hostname_len ); ssl->hostname[hostname_len] = '\0'; return( 0 ); } #endif #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) void mbedtls_ssl_conf_sni( mbedtls_ssl_config *conf, int (*f_sni)(void *, mbedtls_ssl_context *, const unsigned char *, size_t), void *p_sni ) { conf->f_sni = f_sni; conf->p_sni = p_sni; } #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */ #if defined(MBEDTLS_SSL_ALPN) int mbedtls_ssl_conf_alpn_protocols( mbedtls_ssl_config *conf, const char **protos ) { size_t cur_len, tot_len; const char **p; /* * RFC 7301 3.1: "Empty strings MUST NOT be included and byte strings * MUST NOT be truncated." * We check lengths now rather than later. */ tot_len = 0; for( p = protos; *p != NULL; p++ ) { cur_len = strlen( *p ); tot_len += cur_len; if( cur_len == 0 || cur_len > 255 || tot_len > 65535 ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } conf->alpn_list = protos; return( 0 ); } const char *mbedtls_ssl_get_alpn_protocol( const mbedtls_ssl_context *ssl ) { return( ssl->alpn_chosen ); } #endif /* MBEDTLS_SSL_ALPN */ void mbedtls_ssl_conf_max_version( mbedtls_ssl_config *conf, int major, int minor ) { conf->max_major_ver = major; conf->max_minor_ver = minor; } void mbedtls_ssl_conf_min_version( mbedtls_ssl_config *conf, int major, int minor ) { conf->min_major_ver = major; conf->min_minor_ver = minor; } #if defined(MBEDTLS_SSL_FALLBACK_SCSV) && defined(MBEDTLS_SSL_CLI_C) void mbedtls_ssl_conf_fallback( mbedtls_ssl_config *conf, char fallback ) { conf->fallback = fallback; } #endif #if defined(MBEDTLS_SSL_SRV_C) void mbedtls_ssl_conf_cert_req_ca_list( mbedtls_ssl_config *conf, char cert_req_ca_list ) { conf->cert_req_ca_list = cert_req_ca_list; } #endif #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) void mbedtls_ssl_conf_encrypt_then_mac( mbedtls_ssl_config *conf, char etm ) { conf->encrypt_then_mac = etm; } #endif #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) void mbedtls_ssl_conf_extended_master_secret( mbedtls_ssl_config *conf, char ems ) { conf->extended_ms = ems; } #endif #if defined(MBEDTLS_ARC4_C) void mbedtls_ssl_conf_arc4_support( mbedtls_ssl_config *conf, char arc4 ) { conf->arc4_disabled = arc4; } #endif #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) int mbedtls_ssl_conf_max_frag_len( mbedtls_ssl_config *conf, unsigned char mfl_code ) { if( mfl_code >= MBEDTLS_SSL_MAX_FRAG_LEN_INVALID || mfl_code_to_length[mfl_code] > MBEDTLS_SSL_MAX_CONTENT_LEN ) { return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } conf->mfl_code = mfl_code; return( 0 ); } #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ #if defined(MBEDTLS_SSL_TRUNCATED_HMAC) void mbedtls_ssl_conf_truncated_hmac( mbedtls_ssl_config *conf, int truncate ) { conf->trunc_hmac = truncate; } #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */ #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING) void mbedtls_ssl_conf_cbc_record_splitting( mbedtls_ssl_config *conf, char split ) { conf->cbc_record_splitting = split; } #endif void mbedtls_ssl_conf_legacy_renegotiation( mbedtls_ssl_config *conf, int allow_legacy ) { conf->allow_legacy_renegotiation = allow_legacy; } #if defined(MBEDTLS_SSL_RENEGOTIATION) void mbedtls_ssl_conf_renegotiation( mbedtls_ssl_config *conf, int renegotiation ) { conf->disable_renegotiation = renegotiation; } void mbedtls_ssl_conf_renegotiation_enforced( mbedtls_ssl_config *conf, int max_records ) { conf->renego_max_records = max_records; } void mbedtls_ssl_conf_renegotiation_period( mbedtls_ssl_config *conf, const unsigned char period[8] ) { memcpy( conf->renego_period, period, 8 ); } #endif /* MBEDTLS_SSL_RENEGOTIATION */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) #if defined(MBEDTLS_SSL_CLI_C) void mbedtls_ssl_conf_session_tickets( mbedtls_ssl_config *conf, int use_tickets ) { conf->session_tickets = use_tickets; } #endif #if defined(MBEDTLS_SSL_SRV_C) void mbedtls_ssl_conf_session_tickets_cb( mbedtls_ssl_config *conf, mbedtls_ssl_ticket_write_t *f_ticket_write, mbedtls_ssl_ticket_parse_t *f_ticket_parse, void *p_ticket ) { conf->f_ticket_write = f_ticket_write; conf->f_ticket_parse = f_ticket_parse; conf->p_ticket = p_ticket; } #endif #endif /* MBEDTLS_SSL_SESSION_TICKETS */ #if defined(MBEDTLS_SSL_EXPORT_KEYS) void mbedtls_ssl_conf_export_keys_cb( mbedtls_ssl_config *conf, mbedtls_ssl_export_keys_t *f_export_keys, void *p_export_keys ) { conf->f_export_keys = f_export_keys; conf->p_export_keys = p_export_keys; } #endif /* * SSL get accessors */ size_t mbedtls_ssl_get_bytes_avail( const mbedtls_ssl_context *ssl ) { return( ssl->in_offt == NULL ? 0 : ssl->in_msglen ); } uint32_t mbedtls_ssl_get_verify_result( const mbedtls_ssl_context *ssl ) { if( ssl->session != NULL ) return( ssl->session->verify_result ); if( ssl->session_negotiate != NULL ) return( ssl->session_negotiate->verify_result ); return( 0xFFFFFFFF ); } const char *mbedtls_ssl_get_ciphersuite( const mbedtls_ssl_context *ssl ) { if( ssl == NULL || ssl->session == NULL ) return( NULL ); return mbedtls_ssl_get_ciphersuite_name( ssl->session->ciphersuite ); } const char *mbedtls_ssl_get_version( const mbedtls_ssl_context *ssl ) { #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { switch( ssl->minor_ver ) { case MBEDTLS_SSL_MINOR_VERSION_2: return( "DTLSv1.0" ); case MBEDTLS_SSL_MINOR_VERSION_3: return( "DTLSv1.2" ); default: return( "unknown (DTLS)" ); } } #endif switch( ssl->minor_ver ) { case MBEDTLS_SSL_MINOR_VERSION_0: return( "SSLv3.0" ); case MBEDTLS_SSL_MINOR_VERSION_1: return( "TLSv1.0" ); case MBEDTLS_SSL_MINOR_VERSION_2: return( "TLSv1.1" ); case MBEDTLS_SSL_MINOR_VERSION_3: return( "TLSv1.2" ); default: return( "unknown" ); } } int mbedtls_ssl_get_record_expansion( const mbedtls_ssl_context *ssl ) { size_t transform_expansion; const mbedtls_ssl_transform *transform = ssl->transform_out; #if defined(MBEDTLS_ZLIB_SUPPORT) if( ssl->session_out->compression != MBEDTLS_SSL_COMPRESS_NULL ) return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); #endif if( transform == NULL ) return( (int) mbedtls_ssl_hdr_len( ssl ) ); switch( mbedtls_cipher_get_cipher_mode( &transform->cipher_ctx_enc ) ) { case MBEDTLS_MODE_GCM: case MBEDTLS_MODE_CCM: case MBEDTLS_MODE_STREAM: transform_expansion = transform->minlen; break; case MBEDTLS_MODE_CBC: transform_expansion = transform->maclen + mbedtls_cipher_get_block_size( &transform->cipher_ctx_enc ); break; default: MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } return( (int)( mbedtls_ssl_hdr_len( ssl ) + transform_expansion ) ); } #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) size_t mbedtls_ssl_get_max_frag_len( const mbedtls_ssl_context *ssl ) { size_t max_len; /* * Assume mfl_code is correct since it was checked when set */ max_len = mfl_code_to_length[ssl->conf->mfl_code]; /* * Check if a smaller max length was negotiated */ if( ssl->session_out != NULL && mfl_code_to_length[ssl->session_out->mfl_code] < max_len ) { max_len = mfl_code_to_length[ssl->session_out->mfl_code]; } return max_len; } #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ #if defined(MBEDTLS_X509_CRT_PARSE_C) const mbedtls_x509_crt *mbedtls_ssl_get_peer_cert( const mbedtls_ssl_context *ssl ) { if( ssl == NULL || ssl->session == NULL ) return( NULL ); return( ssl->session->peer_cert ); } #endif /* MBEDTLS_X509_CRT_PARSE_C */ #if defined(MBEDTLS_SSL_CLI_C) int mbedtls_ssl_get_session( const mbedtls_ssl_context *ssl, mbedtls_ssl_session *dst ) { if( ssl == NULL || dst == NULL || ssl->session == NULL || ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT ) { return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } return( ssl_session_copy( dst, ssl->session ) ); } #endif /* MBEDTLS_SSL_CLI_C */ /* * Perform a single step of the SSL handshake */ int mbedtls_ssl_handshake_step( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; if( ssl == NULL || ssl->conf == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); #if defined(MBEDTLS_SSL_CLI_C) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) ret = mbedtls_ssl_handshake_client_step( ssl ); #endif #if defined(MBEDTLS_SSL_SRV_C) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER ) ret = mbedtls_ssl_handshake_server_step( ssl ); #endif return( ret ); } /* * Perform the SSL handshake */ int mbedtls_ssl_handshake( mbedtls_ssl_context *ssl ) { int ret = 0; if( ssl == NULL || ssl->conf == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> handshake" ) ); while( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) { ret = mbedtls_ssl_handshake_step( ssl ); if( ret != 0 ) break; } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= handshake" ) ); return( ret ); } #if defined(MBEDTLS_SSL_RENEGOTIATION) #if defined(MBEDTLS_SSL_SRV_C) /* * Write HelloRequest to request renegotiation on server */ static int ssl_write_hello_request( mbedtls_ssl_context *ssl ) { int ret; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write hello request" ) ); ssl->out_msglen = 4; ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_HELLO_REQUEST; if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write hello request" ) ); return( 0 ); } #endif /* MBEDTLS_SSL_SRV_C */ /* * Actually renegotiate current connection, triggered by either: * - any side: calling mbedtls_ssl_renegotiate(), * - client: receiving a HelloRequest during mbedtls_ssl_read(), * - server: receiving any handshake message on server during mbedtls_ssl_read() after * the initial handshake is completed. * If the handshake doesn't complete due to waiting for I/O, it will continue * during the next calls to mbedtls_ssl_renegotiate() or mbedtls_ssl_read() respectively. */ static int ssl_start_renegotiation( mbedtls_ssl_context *ssl ) { int ret; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> renegotiate" ) ); if( ( ret = ssl_handshake_init( ssl ) ) != 0 ) return( ret ); /* RFC 6347 4.2.2: "[...] the HelloRequest will have message_seq = 0 and * the ServerHello will have message_seq = 1" */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ) { if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER ) ssl->handshake->out_msg_seq = 1; else ssl->handshake->in_msg_seq = 1; } #endif ssl->state = MBEDTLS_SSL_HELLO_REQUEST; ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS; if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= renegotiate" ) ); return( 0 ); } /* * Renegotiate current connection on client, * or request renegotiation on server */ int mbedtls_ssl_renegotiate( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; if( ssl == NULL || ssl->conf == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); #if defined(MBEDTLS_SSL_SRV_C) /* On server, just send the request */ if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER ) { if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING; /* Did we already try/start sending HelloRequest? */ if( ssl->out_left != 0 ) return( mbedtls_ssl_flush_output( ssl ) ); return( ssl_write_hello_request( ssl ) ); } #endif /* MBEDTLS_SSL_SRV_C */ #if defined(MBEDTLS_SSL_CLI_C) /* * On client, either start the renegotiation process or, * if already in progress, continue the handshake */ if( ssl->renego_status != MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS ) { if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); if( ( ret = ssl_start_renegotiation( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_start_renegotiation", ret ); return( ret ); } } else { if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret ); return( ret ); } } #endif /* MBEDTLS_SSL_CLI_C */ return( ret ); } /* * Check record counters and renegotiate if they're above the limit. */ static int ssl_check_ctr_renegotiate( mbedtls_ssl_context *ssl ) { size_t ep_len = ssl_ep_len( ssl ); int in_ctr_cmp; int out_ctr_cmp; if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER || ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING || ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED ) { return( 0 ); } in_ctr_cmp = memcmp( ssl->in_ctr + ep_len, ssl->conf->renego_period + ep_len, 8 - ep_len ); out_ctr_cmp = memcmp( ssl->out_ctr + ep_len, ssl->conf->renego_period + ep_len, 8 - ep_len ); if( in_ctr_cmp <= 0 && out_ctr_cmp <= 0 ) { return( 0 ); } MBEDTLS_SSL_DEBUG_MSG( 1, ( "record counter limit reached: renegotiate" ) ); return( mbedtls_ssl_renegotiate( ssl ) ); } #endif /* MBEDTLS_SSL_RENEGOTIATION */ /* * Receive application data decrypted from the SSL layer */ int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len ) { int ret, record_read = 0; size_t n; if( ssl == NULL || ssl->conf == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> read" ) ); #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 ) return( ret ); if( ssl->handshake != NULL && ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING ) { if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 ) return( ret ); } } #endif #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ( ret = ssl_check_ctr_renegotiate( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_check_ctr_renegotiate", ret ); return( ret ); } #endif if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) { ret = mbedtls_ssl_handshake( ssl ); if( ret == MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO ) { record_read = 1; } else if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret ); return( ret ); } } if( ssl->in_offt == NULL ) { /* Start timer if not already running */ if( ssl->f_get_timer != NULL && ssl->f_get_timer( ssl->p_timer ) == -1 ) { ssl_set_timer( ssl, ssl->conf->read_timeout ); } if( ! record_read ) { if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 ) { if( ret == MBEDTLS_ERR_SSL_CONN_EOF ) return( 0 ); MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); return( ret ); } } if( ssl->in_msglen == 0 && ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA ) { /* * OpenSSL sends empty messages to randomize the IV */ if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 ) { if( ret == MBEDTLS_ERR_SSL_CONN_EOF ) return( 0 ); MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); return( ret ); } } #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "received handshake message" ) ); #if defined(MBEDTLS_SSL_CLI_C) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT && ( ssl->in_msg[0] != MBEDTLS_SSL_HS_HELLO_REQUEST || ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake received (not HelloRequest)" ) ); /* With DTLS, drop the packet (probably from last handshake) */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) return( MBEDTLS_ERR_SSL_WANT_READ ); #endif return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_HELLO ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "handshake received (not ClientHello)" ) ); /* With DTLS, drop the packet (probably from last handshake) */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) return( MBEDTLS_ERR_SSL_WANT_READ ); #endif return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } #endif if( ssl->conf->disable_renegotiation == MBEDTLS_SSL_RENEGOTIATION_DISABLED || ( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION && ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION ) ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "refusing renegotiation, sending alert" ) ); #if defined(MBEDTLS_SSL_PROTO_SSL3) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) { /* * SSLv3 does not have a "no_renegotiation" alert */ if( ( ret = mbedtls_ssl_send_fatal_handshake_failure( ssl ) ) != 0 ) return( ret ); } else #endif /* MBEDTLS_SSL_PROTO_SSL3 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 ) { if( ( ret = mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_WARNING, MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION ) ) != 0 ) { return( ret ); } } else #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } } else { /* DTLS clients need to know renego is server-initiated */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT ) { ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING; } #endif ret = ssl_start_renegotiation( ssl ); if( ret == MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO ) { record_read = 1; } else if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_start_renegotiation", ret ); return( ret ); } } /* If a non-handshake record was read during renego, fallthrough, * else tell the user they should call mbedtls_ssl_read() again */ if( ! record_read ) return( MBEDTLS_ERR_SSL_WANT_READ ); } else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ) { if( ssl->conf->renego_max_records >= 0 ) { if( ++ssl->renego_records_seen > ssl->conf->renego_max_records ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation requested, " "but not honored by client" ) ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } } } #endif /* MBEDTLS_SSL_RENEGOTIATION */ /* Fatal and closure alerts handled by mbedtls_ssl_read_record() */ if( ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "ignoring non-fatal non-closure alert" ) ); return( MBEDTLS_ERR_SSL_WANT_READ ); } if( ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad application data message" ) ); return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE ); } ssl->in_offt = ssl->in_msg; /* We're going to return something now, cancel timer, * except if handshake (renegotiation) is in progress */ if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER ) ssl_set_timer( ssl, 0 ); #if defined(MBEDTLS_SSL_PROTO_DTLS) /* If we requested renego but received AppData, resend HelloRequest. * Do it now, after setting in_offt, to avoid taking this branch * again if ssl_write_hello_request() returns WANT_WRITE */ #if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER && ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING ) { if( ( ret = ssl_resend_hello_request( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_resend_hello_request", ret ); return( ret ); } } #endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */ #endif } n = ( len < ssl->in_msglen ) ? len : ssl->in_msglen; memcpy( buf, ssl->in_offt, n ); ssl->in_msglen -= n; if( ssl->in_msglen == 0 ) /* all bytes consumed */ ssl->in_offt = NULL; else /* more data available */ ssl->in_offt += n; MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= read" ) ); return( (int) n ); } /* * Send application data to be encrypted by the SSL layer, * taking care of max fragment length and buffer size */ static int ssl_write_real( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { int ret; #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) size_t max_len = mbedtls_ssl_get_max_frag_len( ssl ); if( len > max_len ) { #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "fragment larger than the (negotiated) " "maximum fragment length: %d > %d", len, max_len ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } else #endif len = max_len; } #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ if( ssl->out_left != 0 ) { if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flush_output", ret ); return( ret ); } } else { ssl->out_msglen = len; ssl->out_msgtype = MBEDTLS_SSL_MSG_APPLICATION_DATA; memcpy( ssl->out_msg, buf, len ); if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret ); return( ret ); } } return( (int) len ); } /* * Write application data, doing 1/n-1 splitting if necessary. * * With non-blocking I/O, ssl_write_real() may return WANT_WRITE, * then the caller will call us again with the same arguments, so * remember wether we already did the split or not. */ #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING) static int ssl_write_split( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { int ret; if( ssl->conf->cbc_record_splitting == MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED || len <= 1 || ssl->minor_ver > MBEDTLS_SSL_MINOR_VERSION_1 || mbedtls_cipher_get_cipher_mode( &ssl->transform_out->cipher_ctx_enc ) != MBEDTLS_MODE_CBC ) { return( ssl_write_real( ssl, buf, len ) ); } if( ssl->split_done == 0 ) { if( ( ret = ssl_write_real( ssl, buf, 1 ) ) <= 0 ) return( ret ); ssl->split_done = 1; } if( ( ret = ssl_write_real( ssl, buf + 1, len - 1 ) ) <= 0 ) return( ret ); ssl->split_done = 0; return( ret + 1 ); } #endif /* MBEDTLS_SSL_CBC_RECORD_SPLITTING */ /* * Write application data (public-facing wrapper) */ int mbedtls_ssl_write( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { int ret; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write" ) ); if( ssl == NULL || ssl->conf == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ( ret = ssl_check_ctr_renegotiate( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_check_ctr_renegotiate", ret ); return( ret ); } #endif if( ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER ) { if( ( ret = mbedtls_ssl_handshake( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_handshake", ret ); return( ret ); } } #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING) ret = ssl_write_split( ssl, buf, len ); #else ret = ssl_write_real( ssl, buf, len ); #endif MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write" ) ); return( ret ); } /* * Notify the peer that the connection is being closed */ int mbedtls_ssl_close_notify( mbedtls_ssl_context *ssl ) { int ret; if( ssl == NULL || ssl->conf == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write close notify" ) ); if( ssl->out_left != 0 ) return( mbedtls_ssl_flush_output( ssl ) ); if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER ) { if( ( ret = mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_WARNING, MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_send_alert_message", ret ); return( ret ); } } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write close notify" ) ); return( 0 ); } void mbedtls_ssl_transform_free( mbedtls_ssl_transform *transform ) { if( transform == NULL ) return; #if defined(MBEDTLS_ZLIB_SUPPORT) deflateEnd( &transform->ctx_deflate ); inflateEnd( &transform->ctx_inflate ); #endif mbedtls_cipher_free( &transform->cipher_ctx_enc ); mbedtls_cipher_free( &transform->cipher_ctx_dec ); mbedtls_md_free( &transform->md_ctx_enc ); mbedtls_md_free( &transform->md_ctx_dec ); mbedtls_zeroize( transform, sizeof( mbedtls_ssl_transform ) ); } #if defined(MBEDTLS_X509_CRT_PARSE_C) static void ssl_key_cert_free( mbedtls_ssl_key_cert *key_cert ) { mbedtls_ssl_key_cert *cur = key_cert, *next; while( cur != NULL ) { next = cur->next; mbedtls_free( cur ); cur = next; } } #endif /* MBEDTLS_X509_CRT_PARSE_C */ void mbedtls_ssl_handshake_free( mbedtls_ssl_handshake_params *handshake ) { if( handshake == NULL ) return; #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) mbedtls_md5_free( &handshake->fin_md5 ); mbedtls_sha1_free( &handshake->fin_sha1 ); #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) #if defined(MBEDTLS_SHA256_C) mbedtls_sha256_free( &handshake->fin_sha256 ); #endif #if defined(MBEDTLS_SHA512_C) mbedtls_sha512_free( &handshake->fin_sha512 ); #endif #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ #if defined(MBEDTLS_DHM_C) mbedtls_dhm_free( &handshake->dhm_ctx ); #endif #if defined(MBEDTLS_ECDH_C) mbedtls_ecdh_free( &handshake->ecdh_ctx ); #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) mbedtls_ecjpake_free( &handshake->ecjpake_ctx ); #if defined(MBEDTLS_SSL_CLI_C) mbedtls_free( handshake->ecjpake_cache ); handshake->ecjpake_cache = NULL; handshake->ecjpake_cache_len = 0; #endif #endif #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) /* explicit void pointer cast for buggy MS compiler */ mbedtls_free( (void *) handshake->curves ); #endif #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) if( handshake->psk != NULL ) { mbedtls_zeroize( handshake->psk, handshake->psk_len ); mbedtls_free( handshake->psk ); } #endif #if defined(MBEDTLS_X509_CRT_PARSE_C) && \ defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) /* * Free only the linked list wrapper, not the keys themselves * since the belong to the SNI callback */ if( handshake->sni_key_cert != NULL ) { mbedtls_ssl_key_cert *cur = handshake->sni_key_cert, *next; while( cur != NULL ) { next = cur->next; mbedtls_free( cur ); cur = next; } } #endif /* MBEDTLS_X509_CRT_PARSE_C && MBEDTLS_SSL_SERVER_NAME_INDICATION */ #if defined(MBEDTLS_SSL_PROTO_DTLS) mbedtls_free( handshake->verify_cookie ); mbedtls_free( handshake->hs_msg ); ssl_flight_free( handshake->flight ); #endif mbedtls_zeroize( handshake, sizeof( mbedtls_ssl_handshake_params ) ); } void mbedtls_ssl_session_free( mbedtls_ssl_session *session ) { if( session == NULL ) return; #if defined(MBEDTLS_X509_CRT_PARSE_C) if( session->peer_cert != NULL ) { mbedtls_x509_crt_free( session->peer_cert ); mbedtls_free( session->peer_cert ); } #endif #if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C) mbedtls_free( session->ticket ); #endif mbedtls_zeroize( session, sizeof( mbedtls_ssl_session ) ); } /* * Free an SSL context */ void mbedtls_ssl_free( mbedtls_ssl_context *ssl ) { if( ssl == NULL ) return; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> free" ) ); if( ssl->out_buf != NULL ) { mbedtls_zeroize( ssl->out_buf, MBEDTLS_SSL_BUFFER_LEN ); mbedtls_free( ssl->out_buf ); } if( ssl->in_buf != NULL ) { mbedtls_zeroize( ssl->in_buf, MBEDTLS_SSL_BUFFER_LEN ); mbedtls_free( ssl->in_buf ); } #if defined(MBEDTLS_ZLIB_SUPPORT) if( ssl->compress_buf != NULL ) { mbedtls_zeroize( ssl->compress_buf, MBEDTLS_SSL_BUFFER_LEN ); mbedtls_free( ssl->compress_buf ); } #endif if( ssl->transform ) { mbedtls_ssl_transform_free( ssl->transform ); mbedtls_free( ssl->transform ); } if( ssl->handshake ) { mbedtls_ssl_handshake_free( ssl->handshake ); mbedtls_ssl_transform_free( ssl->transform_negotiate ); mbedtls_ssl_session_free( ssl->session_negotiate ); mbedtls_free( ssl->handshake ); mbedtls_free( ssl->transform_negotiate ); mbedtls_free( ssl->session_negotiate ); } if( ssl->session ) { mbedtls_ssl_session_free( ssl->session ); mbedtls_free( ssl->session ); } #if defined(MBEDTLS_X509_CRT_PARSE_C) if( ssl->hostname != NULL ) { mbedtls_zeroize( ssl->hostname, strlen( ssl->hostname ) ); mbedtls_free( ssl->hostname ); } #endif #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) if( mbedtls_ssl_hw_record_finish != NULL ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "going for mbedtls_ssl_hw_record_finish()" ) ); mbedtls_ssl_hw_record_finish( ssl ); } #endif #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C) mbedtls_free( ssl->cli_id ); #endif MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= free" ) ); /* Actually clear after last debug message */ mbedtls_zeroize( ssl, sizeof( mbedtls_ssl_context ) ); } /* * Initialze mbedtls_ssl_config */ void mbedtls_ssl_config_init( mbedtls_ssl_config *conf ) { memset( conf, 0, sizeof( mbedtls_ssl_config ) ); } #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED) static int ssl_preset_default_hashes[] = { #if defined(MBEDTLS_SHA512_C) MBEDTLS_MD_SHA512, MBEDTLS_MD_SHA384, #endif #if defined(MBEDTLS_SHA256_C) MBEDTLS_MD_SHA256, MBEDTLS_MD_SHA224, #endif #if defined(MBEDTLS_SHA1_C) MBEDTLS_MD_SHA1, #endif MBEDTLS_MD_NONE }; #endif static int ssl_preset_suiteb_ciphersuites[] = { MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, 0 }; #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED) static int ssl_preset_suiteb_hashes[] = { MBEDTLS_MD_SHA256, MBEDTLS_MD_SHA384, MBEDTLS_MD_NONE }; #endif #if defined(MBEDTLS_ECP_C) static mbedtls_ecp_group_id ssl_preset_suiteb_curves[] = { MBEDTLS_ECP_DP_SECP256R1, MBEDTLS_ECP_DP_SECP384R1, MBEDTLS_ECP_DP_NONE }; #endif /* * Load default in mbedtls_ssl_config */ int mbedtls_ssl_config_defaults( mbedtls_ssl_config *conf, int endpoint, int transport, int preset ) { #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C) int ret; #endif /* Use the functions here so that they are covered in tests, * but otherwise access member directly for efficiency */ mbedtls_ssl_conf_endpoint( conf, endpoint ); mbedtls_ssl_conf_transport( conf, transport ); /* * Things that are common to all presets */ #if defined(MBEDTLS_SSL_CLI_C) if( endpoint == MBEDTLS_SSL_IS_CLIENT ) { conf->authmode = MBEDTLS_SSL_VERIFY_REQUIRED; #if defined(MBEDTLS_SSL_SESSION_TICKETS) conf->session_tickets = MBEDTLS_SSL_SESSION_TICKETS_ENABLED; #endif } #endif #if defined(MBEDTLS_ARC4_C) conf->arc4_disabled = MBEDTLS_SSL_ARC4_DISABLED; #endif #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) conf->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED; #endif #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) conf->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED; #endif #if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING) conf->cbc_record_splitting = MBEDTLS_SSL_CBC_RECORD_SPLITTING_ENABLED; #endif #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C) conf->f_cookie_write = ssl_cookie_write_dummy; conf->f_cookie_check = ssl_cookie_check_dummy; #endif #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) conf->anti_replay = MBEDTLS_SSL_ANTI_REPLAY_ENABLED; #endif #if defined(MBEDTLS_SSL_SRV_C) conf->cert_req_ca_list = MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED; #endif #if defined(MBEDTLS_SSL_PROTO_DTLS) conf->hs_timeout_min = MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MIN; conf->hs_timeout_max = MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MAX; #endif #if defined(MBEDTLS_SSL_RENEGOTIATION) conf->renego_max_records = MBEDTLS_SSL_RENEGO_MAX_RECORDS_DEFAULT; memset( conf->renego_period, 0x00, 2 ); memset( conf->renego_period + 2, 0xFF, 6 ); #endif #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C) if( endpoint == MBEDTLS_SSL_IS_SERVER ) { if( ( ret = mbedtls_ssl_conf_dh_param( conf, MBEDTLS_DHM_RFC5114_MODP_2048_P, MBEDTLS_DHM_RFC5114_MODP_2048_G ) ) != 0 ) { return( ret ); } } #endif /* * Preset-specific defaults */ switch( preset ) { /* * NSA Suite B */ case MBEDTLS_SSL_PRESET_SUITEB: conf->min_major_ver = MBEDTLS_SSL_MAJOR_VERSION_3; conf->min_minor_ver = MBEDTLS_SSL_MINOR_VERSION_3; /* TLS 1.2 */ conf->max_major_ver = MBEDTLS_SSL_MAX_MAJOR_VERSION; conf->max_minor_ver = MBEDTLS_SSL_MAX_MINOR_VERSION; conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] = conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] = conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] = conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] = ssl_preset_suiteb_ciphersuites; #if defined(MBEDTLS_X509_CRT_PARSE_C) conf->cert_profile = &mbedtls_x509_crt_profile_suiteb; #endif #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED) conf->sig_hashes = ssl_preset_suiteb_hashes; #endif #if defined(MBEDTLS_ECP_C) conf->curve_list = ssl_preset_suiteb_curves; #endif break; /* * Default */ default: conf->min_major_ver = MBEDTLS_SSL_MAJOR_VERSION_3; conf->min_minor_ver = MBEDTLS_SSL_MINOR_VERSION_1; /* TLS 1.0 */ conf->max_major_ver = MBEDTLS_SSL_MAX_MAJOR_VERSION; conf->max_minor_ver = MBEDTLS_SSL_MAX_MINOR_VERSION; #if defined(MBEDTLS_SSL_PROTO_DTLS) if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) conf->min_minor_ver = MBEDTLS_SSL_MINOR_VERSION_2; #endif conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] = conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] = conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] = conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] = mbedtls_ssl_list_ciphersuites(); #if defined(MBEDTLS_X509_CRT_PARSE_C) conf->cert_profile = &mbedtls_x509_crt_profile_default; #endif #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED) conf->sig_hashes = ssl_preset_default_hashes; #endif #if defined(MBEDTLS_ECP_C) conf->curve_list = mbedtls_ecp_grp_id_list(); #endif #if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C) conf->dhm_min_bitlen = 1024; #endif } return( 0 ); } /* * Free mbedtls_ssl_config */ void mbedtls_ssl_config_free( mbedtls_ssl_config *conf ) { #if defined(MBEDTLS_DHM_C) mbedtls_mpi_free( &conf->dhm_P ); mbedtls_mpi_free( &conf->dhm_G ); #endif #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED) if( conf->psk != NULL ) { mbedtls_zeroize( conf->psk, conf->psk_len ); mbedtls_zeroize( conf->psk_identity, conf->psk_identity_len ); mbedtls_free( conf->psk ); mbedtls_free( conf->psk_identity ); conf->psk_len = 0; conf->psk_identity_len = 0; } #endif #if defined(MBEDTLS_X509_CRT_PARSE_C) ssl_key_cert_free( conf->key_cert ); #endif mbedtls_zeroize( conf, sizeof( mbedtls_ssl_config ) ); } #if defined(MBEDTLS_PK_C) && \ ( defined(MBEDTLS_RSA_C) || defined(MBEDTLS_ECDSA_C) ) /* * Convert between MBEDTLS_PK_XXX and SSL_SIG_XXX */ unsigned char mbedtls_ssl_sig_from_pk( mbedtls_pk_context *pk ) { #if defined(MBEDTLS_RSA_C) if( mbedtls_pk_can_do( pk, MBEDTLS_PK_RSA ) ) return( MBEDTLS_SSL_SIG_RSA ); #endif #if defined(MBEDTLS_ECDSA_C) if( mbedtls_pk_can_do( pk, MBEDTLS_PK_ECDSA ) ) return( MBEDTLS_SSL_SIG_ECDSA ); #endif return( MBEDTLS_SSL_SIG_ANON ); } mbedtls_pk_type_t mbedtls_ssl_pk_alg_from_sig( unsigned char sig ) { switch( sig ) { #if defined(MBEDTLS_RSA_C) case MBEDTLS_SSL_SIG_RSA: return( MBEDTLS_PK_RSA ); #endif #if defined(MBEDTLS_ECDSA_C) case MBEDTLS_SSL_SIG_ECDSA: return( MBEDTLS_PK_ECDSA ); #endif default: return( MBEDTLS_PK_NONE ); } } #endif /* MBEDTLS_PK_C && ( MBEDTLS_RSA_C || MBEDTLS_ECDSA_C ) */ /* * Convert from MBEDTLS_SSL_HASH_XXX to MBEDTLS_MD_XXX */ mbedtls_md_type_t mbedtls_ssl_md_alg_from_hash( unsigned char hash ) { switch( hash ) { #if defined(MBEDTLS_MD5_C) case MBEDTLS_SSL_HASH_MD5: return( MBEDTLS_MD_MD5 ); #endif #if defined(MBEDTLS_SHA1_C) case MBEDTLS_SSL_HASH_SHA1: return( MBEDTLS_MD_SHA1 ); #endif #if defined(MBEDTLS_SHA256_C) case MBEDTLS_SSL_HASH_SHA224: return( MBEDTLS_MD_SHA224 ); case MBEDTLS_SSL_HASH_SHA256: return( MBEDTLS_MD_SHA256 ); #endif #if defined(MBEDTLS_SHA512_C) case MBEDTLS_SSL_HASH_SHA384: return( MBEDTLS_MD_SHA384 ); case MBEDTLS_SSL_HASH_SHA512: return( MBEDTLS_MD_SHA512 ); #endif default: return( MBEDTLS_MD_NONE ); } } /* * Convert from MBEDTLS_MD_XXX to MBEDTLS_SSL_HASH_XXX */ unsigned char mbedtls_ssl_hash_from_md_alg( int md ) { switch( md ) { #if defined(MBEDTLS_MD5_C) case MBEDTLS_MD_MD5: return( MBEDTLS_SSL_HASH_MD5 ); #endif #if defined(MBEDTLS_SHA1_C) case MBEDTLS_MD_SHA1: return( MBEDTLS_SSL_HASH_SHA1 ); #endif #if defined(MBEDTLS_SHA256_C) case MBEDTLS_MD_SHA224: return( MBEDTLS_SSL_HASH_SHA224 ); case MBEDTLS_MD_SHA256: return( MBEDTLS_SSL_HASH_SHA256 ); #endif #if defined(MBEDTLS_SHA512_C) case MBEDTLS_MD_SHA384: return( MBEDTLS_SSL_HASH_SHA384 ); case MBEDTLS_MD_SHA512: return( MBEDTLS_SSL_HASH_SHA512 ); #endif default: return( MBEDTLS_SSL_HASH_NONE ); } } #if defined(MBEDTLS_ECP_C) /* * Check if a curve proposed by the peer is in our list. * Return 0 if we're willing to use it, -1 otherwise. */ int mbedtls_ssl_check_curve( const mbedtls_ssl_context *ssl, mbedtls_ecp_group_id grp_id ) { const mbedtls_ecp_group_id *gid; if( ssl->conf->curve_list == NULL ) return( -1 ); for( gid = ssl->conf->curve_list; *gid != MBEDTLS_ECP_DP_NONE; gid++ ) if( *gid == grp_id ) return( 0 ); return( -1 ); } #endif /* MBEDTLS_ECP_C */ #if defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED) /* * Check if a hash proposed by the peer is in our list. * Return 0 if we're willing to use it, -1 otherwise. */ int mbedtls_ssl_check_sig_hash( const mbedtls_ssl_context *ssl, mbedtls_md_type_t md ) { const int *cur; if( ssl->conf->sig_hashes == NULL ) return( -1 ); for( cur = ssl->conf->sig_hashes; *cur != MBEDTLS_MD_NONE; cur++ ) if( *cur == (int) md ) return( 0 ); return( -1 ); } #endif /* MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */ #if defined(MBEDTLS_X509_CRT_PARSE_C) int mbedtls_ssl_check_cert_usage( const mbedtls_x509_crt *cert, const mbedtls_ssl_ciphersuite_t *ciphersuite, int cert_endpoint, uint32_t *flags ) { int ret = 0; #if defined(MBEDTLS_X509_CHECK_KEY_USAGE) int usage = 0; #endif #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE) const char *ext_oid; size_t ext_len; #endif #if !defined(MBEDTLS_X509_CHECK_KEY_USAGE) && \ !defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE) ((void) cert); ((void) cert_endpoint); ((void) flags); #endif #if defined(MBEDTLS_X509_CHECK_KEY_USAGE) if( cert_endpoint == MBEDTLS_SSL_IS_SERVER ) { /* Server part of the key exchange */ switch( ciphersuite->key_exchange ) { case MBEDTLS_KEY_EXCHANGE_RSA: case MBEDTLS_KEY_EXCHANGE_RSA_PSK: usage = MBEDTLS_X509_KU_KEY_ENCIPHERMENT; break; case MBEDTLS_KEY_EXCHANGE_DHE_RSA: case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA: case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA: usage = MBEDTLS_X509_KU_DIGITAL_SIGNATURE; break; case MBEDTLS_KEY_EXCHANGE_ECDH_RSA: case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA: usage = MBEDTLS_X509_KU_KEY_AGREEMENT; break; /* Don't use default: we want warnings when adding new values */ case MBEDTLS_KEY_EXCHANGE_NONE: case MBEDTLS_KEY_EXCHANGE_PSK: case MBEDTLS_KEY_EXCHANGE_DHE_PSK: case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK: case MBEDTLS_KEY_EXCHANGE_ECJPAKE: usage = 0; } } else { /* Client auth: we only implement rsa_sign and mbedtls_ecdsa_sign for now */ usage = MBEDTLS_X509_KU_DIGITAL_SIGNATURE; } if( mbedtls_x509_crt_check_key_usage( cert, usage ) != 0 ) { *flags |= MBEDTLS_X509_BADCERT_KEY_USAGE; ret = -1; } #else ((void) ciphersuite); #endif /* MBEDTLS_X509_CHECK_KEY_USAGE */ #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE) if( cert_endpoint == MBEDTLS_SSL_IS_SERVER ) { ext_oid = MBEDTLS_OID_SERVER_AUTH; ext_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_SERVER_AUTH ); } else { ext_oid = MBEDTLS_OID_CLIENT_AUTH; ext_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_CLIENT_AUTH ); } if( mbedtls_x509_crt_check_extended_key_usage( cert, ext_oid, ext_len ) != 0 ) { *flags |= MBEDTLS_X509_BADCERT_EXT_KEY_USAGE; ret = -1; } #endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */ return( ret ); } #endif /* MBEDTLS_X509_CRT_PARSE_C */ /* * Convert version numbers to/from wire format * and, for DTLS, to/from TLS equivalent. * * For TLS this is the identity. * For DTLS, use 1's complement (v -> 255 - v, and then map as follows: * 1.0 <-> 3.2 (DTLS 1.0 is based on TLS 1.1) * 1.x <-> 3.x+1 for x != 0 (DTLS 1.2 based on TLS 1.2) */ void mbedtls_ssl_write_version( int major, int minor, int transport, unsigned char ver[2] ) { #if defined(MBEDTLS_SSL_PROTO_DTLS) if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { if( minor == MBEDTLS_SSL_MINOR_VERSION_2 ) --minor; /* DTLS 1.0 stored as TLS 1.1 internally */ ver[0] = (unsigned char)( 255 - ( major - 2 ) ); ver[1] = (unsigned char)( 255 - ( minor - 1 ) ); } else #else ((void) transport); #endif { ver[0] = (unsigned char) major; ver[1] = (unsigned char) minor; } } void mbedtls_ssl_read_version( int *major, int *minor, int transport, const unsigned char ver[2] ) { #if defined(MBEDTLS_SSL_PROTO_DTLS) if( transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { *major = 255 - ver[0] + 2; *minor = 255 - ver[1] + 1; if( *minor == MBEDTLS_SSL_MINOR_VERSION_1 ) ++*minor; /* DTLS 1.0 stored as TLS 1.1 internally */ } else #else ((void) transport); #endif { *major = ver[0]; *minor = ver[1]; } } int mbedtls_ssl_set_calc_verify_md( mbedtls_ssl_context *ssl, int md ) { #if defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 ) return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH; switch( md ) { #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) #if defined(MBEDTLS_MD5_C) case MBEDTLS_SSL_HASH_MD5: return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH; #endif #if defined(MBEDTLS_SHA1_C) case MBEDTLS_SSL_HASH_SHA1: ssl->handshake->calc_verify = ssl_calc_verify_tls; break; #endif #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */ #if defined(MBEDTLS_SHA512_C) case MBEDTLS_SSL_HASH_SHA384: ssl->handshake->calc_verify = ssl_calc_verify_tls_sha384; break; #endif #if defined(MBEDTLS_SHA256_C) case MBEDTLS_SSL_HASH_SHA256: ssl->handshake->calc_verify = ssl_calc_verify_tls_sha256; break; #endif default: return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH; } return 0; #else /* !MBEDTLS_SSL_PROTO_TLS1_2 */ (void) ssl; (void) md; return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH; #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ } #endif /* MBEDTLS_SSL_TLS_C */ #endif
the_stack_data/35601.c
#include <stdio.h> #define MAX 100 int factoriel(int n) { if (n==1) { return 1; } return n * factoriel(n-1); } int main() { int n, result; printf("Vnesi broj na koj sakas da presmetas faktoriel: "); scanf("%d", &n); result = factoriel(n); printf("Factoriel na %d e %d.", n, result); return 0; }
the_stack_data/921319.c
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #define MAX_CMD 256 void DoCmd(char *cmd) // 1초만 기다리는 건데 { // 연속으로 치면 따로 실행됨. printf("Doing %s", cmd); sleep(1); printf("Done\n"); } int main() { char cmd[MAX_CMD]; // 커맨드 입력 버퍼 while (1) { printf("CMD> "); fgets(cmd, MAX_CMD, stdin); if (cmd[0] == 'q') // q이면 입력 종료. break; DoCmd(cmd); } }
the_stack_data/12147.c
#include <stdio.h> #include <stdlib.h> typedef struct Person { char Name[20]; int Age; } Person; int main() { Person *person; person = NULL; for (int index = 0; index < 5; index++) { if (person != NULL) { printf("\n Pointer with trash!"); system("pause"); return 0; } printf("\n Person %d data:", index); person = (Person*)malloc(sizeof(Person)); printf("\n Name: "); scanf("%s", &person->Name); printf("\n Age: "); scanf("%d", &person->Age); } }
the_stack_data/59512476.c
#include <stdio.h> //Conversions.c [Shane Roeseberg] //Converts Celsius to Fahrenheight int main(void) { float celsius, fahrenheit; while(1) { printf("\n"); printf("Please input a temperature in Celsius (type 'stop' to stop): " ); if (scanf("%f", &celsius) != 1) break; fahrenheit = (1.8 * celsius) + 32; printf("Temperature in Fahrenheit: %f\n", fahrenheit); printf("\n"); } return(0); }
the_stack_data/198579716.c
#include <stdio.h> int main(void){ int num; int temp; printf("请输出一个整数:"); scanf("%d",&num); temp = num + 11; while(num < temp){ printf("%d ",num); num++; } printf("\n"); return 0; }
the_stack_data/433873.c
// // main.c // experiment1st_OS_theory // // Created by 幻梦浏光 on 2020/3/12. // Copyright © 2020 sjtu_F17. All rights reserved. // #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #define MEMSIZE 1000 /*双向链表的定义*/ struct map { unsigned m_size; char *m_addr; struct map *next, *prior; }; struct map *coremap; //链表起始指针 struct map *flag; //起始查找指针 /*循环适应的分配函数*/ char *lmalloc(unsigned size) { register char *a; register struct map *bp; bp = flag; do { if(bp->m_size >= size) { a = bp->m_addr; bp->m_addr += size; flag = bp->next; if((bp->m_size -= size) == 0) // 删除用光的空闲区项 { bp->prior->next = bp->next; bp->next->prior = bp->prior; free(bp); } printf("Success: lmalloc size: %d, addr:%p\n", size, a); //分配空间成功 return(a); } bp = bp->next; }while(bp != flag); printf("Error: There is no appropriate memory to be allocated for the size!\n"); //分配空间失败 return(0); } /* 循环首次适应的释放函数 */ char *lfree(unsigned size, char *aa) { struct map *bp; char *a; a = aa; bp = coremap; for(bp = coremap; bp->m_addr <= a; bp = bp->next); if (bp->prior->m_addr + bp->prior->m_size >= a && a >= bp->prior->m_addr && bp->next != bp) /* 情况1,2 */ { if(a + size > bp->m_addr + bp->m_size) // 防止向下溢出一整个空闲项 { printf("Error: Release area out of bounds!\n"); return(0); } else if(bp->prior->m_addr + bp->prior->m_size > a + size) // 防止重复释放已空闲的区域 { printf("Error: Already released!\n"); return(0); } else { if(bp->prior->m_addr + bp->prior->m_size > a) // 警告:所释放的区域与上一个空闲项的后部有重叠,但仍将执行 { printf("Warning: Release area out of bounds!\n"); bp->prior->m_size = a + size - bp->prior->m_addr; } else bp->prior->m_size += size; /* 情况1 */ } if (a + size >= bp->m_addr) /* 情况2 */ { if(a + size > bp->m_addr) // 警告:所释放的区域与下一个空闲项的前部有重叠,但仍将执行 { printf("Warning: Release area out of bounds!\n"); bp->prior->m_size = bp->m_addr + bp->m_size - bp->prior->m_addr; } else bp->prior->m_size += bp->m_size; bp->prior->next = bp->next; bp->next->prior = bp->prior; if(bp == flag) flag = bp->next; free(bp); } } else { if(a + size > bp->m_addr + bp->m_size) // 防止向下溢出一整个空闲项 { printf("Error: Release area out of bounds!\n"); return(0); } else if (a+size == bp->m_addr) /* 情况3 */ { bp->m_addr -= size; bp->m_size += size; } else if(a+size > bp->m_addr) // 警告:所释放的区域与下一个空闲项的前部有重叠,但仍将执行 { printf("Warning: Release area out of bounds!\n"); bp->m_size = bp->m_addr + bp->m_size - a; bp->m_addr = a; } else/* 情况4 */ { struct map *novel; novel = (struct map *)malloc(sizeof(struct map)); novel->m_addr = a; novel->m_size = size; novel->prior = bp->prior; novel->next = bp; bp->prior->next = novel; bp->prior = novel; if(coremap->m_addr > novel->m_addr) coremap = novel; } } printf("Success: lfree mem size=%u, addr=%p\n", size, aa); return(0); } /* coremap链表的初始化程序 */ void initcoremap(char *addr, unsigned size) { printf("init coremap, first addr: %p\n", addr); coremap = (struct map *)malloc(sizeof(struct map)); coremap->m_size = size; coremap->m_addr = addr; coremap->next = coremap; coremap->prior = coremap; flag = coremap; // 初始化coremap双向链表 } /* 输出链表的内容 */ void printcoremap() { struct map *fg; fg = coremap; do { printf("flag->m_addr = %p ", fg->m_addr); printf("flag->m_size = %d\n", fg->m_size); fg = fg->next; }while(fg != coremap); /* Function body: 打印coremap链表中各项的m_size和m_addr */ } /* 主程序的框架 */ int main() { char *mymem; int size; int addr; char cmdchar; char c; if ((mymem = malloc(MEMSIZE)) == NULL) //在真实主存中申请一块作业空间 { printf("Not enough memory to allocate buffer\n"); exit(1); } initcoremap(mymem, MEMSIZE); //初始化空闲双向链表 while(c!='q') { do { c = getchar(); }while(c=='\n'||c=='\t'||c==' '); cmdchar = c; switch (cmdchar) { case 'm': scanf("%u", &size); if(size <= 0) { printf("Error: Wrong size!\n"); break; } lmalloc(size); break; case 'f': scanf("%u %u", &size, &addr); if(size <= 0) { printf("Error: Wrong size!\n"); break; } if(addr > MEMSIZE || addr < 0) { printf("Error: Wrong address!\n"); break; } lfree(size, mymem + addr); break; case 'p': printcoremap(); break; default: break; } } free(mymem); return 0; }
the_stack_data/220455874.c
#include<stdio.h> #include<stdlib.h> #include<math.h> void change(int moeda[6],int sizeof_moeda){ moeda[100]=0; int resto=0; int moeda100=0; int moeda50=0; int moeda25=0; int moeda10=0; int moeda5=0; int moeda1=0; scanf("%d", &resto); //para inserir o valor do troco if(resto>=100){ moeda100=resto/100; resto=resto%100; //para saber a quantia de moedas de 1 real moeda[0]=moeda100; } if(resto>=50){ moeda50=resto/50; resto=resto%50; //para saber a quantia de moedas de 50 centavos moeda[1]=moeda50; } if(resto>=25){ moeda25=resto/25; resto=resto%25; //para saber a quantia de moedas de 25 centavos moeda[2]=moeda25; } if(resto>=10){ moeda10=resto/10; resto=resto%10; //para saber a quantia de moedas de 10 centavos moeda[3]=moeda10; } if(resto>=5){ moeda5=resto/5; resto=resto%5; //para saber a quantia de moedas de 5 centavos moeda[4]=moeda5; } if(resto>=1){ moeda1=resto/1; //para saber a quantia de moedas de 1 centavo moeda[5]=moeda1; } } int main(){ int a[100]; a[0]=0; a[1]=0; a[2]=0; a[3]=0; //para iniciar as variaveis com zero a[4]=0; a[5]=0; change(a,6); //para transferiri os valores da função para a variavel printf("O valor consiste em %d moedas de 1 real\nO valor consiste em %d moedas de 50 centavos\nO valor consiste em %d moedas de 25 centavos\nO valor consiste em %d moedas de 10 centavos\nO valor consiste em %d moedas de 5 centavos\nO valor consiste em %d moedas de 1 centavo\n", a[0],a[1],a[2],a[3],a[4],a[5]); return 0; }
the_stack_data/200144371.c
#define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> int main() { FILE *fd = NULL; fd = fopen("/proc/meminfo", "r"); if (!fd) { printf("Unkown"); } char *line = NULL; size_t len = 0; ssize_t read; unsigned long total = 0; unsigned long available = 0; for(int i = 0; i<3; i++) { line = NULL; len = 0; if((read = getline(&line, &len, fd)) != -1) { if(i == 0) { sscanf(line, "%*s %lu ", &total); } else if (i == 2) { sscanf(line, "%*s %lu ", &available); } free(line); } } printf("%.2lf GB", (double)(total - available) / (double)(1<<20)); fclose(fd); return 0; }
the_stack_data/40761557.c
/* Mulator - An extensible {e,si}mulator * Copyright 2011-2020 Pat Pannuto <[email protected]> * * Licensed under either of the Apache License, Version 2.0 * or the MIT license, at your option. */ int CONF_no_terminate; int CONF_rzwi_memory;
the_stack_data/132953717.c
// RUN: %clang_cc1 -x c -emit-llvm %s -o - -triple=i386-pc-win32 | FileCheck %s // RUN: %clang_cc1 -x c -emit-llvm %s -o - -triple=x86_64-pc-win32 | FileCheck %s void crbug857442(int x) { // Make sure to handle truncated or padded literals. The truncation is only valid in C. struct {int x; char s[2]; } truncatedAscii = {x, "hello"}; // CHECK: "??_C@_01CONKJJHI@he@" struct {int x; char s[16]; } paddedAscii = {x, "hello"}; // CHECK: "??_C@_0BA@EAAINDNC@hello?$AA?$AA?$AA?$AA?$AA?$AA?$AA?$AA?$AA?$AA?$AA@" }
the_stack_data/1045002.c
/* FFTE: A FAST FOURIER TRANSFORM PACKAGE (C) COPYRIGHT SOFTWARE, 2000-2004, 2008-2014, ALL RIGHTS RESERVED BY DAISUKE TAKAHASHI FACULTY OF ENGINEERING, INFORMATION AND SYSTEMS UNIVERSITY OF TSUKUBA 1-1-1 TENNODAI, TSUKUBA, IBARAKI 305-8573, JAPAN E-MAIL: [email protected] WRITTEN BY DAISUKE TAKAHASHI THIS KERNEL WAS GENERATED BY SPIRAL 8.2.0a03 */ void dft6b_(double *Y, double *X, double *TW1, int *lp1, int *mp1) { double a689, a690, a691, a692, a693, a694, a695, a696, a697, a698, s211, s212, s213, s214, s215, s216, s217, s218, s219, s220, s221, s222, s223, s224, s225, s226, s227, s228, s229, s230, s231, s232, s233, s234, s235, s236, s237, s238, s239, s240, t494, t495, t496, t497, t498, t499, t500, t501, t502, t503, t504, t505, t506, t507, t508, t509, t510, t511, t512, t513; int a680, a681, a682, a683, a684, a685, a686, a687, a688, a699, a700, a701, a702, a703, a704, a705, b90, j1, l1, m1; l1 = *(lp1); m1 = *(mp1); for(int j2 = 0; j2 < (l1 - 1); j2++) { j1 = (j2 + 1); for(int k1 = 0; k1 < m1; k1++) { a680 = (2*k1); a681 = (j1*m1); a682 = (a680 + (2*a681)); s211 = X[a682]; s212 = X[(a682 + 1)]; b90 = (l1*m1); a683 = (a682 + (2*b90)); s213 = X[a683]; s214 = X[(a683 + 1)]; a684 = (a682 + (4*b90)); s215 = X[a684]; s216 = X[(a684 + 1)]; a685 = (a682 + (6*b90)); s217 = X[a685]; s218 = X[(a685 + 1)]; a686 = (a682 + (8*b90)); s219 = X[a686]; s220 = X[(a686 + 1)]; a687 = (a682 + (10*b90)); s221 = X[a687]; s222 = X[(a687 + 1)]; t494 = (s215 + s219); t495 = (s216 + s220); t496 = (s211 + t494); t497 = (s212 + t495); t498 = (s211 - (0.5*t494)); t499 = (s212 - (0.5*t495)); s223 = (0.8660254037844386*(s216 - s220)); s224 = (0.8660254037844386*(s215 - s219)); t500 = (t498 + s223); t501 = (t499 - s224); t502 = (t498 - s223); t503 = (t499 + s224); t504 = (s217 + s221); t505 = (s218 + s222); t506 = (s213 + t504); t507 = (s214 + t505); t508 = (s213 - (0.5*t504)); t509 = (s214 - (0.5*t505)); s225 = (0.8660254037844386*(s218 - s222)); s226 = (0.8660254037844386*(s217 - s221)); t510 = (t508 + s225); t511 = (t509 - s226); t512 = (t508 - s225); t513 = (t509 + s226); s227 = ((0.5*t510) + (0.8660254037844386*t511)); s228 = ((0.5*t511) - (0.8660254037844386*t510)); s229 = ((0.8660254037844386*t513) - (0.5*t512)); s230 = ((0.8660254037844386*t512) + (0.5*t513)); s231 = (t496 - t506); s232 = (t497 - t507); s233 = (t500 + s227); s234 = (t501 + s228); s235 = (t500 - s227); s236 = (t501 - s228); s237 = (t502 + s229); s238 = (t503 - s230); s239 = (t502 - s229); s240 = (t503 + s230); a688 = (10*j1); a689 = TW1[a688]; a690 = TW1[(a688 + 1)]; a691 = TW1[(a688 + 2)]; a692 = TW1[(a688 + 3)]; a693 = TW1[(a688 + 4)]; a694 = TW1[(a688 + 5)]; a695 = TW1[(a688 + 6)]; a696 = TW1[(a688 + 7)]; a697 = TW1[(a688 + 8)]; a698 = TW1[(a688 + 9)]; a699 = (12*a681); a700 = (a680 + a699); Y[a700] = (t496 + t506); Y[(a700 + 1)] = (t497 + t507); a701 = (a680 + (2*m1) + a699); Y[a701] = ((a689*s233) - (a690*s234)); Y[(a701 + 1)] = ((a690*s233) + (a689*s234)); a702 = (a680 + (4*m1) + a699); Y[a702] = ((a691*s237) - (a692*s238)); Y[(a702 + 1)] = ((a692*s237) + (a691*s238)); a703 = (a680 + (6*m1) + a699); Y[a703] = ((a693*s231) - (a694*s232)); Y[(a703 + 1)] = ((a694*s231) + (a693*s232)); a704 = (a680 + (8*m1) + a699); Y[a704] = ((a695*s235) - (a696*s236)); Y[(a704 + 1)] = ((a696*s235) + (a695*s236)); a705 = (a680 + (10*m1) + a699); Y[a705] = ((a697*s239) - (a698*s240)); Y[(a705 + 1)] = ((a698*s239) + (a697*s240)); } } }
the_stack_data/64200674.c
/* * This source herein may be modified and/or distributed by anybody who * so desires, with the following restrictions: * 1.) No portion of this notice shall be removed. * 2.) Credit shall not be taken for the creation of this source. * 3.) This code is not to be traded, sold, or used for personal * gain or profit. */ #ifdef CURSES /* The following is a curses emulation package suitable for the rogue program * in which it is included. No other suitability is claimed or suspected. * Only those routines currently needed by this rogue program are included. * This is being provided for those systems that don't have a suitable * curses package and want to run this rogue program. * * Compile the entire program with -DCURSES to incorporate this package. * * The following is NOT supported: * "%D", "%B", "%n", or "%>" inside a cursor motion (cm) termcap string. * Terminals in which the cursor motion addresses the row differently from * the column, as in ":cm=\E%2,%3" or ":cm=\EY%+x;%+y" * Termcap database stored in the TERMCAP environ variable as returned * from md_getenv(). Only the termcap file name can be stored there. * See the comments for md_getenv() in machdep.c. * Terminals without non-destructive backspace. Backspace (^H) is used * for cursor motion regardless of any termcap entries. * The ":tc=" termcap entry is ignored. * * Suggestions: * Use line-feed as your termcap "do" entry: ":do=^J", ":do=\012" or * ":do=\n" This will help cursor motion optimization. If line-feed * won't work, then a short escape sequence will do. */ #include <string.h> #include "rogue.h" #define BS 010 #define LF 012 #define CR 015 #define ESC '\033' #define TAB '\011' #define ST_MASK 0x80 char terminal[DROWS][DCOLS]; char buffer[DROWS][DCOLS]; char cm_esc[16]; char cm_sep[16]; char cm_end[16]; boolean cm_reverse = 0; boolean cm_two = 0; boolean cm_three = 0; boolean cm_char = 0; short cm_inc = 0; boolean screen_dirty; boolean lines_dirty[DROWS]; boolean buf_stand_out = 0; boolean term_stand_out = 0; int LINES = DROWS; int COLS = DCOLS; WINDOW scr_buf; WINDOW *curscr = &scr_buf; char *CL = (char *) 0; char *CM = (char *) 0; char *UC = (char *) 0; /* UP */ char *DO = (char *) 0; char *VS = ""; char *VE = ""; char *TI = ""; char *TE = ""; char *SO = ""; char *SE = ""; short cur_row; short cur_col; #ifndef ANSI #define BUFLEN 256 static boolean tc_tname(fp, term, buf) FILE *fp; char *term; char *buf; { int i, j; boolean found = 0; char *fg; while (!found) { i = 0; fg = fgets(buf, BUFLEN, fp); if (fg != NULL) { if ((buf[0] != '#') && (buf[0] != ' ') && (buf[0] != TAB) && (buf[0] != CR) && (buf[0] != LF)) { while (buf[i] && (!found)) { j = 0; while (buf[i] == term[j]) { i++; j++; } if ((!term[j]) && ((buf[i] == '|') || (buf[i] == ':'))) { found = 1; } else { while (buf[i] && (buf[i] != '|') && (buf[i] != ':')) { i++; } if (buf[i]) { i++; } } } } } else { break; } } return(found); } static void tc_gets(ibuf, tcstr) char *ibuf; char **tcstr; { int i, j, k, n; char obuf[BUFLEN]; i = 4; j = 0; while (ibuf[i] && is_digit(ibuf[i])) { i++; } while (ibuf[i] && (ibuf[i] != ':')) { if (ibuf[i] == '\\') { i++; switch(ibuf[i]) { case 'E': obuf[j] = ESC; i++; break; case 'n': obuf[j] = LF; i++; break; case 'r': obuf[j] = CR; i++; break; case 'b': obuf[j] = BS; i++; break; case 't': obuf[j] = TAB; i++; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': n = 0; k = 0; while (k < 3 && ibuf[i] && is_digit(ibuf[i])) { n = (8 * n) + (ibuf[i] - '0'); i++; k++; } obuf[j] = (char) n; break; default: obuf[j] = ibuf[i]; i++; } } else if (ibuf[i] == '^') { obuf[j] = ibuf[i+1] - 64; i += 2; } else { obuf[j] = ibuf[i++]; } j++; } obuf[j] = 0; if (!(*tcstr = md_malloc(j + 1))) { clean_up("cannot alloc() memory"); } (void) strcpy(*tcstr, obuf); } static void tc_gnum(ibuf, n) char *ibuf; int *n; { int i, r = 0; i = 4; while (is_digit(ibuf[i])) { r = (r * 10) + (ibuf[i] - '0'); i++; } *n = r; } static void tc_cmget() { int i = 0, j = 0, rc_spec = 0; while (CM[i] && (CM[i] != '%') && (j < 15)) { cm_esc[j++] = CM[i++]; } cm_esc[j] = 0; while (CM[i] && (rc_spec < 2)) { if (CM[i] == '%') { i++; switch(CM[i]) { case 'd': rc_spec++; break; case 'i': cm_inc = 1; break; case '2': cm_two = 1; rc_spec++; break; case '3': cm_three = 1; rc_spec++; break; case '.': cm_char = 1; rc_spec++; break; case 'r': cm_reverse = 1; break; case '+': i++; cm_inc = CM[i]; cm_char = 1; rc_spec++; break; } i++; } else { j = 0; while (CM[i] && (CM[i] != '%')) { cm_sep[j++] = CM[i++]; } cm_sep[j] = 0; } } j = 0; if (rc_spec == 2) { while (CM[i] && (j < 15)) { cm_end[j++] = CM[i++]; } } cm_end[j] = 0; } static void tc_gtdata(fp, buf) FILE *fp; char *buf; { int i; boolean first = 1; do { if (!first) { if ((buf[0] != TAB) && (buf[0] != ' ')) { break; } } first = 0; i = 0; while (buf[i]) { while (buf[i] && (buf[i] != ':')) { i++; } if (buf[i] == ':') { if (!strncmp(buf + i, ":cl=", 4)) { tc_gets(buf + i, &CL); } else if (!strncmp(buf + i, ":cm=", 4)) { tc_gets(buf + i, &CM); } else if (!strncmp(buf + i, ":up=", 4)) { tc_gets(buf + i, &UC); } else if (!strncmp(buf + i, ":do=", 4)) { tc_gets(buf + i, &DO); } else if (!strncmp(buf + i, ":vs=", 4)) { tc_gets(buf + i, &VS); } else if (!strncmp(buf + i, ":ve=", 4)) { tc_gets(buf + i, &VE); } else if (!strncmp(buf + i, ":ti=", 4)) { tc_gets(buf + i, &TI); } else if (!strncmp(buf + i, ":te=", 4)) { tc_gets(buf + i, &TE); } else if (!strncmp(buf + i, ":so=", 4)) { tc_gets(buf + i, &SO); } else if (!strncmp(buf + i, ":se=", 4)) { tc_gets(buf + i, &SE); } else if (!strncmp(buf + i, ":li#", 4)) { tc_gnum(buf + i, &LINES); } else if (!strncmp(buf + i, ":co#", 4)) { tc_gnum(buf + i, &COLS); } i++; } } } while (fgets(buf, BUFLEN, fp) != NULL); if ((!CM) || (!CL)) { clean_up("Terminal and termcap must have cm and cl"); } tc_cmget(); } #endif /* ANSI */ static void get_term_info() { #ifdef ANSI /* Generic ANSI display. */ LINES = DROWS; COLS = DCOLS; CL = "\33[H\33[2J"; UC = "\33[A"; DO = "\33[B"; SO = "\33[7m"; SE = "\33[m"; cm_inc = 1; strcpy (cm_esc, "\33["); strcpy (cm_sep, ";"); strcpy (cm_end, "H"); #else FILE *fp; char *term, *tcf; char buf[BUFLEN]; char *tc_file = "/etc/termcap"; tcf = md_getenv("TERMCAP"); if (tcf) { if (strlen(tcf) > 40) { clean_up("TERMCAP file name too long"); } tc_file = tcf; } term = md_getenv("TERM"); if (! term) { clean_up("Cannot find TERM variable in environ"); } fp = fopen(tc_file, "r"); if (! fp) { sprintf(buf, "Cannot open TERMCAP file: %s", tc_file); clean_up(buf); } if (! tc_tname(fp, term, buf)) { sprintf(buf, "Cannot find TERM type: %s in TERMCAP file: %s", term, tc_file); clean_up(buf); } tc_gtdata(fp, buf); fclose(fp); #endif } void initscr() { clear(); get_term_info(); printf("%s%s", TI, VS); } void endwin() { printf("%s%s", TE, VE); md_cbreak_no_echo_nonl(0); } void move(row, col) int row, col; { curscr->_cury = row; curscr->_curx = col; screen_dirty = 1; } void mvaddstr(row, col, str) int row, col; char *str; { move(row, col); addstr(str); } void addstr(str) char *str; { while (*str) { addch((int) *str++); } } void addch(ch) register int ch; { int row, col; row = curscr->_cury; col = curscr->_curx++; if (buf_stand_out) { ch |= ST_MASK; } buffer[row][col] = (char) ch; lines_dirty[row] = 1; screen_dirty = 1; } void mvaddch(row, col, ch) int row, col, ch; { move(row, col); addch(ch); } static void put_st_char(ch) register int ch; { if ((ch & ST_MASK) && (!term_stand_out)) { ch &= ~ST_MASK; printf("%s%c", SO, ch); term_stand_out = 1; } else if ((!(ch & ST_MASK)) && term_stand_out) { printf("%s%c", SE, ch); term_stand_out = 0; } else { ch &= ~ST_MASK; putchar(ch); } } static void put_cursor(row, col) register int row, col; { register int i, rdif, cdif; int ch, t; rdif = (row > cur_row) ? row - cur_row : cur_row - row; cdif = (col > cur_col) ? col - cur_col : cur_col - col; if (((row > cur_row) && DO) || ((cur_row > row) && UC)) { if ((rdif < 4) && (cdif < 4)) { for (i = 0; i < rdif; i++) { printf("%s", ((row < cur_row) ? UC : DO)); } cur_row = row; if (col == cur_col) { return; } } } if (row == cur_row) { if (cdif <= 6) { for (i = 0; i < cdif; i++) { ch = (col < cur_col) ? BS : terminal[row][cur_col + i]; put_st_char((int) ch); } cur_row = row; cur_col = col; return; } } cur_row = row; cur_col = col; row += cm_inc; col += cm_inc; if (cm_reverse) { t = row; row = col; col = t; } if (cm_two) { printf("%s%02d%s%02d%s", cm_esc, row, cm_sep, col, cm_end); } else if (cm_three) { printf("%s%03d%s%03d%s", cm_esc, row, cm_sep, col, cm_end); } else if (cm_char) { printf("%s%c%s%c%s", cm_esc, row, cm_sep, col, cm_end); } else { printf("%s%d%s%d%s", cm_esc, row, cm_sep, col, cm_end); } } static void put_char_at(row, col, ch) register int row, col, ch; { put_cursor(row, col); put_st_char(ch); terminal[row][col] = (char) ch; cur_col++; } void refresh() { register int i, j, line; int old_row, old_col, first_row; if (screen_dirty) { old_row = curscr->_cury; old_col = curscr->_curx; first_row = cur_row; for (i = 0; i < DROWS; i++) { line = (first_row + i) % DROWS; if (lines_dirty[line]) { for (j = 0; j < DCOLS; j++) { if (buffer[line][j] != terminal[line][j]) { put_char_at(line, j, buffer[line][j]); } } lines_dirty[line] = 0; } } put_cursor(old_row, old_col); screen_dirty = 0; fflush(stdout); } } void wrefresh(scr) WINDOW *scr; { int i, col; printf("%s", CL); cur_row = cur_col = 0; for (i = 0; i < DROWS; i++) { col = 0; while (col < DCOLS) { while ((col < DCOLS) && (buffer[i][col] == ' ')) { col++; } if (col < DCOLS) { put_cursor(i, col); } while ((col < DCOLS) && (buffer[i][col] != ' ')) { put_st_char((int) buffer[i][col]); cur_col++; col++; } } } put_cursor(curscr->_cury, curscr->_curx); fflush(stdout); scr = scr; /* make lint happy */ } int mvinch(row, col) int row, col; { move(row, col); return((int) buffer[row][col]); } static void clear_buffers() { register int i, j; screen_dirty = 0; for (i = 0; i < DROWS; i++) { lines_dirty[i] = 0; for (j = 0; j < DCOLS; j++) { terminal[i][j] = ' '; buffer[i][j] = ' '; } } } void clear() { printf("%s", CL); fflush(stdout); cur_row = cur_col = 0; move(0, 0); clear_buffers(); } void clrtoeol() { int row, col; row = curscr->_cury; for (col = curscr->_curx; col < DCOLS; col++) { buffer[row][col] = ' '; } lines_dirty[row] = 1; } void standout() { buf_stand_out = 1; } void standend() { buf_stand_out = 0; } void crmode() { md_cbreak_no_echo_nonl(1); } void noecho() { /* crmode() takes care of this */ } void nonl() { /* crmode() takes care of this */ } void tstp() { endwin(); md_tstp(); start_window(); printf("%s%s", TI, VS); wrefresh(curscr); md_slurp(); } #endif /* CURSES */
the_stack_data/6388002.c
#include <assert.h> #include <stdlib.h> typedef struct { int original; int weighted; }Value; Value *createArrayOfValues(int *array, int arrayLength) { Value *newArray = (Value *)malloc(arrayLength * sizeof(Value)); for(int i=0; i < arrayLength; i++) { newArray[i].original = array[i]; newArray[i].weighted = array[i] * (i+1); } return newArray; } // Selection Sort: O(n^2) void sort(Value *array, int arrayLength) { for(int i=0; i < arrayLength-1; i++) { int minValue = array[i].weighted; int minIndex = i; for(int j=i+1; j < arrayLength; j++) { if (array[j].weighted < minValue) { minValue = array[j].weighted; minIndex = j; } } Value temp = array[i]; array[i] = array[minIndex]; array[minIndex] = temp; } } int* sortByValueAndIndex(int* array, int arrayLength) { Value *valuesArray = createArrayOfValues(array, arrayLength); sort(valuesArray, arrayLength); int *sortedArray = malloc(arrayLength * sizeof(int)); for (int i=0; i < arrayLength; i++) { sortedArray[i] = valuesArray[i].original; } return sortedArray; } // Test Helper Forward Declaration int cmp(int *array1, int *array2, size_t n); int main (int argc, char *argv[]) { int array1[] = { 1, 2, 3, 4, 5 }; int expected1[] = { 1, 2, 3, 4, 5 }; int* actual1 = sortByValueAndIndex(array1, 5); assert(cmp(actual1, expected1, 5)); int array2[] = { 23, 2, 3, 4, 5 }; int expected2[] = { 2, 3, 4, 23, 5 }; int* actual2 = sortByValueAndIndex(array2, 5); assert(cmp(actual2, expected2, 5)); int array3[] = { 26, 2, 3, 4, 5 }; int expected3[] = { 2, 3, 4, 5, 26 }; int* actual3 = sortByValueAndIndex(array3, 5); assert(cmp(actual3, expected3, 5)); int array4[] = { 9, 5, 1, 4, 3 }; int expected4[] = { 1, 9, 5, 3, 4 }; int* actual4 = sortByValueAndIndex(array4, 5); assert(cmp(actual4, expected4, 5)); } int cmp(int *array1, int *array2, size_t n) { for (int i=0; i < n; i++) { if (array1[i] != array2[i]) { return 0; } } return 1; }
the_stack_data/114768.c
#include <stdio.h> #include <sys/time.h> #include <memory.h> #include <stdlib.h> #include <math.h> #include <inttypes.h> /* The cst_time_memcmp() function compares the first n bytes (each interpreted * as unsigned char) of the n bytes long memory areas m1 and m2 in a time * exactly proportional to n. * * The cst_time_memcmp() function returns 0 if the n first bytes of m1 and * m2 are equal. If the first different byte is found at index k, the function * returns -1 if m1[k] < m2[k], and +1 if m1[k] > m2[k]. Appart from the * comparision result, this function reveals nothing of m1 or m2. * * The function returns also 0 when at least one of the following conditions * is true. * * - n is zero ; * - m1 and m2 are the same memory area ; * - m1 is NULL ; * - m2 is NULL. */ int cst_time_memcmp_fastest2(const void *m1, const void *m2, size_t n) { int res = 0; if (m1 != m2 && n && m1 && m2) { const unsigned char *pm1 = (const unsigned char *)m1 + n; const unsigned char *pm2 = (const unsigned char *)m2 + n; do { int diff = *--pm1 - *--pm2; // if (diff != 0) res = diff; res = (res & -!diff) | diff; } while (pm1 != m1); } return (res > 0) - (res < 0); } int cst_time_memcmp_fastest1(const void *m1, const void *m2, size_t n) { int res = 0, diff; if (m1 != m2 && n && m1 && m2) { const unsigned char *pm1 = (const unsigned char *)m1; const unsigned char *pm2 = (const unsigned char *)m2; do { --n; diff = pm1[n] - pm2[n]; // if (diff != 0) res = diff; res = (res & -!diff) | diff; } while (n != 0); } return (res > 0) - (res < 0); } int cst_time_memcmp_safest1(const void *m1, const void *m2, size_t n) { int res = 0, diff; if (m1 != m2 && n && m1 && m2) { const unsigned char *pm1 = (const unsigned char *)m1; const unsigned char *pm2 = (const unsigned char *)m2; do { --n; diff = pm1[n] - pm2[n]; // if (diff != 0) res = diff; res = (res & (((diff - 1) & ~diff) >> 8)) | diff; } while (n != 0); } return ((res - 1) >> 8) + (res >> 8) + 1; } int cst_time_memcmp_safest2(const void *m1, const void *m2, size_t n) { int res = 0, diff; if (m1 != m2 && n && m1 && m2) { const unsigned char *pm1 = (const unsigned char *)m1 + n; const unsigned char *pm2 = (const unsigned char *)m2 + n; do { diff = *--pm1 - *--pm2; // if (diff != 0) res = diff; res = (res & (((diff - 1) & ~diff) >> 8)) | diff; } while (pm1 != m1); } return ((res - 1) >> 8) + (res >> 8) + 1; } int consttime_memcmp(const void *b1, const void *b2, size_t len) { const uint8_t *c1, *c2; uint16_t d, r, m; uint16_t v; c1 = b1; c2 = b2; r = 0; while (len) { v = ((uint16_t)(uint8_t)r)+255; m = v/256-1; d = (uint16_t)((int)*c1 - (int)*c2); r |= (d & m); ++c1; ++c2; --len; } return (int)((int32_t)(uint16_t)((uint32_t)r + 0x8000) - 0x8000); } const char *data_to_hex(const unsigned char *a, size_t n) { static char buf[100]; if (!a) { sprintf(buf, "NULL"); } else if (n < 33) { char *p = buf; size_t i; for (i = 0; i < n; ++i) { p += sprintf(p, "%02X ", a[i]); } if (p != buf) { *--p = '\0'; } } else { sprintf(buf, "data[%zu] too long", n); } return buf; } #define TEST_ONE_SMALLER(A,B,N,F) do { \ if (F(A, B, N) < 0) \ printf("SUCCESS test a < b\n"); \ else \ printf("FAIL ! test a < b\n"); \ } while (0) #define TEST_ONE_EQUAL(A,B,N,F) do { \ if (F(A, B, N) == 0) \ printf("SUCCESS test a = b\n"); \ else \ printf("FAIL ! test a = b\n"); \ } while (0) #define TEST_ONE_BIGGER(A,B,N,F) do { \ if (F(A, B, N) > 0) \ printf("SUCCESS test a > b\n"); \ else \ printf("FAIL ! test a > b\n"); \ } while (0) const unsigned char d[6][5] = { { 0x12, 0x34, 0x56, 0x78, 0x90 }, { 0x12, 0x34, 0x56, 0x78, 0x90 }, { 0x12, 0x34, 0x56, 0x90, 0x78 }, { 0x12, 0x34, 0x78, 0x56, 0x90 }, { 0x12, 0x90, 0x34, 0x56, 0x78 }, { 0x90, 0x12, 0x34, 0x56, 0x78 } }; #define TEST_ALL(F) do { \ size_t i, j, n = 6, l = 5; \ printf("---- %s\n", #F ); \ for (i = 0; i < n; ++i) { \ for (j = 0; j < n; ++j) { \ if (i == j) \ continue; \ puts(""); \ printf(" a(%p)= %s\n", d[i], data_to_hex(d[i], l)); \ printf(" b(%p)= %s\n", d[j], data_to_hex(d[j], l)); \ if (i < 2 && j < 2) \ TEST_ONE_EQUAL(d[i], d[j], l, F); \ else if (i < j) \ TEST_ONE_SMALLER(d[i], d[j], l, F); \ else \ TEST_ONE_BIGGER(d[i], d[j], l, F); \ } \ } \ } while (0) #define TEST_TIME_ONE(A,B,K,L,N,F,MEAN,VAR) do{ \ struct timeval t1, t2; \ size_t i,j, nval=0; \ double m1 = 0.0, m2 = 0.0; \ int tmp = x; \ for (j = 0; j < N; ++j) { \ double elapsed_time_ms; \ gettimeofday(&t1, NULL); \ for (i = 0; i < L; ++i) { \ tmp += F(A, B, K) * i; \ } \ gettimeofday(&t2, NULL); \ elapsed_time_ms = (t2.tv_sec - t1.tv_sec) * 1000.0; \ elapsed_time_ms += (t2.tv_usec - t1.tv_usec) / 1000.0; \ ++nval; \ double delta = elapsed_time_ms - m1; \ m1 += delta / nval; \ m2 += delta * (elapsed_time_ms - m1); \ } \ VAR = m2 / (nval - 1); \ MEAN = m1; \ x += tmp; \ } while(0) #define TEST_TIME(F) do { \ size_t k = 1024*1024, l = 100, n = 100; \ unsigned char *buf1 = malloc(k), *buf2 = malloc(k); \ double mean = 0.0, var = 0.0; \ int x = 0; \ memset(buf1, 0, k); \ memset(buf2, 0, k); \ printf("---- %s\n", #F ); \ TEST_TIME_ONE(buf1, buf2, k, l, n, F, mean, var); \ TEST_TIME_ONE(buf1, buf2, k, l, n, F, mean, var); \ printf("test 1 : mean=%f ms stddev=%f n=%zu\n", \ mean, sqrt(var), n); \ memset(buf2+k/2, 0xFF, k-k/2); \ TEST_TIME_ONE(buf1, buf2, k, l, n, F, mean, var); \ printf("test 2 : mean=%f ms stddev=%f n=%zu\n", \ mean, sqrt(var), n); \ memset(buf2, 0xFF, k); \ TEST_TIME_ONE(buf1, buf2, k, l, n, F, mean, var); \ printf("test 3 : mean=%f ms stddev=%f n=%zu\n", \ mean, sqrt(var), n); \ printf("x : 0x%08X\n", x); \ } while (0); int main(void) { puts("Start testing"); TEST_ALL(cst_time_memcmp_fastest1); TEST_ALL(cst_time_memcmp_fastest2); TEST_ALL(cst_time_memcmp_safest1); TEST_ALL(cst_time_memcmp_safest2); TEST_ALL(consttime_memcmp); puts(""); TEST_TIME(cst_time_memcmp_fastest1); TEST_TIME(cst_time_memcmp_fastest2); TEST_TIME(cst_time_memcmp_safest1); TEST_TIME(cst_time_memcmp_safest2); TEST_TIME(consttime_memcmp); puts("done"); return 0; }
the_stack_data/87637272.c
#include <stdio.h> int main() { char str[100]; int i; printf("Enter a value\n"); scanf("%s %d", str, &i); printf("You entered: %s %d\n", str, i); return 0; }
the_stack_data/248582024.c
/* crypto/seed/seed_ofb.c */ /* ==================================================================== * Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * [email protected]. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.openssl.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * */ /* Copyright (C) 1995-1998 Eric Young ([email protected]) * All rights reserved. * * This package is an SSL implementation written * by Eric Young ([email protected]). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson ([email protected]). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * 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 copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young ([email protected])" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson ([email protected])" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ #include <openssl/seed.h> #include <openssl/modes.h> void SEED_ofb128_encrypt(const unsigned char *in, unsigned char *out, size_t len, const SEED_KEY_SCHEDULE *ks, unsigned char ivec[SEED_BLOCK_SIZE], int *num) { CRYPTO_ofb128_encrypt(in, out, len, ks, ivec, num, (block128_f) SEED_encrypt); }
the_stack_data/45451285.c
int test_while_x2; int i; void undo_test_while2(void); void test_while2(void) { i = 5; while (test_while_x2 < i) { test_while_x2++; } }
the_stack_data/181394057.c
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> // printf() in second.c extern int g_int;// referencing declaration static void tool(void) { // } void fun_second(void); void fun_second(void) { tool(); g_int += 1; printf("g_int in fun_second() %d %p\n", g_int, &g_int); }
the_stack_data/86076653.c
/* Generated by CIL v. 1.7.0 */ /* print_CIL_Input is false */ struct _IO_FILE; struct timeval; extern void signal(int sig , void *func ) ; extern float strtof(char const *str , char const *endptr ) ; typedef struct _IO_FILE FILE; extern int atoi(char const *s ) ; extern double strtod(char const *str , char const *endptr ) ; extern int fclose(void *stream ) ; extern void *fopen(char const *filename , char const *mode ) ; extern void abort() ; extern void exit(int status ) ; extern int raise(int sig ) ; extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ; extern int strcmp(char const *a , char const *b ) ; extern int rand() ; extern unsigned long strtoul(char const *str , char const *endptr , int base ) ; void RandomFunc(unsigned long input[1] , unsigned long output[1] ) ; extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ; extern int gettimeofday(struct timeval *tv , void *tz , ...) ; extern int printf(char const *format , ...) ; int main(int argc , char *argv[] ) ; void megaInit(void) ; extern unsigned long strlen(char const *s ) ; extern long strtol(char const *str , char const *endptr , int base ) ; extern unsigned long strnlen(char const *s , unsigned long maxlen ) ; extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ; struct timeval { long tv_sec ; long tv_usec ; }; extern void *malloc(unsigned long size ) ; extern int scanf(char const *format , ...) ; void megaInit(void) { { } } int main(int argc , char *argv[] ) { unsigned long input[1] ; unsigned long output[1] ; int randomFuns_i5 ; unsigned long randomFuns_value6 ; int randomFuns_main_i7 ; { megaInit(); if (argc != 2) { printf("Call this program with %i arguments\n", 1); exit(-1); } else { } randomFuns_i5 = 0; while (randomFuns_i5 < 1) { randomFuns_value6 = strtoul(argv[randomFuns_i5 + 1], 0, 10); input[randomFuns_i5] = randomFuns_value6; randomFuns_i5 ++; } RandomFunc(input, output); if (output[0] == 4242424242UL) { printf("You win!\n"); } else { } randomFuns_main_i7 = 0; while (randomFuns_main_i7 < 1) { printf("%lu\n", output[randomFuns_main_i7]); randomFuns_main_i7 ++; } } } void RandomFunc(unsigned long input[1] , unsigned long output[1] ) { unsigned long state[1] ; unsigned long local1 ; unsigned short copy11 ; { state[0UL] = (input[0UL] - 51238316UL) - 339126204UL; local1 = 0UL; while (local1 < input[1UL]) { if (state[0UL] > local1) { state[0UL] |= (((state[local1] >> ((state[local1] & 15UL) | 1UL)) | (state[local1] << (64 - ((state[local1] & 15UL) | 1UL)))) & 63UL) << 4UL; copy11 = *((unsigned short *)(& state[local1]) + 1); *((unsigned short *)(& state[local1]) + 1) = *((unsigned short *)(& state[local1]) + 0); *((unsigned short *)(& state[local1]) + 0) = copy11; copy11 = *((unsigned short *)(& state[local1]) + 0); *((unsigned short *)(& state[local1]) + 0) = *((unsigned short *)(& state[local1]) + 2); *((unsigned short *)(& state[local1]) + 2) = copy11; } else { state[0UL] = (state[0UL] << (((state[0UL] >> 2UL) & 15UL) | 1UL)) | (state[0UL] >> (64 - (((state[0UL] >> 2UL) & 15UL) | 1UL))); state[0UL] |= ((state[0UL] + state[local1]) & 15UL) << 2UL; } local1 ++; } output[0UL] = ((state[0UL] >> 13UL) | (state[0UL] << 51UL)) + 563432908449020955UL; } }
the_stack_data/89199271.c
/* Generate assembler source containing symbol information * * Copyright 2002 by Kai Germaschewski * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. * * Usage: nm -n vmlinux | scripts/kallsyms [--all-symbols] > symbols.S * * Table compression uses all the unused char codes on the symbols and * maps these to the most used substrings (tokens). For instance, it might * map char code 0xF7 to represent "write_" and then in every symbol where * "write_" appears it can be replaced by 0xF7, saving 5 bytes. * The used codes themselves are also placed in the table so that the * decompresion can work without "special cases". * Applied to kernel symbols, this usually produces a compression ratio * of about 50%. * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <limits.h> #ifndef ARRAY_SIZE #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof(arr[0])) #endif #define KSYM_NAME_LEN 128 struct sym_entry { unsigned long long addr; unsigned int len; unsigned int start_pos; unsigned char *sym; unsigned int percpu_absolute; }; struct addr_range { const char *start_sym, *end_sym; unsigned long long start, end; }; static unsigned long long _text; static unsigned long long relative_base; static struct addr_range text_ranges[] = { { "_stext", "_etext" }, { "_sinittext", "_einittext" }, { "_stext_l1", "_etext_l1" }, /* Blackfin on-chip L1 inst SRAM */ { "_stext_l2", "_etext_l2" }, /* Blackfin on-chip L2 SRAM */ }; #define text_range_text (&text_ranges[0]) #define text_range_inittext (&text_ranges[1]) static struct addr_range percpu_range = { "__per_cpu_start", "__per_cpu_end", -1ULL, 0 }; static struct sym_entry *table; static unsigned int table_size, table_cnt; static int all_symbols = 0; static int uncompressed = 0; static int absolute_percpu = 0; static char symbol_prefix_char = '\0'; static int base_relative = 0; int token_profit[0x10000]; /* the table that holds the result of the compression */ unsigned char best_table[256][2]; unsigned char best_table_len[256]; static void usage(void) { fprintf(stderr, "Usage: kallsyms [--all-symbols] " "[--symbol-prefix=<prefix char>] " "[--page-offset=<CONFIG_PAGE_OFFSET>] " "[--base-relative] < in.map > out.S\n"); exit(1); } /* * This ignores the intensely annoying "mapping symbols" found * in ARM ELF files: $a, $t and $d. */ static inline int is_arm_mapping_symbol(const char *str) { return str[0] == '$' && strchr("axtd", str[1]) && (str[2] == '\0' || str[2] == '.'); } static int check_symbol_range(const char *sym, unsigned long long addr, struct addr_range *ranges, int entries) { size_t i; struct addr_range *ar; for (i = 0; i < entries; ++i) { ar = &ranges[i]; if (strcmp(sym, ar->start_sym) == 0) { ar->start = addr; return 0; } else if (strcmp(sym, ar->end_sym) == 0) { ar->end = addr; return 0; } } return 1; } static int read_symbol(FILE *in, struct sym_entry *s) { char str[500]; char *sym, stype; int rc; rc = fscanf(in, "%llx %c %499s\n", &s->addr, &stype, str); if (rc != 3) { if (rc != EOF && fgets(str, 500, in) == NULL) fprintf(stderr, "Read error or end of file.\n"); return -1; } if (strlen(str) > KSYM_NAME_LEN) { fprintf(stderr, "Symbol %s too long for kallsyms (%zu vs %d).\n" "Please increase KSYM_NAME_LEN both in kernel and kallsyms.c\n", str, strlen(str), KSYM_NAME_LEN); return -1; } sym = str; /* skip prefix char */ if (symbol_prefix_char && str[0] == symbol_prefix_char) sym++; /* Ignore most absolute/undefined (?) symbols. */ if (strcmp(sym, "_text") == 0) _text = s->addr; else if (check_symbol_range(sym, s->addr, text_ranges, ARRAY_SIZE(text_ranges)) == 0) /* nothing to do */; else if (toupper(stype) == 'A') { /* Keep these useful absolute symbols */ if (strcmp(sym, "__kernel_syscall_via_break") && strcmp(sym, "__kernel_syscall_via_epc") && strcmp(sym, "__kernel_sigtramp") && strcmp(sym, "__gp")) return -1; } else if (toupper(stype) == 'U' || is_arm_mapping_symbol(sym)) return -1; /* exclude also MIPS ELF local symbols ($L123 instead of .L123) */ else if (str[0] == '$') return -1; /* exclude debugging symbols */ else if (stype == 'N') return -1; /* exclude s390 kasan local symbols */ else if (!strncmp(sym, ".LASANPC", 8)) return -1; /* include the type field in the symbol name, so that it gets * compressed together */ s->len = strlen(str) + 1; s->sym = malloc(s->len + 1); if (!s->sym) { fprintf(stderr, "kallsyms failure: " "unable to allocate required amount of memory\n"); exit(EXIT_FAILURE); } strcpy((char *)s->sym + 1, str); s->sym[0] = stype; s->percpu_absolute = 0; /* Record if we've found __per_cpu_start/end. */ check_symbol_range(sym, s->addr, &percpu_range, 1); return 0; } static int symbol_in_range(struct sym_entry *s, struct addr_range *ranges, int entries) { size_t i; struct addr_range *ar; for (i = 0; i < entries; ++i) { ar = &ranges[i]; if (s->addr >= ar->start && s->addr <= ar->end) return 1; } return 0; } static int symbol_valid(struct sym_entry *s) { /* Symbols which vary between passes. Passes 1 and 2 must have * identical symbol lists. The kallsyms_* symbols below are only added * after pass 1, they would be included in pass 2 when --all-symbols is * specified so exclude them to get a stable symbol list. */ static char *special_symbols[] = { "kallsyms_addresses", "kallsyms_offsets", "kallsyms_relative_base", "kallsyms_num_syms", "kallsyms_names", "kallsyms_markers", "kallsyms_token_table", "kallsyms_token_index", /* Exclude linker generated symbols which vary between passes */ "_SDA_BASE_", /* ppc */ "_SDA2_BASE_", /* ppc */ NULL }; static char *special_suffixes[] = { "_veneer", /* arm */ "_from_arm", /* arm */ "_from_thumb", /* arm */ NULL }; int i; char *sym_name = (char *)s->sym + 1; /* skip prefix char */ if (symbol_prefix_char && *sym_name == symbol_prefix_char) sym_name++; /* if --all-symbols is not specified, then symbols outside the text * and inittext sections are discarded */ if (!all_symbols) { if (symbol_in_range(s, text_ranges, ARRAY_SIZE(text_ranges)) == 0) return 0; /* Corner case. Discard any symbols with the same value as * _etext _einittext; they can move between pass 1 and 2 when * the kallsyms data are added. If these symbols move then * they may get dropped in pass 2, which breaks the kallsyms * rules. */ if ((s->addr == text_range_text->end && strcmp(sym_name, text_range_text->end_sym)) || (s->addr == text_range_inittext->end && strcmp(sym_name, text_range_inittext->end_sym))) return 0; } /* Exclude symbols which vary between passes. */ for (i = 0; special_symbols[i]; i++) if (strcmp(sym_name, special_symbols[i]) == 0) return 0; for (i = 0; special_suffixes[i]; i++) { int l = strlen(sym_name) - strlen(special_suffixes[i]); if (l >= 0 && strcmp(sym_name + l, special_suffixes[i]) == 0) return 0; } return 1; } static void read_map(FILE *in) { while (!feof(in)) { if (table_cnt >= table_size) { table_size += 10000; table = realloc(table, sizeof(*table) * table_size); if (!table) { fprintf(stderr, "out of memory\n"); exit (1); } } if (read_symbol(in, &table[table_cnt]) == 0) { table[table_cnt].start_pos = table_cnt; table_cnt++; } } } static void output_label(char *label) { if (symbol_prefix_char) printf(".globl %c%s\n", symbol_prefix_char, label); else printf(".globl %s\n", label); printf("\tALGN\n"); if (symbol_prefix_char) printf("%c%s:\n", symbol_prefix_char, label); else printf("%s:\n", label); } /* uncompress a compressed symbol. When this function is called, the best table * might still be compressed itself, so the function needs to be recursive */ static int expand_symbol(unsigned char *data, int len, char *result) { int c, rlen, total=0; while (len) { c = *data; /* if the table holds a single char that is the same as the one * we are looking for, then end the search */ if (best_table[c][0]==c && best_table_len[c]==1) { *result++ = c; total++; } else { /* if not, recurse and expand */ rlen = expand_symbol(best_table[c], best_table_len[c], result); total += rlen; result += rlen; } data++; len--; } *result=0; return total; } static int symbol_absolute(struct sym_entry *s) { return s->percpu_absolute; } static void write_src(void) { unsigned int i, k, off; unsigned int best_idx[256]; unsigned int *markers; char buf[KSYM_NAME_LEN]; printf("#include <asm/types.h>\n"); printf("#if BITS_PER_LONG == 64\n"); printf("#define PTR .quad\n"); printf("#define ALGN .align 8\n"); printf("#else\n"); printf("#define PTR .long\n"); printf("#define ALGN .align 4\n"); printf("#endif\n"); printf("\t.section .rodata, \"a\"\n"); /* Provide proper symbols relocatability by their relativeness * to a fixed anchor point in the runtime image, either '_text' * for absolute address tables, in which case the linker will * emit the final addresses at build time. Otherwise, use the * offset relative to the lowest value encountered of all relative * symbols, and emit non-relocatable fixed offsets that will be fixed * up at runtime. * * The symbol names cannot be used to construct normal symbol * references as the list of symbols contains symbols that are * declared static and are private to their .o files. This prevents * .tmp_kallsyms.o or any other object from referencing them. */ if (!base_relative) output_label("kallsyms_addresses"); else output_label("kallsyms_offsets"); for (i = 0; i < table_cnt; i++) { if (base_relative) { long long offset; int overflow; if (!absolute_percpu) { offset = table[i].addr - relative_base; overflow = (offset < 0 || offset > UINT_MAX); } else if (symbol_absolute(&table[i])) { offset = table[i].addr; overflow = (offset < 0 || offset > INT_MAX); } else { offset = relative_base - table[i].addr - 1; overflow = (offset < INT_MIN || offset >= 0); } if (overflow) { fprintf(stderr, "kallsyms failure: " "%s symbol value %#llx out of range in relative mode\n", symbol_absolute(&table[i]) ? "absolute" : "relative", table[i].addr); exit(EXIT_FAILURE); } printf("\t.long\t%#x\n", (int)offset); } else if (!symbol_absolute(&table[i])) { if (_text <= table[i].addr) printf("\tPTR\t_text + %#llx\n", table[i].addr - _text); else printf("\tPTR\t_text - %#llx\n", _text - table[i].addr); } else { printf("\tPTR\t%#llx\n", table[i].addr); } } printf("\n"); if (base_relative) { output_label("kallsyms_relative_base"); printf("\tPTR\t_text - %#llx\n", _text - relative_base); printf("\n"); } output_label("kallsyms_num_syms"); printf("\tPTR\t%d\n", table_cnt); printf("\n"); /* table of offset markers, that give the offset in the compressed stream * every 256 symbols */ markers = malloc(sizeof(unsigned int) * ((table_cnt + 255) / 256)); if (!markers) { fprintf(stderr, "kallsyms failure: " "unable to allocate required memory\n"); exit(EXIT_FAILURE); } output_label("kallsyms_names"); off = 0; for (i = 0; i < table_cnt; i++) { if ((i & 0xFF) == 0) markers[i >> 8] = off; printf("\t.byte 0x%02x", table[i].len); for (k = 0; k < table[i].len; k++) printf(", 0x%02x", table[i].sym[k]); printf("\n"); off += table[i].len + 1; } printf("\n"); output_label("kallsyms_markers"); for (i = 0; i < ((table_cnt + 255) >> 8); i++) printf("\tPTR\t%d\n", markers[i]); printf("\n"); free(markers); if (uncompressed) return; output_label("kallsyms_token_table"); off = 0; for (i = 0; i < 256; i++) { best_idx[i] = off; expand_symbol(best_table[i], best_table_len[i], buf); printf("\t.asciz\t\"%s\"\n", buf); off += strlen(buf) + 1; } printf("\n"); output_label("kallsyms_token_index"); for (i = 0; i < 256; i++) printf("\t.short\t%d\n", best_idx[i]); printf("\n"); } /* table lookup compression functions */ /* count all the possible tokens in a symbol */ static void learn_symbol(unsigned char *symbol, int len) { int i; for (i = 0; i < len - 1; i++) token_profit[ symbol[i] + (symbol[i + 1] << 8) ]++; } /* decrease the count for all the possible tokens in a symbol */ static void forget_symbol(unsigned char *symbol, int len) { int i; for (i = 0; i < len - 1; i++) token_profit[ symbol[i] + (symbol[i + 1] << 8) ]--; } /* remove all the invalid symbols from the table and do the initial token count */ static void build_initial_tok_table(void) { unsigned int i, pos; pos = 0; for (i = 0; i < table_cnt; i++) { if ( symbol_valid(&table[i]) ) { if (pos != i) table[pos] = table[i]; learn_symbol(table[pos].sym, table[pos].len); pos++; } else { free(table[i].sym); } } table_cnt = pos; } static void *find_token(unsigned char *str, int len, unsigned char *token) { int i; if (uncompressed) return NULL; for (i = 0; i < len - 1; i++) { if (str[i] == token[0] && str[i+1] == token[1]) return &str[i]; } return NULL; } /* replace a given token in all the valid symbols. Use the sampled symbols * to update the counts */ static void compress_symbols(unsigned char *str, int idx) { unsigned int i, len, size; unsigned char *p1, *p2; for (i = 0; i < table_cnt; i++) { len = table[i].len; p1 = table[i].sym; /* find the token on the symbol */ p2 = find_token(p1, len, str); if (!p2) continue; /* decrease the counts for this symbol's tokens */ forget_symbol(table[i].sym, len); size = len; do { *p2 = idx; p2++; size -= (p2 - p1); memmove(p2, p2 + 1, size); p1 = p2; len--; if (size < 2) break; /* find the token on the symbol */ p2 = find_token(p1, size, str); } while (p2); table[i].len = len; /* increase the counts for this symbol's new tokens */ learn_symbol(table[i].sym, len); } } /* search the token with the maximum profit */ static int find_best_token(void) { int i, best, bestprofit; bestprofit=-10000; best = 0; for (i = 0; i < 0x10000; i++) { if (token_profit[i] > bestprofit) { best = i; bestprofit = token_profit[i]; } } return best; } /* this is the core of the algorithm: calculate the "best" table */ static void optimize_result(void) { int i, best; if (uncompressed) return; /* using the '\0' symbol last allows compress_symbols to use standard * fast string functions */ for (i = 255; i >= 0; i--) { /* if this table slot is empty (it is not used by an actual * original char code */ if (!best_table_len[i]) { /* find the token with the breates profit value */ best = find_best_token(); if (token_profit[best] == 0) break; /* place it in the "best" table */ best_table_len[i] = 2; best_table[i][0] = best & 0xFF; best_table[i][1] = (best >> 8) & 0xFF; /* replace this token in all the valid symbols */ compress_symbols(best_table[i], i); } } } /* start by placing the symbols that are actually used on the table */ static void insert_real_symbols_in_table(void) { unsigned int i, j, c; memset(best_table, 0, sizeof(best_table)); memset(best_table_len, 0, sizeof(best_table_len)); for (i = 0; i < table_cnt; i++) { for (j = 0; j < table[i].len; j++) { c = table[i].sym[j]; best_table[c][0]=c; best_table_len[c]=1; } } } static void optimize_token_table(void) { build_initial_tok_table(); insert_real_symbols_in_table(); /* When valid symbol is not registered, exit to error */ if (!table_cnt) { fprintf(stderr, "No valid symbol.\n"); exit(1); } optimize_result(); } /* guess for "linker script provide" symbol */ static int may_be_linker_script_provide_symbol(const struct sym_entry *se) { const char *symbol = (char *)se->sym + 1; int len = se->len - 1; if (len < 8) return 0; if (symbol[0] != '_' || symbol[1] != '_') return 0; /* __start_XXXXX */ if (!memcmp(symbol + 2, "start_", 6)) return 1; /* __stop_XXXXX */ if (!memcmp(symbol + 2, "stop_", 5)) return 1; /* __end_XXXXX */ if (!memcmp(symbol + 2, "end_", 4)) return 1; /* __XXXXX_start */ if (!memcmp(symbol + len - 6, "_start", 6)) return 1; /* __XXXXX_end */ if (!memcmp(symbol + len - 4, "_end", 4)) return 1; return 0; } static int prefix_underscores_count(const char *str) { const char *tail = str; while (*tail == '_') tail++; return tail - str; } static int compare_symbols(const void *a, const void *b) { const struct sym_entry *sa; const struct sym_entry *sb; int wa, wb; sa = a; sb = b; /* sort by address first */ if (sa->addr > sb->addr) return 1; if (sa->addr < sb->addr) return -1; /* sort by "weakness" type */ wa = (sa->sym[0] == 'w') || (sa->sym[0] == 'W'); wb = (sb->sym[0] == 'w') || (sb->sym[0] == 'W'); if (wa != wb) return wa - wb; /* sort by "linker script provide" type */ wa = may_be_linker_script_provide_symbol(sa); wb = may_be_linker_script_provide_symbol(sb); if (wa != wb) return wa - wb; /* sort by the number of prefix underscores */ wa = prefix_underscores_count((const char *)sa->sym + 1); wb = prefix_underscores_count((const char *)sb->sym + 1); if (wa != wb) return wa - wb; /* sort by initial order, so that other symbols are left undisturbed */ return sa->start_pos - sb->start_pos; } static void sort_symbols(void) { qsort(table, table_cnt, sizeof(struct sym_entry), compare_symbols); } static void make_percpus_absolute(void) { unsigned int i; for (i = 0; i < table_cnt; i++) if (symbol_in_range(&table[i], &percpu_range, 1)) { /* * Keep the 'A' override for percpu symbols to * ensure consistent behavior compared to older * versions of this tool. */ table[i].sym[0] = 'A'; table[i].percpu_absolute = 1; } } /* find the minimum non-absolute symbol address */ static void record_relative_base(void) { unsigned int i; relative_base = -1ULL; for (i = 0; i < table_cnt; i++) if (!symbol_absolute(&table[i]) && table[i].addr < relative_base) relative_base = table[i].addr; } int main(int argc, char **argv) { if (argc >= 2) { int i; for (i = 1; i < argc; i++) { if(strcmp(argv[i], "--all-symbols") == 0) all_symbols = 1; else if (strcmp(argv[i], "--absolute-percpu") == 0) absolute_percpu = 1; else if (strncmp(argv[i], "--symbol-prefix=", 16) == 0) { char *p = &argv[i][16]; /* skip quote */ if ((*p == '"' && *(p+2) == '"') || (*p == '\'' && *(p+2) == '\'')) p++; symbol_prefix_char = *p; } else if (strcmp(argv[i], "--base-relative") == 0) base_relative = 1; else if (strcmp(argv[i], "--uncompressed") == 0) uncompressed = 1; else usage(); } } else if (argc != 1) usage(); read_map(stdin); if (absolute_percpu) make_percpus_absolute(); if (base_relative) record_relative_base(); sort_symbols(); optimize_token_table(); write_src(); return 0; }
the_stack_data/146673.c
// Here we test that __CPROVER_havoc_slice checks fail as expected #include <stdint.h> #include <stdlib.h> int main() { // invalid pointer int *invalid_ptr; __CPROVER_havoc_slice(invalid_ptr, 1); // null pointer int *null_ptr = NULL; __CPROVER_havoc_slice(null_ptr, 1); int a[4]; // positive size but out of bounds __CPROVER_havoc_slice(&a[2], 3 * sizeof(*a)); // positive size but out of bounds __CPROVER_havoc_slice(a, 5 * sizeof(*a)); // pointer invalidated by overflow __CPROVER_havoc_slice(&a[0] + 6, sizeof(*a)); // pointer invalidated by underflow __CPROVER_havoc_slice(&a[0] - 1, sizeof(*a)); // negative size __CPROVER_havoc_slice(&a[0], -2); }
the_stack_data/69484.c
void copy_16(void * dest, void * src, unsigned int n) { while (n > 1) { *((unsigned short *)dest) = *((unsigned short *)src); dest += 2; src += 2; n -= 2; } } void copy_32(void * dest, void * src, unsigned int n) { while (n > 1) { *((unsigned int *)dest) = *((unsigned int *)src); dest += 4; src += 4; n -= 4; } } void fill_16(void * dest, unsigned short c, unsigned int n) { while (n > 1) { *((unsigned short *)dest) = c; dest += 2; n -= 2; } } void fill_32(void * dest, unsigned int c, unsigned int n) { while (n > 1) { *((unsigned int *)dest) = c; dest += 4; n -= 4; } }
the_stack_data/111078305.c
#include <stdio.h> #include <stdlib.h> char * itoa(int value, char * str, int base) { char * rc; char * ptr; char * low; if(base < 2 || base > 36) { *str = '\0'; return str; } rc = ptr = str; if(value < 0 && base == 10) *ptr++ = '-'; low = ptr; do { *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz"[35 + value % base]; value /= base; } while(value); *ptr-- = '\0'; while(low<ptr){ char tmp = *low; *low++ = *ptr; *ptr-- = tmp; } return rc; }
the_stack_data/86075888.c
extern float __VERIFIER_nondet_float(void); extern int __VERIFIER_nondet_int(void); typedef enum {false, true} bool; bool __VERIFIER_nondet_bool(void) { return __VERIFIER_nondet_int() != 0; } int main() { bool _EL_U_2383, _x__EL_U_2383; float x_13, _x_x_13; float x_6, _x_x_6; float x_26, _x_x_26; float x_2, _x_x_2; float x_24, _x_x_24; float x_17, _x_x_17; float x_3, _x_x_3; float x_21, _x_x_21; float x_12, _x_x_12; float x_1, _x_x_1; float x_15, _x_x_15; float x_0, _x_x_0; float x_18, _x_x_18; float x_4, _x_x_4; float x_5, _x_x_5; float x_10, _x_x_10; float x_27, _x_x_27; float x_11, _x_x_11; float x_16, _x_x_16; float x_14, _x_x_14; float x_19, _x_x_19; float x_20, _x_x_20; float x_9, _x_x_9; float x_22, _x_x_22; float x_23, _x_x_23; float x_25, _x_x_25; float x_7, _x_x_7; float x_8, _x_x_8; int __steps_to_fair = __VERIFIER_nondet_int(); _EL_U_2383 = __VERIFIER_nondet_bool(); x_13 = __VERIFIER_nondet_float(); x_6 = __VERIFIER_nondet_float(); x_26 = __VERIFIER_nondet_float(); x_2 = __VERIFIER_nondet_float(); x_24 = __VERIFIER_nondet_float(); x_17 = __VERIFIER_nondet_float(); x_3 = __VERIFIER_nondet_float(); x_21 = __VERIFIER_nondet_float(); x_12 = __VERIFIER_nondet_float(); x_1 = __VERIFIER_nondet_float(); x_15 = __VERIFIER_nondet_float(); x_0 = __VERIFIER_nondet_float(); x_18 = __VERIFIER_nondet_float(); x_4 = __VERIFIER_nondet_float(); x_5 = __VERIFIER_nondet_float(); x_10 = __VERIFIER_nondet_float(); x_27 = __VERIFIER_nondet_float(); x_11 = __VERIFIER_nondet_float(); x_16 = __VERIFIER_nondet_float(); x_14 = __VERIFIER_nondet_float(); x_19 = __VERIFIER_nondet_float(); x_20 = __VERIFIER_nondet_float(); x_9 = __VERIFIER_nondet_float(); x_22 = __VERIFIER_nondet_float(); x_23 = __VERIFIER_nondet_float(); x_25 = __VERIFIER_nondet_float(); x_7 = __VERIFIER_nondet_float(); x_8 = __VERIFIER_nondet_float(); bool __ok = (1 && (( !((14.0 <= (x_21 + (-1.0 * x_24))) || ( !((x_17 + (-1.0 * x_24)) <= 4.0)))) || ((9.0 <= (x_6 + (-1.0 * x_13))) && _EL_U_2383))); while (__steps_to_fair >= 0 && __ok) { if ((( !((14.0 <= (x_21 + (-1.0 * x_24))) || ( !((x_17 + (-1.0 * x_24)) <= 4.0)))) || ( !(( !((14.0 <= (x_21 + (-1.0 * x_24))) || ( !((x_17 + (-1.0 * x_24)) <= 4.0)))) || ((9.0 <= (x_6 + (-1.0 * x_13))) && _EL_U_2383))))) { __steps_to_fair = __VERIFIER_nondet_int(); } else { __steps_to_fair--; } _x__EL_U_2383 = __VERIFIER_nondet_bool(); _x_x_13 = __VERIFIER_nondet_float(); _x_x_6 = __VERIFIER_nondet_float(); _x_x_26 = __VERIFIER_nondet_float(); _x_x_2 = __VERIFIER_nondet_float(); _x_x_24 = __VERIFIER_nondet_float(); _x_x_17 = __VERIFIER_nondet_float(); _x_x_3 = __VERIFIER_nondet_float(); _x_x_21 = __VERIFIER_nondet_float(); _x_x_12 = __VERIFIER_nondet_float(); _x_x_1 = __VERIFIER_nondet_float(); _x_x_15 = __VERIFIER_nondet_float(); _x_x_0 = __VERIFIER_nondet_float(); _x_x_18 = __VERIFIER_nondet_float(); _x_x_4 = __VERIFIER_nondet_float(); _x_x_5 = __VERIFIER_nondet_float(); _x_x_10 = __VERIFIER_nondet_float(); _x_x_27 = __VERIFIER_nondet_float(); _x_x_11 = __VERIFIER_nondet_float(); _x_x_16 = __VERIFIER_nondet_float(); _x_x_14 = __VERIFIER_nondet_float(); _x_x_19 = __VERIFIER_nondet_float(); _x_x_20 = __VERIFIER_nondet_float(); _x_x_9 = __VERIFIER_nondet_float(); _x_x_22 = __VERIFIER_nondet_float(); _x_x_23 = __VERIFIER_nondet_float(); _x_x_25 = __VERIFIER_nondet_float(); _x_x_7 = __VERIFIER_nondet_float(); _x_x_8 = __VERIFIER_nondet_float(); __ok = ((((((((((((((((((((((((((((((((x_25 + (-1.0 * _x_x_0)) <= -11.0) && (((x_23 + (-1.0 * _x_x_0)) <= -2.0) && (((x_22 + (-1.0 * _x_x_0)) <= -12.0) && (((x_21 + (-1.0 * _x_x_0)) <= -18.0) && (((x_18 + (-1.0 * _x_x_0)) <= -3.0) && (((x_17 + (-1.0 * _x_x_0)) <= -10.0) && (((x_16 + (-1.0 * _x_x_0)) <= -8.0) && (((x_14 + (-1.0 * _x_x_0)) <= -14.0) && (((x_13 + (-1.0 * _x_x_0)) <= -10.0) && (((x_11 + (-1.0 * _x_x_0)) <= -9.0) && (((x_8 + (-1.0 * _x_x_0)) <= -15.0) && (((x_4 + (-1.0 * _x_x_0)) <= -3.0) && (((x_1 + (-1.0 * _x_x_0)) <= -10.0) && ((x_3 + (-1.0 * _x_x_0)) <= -15.0)))))))))))))) && (((x_25 + (-1.0 * _x_x_0)) == -11.0) || (((x_23 + (-1.0 * _x_x_0)) == -2.0) || (((x_22 + (-1.0 * _x_x_0)) == -12.0) || (((x_21 + (-1.0 * _x_x_0)) == -18.0) || (((x_18 + (-1.0 * _x_x_0)) == -3.0) || (((x_17 + (-1.0 * _x_x_0)) == -10.0) || (((x_16 + (-1.0 * _x_x_0)) == -8.0) || (((x_14 + (-1.0 * _x_x_0)) == -14.0) || (((x_13 + (-1.0 * _x_x_0)) == -10.0) || (((x_11 + (-1.0 * _x_x_0)) == -9.0) || (((x_8 + (-1.0 * _x_x_0)) == -15.0) || (((x_4 + (-1.0 * _x_x_0)) == -3.0) || (((x_1 + (-1.0 * _x_x_0)) == -10.0) || ((x_3 + (-1.0 * _x_x_0)) == -15.0))))))))))))))) && ((((x_24 + (-1.0 * _x_x_1)) <= -15.0) && (((x_23 + (-1.0 * _x_x_1)) <= -8.0) && (((x_22 + (-1.0 * _x_x_1)) <= -12.0) && (((x_20 + (-1.0 * _x_x_1)) <= -1.0) && (((x_19 + (-1.0 * _x_x_1)) <= -15.0) && (((x_18 + (-1.0 * _x_x_1)) <= -8.0) && (((x_17 + (-1.0 * _x_x_1)) <= -7.0) && (((x_16 + (-1.0 * _x_x_1)) <= -11.0) && (((x_14 + (-1.0 * _x_x_1)) <= -14.0) && (((x_9 + (-1.0 * _x_x_1)) <= -19.0) && (((x_8 + (-1.0 * _x_x_1)) <= -10.0) && (((x_6 + (-1.0 * _x_x_1)) <= -4.0) && (((x_3 + (-1.0 * _x_x_1)) <= -6.0) && ((x_4 + (-1.0 * _x_x_1)) <= -7.0)))))))))))))) && (((x_24 + (-1.0 * _x_x_1)) == -15.0) || (((x_23 + (-1.0 * _x_x_1)) == -8.0) || (((x_22 + (-1.0 * _x_x_1)) == -12.0) || (((x_20 + (-1.0 * _x_x_1)) == -1.0) || (((x_19 + (-1.0 * _x_x_1)) == -15.0) || (((x_18 + (-1.0 * _x_x_1)) == -8.0) || (((x_17 + (-1.0 * _x_x_1)) == -7.0) || (((x_16 + (-1.0 * _x_x_1)) == -11.0) || (((x_14 + (-1.0 * _x_x_1)) == -14.0) || (((x_9 + (-1.0 * _x_x_1)) == -19.0) || (((x_8 + (-1.0 * _x_x_1)) == -10.0) || (((x_6 + (-1.0 * _x_x_1)) == -4.0) || (((x_3 + (-1.0 * _x_x_1)) == -6.0) || ((x_4 + (-1.0 * _x_x_1)) == -7.0)))))))))))))))) && ((((x_27 + (-1.0 * _x_x_2)) <= -18.0) && (((x_26 + (-1.0 * _x_x_2)) <= -9.0) && (((x_25 + (-1.0 * _x_x_2)) <= -18.0) && (((x_24 + (-1.0 * _x_x_2)) <= -2.0) && (((x_23 + (-1.0 * _x_x_2)) <= -15.0) && (((x_21 + (-1.0 * _x_x_2)) <= -15.0) && (((x_17 + (-1.0 * _x_x_2)) <= -14.0) && (((x_15 + (-1.0 * _x_x_2)) <= -16.0) && (((x_13 + (-1.0 * _x_x_2)) <= -2.0) && (((x_9 + (-1.0 * _x_x_2)) <= -10.0) && (((x_8 + (-1.0 * _x_x_2)) <= -15.0) && (((x_7 + (-1.0 * _x_x_2)) <= -12.0) && (((x_0 + (-1.0 * _x_x_2)) <= -5.0) && ((x_1 + (-1.0 * _x_x_2)) <= -9.0)))))))))))))) && (((x_27 + (-1.0 * _x_x_2)) == -18.0) || (((x_26 + (-1.0 * _x_x_2)) == -9.0) || (((x_25 + (-1.0 * _x_x_2)) == -18.0) || (((x_24 + (-1.0 * _x_x_2)) == -2.0) || (((x_23 + (-1.0 * _x_x_2)) == -15.0) || (((x_21 + (-1.0 * _x_x_2)) == -15.0) || (((x_17 + (-1.0 * _x_x_2)) == -14.0) || (((x_15 + (-1.0 * _x_x_2)) == -16.0) || (((x_13 + (-1.0 * _x_x_2)) == -2.0) || (((x_9 + (-1.0 * _x_x_2)) == -10.0) || (((x_8 + (-1.0 * _x_x_2)) == -15.0) || (((x_7 + (-1.0 * _x_x_2)) == -12.0) || (((x_0 + (-1.0 * _x_x_2)) == -5.0) || ((x_1 + (-1.0 * _x_x_2)) == -9.0)))))))))))))))) && ((((x_27 + (-1.0 * _x_x_3)) <= -10.0) && (((x_26 + (-1.0 * _x_x_3)) <= -9.0) && (((x_23 + (-1.0 * _x_x_3)) <= -15.0) && (((x_22 + (-1.0 * _x_x_3)) <= -2.0) && (((x_21 + (-1.0 * _x_x_3)) <= -6.0) && (((x_18 + (-1.0 * _x_x_3)) <= -18.0) && (((x_17 + (-1.0 * _x_x_3)) <= -17.0) && (((x_16 + (-1.0 * _x_x_3)) <= -7.0) && (((x_15 + (-1.0 * _x_x_3)) <= -14.0) && (((x_12 + (-1.0 * _x_x_3)) <= -8.0) && (((x_9 + (-1.0 * _x_x_3)) <= -10.0) && (((x_5 + (-1.0 * _x_x_3)) <= -4.0) && (((x_1 + (-1.0 * _x_x_3)) <= -15.0) && ((x_2 + (-1.0 * _x_x_3)) <= -9.0)))))))))))))) && (((x_27 + (-1.0 * _x_x_3)) == -10.0) || (((x_26 + (-1.0 * _x_x_3)) == -9.0) || (((x_23 + (-1.0 * _x_x_3)) == -15.0) || (((x_22 + (-1.0 * _x_x_3)) == -2.0) || (((x_21 + (-1.0 * _x_x_3)) == -6.0) || (((x_18 + (-1.0 * _x_x_3)) == -18.0) || (((x_17 + (-1.0 * _x_x_3)) == -17.0) || (((x_16 + (-1.0 * _x_x_3)) == -7.0) || (((x_15 + (-1.0 * _x_x_3)) == -14.0) || (((x_12 + (-1.0 * _x_x_3)) == -8.0) || (((x_9 + (-1.0 * _x_x_3)) == -10.0) || (((x_5 + (-1.0 * _x_x_3)) == -4.0) || (((x_1 + (-1.0 * _x_x_3)) == -15.0) || ((x_2 + (-1.0 * _x_x_3)) == -9.0)))))))))))))))) && ((((x_27 + (-1.0 * _x_x_4)) <= -13.0) && (((x_24 + (-1.0 * _x_x_4)) <= -12.0) && (((x_20 + (-1.0 * _x_x_4)) <= -14.0) && (((x_19 + (-1.0 * _x_x_4)) <= -16.0) && (((x_18 + (-1.0 * _x_x_4)) <= -8.0) && (((x_14 + (-1.0 * _x_x_4)) <= -14.0) && (((x_11 + (-1.0 * _x_x_4)) <= -9.0) && (((x_10 + (-1.0 * _x_x_4)) <= -12.0) && (((x_8 + (-1.0 * _x_x_4)) <= -3.0) && (((x_7 + (-1.0 * _x_x_4)) <= -9.0) && (((x_6 + (-1.0 * _x_x_4)) <= -2.0) && (((x_5 + (-1.0 * _x_x_4)) <= -12.0) && (((x_0 + (-1.0 * _x_x_4)) <= -19.0) && ((x_2 + (-1.0 * _x_x_4)) <= -10.0)))))))))))))) && (((x_27 + (-1.0 * _x_x_4)) == -13.0) || (((x_24 + (-1.0 * _x_x_4)) == -12.0) || (((x_20 + (-1.0 * _x_x_4)) == -14.0) || (((x_19 + (-1.0 * _x_x_4)) == -16.0) || (((x_18 + (-1.0 * _x_x_4)) == -8.0) || (((x_14 + (-1.0 * _x_x_4)) == -14.0) || (((x_11 + (-1.0 * _x_x_4)) == -9.0) || (((x_10 + (-1.0 * _x_x_4)) == -12.0) || (((x_8 + (-1.0 * _x_x_4)) == -3.0) || (((x_7 + (-1.0 * _x_x_4)) == -9.0) || (((x_6 + (-1.0 * _x_x_4)) == -2.0) || (((x_5 + (-1.0 * _x_x_4)) == -12.0) || (((x_0 + (-1.0 * _x_x_4)) == -19.0) || ((x_2 + (-1.0 * _x_x_4)) == -10.0)))))))))))))))) && ((((x_27 + (-1.0 * _x_x_5)) <= -9.0) && (((x_24 + (-1.0 * _x_x_5)) <= -18.0) && (((x_23 + (-1.0 * _x_x_5)) <= -1.0) && (((x_21 + (-1.0 * _x_x_5)) <= -1.0) && (((x_20 + (-1.0 * _x_x_5)) <= -5.0) && (((x_16 + (-1.0 * _x_x_5)) <= -8.0) && (((x_15 + (-1.0 * _x_x_5)) <= -2.0) && (((x_13 + (-1.0 * _x_x_5)) <= -14.0) && (((x_7 + (-1.0 * _x_x_5)) <= -4.0) && (((x_6 + (-1.0 * _x_x_5)) <= -14.0) && (((x_4 + (-1.0 * _x_x_5)) <= -19.0) && (((x_3 + (-1.0 * _x_x_5)) <= -20.0) && (((x_1 + (-1.0 * _x_x_5)) <= -16.0) && ((x_2 + (-1.0 * _x_x_5)) <= -16.0)))))))))))))) && (((x_27 + (-1.0 * _x_x_5)) == -9.0) || (((x_24 + (-1.0 * _x_x_5)) == -18.0) || (((x_23 + (-1.0 * _x_x_5)) == -1.0) || (((x_21 + (-1.0 * _x_x_5)) == -1.0) || (((x_20 + (-1.0 * _x_x_5)) == -5.0) || (((x_16 + (-1.0 * _x_x_5)) == -8.0) || (((x_15 + (-1.0 * _x_x_5)) == -2.0) || (((x_13 + (-1.0 * _x_x_5)) == -14.0) || (((x_7 + (-1.0 * _x_x_5)) == -4.0) || (((x_6 + (-1.0 * _x_x_5)) == -14.0) || (((x_4 + (-1.0 * _x_x_5)) == -19.0) || (((x_3 + (-1.0 * _x_x_5)) == -20.0) || (((x_1 + (-1.0 * _x_x_5)) == -16.0) || ((x_2 + (-1.0 * _x_x_5)) == -16.0)))))))))))))))) && ((((x_27 + (-1.0 * _x_x_6)) <= -15.0) && (((x_26 + (-1.0 * _x_x_6)) <= -5.0) && (((x_24 + (-1.0 * _x_x_6)) <= -5.0) && (((x_21 + (-1.0 * _x_x_6)) <= -5.0) && (((x_20 + (-1.0 * _x_x_6)) <= -6.0) && (((x_19 + (-1.0 * _x_x_6)) <= -16.0) && (((x_16 + (-1.0 * _x_x_6)) <= -11.0) && (((x_14 + (-1.0 * _x_x_6)) <= -15.0) && (((x_11 + (-1.0 * _x_x_6)) <= -1.0) && (((x_8 + (-1.0 * _x_x_6)) <= -12.0) && (((x_7 + (-1.0 * _x_x_6)) <= -10.0) && (((x_3 + (-1.0 * _x_x_6)) <= -10.0) && (((x_0 + (-1.0 * _x_x_6)) <= -15.0) && ((x_2 + (-1.0 * _x_x_6)) <= -19.0)))))))))))))) && (((x_27 + (-1.0 * _x_x_6)) == -15.0) || (((x_26 + (-1.0 * _x_x_6)) == -5.0) || (((x_24 + (-1.0 * _x_x_6)) == -5.0) || (((x_21 + (-1.0 * _x_x_6)) == -5.0) || (((x_20 + (-1.0 * _x_x_6)) == -6.0) || (((x_19 + (-1.0 * _x_x_6)) == -16.0) || (((x_16 + (-1.0 * _x_x_6)) == -11.0) || (((x_14 + (-1.0 * _x_x_6)) == -15.0) || (((x_11 + (-1.0 * _x_x_6)) == -1.0) || (((x_8 + (-1.0 * _x_x_6)) == -12.0) || (((x_7 + (-1.0 * _x_x_6)) == -10.0) || (((x_3 + (-1.0 * _x_x_6)) == -10.0) || (((x_0 + (-1.0 * _x_x_6)) == -15.0) || ((x_2 + (-1.0 * _x_x_6)) == -19.0)))))))))))))))) && ((((x_24 + (-1.0 * _x_x_7)) <= -16.0) && (((x_23 + (-1.0 * _x_x_7)) <= -7.0) && (((x_22 + (-1.0 * _x_x_7)) <= -2.0) && (((x_21 + (-1.0 * _x_x_7)) <= -13.0) && (((x_19 + (-1.0 * _x_x_7)) <= -14.0) && (((x_18 + (-1.0 * _x_x_7)) <= -10.0) && (((x_17 + (-1.0 * _x_x_7)) <= -13.0) && (((x_16 + (-1.0 * _x_x_7)) <= -2.0) && (((x_15 + (-1.0 * _x_x_7)) <= -2.0) && (((x_11 + (-1.0 * _x_x_7)) <= -17.0) && (((x_10 + (-1.0 * _x_x_7)) <= -8.0) && (((x_6 + (-1.0 * _x_x_7)) <= -20.0) && (((x_0 + (-1.0 * _x_x_7)) <= -3.0) && ((x_3 + (-1.0 * _x_x_7)) <= -16.0)))))))))))))) && (((x_24 + (-1.0 * _x_x_7)) == -16.0) || (((x_23 + (-1.0 * _x_x_7)) == -7.0) || (((x_22 + (-1.0 * _x_x_7)) == -2.0) || (((x_21 + (-1.0 * _x_x_7)) == -13.0) || (((x_19 + (-1.0 * _x_x_7)) == -14.0) || (((x_18 + (-1.0 * _x_x_7)) == -10.0) || (((x_17 + (-1.0 * _x_x_7)) == -13.0) || (((x_16 + (-1.0 * _x_x_7)) == -2.0) || (((x_15 + (-1.0 * _x_x_7)) == -2.0) || (((x_11 + (-1.0 * _x_x_7)) == -17.0) || (((x_10 + (-1.0 * _x_x_7)) == -8.0) || (((x_6 + (-1.0 * _x_x_7)) == -20.0) || (((x_0 + (-1.0 * _x_x_7)) == -3.0) || ((x_3 + (-1.0 * _x_x_7)) == -16.0)))))))))))))))) && ((((x_27 + (-1.0 * _x_x_8)) <= -5.0) && (((x_25 + (-1.0 * _x_x_8)) <= -8.0) && (((x_24 + (-1.0 * _x_x_8)) <= -18.0) && (((x_23 + (-1.0 * _x_x_8)) <= -3.0) && (((x_19 + (-1.0 * _x_x_8)) <= -18.0) && (((x_18 + (-1.0 * _x_x_8)) <= -17.0) && (((x_16 + (-1.0 * _x_x_8)) <= -16.0) && (((x_14 + (-1.0 * _x_x_8)) <= -7.0) && (((x_13 + (-1.0 * _x_x_8)) <= -10.0) && (((x_10 + (-1.0 * _x_x_8)) <= -6.0) && (((x_5 + (-1.0 * _x_x_8)) <= -12.0) && (((x_3 + (-1.0 * _x_x_8)) <= -13.0) && (((x_0 + (-1.0 * _x_x_8)) <= -11.0) && ((x_2 + (-1.0 * _x_x_8)) <= -9.0)))))))))))))) && (((x_27 + (-1.0 * _x_x_8)) == -5.0) || (((x_25 + (-1.0 * _x_x_8)) == -8.0) || (((x_24 + (-1.0 * _x_x_8)) == -18.0) || (((x_23 + (-1.0 * _x_x_8)) == -3.0) || (((x_19 + (-1.0 * _x_x_8)) == -18.0) || (((x_18 + (-1.0 * _x_x_8)) == -17.0) || (((x_16 + (-1.0 * _x_x_8)) == -16.0) || (((x_14 + (-1.0 * _x_x_8)) == -7.0) || (((x_13 + (-1.0 * _x_x_8)) == -10.0) || (((x_10 + (-1.0 * _x_x_8)) == -6.0) || (((x_5 + (-1.0 * _x_x_8)) == -12.0) || (((x_3 + (-1.0 * _x_x_8)) == -13.0) || (((x_0 + (-1.0 * _x_x_8)) == -11.0) || ((x_2 + (-1.0 * _x_x_8)) == -9.0)))))))))))))))) && ((((x_27 + (-1.0 * _x_x_9)) <= -3.0) && (((x_23 + (-1.0 * _x_x_9)) <= -3.0) && (((x_22 + (-1.0 * _x_x_9)) <= -3.0) && (((x_21 + (-1.0 * _x_x_9)) <= -17.0) && (((x_18 + (-1.0 * _x_x_9)) <= -4.0) && (((x_14 + (-1.0 * _x_x_9)) <= -7.0) && (((x_12 + (-1.0 * _x_x_9)) <= -5.0) && (((x_10 + (-1.0 * _x_x_9)) <= -2.0) && (((x_8 + (-1.0 * _x_x_9)) <= -3.0) && (((x_7 + (-1.0 * _x_x_9)) <= -3.0) && (((x_6 + (-1.0 * _x_x_9)) <= -11.0) && (((x_3 + (-1.0 * _x_x_9)) <= -6.0) && (((x_0 + (-1.0 * _x_x_9)) <= -7.0) && ((x_2 + (-1.0 * _x_x_9)) <= -5.0)))))))))))))) && (((x_27 + (-1.0 * _x_x_9)) == -3.0) || (((x_23 + (-1.0 * _x_x_9)) == -3.0) || (((x_22 + (-1.0 * _x_x_9)) == -3.0) || (((x_21 + (-1.0 * _x_x_9)) == -17.0) || (((x_18 + (-1.0 * _x_x_9)) == -4.0) || (((x_14 + (-1.0 * _x_x_9)) == -7.0) || (((x_12 + (-1.0 * _x_x_9)) == -5.0) || (((x_10 + (-1.0 * _x_x_9)) == -2.0) || (((x_8 + (-1.0 * _x_x_9)) == -3.0) || (((x_7 + (-1.0 * _x_x_9)) == -3.0) || (((x_6 + (-1.0 * _x_x_9)) == -11.0) || (((x_3 + (-1.0 * _x_x_9)) == -6.0) || (((x_0 + (-1.0 * _x_x_9)) == -7.0) || ((x_2 + (-1.0 * _x_x_9)) == -5.0)))))))))))))))) && ((((x_26 + (-1.0 * _x_x_10)) <= -13.0) && (((x_25 + (-1.0 * _x_x_10)) <= -17.0) && (((x_24 + (-1.0 * _x_x_10)) <= -9.0) && (((x_22 + (-1.0 * _x_x_10)) <= -11.0) && (((x_21 + (-1.0 * _x_x_10)) <= -14.0) && (((x_18 + (-1.0 * _x_x_10)) <= -14.0) && (((x_17 + (-1.0 * _x_x_10)) <= -14.0) && (((x_15 + (-1.0 * _x_x_10)) <= -10.0) && (((x_14 + (-1.0 * _x_x_10)) <= -12.0) && (((x_12 + (-1.0 * _x_x_10)) <= -10.0) && (((x_11 + (-1.0 * _x_x_10)) <= -16.0) && (((x_6 + (-1.0 * _x_x_10)) <= -17.0) && (((x_0 + (-1.0 * _x_x_10)) <= -14.0) && ((x_3 + (-1.0 * _x_x_10)) <= -15.0)))))))))))))) && (((x_26 + (-1.0 * _x_x_10)) == -13.0) || (((x_25 + (-1.0 * _x_x_10)) == -17.0) || (((x_24 + (-1.0 * _x_x_10)) == -9.0) || (((x_22 + (-1.0 * _x_x_10)) == -11.0) || (((x_21 + (-1.0 * _x_x_10)) == -14.0) || (((x_18 + (-1.0 * _x_x_10)) == -14.0) || (((x_17 + (-1.0 * _x_x_10)) == -14.0) || (((x_15 + (-1.0 * _x_x_10)) == -10.0) || (((x_14 + (-1.0 * _x_x_10)) == -12.0) || (((x_12 + (-1.0 * _x_x_10)) == -10.0) || (((x_11 + (-1.0 * _x_x_10)) == -16.0) || (((x_6 + (-1.0 * _x_x_10)) == -17.0) || (((x_0 + (-1.0 * _x_x_10)) == -14.0) || ((x_3 + (-1.0 * _x_x_10)) == -15.0)))))))))))))))) && ((((x_27 + (-1.0 * _x_x_11)) <= -15.0) && (((x_21 + (-1.0 * _x_x_11)) <= -20.0) && (((x_20 + (-1.0 * _x_x_11)) <= -3.0) && (((x_18 + (-1.0 * _x_x_11)) <= -15.0) && (((x_15 + (-1.0 * _x_x_11)) <= -10.0) && (((x_14 + (-1.0 * _x_x_11)) <= -14.0) && (((x_13 + (-1.0 * _x_x_11)) <= -5.0) && (((x_11 + (-1.0 * _x_x_11)) <= -14.0) && (((x_9 + (-1.0 * _x_x_11)) <= -6.0) && (((x_8 + (-1.0 * _x_x_11)) <= -18.0) && (((x_7 + (-1.0 * _x_x_11)) <= -7.0) && (((x_5 + (-1.0 * _x_x_11)) <= -2.0) && (((x_2 + (-1.0 * _x_x_11)) <= -2.0) && ((x_3 + (-1.0 * _x_x_11)) <= -12.0)))))))))))))) && (((x_27 + (-1.0 * _x_x_11)) == -15.0) || (((x_21 + (-1.0 * _x_x_11)) == -20.0) || (((x_20 + (-1.0 * _x_x_11)) == -3.0) || (((x_18 + (-1.0 * _x_x_11)) == -15.0) || (((x_15 + (-1.0 * _x_x_11)) == -10.0) || (((x_14 + (-1.0 * _x_x_11)) == -14.0) || (((x_13 + (-1.0 * _x_x_11)) == -5.0) || (((x_11 + (-1.0 * _x_x_11)) == -14.0) || (((x_9 + (-1.0 * _x_x_11)) == -6.0) || (((x_8 + (-1.0 * _x_x_11)) == -18.0) || (((x_7 + (-1.0 * _x_x_11)) == -7.0) || (((x_5 + (-1.0 * _x_x_11)) == -2.0) || (((x_2 + (-1.0 * _x_x_11)) == -2.0) || ((x_3 + (-1.0 * _x_x_11)) == -12.0)))))))))))))))) && ((((x_25 + (-1.0 * _x_x_12)) <= -8.0) && (((x_22 + (-1.0 * _x_x_12)) <= -16.0) && (((x_21 + (-1.0 * _x_x_12)) <= -7.0) && (((x_19 + (-1.0 * _x_x_12)) <= -9.0) && (((x_18 + (-1.0 * _x_x_12)) <= -20.0) && (((x_14 + (-1.0 * _x_x_12)) <= -20.0) && (((x_12 + (-1.0 * _x_x_12)) <= -16.0) && (((x_8 + (-1.0 * _x_x_12)) <= -17.0) && (((x_7 + (-1.0 * _x_x_12)) <= -17.0) && (((x_6 + (-1.0 * _x_x_12)) <= -2.0) && (((x_5 + (-1.0 * _x_x_12)) <= -11.0) && (((x_2 + (-1.0 * _x_x_12)) <= -2.0) && (((x_0 + (-1.0 * _x_x_12)) <= -1.0) && ((x_1 + (-1.0 * _x_x_12)) <= -19.0)))))))))))))) && (((x_25 + (-1.0 * _x_x_12)) == -8.0) || (((x_22 + (-1.0 * _x_x_12)) == -16.0) || (((x_21 + (-1.0 * _x_x_12)) == -7.0) || (((x_19 + (-1.0 * _x_x_12)) == -9.0) || (((x_18 + (-1.0 * _x_x_12)) == -20.0) || (((x_14 + (-1.0 * _x_x_12)) == -20.0) || (((x_12 + (-1.0 * _x_x_12)) == -16.0) || (((x_8 + (-1.0 * _x_x_12)) == -17.0) || (((x_7 + (-1.0 * _x_x_12)) == -17.0) || (((x_6 + (-1.0 * _x_x_12)) == -2.0) || (((x_5 + (-1.0 * _x_x_12)) == -11.0) || (((x_2 + (-1.0 * _x_x_12)) == -2.0) || (((x_0 + (-1.0 * _x_x_12)) == -1.0) || ((x_1 + (-1.0 * _x_x_12)) == -19.0)))))))))))))))) && ((((x_27 + (-1.0 * _x_x_13)) <= -20.0) && (((x_25 + (-1.0 * _x_x_13)) <= -18.0) && (((x_23 + (-1.0 * _x_x_13)) <= -20.0) && (((x_22 + (-1.0 * _x_x_13)) <= -14.0) && (((x_20 + (-1.0 * _x_x_13)) <= -9.0) && (((x_10 + (-1.0 * _x_x_13)) <= -6.0) && (((x_9 + (-1.0 * _x_x_13)) <= -18.0) && (((x_8 + (-1.0 * _x_x_13)) <= -7.0) && (((x_6 + (-1.0 * _x_x_13)) <= -11.0) && (((x_5 + (-1.0 * _x_x_13)) <= -20.0) && (((x_4 + (-1.0 * _x_x_13)) <= -11.0) && (((x_3 + (-1.0 * _x_x_13)) <= -19.0) && (((x_0 + (-1.0 * _x_x_13)) <= -13.0) && ((x_1 + (-1.0 * _x_x_13)) <= -5.0)))))))))))))) && (((x_27 + (-1.0 * _x_x_13)) == -20.0) || (((x_25 + (-1.0 * _x_x_13)) == -18.0) || (((x_23 + (-1.0 * _x_x_13)) == -20.0) || (((x_22 + (-1.0 * _x_x_13)) == -14.0) || (((x_20 + (-1.0 * _x_x_13)) == -9.0) || (((x_10 + (-1.0 * _x_x_13)) == -6.0) || (((x_9 + (-1.0 * _x_x_13)) == -18.0) || (((x_8 + (-1.0 * _x_x_13)) == -7.0) || (((x_6 + (-1.0 * _x_x_13)) == -11.0) || (((x_5 + (-1.0 * _x_x_13)) == -20.0) || (((x_4 + (-1.0 * _x_x_13)) == -11.0) || (((x_3 + (-1.0 * _x_x_13)) == -19.0) || (((x_0 + (-1.0 * _x_x_13)) == -13.0) || ((x_1 + (-1.0 * _x_x_13)) == -5.0)))))))))))))))) && ((((x_27 + (-1.0 * _x_x_14)) <= -10.0) && (((x_23 + (-1.0 * _x_x_14)) <= -18.0) && (((x_22 + (-1.0 * _x_x_14)) <= -11.0) && (((x_21 + (-1.0 * _x_x_14)) <= -5.0) && (((x_20 + (-1.0 * _x_x_14)) <= -13.0) && (((x_17 + (-1.0 * _x_x_14)) <= -1.0) && (((x_16 + (-1.0 * _x_x_14)) <= -7.0) && (((x_14 + (-1.0 * _x_x_14)) <= -6.0) && (((x_10 + (-1.0 * _x_x_14)) <= -16.0) && (((x_5 + (-1.0 * _x_x_14)) <= -2.0) && (((x_4 + (-1.0 * _x_x_14)) <= -1.0) && (((x_2 + (-1.0 * _x_x_14)) <= -1.0) && (((x_0 + (-1.0 * _x_x_14)) <= -19.0) && ((x_1 + (-1.0 * _x_x_14)) <= -11.0)))))))))))))) && (((x_27 + (-1.0 * _x_x_14)) == -10.0) || (((x_23 + (-1.0 * _x_x_14)) == -18.0) || (((x_22 + (-1.0 * _x_x_14)) == -11.0) || (((x_21 + (-1.0 * _x_x_14)) == -5.0) || (((x_20 + (-1.0 * _x_x_14)) == -13.0) || (((x_17 + (-1.0 * _x_x_14)) == -1.0) || (((x_16 + (-1.0 * _x_x_14)) == -7.0) || (((x_14 + (-1.0 * _x_x_14)) == -6.0) || (((x_10 + (-1.0 * _x_x_14)) == -16.0) || (((x_5 + (-1.0 * _x_x_14)) == -2.0) || (((x_4 + (-1.0 * _x_x_14)) == -1.0) || (((x_2 + (-1.0 * _x_x_14)) == -1.0) || (((x_0 + (-1.0 * _x_x_14)) == -19.0) || ((x_1 + (-1.0 * _x_x_14)) == -11.0)))))))))))))))) && ((((x_26 + (-1.0 * _x_x_15)) <= -16.0) && (((x_23 + (-1.0 * _x_x_15)) <= -5.0) && (((x_22 + (-1.0 * _x_x_15)) <= -14.0) && (((x_21 + (-1.0 * _x_x_15)) <= -13.0) && (((x_19 + (-1.0 * _x_x_15)) <= -1.0) && (((x_18 + (-1.0 * _x_x_15)) <= -19.0) && (((x_17 + (-1.0 * _x_x_15)) <= -4.0) && (((x_16 + (-1.0 * _x_x_15)) <= -10.0) && (((x_13 + (-1.0 * _x_x_15)) <= -12.0) && (((x_10 + (-1.0 * _x_x_15)) <= -8.0) && (((x_8 + (-1.0 * _x_x_15)) <= -17.0) && (((x_4 + (-1.0 * _x_x_15)) <= -9.0) && (((x_1 + (-1.0 * _x_x_15)) <= -6.0) && ((x_2 + (-1.0 * _x_x_15)) <= -1.0)))))))))))))) && (((x_26 + (-1.0 * _x_x_15)) == -16.0) || (((x_23 + (-1.0 * _x_x_15)) == -5.0) || (((x_22 + (-1.0 * _x_x_15)) == -14.0) || (((x_21 + (-1.0 * _x_x_15)) == -13.0) || (((x_19 + (-1.0 * _x_x_15)) == -1.0) || (((x_18 + (-1.0 * _x_x_15)) == -19.0) || (((x_17 + (-1.0 * _x_x_15)) == -4.0) || (((x_16 + (-1.0 * _x_x_15)) == -10.0) || (((x_13 + (-1.0 * _x_x_15)) == -12.0) || (((x_10 + (-1.0 * _x_x_15)) == -8.0) || (((x_8 + (-1.0 * _x_x_15)) == -17.0) || (((x_4 + (-1.0 * _x_x_15)) == -9.0) || (((x_1 + (-1.0 * _x_x_15)) == -6.0) || ((x_2 + (-1.0 * _x_x_15)) == -1.0)))))))))))))))) && ((((x_27 + (-1.0 * _x_x_16)) <= -10.0) && (((x_25 + (-1.0 * _x_x_16)) <= -12.0) && (((x_22 + (-1.0 * _x_x_16)) <= -6.0) && (((x_21 + (-1.0 * _x_x_16)) <= -17.0) && (((x_19 + (-1.0 * _x_x_16)) <= -5.0) && (((x_18 + (-1.0 * _x_x_16)) <= -2.0) && (((x_17 + (-1.0 * _x_x_16)) <= -13.0) && (((x_14 + (-1.0 * _x_x_16)) <= -5.0) && (((x_9 + (-1.0 * _x_x_16)) <= -1.0) && (((x_6 + (-1.0 * _x_x_16)) <= -12.0) && (((x_4 + (-1.0 * _x_x_16)) <= -3.0) && (((x_3 + (-1.0 * _x_x_16)) <= -19.0) && (((x_1 + (-1.0 * _x_x_16)) <= -1.0) && ((x_2 + (-1.0 * _x_x_16)) <= -16.0)))))))))))))) && (((x_27 + (-1.0 * _x_x_16)) == -10.0) || (((x_25 + (-1.0 * _x_x_16)) == -12.0) || (((x_22 + (-1.0 * _x_x_16)) == -6.0) || (((x_21 + (-1.0 * _x_x_16)) == -17.0) || (((x_19 + (-1.0 * _x_x_16)) == -5.0) || (((x_18 + (-1.0 * _x_x_16)) == -2.0) || (((x_17 + (-1.0 * _x_x_16)) == -13.0) || (((x_14 + (-1.0 * _x_x_16)) == -5.0) || (((x_9 + (-1.0 * _x_x_16)) == -1.0) || (((x_6 + (-1.0 * _x_x_16)) == -12.0) || (((x_4 + (-1.0 * _x_x_16)) == -3.0) || (((x_3 + (-1.0 * _x_x_16)) == -19.0) || (((x_1 + (-1.0 * _x_x_16)) == -1.0) || ((x_2 + (-1.0 * _x_x_16)) == -16.0)))))))))))))))) && ((((x_25 + (-1.0 * _x_x_17)) <= -12.0) && (((x_22 + (-1.0 * _x_x_17)) <= -15.0) && (((x_20 + (-1.0 * _x_x_17)) <= -13.0) && (((x_17 + (-1.0 * _x_x_17)) <= -6.0) && (((x_15 + (-1.0 * _x_x_17)) <= -13.0) && (((x_13 + (-1.0 * _x_x_17)) <= -3.0) && (((x_12 + (-1.0 * _x_x_17)) <= -1.0) && (((x_9 + (-1.0 * _x_x_17)) <= -5.0) && (((x_7 + (-1.0 * _x_x_17)) <= -17.0) && (((x_5 + (-1.0 * _x_x_17)) <= -15.0) && (((x_4 + (-1.0 * _x_x_17)) <= -6.0) && (((x_3 + (-1.0 * _x_x_17)) <= -12.0) && (((x_0 + (-1.0 * _x_x_17)) <= -10.0) && ((x_2 + (-1.0 * _x_x_17)) <= -8.0)))))))))))))) && (((x_25 + (-1.0 * _x_x_17)) == -12.0) || (((x_22 + (-1.0 * _x_x_17)) == -15.0) || (((x_20 + (-1.0 * _x_x_17)) == -13.0) || (((x_17 + (-1.0 * _x_x_17)) == -6.0) || (((x_15 + (-1.0 * _x_x_17)) == -13.0) || (((x_13 + (-1.0 * _x_x_17)) == -3.0) || (((x_12 + (-1.0 * _x_x_17)) == -1.0) || (((x_9 + (-1.0 * _x_x_17)) == -5.0) || (((x_7 + (-1.0 * _x_x_17)) == -17.0) || (((x_5 + (-1.0 * _x_x_17)) == -15.0) || (((x_4 + (-1.0 * _x_x_17)) == -6.0) || (((x_3 + (-1.0 * _x_x_17)) == -12.0) || (((x_0 + (-1.0 * _x_x_17)) == -10.0) || ((x_2 + (-1.0 * _x_x_17)) == -8.0)))))))))))))))) && ((((x_26 + (-1.0 * _x_x_18)) <= -7.0) && (((x_25 + (-1.0 * _x_x_18)) <= -20.0) && (((x_23 + (-1.0 * _x_x_18)) <= -19.0) && (((x_22 + (-1.0 * _x_x_18)) <= -20.0) && (((x_18 + (-1.0 * _x_x_18)) <= -4.0) && (((x_16 + (-1.0 * _x_x_18)) <= -3.0) && (((x_12 + (-1.0 * _x_x_18)) <= -16.0) && (((x_11 + (-1.0 * _x_x_18)) <= -16.0) && (((x_9 + (-1.0 * _x_x_18)) <= -13.0) && (((x_8 + (-1.0 * _x_x_18)) <= -5.0) && (((x_6 + (-1.0 * _x_x_18)) <= -3.0) && (((x_2 + (-1.0 * _x_x_18)) <= -12.0) && (((x_0 + (-1.0 * _x_x_18)) <= -19.0) && ((x_1 + (-1.0 * _x_x_18)) <= -3.0)))))))))))))) && (((x_26 + (-1.0 * _x_x_18)) == -7.0) || (((x_25 + (-1.0 * _x_x_18)) == -20.0) || (((x_23 + (-1.0 * _x_x_18)) == -19.0) || (((x_22 + (-1.0 * _x_x_18)) == -20.0) || (((x_18 + (-1.0 * _x_x_18)) == -4.0) || (((x_16 + (-1.0 * _x_x_18)) == -3.0) || (((x_12 + (-1.0 * _x_x_18)) == -16.0) || (((x_11 + (-1.0 * _x_x_18)) == -16.0) || (((x_9 + (-1.0 * _x_x_18)) == -13.0) || (((x_8 + (-1.0 * _x_x_18)) == -5.0) || (((x_6 + (-1.0 * _x_x_18)) == -3.0) || (((x_2 + (-1.0 * _x_x_18)) == -12.0) || (((x_0 + (-1.0 * _x_x_18)) == -19.0) || ((x_1 + (-1.0 * _x_x_18)) == -3.0)))))))))))))))) && ((((x_22 + (-1.0 * _x_x_19)) <= -9.0) && (((x_21 + (-1.0 * _x_x_19)) <= -14.0) && (((x_20 + (-1.0 * _x_x_19)) <= -6.0) && (((x_19 + (-1.0 * _x_x_19)) <= -13.0) && (((x_17 + (-1.0 * _x_x_19)) <= -20.0) && (((x_13 + (-1.0 * _x_x_19)) <= -3.0) && (((x_12 + (-1.0 * _x_x_19)) <= -14.0) && (((x_10 + (-1.0 * _x_x_19)) <= -7.0) && (((x_9 + (-1.0 * _x_x_19)) <= -6.0) && (((x_8 + (-1.0 * _x_x_19)) <= -7.0) && (((x_6 + (-1.0 * _x_x_19)) <= -12.0) && (((x_3 + (-1.0 * _x_x_19)) <= -16.0) && (((x_1 + (-1.0 * _x_x_19)) <= -20.0) && ((x_2 + (-1.0 * _x_x_19)) <= -13.0)))))))))))))) && (((x_22 + (-1.0 * _x_x_19)) == -9.0) || (((x_21 + (-1.0 * _x_x_19)) == -14.0) || (((x_20 + (-1.0 * _x_x_19)) == -6.0) || (((x_19 + (-1.0 * _x_x_19)) == -13.0) || (((x_17 + (-1.0 * _x_x_19)) == -20.0) || (((x_13 + (-1.0 * _x_x_19)) == -3.0) || (((x_12 + (-1.0 * _x_x_19)) == -14.0) || (((x_10 + (-1.0 * _x_x_19)) == -7.0) || (((x_9 + (-1.0 * _x_x_19)) == -6.0) || (((x_8 + (-1.0 * _x_x_19)) == -7.0) || (((x_6 + (-1.0 * _x_x_19)) == -12.0) || (((x_3 + (-1.0 * _x_x_19)) == -16.0) || (((x_1 + (-1.0 * _x_x_19)) == -20.0) || ((x_2 + (-1.0 * _x_x_19)) == -13.0)))))))))))))))) && ((((x_24 + (-1.0 * _x_x_20)) <= -17.0) && (((x_23 + (-1.0 * _x_x_20)) <= -3.0) && (((x_22 + (-1.0 * _x_x_20)) <= -5.0) && (((x_21 + (-1.0 * _x_x_20)) <= -7.0) && (((x_20 + (-1.0 * _x_x_20)) <= -16.0) && (((x_16 + (-1.0 * _x_x_20)) <= -14.0) && (((x_15 + (-1.0 * _x_x_20)) <= -11.0) && (((x_12 + (-1.0 * _x_x_20)) <= -8.0) && (((x_11 + (-1.0 * _x_x_20)) <= -8.0) && (((x_9 + (-1.0 * _x_x_20)) <= -20.0) && (((x_6 + (-1.0 * _x_x_20)) <= -13.0) && (((x_5 + (-1.0 * _x_x_20)) <= -1.0) && (((x_3 + (-1.0 * _x_x_20)) <= -20.0) && ((x_4 + (-1.0 * _x_x_20)) <= -19.0)))))))))))))) && (((x_24 + (-1.0 * _x_x_20)) == -17.0) || (((x_23 + (-1.0 * _x_x_20)) == -3.0) || (((x_22 + (-1.0 * _x_x_20)) == -5.0) || (((x_21 + (-1.0 * _x_x_20)) == -7.0) || (((x_20 + (-1.0 * _x_x_20)) == -16.0) || (((x_16 + (-1.0 * _x_x_20)) == -14.0) || (((x_15 + (-1.0 * _x_x_20)) == -11.0) || (((x_12 + (-1.0 * _x_x_20)) == -8.0) || (((x_11 + (-1.0 * _x_x_20)) == -8.0) || (((x_9 + (-1.0 * _x_x_20)) == -20.0) || (((x_6 + (-1.0 * _x_x_20)) == -13.0) || (((x_5 + (-1.0 * _x_x_20)) == -1.0) || (((x_3 + (-1.0 * _x_x_20)) == -20.0) || ((x_4 + (-1.0 * _x_x_20)) == -19.0)))))))))))))))) && ((((x_26 + (-1.0 * _x_x_21)) <= -20.0) && (((x_24 + (-1.0 * _x_x_21)) <= -7.0) && (((x_23 + (-1.0 * _x_x_21)) <= -10.0) && (((x_22 + (-1.0 * _x_x_21)) <= -19.0) && (((x_18 + (-1.0 * _x_x_21)) <= -8.0) && (((x_16 + (-1.0 * _x_x_21)) <= -2.0) && (((x_14 + (-1.0 * _x_x_21)) <= -16.0) && (((x_11 + (-1.0 * _x_x_21)) <= -13.0) && (((x_10 + (-1.0 * _x_x_21)) <= -4.0) && (((x_6 + (-1.0 * _x_x_21)) <= -15.0) && (((x_4 + (-1.0 * _x_x_21)) <= -12.0) && (((x_3 + (-1.0 * _x_x_21)) <= -7.0) && (((x_0 + (-1.0 * _x_x_21)) <= -13.0) && ((x_1 + (-1.0 * _x_x_21)) <= -16.0)))))))))))))) && (((x_26 + (-1.0 * _x_x_21)) == -20.0) || (((x_24 + (-1.0 * _x_x_21)) == -7.0) || (((x_23 + (-1.0 * _x_x_21)) == -10.0) || (((x_22 + (-1.0 * _x_x_21)) == -19.0) || (((x_18 + (-1.0 * _x_x_21)) == -8.0) || (((x_16 + (-1.0 * _x_x_21)) == -2.0) || (((x_14 + (-1.0 * _x_x_21)) == -16.0) || (((x_11 + (-1.0 * _x_x_21)) == -13.0) || (((x_10 + (-1.0 * _x_x_21)) == -4.0) || (((x_6 + (-1.0 * _x_x_21)) == -15.0) || (((x_4 + (-1.0 * _x_x_21)) == -12.0) || (((x_3 + (-1.0 * _x_x_21)) == -7.0) || (((x_0 + (-1.0 * _x_x_21)) == -13.0) || ((x_1 + (-1.0 * _x_x_21)) == -16.0)))))))))))))))) && ((((x_27 + (-1.0 * _x_x_22)) <= -3.0) && (((x_25 + (-1.0 * _x_x_22)) <= -20.0) && (((x_24 + (-1.0 * _x_x_22)) <= -7.0) && (((x_21 + (-1.0 * _x_x_22)) <= -13.0) && (((x_18 + (-1.0 * _x_x_22)) <= -15.0) && (((x_17 + (-1.0 * _x_x_22)) <= -20.0) && (((x_16 + (-1.0 * _x_x_22)) <= -3.0) && (((x_15 + (-1.0 * _x_x_22)) <= -1.0) && (((x_13 + (-1.0 * _x_x_22)) <= -20.0) && (((x_8 + (-1.0 * _x_x_22)) <= -5.0) && (((x_7 + (-1.0 * _x_x_22)) <= -13.0) && (((x_6 + (-1.0 * _x_x_22)) <= -20.0) && (((x_4 + (-1.0 * _x_x_22)) <= -7.0) && ((x_5 + (-1.0 * _x_x_22)) <= -5.0)))))))))))))) && (((x_27 + (-1.0 * _x_x_22)) == -3.0) || (((x_25 + (-1.0 * _x_x_22)) == -20.0) || (((x_24 + (-1.0 * _x_x_22)) == -7.0) || (((x_21 + (-1.0 * _x_x_22)) == -13.0) || (((x_18 + (-1.0 * _x_x_22)) == -15.0) || (((x_17 + (-1.0 * _x_x_22)) == -20.0) || (((x_16 + (-1.0 * _x_x_22)) == -3.0) || (((x_15 + (-1.0 * _x_x_22)) == -1.0) || (((x_13 + (-1.0 * _x_x_22)) == -20.0) || (((x_8 + (-1.0 * _x_x_22)) == -5.0) || (((x_7 + (-1.0 * _x_x_22)) == -13.0) || (((x_6 + (-1.0 * _x_x_22)) == -20.0) || (((x_4 + (-1.0 * _x_x_22)) == -7.0) || ((x_5 + (-1.0 * _x_x_22)) == -5.0)))))))))))))))) && ((((x_26 + (-1.0 * _x_x_23)) <= -10.0) && (((x_21 + (-1.0 * _x_x_23)) <= -6.0) && (((x_20 + (-1.0 * _x_x_23)) <= -3.0) && (((x_19 + (-1.0 * _x_x_23)) <= -11.0) && (((x_16 + (-1.0 * _x_x_23)) <= -11.0) && (((x_15 + (-1.0 * _x_x_23)) <= -18.0) && (((x_14 + (-1.0 * _x_x_23)) <= -17.0) && (((x_13 + (-1.0 * _x_x_23)) <= -14.0) && (((x_12 + (-1.0 * _x_x_23)) <= -12.0) && (((x_11 + (-1.0 * _x_x_23)) <= -20.0) && (((x_10 + (-1.0 * _x_x_23)) <= -11.0) && (((x_6 + (-1.0 * _x_x_23)) <= -1.0) && (((x_0 + (-1.0 * _x_x_23)) <= -1.0) && ((x_1 + (-1.0 * _x_x_23)) <= -4.0)))))))))))))) && (((x_26 + (-1.0 * _x_x_23)) == -10.0) || (((x_21 + (-1.0 * _x_x_23)) == -6.0) || (((x_20 + (-1.0 * _x_x_23)) == -3.0) || (((x_19 + (-1.0 * _x_x_23)) == -11.0) || (((x_16 + (-1.0 * _x_x_23)) == -11.0) || (((x_15 + (-1.0 * _x_x_23)) == -18.0) || (((x_14 + (-1.0 * _x_x_23)) == -17.0) || (((x_13 + (-1.0 * _x_x_23)) == -14.0) || (((x_12 + (-1.0 * _x_x_23)) == -12.0) || (((x_11 + (-1.0 * _x_x_23)) == -20.0) || (((x_10 + (-1.0 * _x_x_23)) == -11.0) || (((x_6 + (-1.0 * _x_x_23)) == -1.0) || (((x_0 + (-1.0 * _x_x_23)) == -1.0) || ((x_1 + (-1.0 * _x_x_23)) == -4.0)))))))))))))))) && ((((x_27 + (-1.0 * _x_x_24)) <= -5.0) && (((x_24 + (-1.0 * _x_x_24)) <= -15.0) && (((x_21 + (-1.0 * _x_x_24)) <= -1.0) && (((x_18 + (-1.0 * _x_x_24)) <= -1.0) && (((x_16 + (-1.0 * _x_x_24)) <= -18.0) && (((x_15 + (-1.0 * _x_x_24)) <= -6.0) && (((x_14 + (-1.0 * _x_x_24)) <= -11.0) && (((x_12 + (-1.0 * _x_x_24)) <= -3.0) && (((x_11 + (-1.0 * _x_x_24)) <= -5.0) && (((x_10 + (-1.0 * _x_x_24)) <= -9.0) && (((x_6 + (-1.0 * _x_x_24)) <= -7.0) && (((x_5 + (-1.0 * _x_x_24)) <= -16.0) && (((x_1 + (-1.0 * _x_x_24)) <= -7.0) && ((x_4 + (-1.0 * _x_x_24)) <= -14.0)))))))))))))) && (((x_27 + (-1.0 * _x_x_24)) == -5.0) || (((x_24 + (-1.0 * _x_x_24)) == -15.0) || (((x_21 + (-1.0 * _x_x_24)) == -1.0) || (((x_18 + (-1.0 * _x_x_24)) == -1.0) || (((x_16 + (-1.0 * _x_x_24)) == -18.0) || (((x_15 + (-1.0 * _x_x_24)) == -6.0) || (((x_14 + (-1.0 * _x_x_24)) == -11.0) || (((x_12 + (-1.0 * _x_x_24)) == -3.0) || (((x_11 + (-1.0 * _x_x_24)) == -5.0) || (((x_10 + (-1.0 * _x_x_24)) == -9.0) || (((x_6 + (-1.0 * _x_x_24)) == -7.0) || (((x_5 + (-1.0 * _x_x_24)) == -16.0) || (((x_1 + (-1.0 * _x_x_24)) == -7.0) || ((x_4 + (-1.0 * _x_x_24)) == -14.0)))))))))))))))) && ((((x_27 + (-1.0 * _x_x_25)) <= -20.0) && (((x_26 + (-1.0 * _x_x_25)) <= -15.0) && (((x_23 + (-1.0 * _x_x_25)) <= -15.0) && (((x_20 + (-1.0 * _x_x_25)) <= -17.0) && (((x_19 + (-1.0 * _x_x_25)) <= -2.0) && (((x_17 + (-1.0 * _x_x_25)) <= -10.0) && (((x_13 + (-1.0 * _x_x_25)) <= -3.0) && (((x_12 + (-1.0 * _x_x_25)) <= -2.0) && (((x_10 + (-1.0 * _x_x_25)) <= -15.0) && (((x_8 + (-1.0 * _x_x_25)) <= -18.0) && (((x_7 + (-1.0 * _x_x_25)) <= -13.0) && (((x_6 + (-1.0 * _x_x_25)) <= -2.0) && (((x_0 + (-1.0 * _x_x_25)) <= -5.0) && ((x_5 + (-1.0 * _x_x_25)) <= -4.0)))))))))))))) && (((x_27 + (-1.0 * _x_x_25)) == -20.0) || (((x_26 + (-1.0 * _x_x_25)) == -15.0) || (((x_23 + (-1.0 * _x_x_25)) == -15.0) || (((x_20 + (-1.0 * _x_x_25)) == -17.0) || (((x_19 + (-1.0 * _x_x_25)) == -2.0) || (((x_17 + (-1.0 * _x_x_25)) == -10.0) || (((x_13 + (-1.0 * _x_x_25)) == -3.0) || (((x_12 + (-1.0 * _x_x_25)) == -2.0) || (((x_10 + (-1.0 * _x_x_25)) == -15.0) || (((x_8 + (-1.0 * _x_x_25)) == -18.0) || (((x_7 + (-1.0 * _x_x_25)) == -13.0) || (((x_6 + (-1.0 * _x_x_25)) == -2.0) || (((x_0 + (-1.0 * _x_x_25)) == -5.0) || ((x_5 + (-1.0 * _x_x_25)) == -4.0)))))))))))))))) && ((((x_27 + (-1.0 * _x_x_26)) <= -2.0) && (((x_25 + (-1.0 * _x_x_26)) <= -15.0) && (((x_23 + (-1.0 * _x_x_26)) <= -1.0) && (((x_22 + (-1.0 * _x_x_26)) <= -19.0) && (((x_19 + (-1.0 * _x_x_26)) <= -9.0) && (((x_18 + (-1.0 * _x_x_26)) <= -10.0) && (((x_17 + (-1.0 * _x_x_26)) <= -15.0) && (((x_15 + (-1.0 * _x_x_26)) <= -8.0) && (((x_13 + (-1.0 * _x_x_26)) <= -12.0) && (((x_12 + (-1.0 * _x_x_26)) <= -15.0) && (((x_5 + (-1.0 * _x_x_26)) <= -8.0) && (((x_3 + (-1.0 * _x_x_26)) <= -14.0) && (((x_0 + (-1.0 * _x_x_26)) <= -7.0) && ((x_2 + (-1.0 * _x_x_26)) <= -4.0)))))))))))))) && (((x_27 + (-1.0 * _x_x_26)) == -2.0) || (((x_25 + (-1.0 * _x_x_26)) == -15.0) || (((x_23 + (-1.0 * _x_x_26)) == -1.0) || (((x_22 + (-1.0 * _x_x_26)) == -19.0) || (((x_19 + (-1.0 * _x_x_26)) == -9.0) || (((x_18 + (-1.0 * _x_x_26)) == -10.0) || (((x_17 + (-1.0 * _x_x_26)) == -15.0) || (((x_15 + (-1.0 * _x_x_26)) == -8.0) || (((x_13 + (-1.0 * _x_x_26)) == -12.0) || (((x_12 + (-1.0 * _x_x_26)) == -15.0) || (((x_5 + (-1.0 * _x_x_26)) == -8.0) || (((x_3 + (-1.0 * _x_x_26)) == -14.0) || (((x_0 + (-1.0 * _x_x_26)) == -7.0) || ((x_2 + (-1.0 * _x_x_26)) == -4.0)))))))))))))))) && ((((x_25 + (-1.0 * _x_x_27)) <= -13.0) && (((x_24 + (-1.0 * _x_x_27)) <= -8.0) && (((x_23 + (-1.0 * _x_x_27)) <= -4.0) && (((x_22 + (-1.0 * _x_x_27)) <= -11.0) && (((x_20 + (-1.0 * _x_x_27)) <= -17.0) && (((x_19 + (-1.0 * _x_x_27)) <= -12.0) && (((x_17 + (-1.0 * _x_x_27)) <= -4.0) && (((x_16 + (-1.0 * _x_x_27)) <= -16.0) && (((x_11 + (-1.0 * _x_x_27)) <= -14.0) && (((x_10 + (-1.0 * _x_x_27)) <= -19.0) && (((x_5 + (-1.0 * _x_x_27)) <= -1.0) && (((x_4 + (-1.0 * _x_x_27)) <= -13.0) && (((x_0 + (-1.0 * _x_x_27)) <= -9.0) && ((x_1 + (-1.0 * _x_x_27)) <= -20.0)))))))))))))) && (((x_25 + (-1.0 * _x_x_27)) == -13.0) || (((x_24 + (-1.0 * _x_x_27)) == -8.0) || (((x_23 + (-1.0 * _x_x_27)) == -4.0) || (((x_22 + (-1.0 * _x_x_27)) == -11.0) || (((x_20 + (-1.0 * _x_x_27)) == -17.0) || (((x_19 + (-1.0 * _x_x_27)) == -12.0) || (((x_17 + (-1.0 * _x_x_27)) == -4.0) || (((x_16 + (-1.0 * _x_x_27)) == -16.0) || (((x_11 + (-1.0 * _x_x_27)) == -14.0) || (((x_10 + (-1.0 * _x_x_27)) == -19.0) || (((x_5 + (-1.0 * _x_x_27)) == -1.0) || (((x_4 + (-1.0 * _x_x_27)) == -13.0) || (((x_0 + (-1.0 * _x_x_27)) == -9.0) || ((x_1 + (-1.0 * _x_x_27)) == -20.0)))))))))))))))) && (_EL_U_2383 == ((_x__EL_U_2383 && (9.0 <= (_x_x_6 + (-1.0 * _x_x_13)))) || ( !(( !((_x_x_17 + (-1.0 * _x_x_24)) <= 4.0)) || (14.0 <= (_x_x_21 + (-1.0 * _x_x_24)))))))); _EL_U_2383 = _x__EL_U_2383; x_13 = _x_x_13; x_6 = _x_x_6; x_26 = _x_x_26; x_2 = _x_x_2; x_24 = _x_x_24; x_17 = _x_x_17; x_3 = _x_x_3; x_21 = _x_x_21; x_12 = _x_x_12; x_1 = _x_x_1; x_15 = _x_x_15; x_0 = _x_x_0; x_18 = _x_x_18; x_4 = _x_x_4; x_5 = _x_x_5; x_10 = _x_x_10; x_27 = _x_x_27; x_11 = _x_x_11; x_16 = _x_x_16; x_14 = _x_x_14; x_19 = _x_x_19; x_20 = _x_x_20; x_9 = _x_x_9; x_22 = _x_x_22; x_23 = _x_x_23; x_25 = _x_x_25; x_7 = _x_x_7; x_8 = _x_x_8; } }
the_stack_data/67326197.c
/*Exercise 2 - Selection Write a program to calculate the amount to be paid for a rented vehicle. • Input the distance the van has travelled • The first 30 km is at a rate of 50/= per km. • The remaining distance is calculated at the rate of 40/= per km. e.g. Distance -> 20 Amount = 20 x 50 = 1000 Distance -> 50 Amount = 30 x 50 + (50-30) x 40 = 2300*/ #include <stdio.h> int main() { int distance, amount; printf("Distance:"); scanf("%d", &distance); printf("Amount :"); if(distance <30) { amount = distance*50; printf("%d", amount); } else { amount =30*50+(distance-30)*40; printf("%d", amount); } return 0; }
the_stack_data/175142109.c
/* Generated by CIL v. 1.7.0 */ /* print_CIL_Input is false */ struct _IO_FILE; struct timeval; extern float strtof(char const *str , char const *endptr ) ; extern void signal(int sig , void *func ) ; typedef struct _IO_FILE FILE; extern int atoi(char const *s ) ; extern double strtod(char const *str , char const *endptr ) ; extern int fclose(void *stream ) ; extern void *fopen(char const *filename , char const *mode ) ; extern void abort() ; extern void exit(int status ) ; extern int raise(int sig ) ; extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ; extern int strcmp(char const *a , char const *b ) ; extern int rand() ; extern unsigned long strtoul(char const *str , char const *endptr , int base ) ; void RandomFunc(unsigned int input[1] , unsigned int output[1] ) ; extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ; extern int gettimeofday(struct timeval *tv , void *tz , ...) ; extern int printf(char const *format , ...) ; int main(int argc , char *argv[] ) ; void megaInit(void) ; extern unsigned long strlen(char const *s ) ; extern long strtol(char const *str , char const *endptr , int base ) ; extern unsigned long strnlen(char const *s , unsigned long maxlen ) ; extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ; struct timeval { long tv_sec ; long tv_usec ; }; extern void *malloc(unsigned long size ) ; extern int scanf(char const *format , ...) ; void RandomFunc(unsigned int input[1] , unsigned int output[1] ) { unsigned int state[1] ; unsigned int local1 ; char copy12 ; { state[0UL] = (input[0UL] | 51238316UL) >> 3U; local1 = 0UL; while (local1 < 1UL) { state[0UL] <<= ((state[0UL] >> 3U) & 7U) | 1UL; local1 += 2UL; } local1 = 0UL; while (local1 < 1UL) { copy12 = *((char *)(& state[local1]) + 1); *((char *)(& state[local1]) + 1) = *((char *)(& state[local1]) + 3); *((char *)(& state[local1]) + 3) = copy12; state[local1] = state[0UL] & state[local1]; local1 ++; } output[0UL] = state[0UL] ^ 326631287U; } } void megaInit(void) { { } } int main(int argc , char *argv[] ) { unsigned int input[1] ; unsigned int output[1] ; int randomFuns_i5 ; unsigned int randomFuns_value6 ; int randomFuns_main_i7 ; { megaInit(); if (argc != 2) { printf("Call this program with %i arguments\n", 1); exit(-1); } else { } randomFuns_i5 = 0; while (randomFuns_i5 < 1) { randomFuns_value6 = (unsigned int )strtoul(argv[randomFuns_i5 + 1], 0, 10); input[randomFuns_i5] = randomFuns_value6; randomFuns_i5 ++; } RandomFunc(input, output); if (output[0] == 4242424242U) { printf("You win!\n"); } else { } randomFuns_main_i7 = 0; while (randomFuns_main_i7 < 1) { printf("%u\n", output[randomFuns_main_i7]); randomFuns_main_i7 ++; } } }
the_stack_data/26980.c
/** * BOJ 9291번 C언어 소스 코드 * 작성자 : 동동매니저 (DDManager) * * ※ 실행 결과 * 사용 메모리 : 1,112 KB / 131,072 KB * 소요 시간 : 0 ms / 1,000 ms * * Copyright 2020. DDManager all rights reserved. */ #include <stdio.h> #define SDK 9 int sudoku[SDK][SDK]; int isValid(void){ int i,j; int group_idx[SDK]={0,3,6,27,30,33,54,57,60}; int group_idx2[SDK]={0,1,2,9,10,11,18,19,20}; for(i=0;i<SDK;i++){ int arr[SDK]={0}; for(j=0;j<SDK;j++){ if(sudoku[i][j]){ if(!arr[sudoku[i][j]-1]) arr[sudoku[i][j]-1]=1; else return 0; } } } for(i=0;i<SDK;i++){ int arr[SDK]={0}; for(j=0;j<SDK;j++){ if(sudoku[j][i]){ if(!arr[sudoku[j][i]-1]) arr[sudoku[j][i]-1]=1; else return 0; } } } for(i=0;i<SDK;i++){ int arr[SDK]={0}; for(j=0;j<SDK;j++){ int idx=group_idx[i]+group_idx2[j]; int n=sudoku[idx/SDK][idx%SDK]-1; if(n>=0){ if(!arr[n]) arr[n]=1; else return 0; } } } return 1; } int main(void){ int T,l; scanf("%d",&T); for(l=1;l<=T;l++){ int i,j; for(i=0;i<SDK;i++) for(j=0;j<SDK;j++) scanf("%d",&sudoku[i][j]); printf("Case %d: %s\n",l,isValid()?"CORRECT":"INCORRECT"); } return 0; }
the_stack_data/61074184.c
/* * PowerPC signal handling routines * * Copyright 2002 Marcus Meissner, SuSE Linux AG * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA */ #ifdef __powerpc__ #include "config.h" #include "wine/port.h" #include <assert.h> #include <signal.h> #include <stdlib.h> #include <stdarg.h> #include <stdio.h> #include <sys/types.h> #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #ifdef HAVE_SYS_PARAM_H # include <sys/param.h> #endif #ifdef HAVE_SYSCALL_H # include <syscall.h> #else # ifdef HAVE_SYS_SYSCALL_H # include <sys/syscall.h> # endif #endif #ifdef HAVE_SYS_SIGNAL_H # include <sys/signal.h> #endif #ifdef HAVE_SYS_UCONTEXT_H # include <sys/ucontext.h> #endif #include "ntstatus.h" #define WIN32_NO_STATUS #include "windef.h" #include "winternl.h" #include "wine/library.h" #include "wine/exception.h" #include "ntdll_misc.h" #include "wine/debug.h" WINE_DEFAULT_DEBUG_CHANNEL(seh); WINE_DECLARE_DEBUG_CHANNEL(relay); static pthread_key_t teb_key; /*********************************************************************** * signal context platform-specific definitions */ #ifdef linux /* All Registers access - only for local access */ # define REG_sig(reg_name, context) ((context)->uc_mcontext.regs->reg_name) /* Gpr Registers access */ # define GPR_sig(reg_num, context) REG_sig(gpr[reg_num], context) # define IAR_sig(context) REG_sig(nip, context) /* Program counter */ # define MSR_sig(context) REG_sig(msr, context) /* Machine State Register (Supervisor) */ # define CTR_sig(context) REG_sig(ctr, context) /* Count register */ # define XER_sig(context) REG_sig(xer, context) /* User's integer exception register */ # define LR_sig(context) REG_sig(link, context) /* Link register */ # define CR_sig(context) REG_sig(ccr, context) /* Condition register */ /* Float Registers access */ # define FLOAT_sig(reg_num, context) (((double*)((char*)((context)->uc_mcontext.regs+48*4)))[reg_num]) # define FPSCR_sig(context) (*(int*)((char*)((context)->uc_mcontext.regs+(48+32*2)*4))) /* Exception Registers access */ # define DAR_sig(context) REG_sig(dar, context) # define DSISR_sig(context) REG_sig(dsisr, context) # define TRAP_sig(context) REG_sig(trap, context) #endif /* linux */ #ifdef __APPLE__ /* All Registers access - only for local access */ # define REG_sig(reg_name, context) ((context)->uc_mcontext->ss.reg_name) # define FLOATREG_sig(reg_name, context) ((context)->uc_mcontext->fs.reg_name) # define EXCEPREG_sig(reg_name, context) ((context)->uc_mcontext->es.reg_name) # define VECREG_sig(reg_name, context) ((context)->uc_mcontext->vs.reg_name) /* Gpr Registers access */ # define GPR_sig(reg_num, context) REG_sig(r##reg_num, context) # define IAR_sig(context) REG_sig(srr0, context) /* Program counter */ # define MSR_sig(context) REG_sig(srr1, context) /* Machine State Register (Supervisor) */ # define CTR_sig(context) REG_sig(ctr, context) # define XER_sig(context) REG_sig(xer, context) /* Link register */ # define LR_sig(context) REG_sig(lr, context) /* User's integer exception register */ # define CR_sig(context) REG_sig(cr, context) /* Condition register */ /* Float Registers access */ # define FLOAT_sig(reg_num, context) FLOATREG_sig(fpregs[reg_num], context) # define FPSCR_sig(context) FLOATREG_sig(fpscr, context) /* Exception Registers access */ # define DAR_sig(context) EXCEPREG_sig(dar, context) /* Fault registers for coredump */ # define DSISR_sig(context) EXCEPREG_sig(dsisr, context) # define TRAP_sig(context) EXCEPREG_sig(exception, context) /* number of powerpc exception taken */ /* Signal defs : Those are undefined on darwin SIGBUS #undef BUS_ADRERR #undef BUS_OBJERR SIGILL #undef ILL_ILLOPN #undef ILL_ILLTRP #undef ILL_ILLADR #undef ILL_COPROC #undef ILL_PRVREG #undef ILL_BADSTK SIGTRAP #undef TRAP_BRKPT #undef TRAP_TRACE SIGFPE */ #endif /* __APPLE__ */ typedef int (*wine_signal_handler)(unsigned int sig); static wine_signal_handler handlers[256]; /*********************************************************************** * dispatch_signal */ static inline int dispatch_signal(unsigned int sig) { if (handlers[sig] == NULL) return 0; return handlers[sig](sig); } /*********************************************************************** * save_context * * Set the register values from a sigcontext. */ static void save_context( CONTEXT *context, const ucontext_t *sigcontext ) { #define C(x) context->Gpr##x = GPR_sig(x,sigcontext) /* Save Gpr registers */ C(0); C(1); C(2); C(3); C(4); C(5); C(6); C(7); C(8); C(9); C(10); C(11); C(12); C(13); C(14); C(15); C(16); C(17); C(18); C(19); C(20); C(21); C(22); C(23); C(24); C(25); C(26); C(27); C(28); C(29); C(30); C(31); #undef C context->Iar = IAR_sig(sigcontext); /* Program Counter */ context->Msr = MSR_sig(sigcontext); /* Machine State Register (Supervisor) */ context->Ctr = CTR_sig(sigcontext); context->Xer = XER_sig(sigcontext); context->Lr = LR_sig(sigcontext); context->Cr = CR_sig(sigcontext); /* Saving Exception regs */ context->Dar = DAR_sig(sigcontext); context->Dsisr = DSISR_sig(sigcontext); context->Trap = TRAP_sig(sigcontext); } /*********************************************************************** * restore_context * * Build a sigcontext from the register values. */ static void restore_context( const CONTEXT *context, ucontext_t *sigcontext ) { #define C(x) GPR_sig(x,sigcontext) = context->Gpr##x C(0); C(1); C(2); C(3); C(4); C(5); C(6); C(7); C(8); C(9); C(10); C(11); C(12); C(13); C(14); C(15); C(16); C(17); C(18); C(19); C(20); C(21); C(22); C(23); C(24); C(25); C(26); C(27); C(28); C(29); C(30); C(31); #undef C IAR_sig(sigcontext) = context->Iar; /* Program Counter */ MSR_sig(sigcontext) = context->Msr; /* Machine State Register (Supervisor) */ CTR_sig(sigcontext) = context->Ctr; XER_sig(sigcontext) = context->Xer; LR_sig(sigcontext) = context->Lr; CR_sig(sigcontext) = context->Cr; /* Setting Exception regs */ DAR_sig(sigcontext) = context->Dar; DSISR_sig(sigcontext) = context->Dsisr; TRAP_sig(sigcontext) = context->Trap; } /*********************************************************************** * save_fpu * * Set the FPU context from a sigcontext. */ static inline void save_fpu( CONTEXT *context, const ucontext_t *sigcontext ) { #define C(x) context->Fpr##x = FLOAT_sig(x,sigcontext) C(0); C(1); C(2); C(3); C(4); C(5); C(6); C(7); C(8); C(9); C(10); C(11); C(12); C(13); C(14); C(15); C(16); C(17); C(18); C(19); C(20); C(21); C(22); C(23); C(24); C(25); C(26); C(27); C(28); C(29); C(30); C(31); #undef C context->Fpscr = FPSCR_sig(sigcontext); } /*********************************************************************** * restore_fpu * * Restore the FPU context to a sigcontext. */ static inline void restore_fpu( CONTEXT *context, const ucontext_t *sigcontext ) { #define C(x) FLOAT_sig(x,sigcontext) = context->Fpr##x C(0); C(1); C(2); C(3); C(4); C(5); C(6); C(7); C(8); C(9); C(10); C(11); C(12); C(13); C(14); C(15); C(16); C(17); C(18); C(19); C(20); C(21); C(22); C(23); C(24); C(25); C(26); C(27); C(28); C(29); C(30); C(31); #undef C FPSCR_sig(sigcontext) = context->Fpscr; } /*********************************************************************** * RtlCaptureContext (NTDLL.@) */ void WINAPI RtlCaptureContext( CONTEXT *context ) { FIXME("not implemented\n"); memset( context, 0, sizeof(*context) ); } /*********************************************************************** * set_cpu_context * * Set the new CPU context. */ static void set_cpu_context( const CONTEXT *context ) { FIXME("not implemented\n"); } /*********************************************************************** * get_server_context_flags * * Convert CPU-specific flags to generic server flags */ static unsigned int get_server_context_flags( DWORD flags ) { unsigned int ret = 0; if (flags & CONTEXT_CONTROL) ret |= SERVER_CTX_CONTROL; if (flags & CONTEXT_INTEGER) ret |= SERVER_CTX_INTEGER; if (flags & CONTEXT_FLOATING_POINT) ret |= SERVER_CTX_FLOATING_POINT; if (flags & CONTEXT_DEBUG_REGISTERS) ret |= SERVER_CTX_DEBUG_REGISTERS; return ret; } /*********************************************************************** * copy_context * * Copy a register context according to the flags. */ static void copy_context( CONTEXT *to, const CONTEXT *from, DWORD flags ) { if (flags & CONTEXT_CONTROL) { to->Msr = from->Msr; to->Ctr = from->Ctr; to->Iar = from->Iar; to->Lr = from->Lr; to->Dar = from->Dar; to->Dsisr = from->Dsisr; to->Trap = from->Trap; } if (flags & CONTEXT_INTEGER) { to->Gpr0 = from->Gpr0; to->Gpr1 = from->Gpr1; to->Gpr2 = from->Gpr2; to->Gpr3 = from->Gpr3; to->Gpr4 = from->Gpr4; to->Gpr5 = from->Gpr5; to->Gpr6 = from->Gpr6; to->Gpr7 = from->Gpr7; to->Gpr8 = from->Gpr8; to->Gpr9 = from->Gpr9; to->Gpr10 = from->Gpr10; to->Gpr11 = from->Gpr11; to->Gpr12 = from->Gpr12; to->Gpr13 = from->Gpr13; to->Gpr14 = from->Gpr14; to->Gpr15 = from->Gpr15; to->Gpr16 = from->Gpr16; to->Gpr17 = from->Gpr17; to->Gpr18 = from->Gpr18; to->Gpr19 = from->Gpr19; to->Gpr20 = from->Gpr20; to->Gpr21 = from->Gpr21; to->Gpr22 = from->Gpr22; to->Gpr23 = from->Gpr23; to->Gpr24 = from->Gpr24; to->Gpr25 = from->Gpr25; to->Gpr26 = from->Gpr26; to->Gpr27 = from->Gpr27; to->Gpr28 = from->Gpr28; to->Gpr29 = from->Gpr29; to->Gpr30 = from->Gpr30; to->Gpr31 = from->Gpr31; to->Xer = from->Xer; to->Cr = from->Cr; } if (flags & CONTEXT_FLOATING_POINT) { to->Fpr0 = from->Fpr0; to->Fpr1 = from->Fpr1; to->Fpr2 = from->Fpr2; to->Fpr3 = from->Fpr3; to->Fpr4 = from->Fpr4; to->Fpr5 = from->Fpr5; to->Fpr6 = from->Fpr6; to->Fpr7 = from->Fpr7; to->Fpr8 = from->Fpr8; to->Fpr9 = from->Fpr9; to->Fpr10 = from->Fpr10; to->Fpr11 = from->Fpr11; to->Fpr12 = from->Fpr12; to->Fpr13 = from->Fpr13; to->Fpr14 = from->Fpr14; to->Fpr15 = from->Fpr15; to->Fpr16 = from->Fpr16; to->Fpr17 = from->Fpr17; to->Fpr18 = from->Fpr18; to->Fpr19 = from->Fpr19; to->Fpr20 = from->Fpr20; to->Fpr21 = from->Fpr21; to->Fpr22 = from->Fpr22; to->Fpr23 = from->Fpr23; to->Fpr24 = from->Fpr24; to->Fpr25 = from->Fpr25; to->Fpr26 = from->Fpr26; to->Fpr27 = from->Fpr27; to->Fpr28 = from->Fpr28; to->Fpr29 = from->Fpr29; to->Fpr30 = from->Fpr30; to->Fpr31 = from->Fpr31; to->Fpscr = from->Fpscr; } } /*********************************************************************** * context_to_server * * Convert a register context to the server format. */ NTSTATUS context_to_server( context_t *to, const CONTEXT *from ) { DWORD flags = from->ContextFlags; /* no CPU id? */ memset( to, 0, sizeof(*to) ); to->cpu = CPU_POWERPC; if (flags & CONTEXT_CONTROL) { to->flags |= SERVER_CTX_CONTROL; to->ctl.powerpc_regs.iar = from->Iar; to->ctl.powerpc_regs.msr = from->Msr; to->ctl.powerpc_regs.ctr = from->Ctr; to->ctl.powerpc_regs.lr = from->Lr; to->ctl.powerpc_regs.dar = from->Dar; to->ctl.powerpc_regs.dsisr = from->Dsisr; to->ctl.powerpc_regs.trap = from->Trap; } if (flags & CONTEXT_INTEGER) { to->flags |= SERVER_CTX_INTEGER; to->integer.powerpc_regs.gpr[0] = from->Gpr0; to->integer.powerpc_regs.gpr[1] = from->Gpr1; to->integer.powerpc_regs.gpr[2] = from->Gpr2; to->integer.powerpc_regs.gpr[3] = from->Gpr3; to->integer.powerpc_regs.gpr[4] = from->Gpr4; to->integer.powerpc_regs.gpr[5] = from->Gpr5; to->integer.powerpc_regs.gpr[6] = from->Gpr6; to->integer.powerpc_regs.gpr[7] = from->Gpr7; to->integer.powerpc_regs.gpr[8] = from->Gpr8; to->integer.powerpc_regs.gpr[9] = from->Gpr9; to->integer.powerpc_regs.gpr[10] = from->Gpr10; to->integer.powerpc_regs.gpr[11] = from->Gpr11; to->integer.powerpc_regs.gpr[12] = from->Gpr12; to->integer.powerpc_regs.gpr[13] = from->Gpr13; to->integer.powerpc_regs.gpr[14] = from->Gpr14; to->integer.powerpc_regs.gpr[15] = from->Gpr15; to->integer.powerpc_regs.gpr[16] = from->Gpr16; to->integer.powerpc_regs.gpr[17] = from->Gpr17; to->integer.powerpc_regs.gpr[18] = from->Gpr18; to->integer.powerpc_regs.gpr[19] = from->Gpr19; to->integer.powerpc_regs.gpr[20] = from->Gpr20; to->integer.powerpc_regs.gpr[21] = from->Gpr21; to->integer.powerpc_regs.gpr[22] = from->Gpr22; to->integer.powerpc_regs.gpr[23] = from->Gpr23; to->integer.powerpc_regs.gpr[24] = from->Gpr24; to->integer.powerpc_regs.gpr[25] = from->Gpr25; to->integer.powerpc_regs.gpr[26] = from->Gpr26; to->integer.powerpc_regs.gpr[27] = from->Gpr27; to->integer.powerpc_regs.gpr[28] = from->Gpr28; to->integer.powerpc_regs.gpr[29] = from->Gpr29; to->integer.powerpc_regs.gpr[30] = from->Gpr30; to->integer.powerpc_regs.gpr[31] = from->Gpr31; to->integer.powerpc_regs.xer = from->Xer; to->integer.powerpc_regs.cr = from->Cr; } if (flags & CONTEXT_FLOATING_POINT) { to->flags |= SERVER_CTX_FLOATING_POINT; to->fp.powerpc_regs.fpr[0] = from->Fpr0; to->fp.powerpc_regs.fpr[1] = from->Fpr1; to->fp.powerpc_regs.fpr[2] = from->Fpr2; to->fp.powerpc_regs.fpr[3] = from->Fpr3; to->fp.powerpc_regs.fpr[4] = from->Fpr4; to->fp.powerpc_regs.fpr[5] = from->Fpr5; to->fp.powerpc_regs.fpr[6] = from->Fpr6; to->fp.powerpc_regs.fpr[7] = from->Fpr7; to->fp.powerpc_regs.fpr[8] = from->Fpr8; to->fp.powerpc_regs.fpr[9] = from->Fpr9; to->fp.powerpc_regs.fpr[10] = from->Fpr10; to->fp.powerpc_regs.fpr[11] = from->Fpr11; to->fp.powerpc_regs.fpr[12] = from->Fpr12; to->fp.powerpc_regs.fpr[13] = from->Fpr13; to->fp.powerpc_regs.fpr[14] = from->Fpr14; to->fp.powerpc_regs.fpr[15] = from->Fpr15; to->fp.powerpc_regs.fpr[16] = from->Fpr16; to->fp.powerpc_regs.fpr[17] = from->Fpr17; to->fp.powerpc_regs.fpr[18] = from->Fpr18; to->fp.powerpc_regs.fpr[19] = from->Fpr19; to->fp.powerpc_regs.fpr[20] = from->Fpr20; to->fp.powerpc_regs.fpr[21] = from->Fpr21; to->fp.powerpc_regs.fpr[22] = from->Fpr22; to->fp.powerpc_regs.fpr[23] = from->Fpr23; to->fp.powerpc_regs.fpr[24] = from->Fpr24; to->fp.powerpc_regs.fpr[25] = from->Fpr25; to->fp.powerpc_regs.fpr[26] = from->Fpr26; to->fp.powerpc_regs.fpr[27] = from->Fpr27; to->fp.powerpc_regs.fpr[28] = from->Fpr28; to->fp.powerpc_regs.fpr[29] = from->Fpr29; to->fp.powerpc_regs.fpr[30] = from->Fpr30; to->fp.powerpc_regs.fpr[31] = from->Fpr31; to->fp.powerpc_regs.fpscr = from->Fpscr; } return STATUS_SUCCESS; } /*********************************************************************** * context_from_server * * Convert a register context from the server format. */ NTSTATUS context_from_server( CONTEXT *to, const context_t *from ) { if (from->cpu != CPU_POWERPC) return STATUS_INVALID_PARAMETER; to->ContextFlags = 0; /* no CPU id? */ if (from->flags & SERVER_CTX_CONTROL) { to->ContextFlags |= CONTEXT_CONTROL; to->Msr = from->ctl.powerpc_regs.msr; to->Ctr = from->ctl.powerpc_regs.ctr; to->Iar = from->ctl.powerpc_regs.iar; to->Lr = from->ctl.powerpc_regs.lr; to->Dar = from->ctl.powerpc_regs.dar; to->Dsisr = from->ctl.powerpc_regs.dsisr; to->Trap = from->ctl.powerpc_regs.trap; } if (from->flags & SERVER_CTX_INTEGER) { to->ContextFlags |= CONTEXT_INTEGER; to->Gpr0 = from->integer.powerpc_regs.gpr[0]; to->Gpr1 = from->integer.powerpc_regs.gpr[1]; to->Gpr2 = from->integer.powerpc_regs.gpr[2]; to->Gpr3 = from->integer.powerpc_regs.gpr[3]; to->Gpr4 = from->integer.powerpc_regs.gpr[4]; to->Gpr5 = from->integer.powerpc_regs.gpr[5]; to->Gpr6 = from->integer.powerpc_regs.gpr[6]; to->Gpr7 = from->integer.powerpc_regs.gpr[7]; to->Gpr8 = from->integer.powerpc_regs.gpr[8]; to->Gpr9 = from->integer.powerpc_regs.gpr[9]; to->Gpr10 = from->integer.powerpc_regs.gpr[10]; to->Gpr11 = from->integer.powerpc_regs.gpr[11]; to->Gpr12 = from->integer.powerpc_regs.gpr[12]; to->Gpr13 = from->integer.powerpc_regs.gpr[13]; to->Gpr14 = from->integer.powerpc_regs.gpr[14]; to->Gpr15 = from->integer.powerpc_regs.gpr[15]; to->Gpr16 = from->integer.powerpc_regs.gpr[16]; to->Gpr17 = from->integer.powerpc_regs.gpr[17]; to->Gpr18 = from->integer.powerpc_regs.gpr[18]; to->Gpr19 = from->integer.powerpc_regs.gpr[19]; to->Gpr20 = from->integer.powerpc_regs.gpr[20]; to->Gpr21 = from->integer.powerpc_regs.gpr[21]; to->Gpr22 = from->integer.powerpc_regs.gpr[22]; to->Gpr23 = from->integer.powerpc_regs.gpr[23]; to->Gpr24 = from->integer.powerpc_regs.gpr[24]; to->Gpr25 = from->integer.powerpc_regs.gpr[25]; to->Gpr26 = from->integer.powerpc_regs.gpr[26]; to->Gpr27 = from->integer.powerpc_regs.gpr[27]; to->Gpr28 = from->integer.powerpc_regs.gpr[28]; to->Gpr29 = from->integer.powerpc_regs.gpr[29]; to->Gpr30 = from->integer.powerpc_regs.gpr[30]; to->Gpr31 = from->integer.powerpc_regs.gpr[31]; to->Xer = from->integer.powerpc_regs.xer; to->Cr = from->integer.powerpc_regs.cr; } if (from->flags & SERVER_CTX_FLOATING_POINT) { to->ContextFlags |= CONTEXT_FLOATING_POINT; to->Fpr0 = from->fp.powerpc_regs.fpr[0]; to->Fpr1 = from->fp.powerpc_regs.fpr[1]; to->Fpr2 = from->fp.powerpc_regs.fpr[2]; to->Fpr3 = from->fp.powerpc_regs.fpr[3]; to->Fpr4 = from->fp.powerpc_regs.fpr[4]; to->Fpr5 = from->fp.powerpc_regs.fpr[5]; to->Fpr6 = from->fp.powerpc_regs.fpr[6]; to->Fpr7 = from->fp.powerpc_regs.fpr[7]; to->Fpr8 = from->fp.powerpc_regs.fpr[8]; to->Fpr9 = from->fp.powerpc_regs.fpr[9]; to->Fpr10 = from->fp.powerpc_regs.fpr[10]; to->Fpr11 = from->fp.powerpc_regs.fpr[11]; to->Fpr12 = from->fp.powerpc_regs.fpr[12]; to->Fpr13 = from->fp.powerpc_regs.fpr[13]; to->Fpr14 = from->fp.powerpc_regs.fpr[14]; to->Fpr15 = from->fp.powerpc_regs.fpr[15]; to->Fpr16 = from->fp.powerpc_regs.fpr[16]; to->Fpr17 = from->fp.powerpc_regs.fpr[17]; to->Fpr18 = from->fp.powerpc_regs.fpr[18]; to->Fpr19 = from->fp.powerpc_regs.fpr[19]; to->Fpr20 = from->fp.powerpc_regs.fpr[20]; to->Fpr21 = from->fp.powerpc_regs.fpr[21]; to->Fpr22 = from->fp.powerpc_regs.fpr[22]; to->Fpr23 = from->fp.powerpc_regs.fpr[23]; to->Fpr24 = from->fp.powerpc_regs.fpr[24]; to->Fpr25 = from->fp.powerpc_regs.fpr[25]; to->Fpr26 = from->fp.powerpc_regs.fpr[26]; to->Fpr27 = from->fp.powerpc_regs.fpr[27]; to->Fpr28 = from->fp.powerpc_regs.fpr[28]; to->Fpr29 = from->fp.powerpc_regs.fpr[29]; to->Fpr30 = from->fp.powerpc_regs.fpr[30]; to->Fpr31 = from->fp.powerpc_regs.fpr[31]; to->Fpscr = from->fp.powerpc_regs.fpscr; } return STATUS_SUCCESS; } /*********************************************************************** * NtSetContextThread (NTDLL.@) * ZwSetContextThread (NTDLL.@) */ NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context ) { NTSTATUS ret; BOOL self; context_t server_context; context_to_server( &server_context, context ); ret = set_thread_context( handle, &server_context, &self ); if (self && ret == STATUS_SUCCESS) set_cpu_context( context ); return ret; } /*********************************************************************** * NtGetContextThread (NTDLL.@) * ZwGetContextThread (NTDLL.@) */ NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context ) { NTSTATUS ret; DWORD needed_flags = context->ContextFlags; BOOL self = (handle == GetCurrentThread()); if (!self) { context_t server_context; unsigned int server_flags = get_server_context_flags( context->ContextFlags ); if ((ret = get_thread_context( handle, &server_context, server_flags, &self ))) return ret; if ((ret = context_from_server( context, &server_context ))) return ret; needed_flags &= ~context->ContextFlags; } if (self && needed_flags) { CONTEXT ctx; RtlCaptureContext( &ctx ); copy_context( context, &ctx, ctx.ContextFlags & needed_flags ); context->ContextFlags |= ctx.ContextFlags & needed_flags; } return STATUS_SUCCESS; } /********************************************************************** * call_stack_handlers * * Call the stack handlers chain. */ static NTSTATUS call_stack_handlers( EXCEPTION_RECORD *rec, CONTEXT *context ) { EXCEPTION_POINTERS ptrs; FIXME( "not implemented on PowerPC\n" ); /* hack: call unhandled exception filter directly */ ptrs.ExceptionRecord = rec; ptrs.ContextRecord = context; call_unhandled_exception_filter( &ptrs ); return STATUS_UNHANDLED_EXCEPTION; } /******************************************************************* * raise_exception * * Implementation of NtRaiseException. */ static NTSTATUS raise_exception( EXCEPTION_RECORD *rec, CONTEXT *context, BOOL first_chance ) { NTSTATUS status; if (first_chance) { DWORD c; TRACE( "code=%x flags=%x addr=%p ip=%x tid=%04x\n", rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress, context->Iar, GetCurrentThreadId() ); for (c = 0; c < rec->NumberParameters; c++) TRACE( " info[%d]=%08lx\n", c, rec->ExceptionInformation[c] ); if (rec->ExceptionCode == EXCEPTION_WINE_STUB) { if (rec->ExceptionInformation[1] >> 16) MESSAGE( "wine: Call from %p to unimplemented function %s.%s, aborting\n", rec->ExceptionAddress, (char*)rec->ExceptionInformation[0], (char*)rec->ExceptionInformation[1] ); else MESSAGE( "wine: Call from %p to unimplemented function %s.%ld, aborting\n", rec->ExceptionAddress, (char*)rec->ExceptionInformation[0], rec->ExceptionInformation[1] ); } else { /* FIXME: dump context */ } status = send_debug_event( rec, TRUE, context ); if (status == DBG_CONTINUE || status == DBG_EXCEPTION_HANDLED) return STATUS_SUCCESS; if (call_vectored_handlers( rec, context ) == EXCEPTION_CONTINUE_EXECUTION) return STATUS_SUCCESS; if ((status = call_stack_handlers( rec, context )) != STATUS_UNHANDLED_EXCEPTION) return status; } /* last chance exception */ status = send_debug_event( rec, FALSE, context ); if (status != DBG_CONTINUE) { if (rec->ExceptionFlags & EH_STACK_INVALID) ERR("Exception frame is not in stack limits => unable to dispatch exception.\n"); else if (rec->ExceptionCode == STATUS_NONCONTINUABLE_EXCEPTION) ERR("Process attempted to continue execution after noncontinuable exception.\n"); else ERR("Unhandled exception code %x flags %x addr %p\n", rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress ); NtTerminateProcess( NtCurrentProcess(), rec->ExceptionCode ); } return STATUS_SUCCESS; } /********************************************************************** * segv_handler * * Handler for SIGSEGV and related errors. */ static void segv_handler( int signal, siginfo_t *siginfo, void *sigcontext ) { EXCEPTION_RECORD rec; CONTEXT context; NTSTATUS status; save_context( &context, sigcontext ); rec.ExceptionRecord = NULL; rec.ExceptionFlags = EXCEPTION_CONTINUABLE; rec.ExceptionAddress = (LPVOID)context.Iar; rec.NumberParameters = 0; switch (signal) { case SIGSEGV: switch (siginfo->si_code & 0xffff) { case SEGV_MAPERR: case SEGV_ACCERR: rec.NumberParameters = 2; rec.ExceptionInformation[0] = 0; /* FIXME ? */ rec.ExceptionInformation[1] = (ULONG_PTR)siginfo->si_addr; if (!(rec.ExceptionCode = virtual_handle_fault(siginfo->si_addr, rec.ExceptionInformation[0], FALSE))) goto done; break; default: FIXME("Unhandled SIGSEGV/%x\n",siginfo->si_code); break; } break; case SIGBUS: switch (siginfo->si_code & 0xffff) { case BUS_ADRALN: rec.ExceptionCode = EXCEPTION_DATATYPE_MISALIGNMENT; break; #ifdef BUS_ADRERR case BUS_ADRERR: #endif #ifdef BUS_OBJERR case BUS_OBJERR: /* FIXME: correct for all cases ? */ rec.NumberParameters = 2; rec.ExceptionInformation[0] = 0; /* FIXME ? */ rec.ExceptionInformation[1] = (ULONG_PTR)siginfo->si_addr; if (!(rec.ExceptionCode = virtual_handle_fault(siginfo->si_addr, rec.ExceptionInformation[0], FALSE))) goto done; break; #endif default: FIXME("Unhandled SIGBUS/%x\n",siginfo->si_code); break; } break; case SIGILL: switch (siginfo->si_code & 0xffff) { case ILL_ILLOPC: /* illegal opcode */ #ifdef ILL_ILLOPN case ILL_ILLOPN: /* illegal operand */ #endif #ifdef ILL_ILLADR case ILL_ILLADR: /* illegal addressing mode */ #endif #ifdef ILL_ILLTRP case ILL_ILLTRP: /* illegal trap */ #endif #ifdef ILL_COPROC case ILL_COPROC: /* coprocessor error */ #endif rec.ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION; break; case ILL_PRVOPC: /* privileged opcode */ #ifdef ILL_PRVREG case ILL_PRVREG: /* privileged register */ #endif rec.ExceptionCode = EXCEPTION_PRIV_INSTRUCTION; break; #ifdef ILL_BADSTK case ILL_BADSTK: /* internal stack error */ rec.ExceptionCode = EXCEPTION_STACK_OVERFLOW; break; #endif default: FIXME("Unhandled SIGILL/%x\n", siginfo->si_code); break; } break; } status = raise_exception( &rec, &context, TRUE ); if (status) raise_status( status, &rec ); done: restore_context( &context, sigcontext ); } /********************************************************************** * trap_handler * * Handler for SIGTRAP. */ static void trap_handler( int signal, siginfo_t *siginfo, void *sigcontext ) { EXCEPTION_RECORD rec; CONTEXT context; NTSTATUS status; save_context( &context, sigcontext ); rec.ExceptionFlags = EXCEPTION_CONTINUABLE; rec.ExceptionRecord = NULL; rec.ExceptionAddress = (LPVOID)context.Iar; rec.NumberParameters = 0; /* FIXME: check if we might need to modify PC */ switch (siginfo->si_code & 0xffff) { #ifdef TRAP_BRKPT case TRAP_BRKPT: rec.ExceptionCode = EXCEPTION_BREAKPOINT; break; #endif #ifdef TRAP_TRACE case TRAP_TRACE: rec.ExceptionCode = EXCEPTION_SINGLE_STEP; break; #endif default: FIXME("Unhandled SIGTRAP/%x\n", siginfo->si_code); break; } status = raise_exception( &rec, &context, TRUE ); if (status) raise_status( status, &rec ); restore_context( &context, sigcontext ); } /********************************************************************** * fpe_handler * * Handler for SIGFPE. */ static void fpe_handler( int signal, siginfo_t *siginfo, void *sigcontext ) { EXCEPTION_RECORD rec; CONTEXT context; NTSTATUS status; save_fpu( &context, sigcontext ); save_context( &context, sigcontext ); switch (siginfo->si_code & 0xffff ) { #ifdef FPE_FLTSUB case FPE_FLTSUB: rec.ExceptionCode = EXCEPTION_ARRAY_BOUNDS_EXCEEDED; break; #endif #ifdef FPE_INTDIV case FPE_INTDIV: rec.ExceptionCode = EXCEPTION_INT_DIVIDE_BY_ZERO; break; #endif #ifdef FPE_INTOVF case FPE_INTOVF: rec.ExceptionCode = EXCEPTION_INT_OVERFLOW; break; #endif #ifdef FPE_FLTDIV case FPE_FLTDIV: rec.ExceptionCode = EXCEPTION_FLT_DIVIDE_BY_ZERO; break; #endif #ifdef FPE_FLTOVF case FPE_FLTOVF: rec.ExceptionCode = EXCEPTION_FLT_OVERFLOW; break; #endif #ifdef FPE_FLTUND case FPE_FLTUND: rec.ExceptionCode = EXCEPTION_FLT_UNDERFLOW; break; #endif #ifdef FPE_FLTRES case FPE_FLTRES: rec.ExceptionCode = EXCEPTION_FLT_INEXACT_RESULT; break; #endif #ifdef FPE_FLTINV case FPE_FLTINV: #endif default: rec.ExceptionCode = EXCEPTION_FLT_INVALID_OPERATION; break; } rec.ExceptionFlags = EXCEPTION_CONTINUABLE; rec.ExceptionRecord = NULL; rec.ExceptionAddress = (LPVOID)context.Iar; rec.NumberParameters = 0; status = raise_exception( &rec, &context, TRUE ); if (status) raise_status( status, &rec ); restore_context( &context, sigcontext ); restore_fpu( &context, sigcontext ); } /********************************************************************** * int_handler * * Handler for SIGINT. */ static void int_handler( int signal, siginfo_t *siginfo, void *sigcontext ) { if (!dispatch_signal(SIGINT)) { EXCEPTION_RECORD rec; CONTEXT context; NTSTATUS status; save_context( &context, sigcontext ); rec.ExceptionCode = CONTROL_C_EXIT; rec.ExceptionFlags = EXCEPTION_CONTINUABLE; rec.ExceptionRecord = NULL; rec.ExceptionAddress = (LPVOID)context.Iar; rec.NumberParameters = 0; status = raise_exception( &rec, &context, TRUE ); if (status) raise_status( status, &rec ); restore_context( &context, sigcontext ); } } /********************************************************************** * abrt_handler * * Handler for SIGABRT. */ static void abrt_handler( int signal, siginfo_t *siginfo, void *sigcontext ) { EXCEPTION_RECORD rec; CONTEXT context; NTSTATUS status; save_context( &context, sigcontext ); rec.ExceptionCode = EXCEPTION_WINE_ASSERTION; rec.ExceptionFlags = EH_NONCONTINUABLE; rec.ExceptionRecord = NULL; rec.ExceptionAddress = (LPVOID)context.Iar; rec.NumberParameters = 0; status = raise_exception( &rec, &context, TRUE ); if (status) raise_status( status, &rec ); restore_context( &context, sigcontext ); } /********************************************************************** * quit_handler * * Handler for SIGQUIT. */ static void quit_handler( int signal, siginfo_t *siginfo, void *sigcontext ) { abort_thread(0); } /********************************************************************** * usr1_handler * * Handler for SIGUSR1, used to signal a thread that it got suspended. */ static void usr1_handler( int signal, siginfo_t *siginfo, void *sigcontext ) { CONTEXT context; save_context( &context, sigcontext ); wait_suspend( &context ); restore_context( &context, sigcontext ); } /*********************************************************************** * __wine_set_signal_handler (NTDLL.@) */ int CDECL __wine_set_signal_handler(unsigned int sig, wine_signal_handler wsh) { if (sig >= ARRAY_SIZE(handlers)) return -1; if (handlers[sig] != NULL) return -2; handlers[sig] = wsh; return 0; } /********************************************************************** * signal_alloc_thread */ NTSTATUS signal_alloc_thread( TEB **teb ) { static size_t sigstack_zero_bits; SIZE_T size; NTSTATUS status; if (!sigstack_zero_bits) { size_t min_size = page_size; /* this is just for the TEB, we don't use a signal stack yet */ /* find the first power of two not smaller than min_size */ while ((1u << sigstack_zero_bits) < min_size) sigstack_zero_bits++; assert( sizeof(TEB) <= min_size ); } size = 1 << sigstack_zero_bits; *teb = NULL; if (!(status = NtAllocateVirtualMemory( NtCurrentProcess(), (void **)teb, sigstack_zero_bits, &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE ))) { (*teb)->Tib.Self = &(*teb)->Tib; (*teb)->Tib.ExceptionList = (void *)~0UL; } return status; } /********************************************************************** * signal_free_thread */ void signal_free_thread( TEB *teb ) { SIZE_T size = 0; NtFreeVirtualMemory( NtCurrentProcess(), (void **)&teb, &size, MEM_RELEASE ); } /********************************************************************** * signal_init_thread */ void signal_init_thread( TEB *teb ) { static BOOL init_done; if (!init_done) { pthread_key_create( &teb_key, NULL ); init_done = TRUE; } pthread_setspecific( teb_key, teb ); } /********************************************************************** * signal_init_process */ void signal_init_process(void) { struct sigaction sig_act; sig_act.sa_mask = server_block_set; sig_act.sa_flags = SA_RESTART | SA_SIGINFO; sig_act.sa_sigaction = int_handler; if (sigaction( SIGINT, &sig_act, NULL ) == -1) goto error; sig_act.sa_sigaction = fpe_handler; if (sigaction( SIGFPE, &sig_act, NULL ) == -1) goto error; sig_act.sa_sigaction = abrt_handler; if (sigaction( SIGABRT, &sig_act, NULL ) == -1) goto error; sig_act.sa_sigaction = quit_handler; if (sigaction( SIGQUIT, &sig_act, NULL ) == -1) goto error; sig_act.sa_sigaction = usr1_handler; if (sigaction( SIGUSR1, &sig_act, NULL ) == -1) goto error; sig_act.sa_sigaction = segv_handler; if (sigaction( SIGSEGV, &sig_act, NULL ) == -1) goto error; if (sigaction( SIGILL, &sig_act, NULL ) == -1) goto error; #ifdef SIGBUS if (sigaction( SIGBUS, &sig_act, NULL ) == -1) goto error; #endif #ifdef SIGTRAP sig_act.sa_sigaction = trap_handler; if (sigaction( SIGTRAP, &sig_act, NULL ) == -1) goto error; #endif return; error: perror("sigaction"); exit(1); } /*********************************************************************** * RtlUnwind (NTDLL.@) */ void WINAPI RtlUnwind( PVOID pEndFrame, PVOID targetIp, PEXCEPTION_RECORD pRecord, PVOID retval ) { FIXME( "Not implemented on PowerPC\n" ); } /******************************************************************* * NtRaiseException (NTDLL.@) */ NTSTATUS WINAPI NtRaiseException( EXCEPTION_RECORD *rec, CONTEXT *context, BOOL first_chance ) { NTSTATUS status = raise_exception( rec, context, first_chance ); if (status == STATUS_SUCCESS) NtSetContextThread( GetCurrentThread(), context ); return status; } /*********************************************************************** * RtlRaiseException (NTDLL.@) */ void WINAPI RtlRaiseException( EXCEPTION_RECORD *rec ) { CONTEXT context; NTSTATUS status; RtlCaptureContext( &context ); rec->ExceptionAddress = (void *)context.Iar; status = raise_exception( rec, &context, TRUE ); if (status) raise_status( status, rec ); } /************************************************************************* * RtlCaptureStackBackTrace (NTDLL.@) */ USHORT WINAPI RtlCaptureStackBackTrace( ULONG skip, ULONG count, PVOID *buffer, ULONG *hash ) { FIXME( "(%d, %d, %p, %p) stub!\n", skip, count, buffer, hash ); return 0; } /*********************************************************************** * call_thread_entry_point */ static void WINAPI call_thread_entry_point( LPTHREAD_START_ROUTINE entry, void *arg ) { __TRY { TRACE_(relay)( "\1Starting thread proc %p (arg=%p)\n", entry, arg ); RtlExitUserThread( entry( arg )); } __EXCEPT(call_unhandled_exception_filter) { NtTerminateThread( GetCurrentThread(), GetExceptionCode() ); } __ENDTRY abort(); /* should not be reached */ } typedef void (WINAPI *thread_start_func)(LPTHREAD_START_ROUTINE,void *); struct startup_info { thread_start_func start; LPTHREAD_START_ROUTINE entry; void *arg; BOOL suspend; }; /*********************************************************************** * thread_startup */ static void thread_startup( void *param ) { CONTEXT context = { 0 }; struct startup_info *info = param; /* build the initial context */ context.ContextFlags = CONTEXT_FULL; context.Gpr1 = (DWORD)NtCurrentTeb()->Tib.StackBase; context.Gpr3 = (DWORD)info->entry; context.Gpr4 = (DWORD)info->arg; context.Iar = (DWORD)info->start; if (info->suspend) wait_suspend( &context ); LdrInitializeThunk( &context, (void **)&context.Gpr3, 0, 0 ); ((thread_start_func)context.Iar)( (LPTHREAD_START_ROUTINE)context.Gpr3, (void *)context.Gpr4 ); } /*********************************************************************** * signal_start_thread * * Thread startup sequence: * signal_start_thread() * -> thread_startup() * -> call_thread_entry_point() */ void signal_start_thread( LPTHREAD_START_ROUTINE entry, void *arg, BOOL suspend ) { struct startup_info info = { call_thread_entry_point, entry, arg, suspend }; wine_switch_to_stack( thread_startup, &info, NtCurrentTeb()->Tib.StackBase ); } /********************************************************************** * signal_start_process * * Process startup sequence: * signal_start_process() * -> thread_startup() * -> kernel32_start_process() */ void signal_start_process( LPTHREAD_START_ROUTINE entry, BOOL suspend ) { struct startup_info info = { kernel32_start_process, entry, NtCurrentTeb()->Peb, suspend }; wine_switch_to_stack( thread_startup, &info, NtCurrentTeb()->Tib.StackBase ); } /*********************************************************************** * signal_exit_thread */ void signal_exit_thread( int status ) { exit_thread( status ); } /*********************************************************************** * signal_exit_process */ void signal_exit_process( int status ) { exit( status ); } /********************************************************************** * DbgBreakPoint (NTDLL.@) */ void WINAPI DbgBreakPoint(void) { kill(getpid(), SIGTRAP); } /********************************************************************** * DbgUserBreakPoint (NTDLL.@) */ void WINAPI DbgUserBreakPoint(void) { kill(getpid(), SIGTRAP); } /********************************************************************** * NtCurrentTeb (NTDLL.@) */ TEB * WINAPI NtCurrentTeb(void) { return pthread_getspecific( teb_key ); } #endif /* __powerpc__ */
the_stack_data/175143281.c
/* ** 2004 May 22 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains code that modified the OS layer in order to simulate ** the effect on the database file of an OS crash or power failure. This ** is used to test the ability of SQLite to recover from those situations. */ #if SQLITE_TEST /* This file is used for testing only */ #include "sqliteInt.h" #if defined(INCLUDE_SQLITE_TCL_H) # include "sqlite_tcl.h" #else # include "tcl.h" #endif #ifndef SQLITE_OMIT_DISKIO /* This file is a no-op if disk I/O is disabled */ /* #define TRACE_CRASHTEST */ typedef struct CrashFile CrashFile; typedef struct CrashGlobal CrashGlobal; typedef struct WriteBuffer WriteBuffer; /* ** Method: ** ** This layer is implemented as a wrapper around the "real" ** sqlite3_file object for the host system. Each time data is ** written to the file object, instead of being written to the ** underlying file, the write operation is stored in an in-memory ** structure (type WriteBuffer). This structure is placed at the ** end of a global ordered list (the write-list). ** ** When data is read from a file object, the requested region is ** first retrieved from the real file. The write-list is then ** traversed and data copied from any overlapping WriteBuffer ** structures to the output buffer. i.e. a read() operation following ** one or more write() operations works as expected, even if no ** data has actually been written out to the real file. ** ** When a fsync() operation is performed, an operating system crash ** may be simulated, in which case exit(-1) is called (the call to ** xSync() never returns). Whether or not a crash is simulated, ** the data associated with a subset of the WriteBuffer structures ** stored in the write-list is written to the real underlying files ** and the entries removed from the write-list. If a crash is simulated, ** a subset of the buffers may be corrupted before the data is written. ** ** The exact subset of the write-list written and/or corrupted is ** determined by the simulated device characteristics and sector-size. ** ** "Normal" mode: ** ** Normal mode is used when the simulated device has none of the ** SQLITE_IOCAP_XXX flags set. ** ** In normal mode, if the fsync() is not a simulated crash, the ** write-list is traversed from beginning to end. Each WriteBuffer ** structure associated with the file handle used to call xSync() ** is written to the real file and removed from the write-list. ** ** If a crash is simulated, one of the following takes place for ** each WriteBuffer in the write-list, regardless of which ** file-handle it is associated with: ** ** 1. The buffer is correctly written to the file, just as if ** a crash were not being simulated. ** ** 2. Nothing is done. ** ** 3. Garbage data is written to all sectors of the file that ** overlap the region specified by the WriteBuffer. Or garbage ** data is written to some contiguous section within the ** overlapped sectors. ** ** Device Characteristic flag handling: ** ** If the IOCAP_ATOMIC flag is set, then option (3) above is ** never selected. ** ** If the IOCAP_ATOMIC512 flag is set, and the WriteBuffer represents ** an aligned write() of an integer number of 512 byte regions, then ** option (3) above is never selected. Instead, each 512 byte region ** is either correctly written or left completely untouched. Similar ** logic governs the behavior if any of the other ATOMICXXX flags ** is set. ** ** If either the IOCAP_SAFEAPPEND or IOCAP_SEQUENTIAL flags are set ** and a crash is being simulated, then an entry of the write-list is ** selected at random. Everything in the list after the selected entry ** is discarded before processing begins. ** ** If IOCAP_SEQUENTIAL is set and a crash is being simulated, option ** (1) is selected for all write-list entries except the last. If a ** crash is not being simulated, then all entries in the write-list ** that occur before at least one write() on the file-handle specified ** as part of the xSync() are written to their associated real files. ** ** If IOCAP_SAFEAPPEND is set and the first byte written by the write() ** operation is one byte past the current end of the file, then option ** (1) is always selected. */ /* ** Each write operation in the write-list is represented by an instance ** of the following structure. ** ** If zBuf is 0, then this structure represents a call to xTruncate(), ** not xWrite(). In that case, iOffset is the size that the file is ** truncated to. */ struct WriteBuffer { i64 iOffset; /* Byte offset of the start of this write() */ int nBuf; /* Number of bytes written */ u8 *zBuf; /* Pointer to copy of written data */ CrashFile *pFile; /* File this write() applies to */ WriteBuffer *pNext; /* Next in CrashGlobal.pWriteList */ }; struct CrashFile { const sqlite3_io_methods *pMethod; /* Must be first */ sqlite3_file *pRealFile; /* Underlying "real" file handle */ char *zName; int flags; /* Flags the file was opened with */ /* Cache of the entire file. This is used to speed up OsRead() and ** OsFileSize() calls. Although both could be done by traversing the ** write-list, in practice this is impractically slow. */ u8 *zData; /* Buffer containing file contents */ int nData; /* Size of buffer allocated at zData */ i64 iSize; /* Size of file in bytes */ }; struct CrashGlobal { WriteBuffer *pWriteList; /* Head of write-list */ WriteBuffer *pWriteListEnd; /* End of write-list */ int iSectorSize; /* Value of simulated sector size */ int iDeviceCharacteristics; /* Value of simulated device characteristics */ int iCrash; /* Crash on the iCrash'th call to xSync() */ char zCrashFile[500]; /* Crash during an xSync() on this file */ }; static CrashGlobal g = {0, 0, SQLITE_DEFAULT_SECTOR_SIZE, 0, 0}; /* ** Set this global variable to 1 to enable crash testing. */ static int sqlite3CrashTestEnable = 0; static void *crash_malloc(int nByte){ return (void *)Tcl_AttemptAlloc((size_t)nByte); } static void crash_free(void *p){ Tcl_Free(p); } static void *crash_realloc(void *p, int n){ return (void *)Tcl_AttemptRealloc(p, (size_t)n); } /* ** Wrapper around the sqlite3OsWrite() function that avoids writing to the ** 512 byte block begining at offset PENDING_BYTE. */ static int writeDbFile(CrashFile *p, u8 *z, i64 iAmt, i64 iOff){ int rc = SQLITE_OK; int iSkip = 0; if( (iAmt-iSkip)>0 ){ rc = sqlite3OsWrite(p->pRealFile, &z[iSkip], (int)(iAmt-iSkip), iOff+iSkip); } return rc; } /* ** Flush the write-list as if xSync() had been called on file handle ** pFile. If isCrash is true, simulate a crash. */ static int writeListSync(CrashFile *pFile, int isCrash){ int rc = SQLITE_OK; int iDc = g.iDeviceCharacteristics; WriteBuffer *pWrite; WriteBuffer **ppPtr; /* If this is not a crash simulation, set pFinal to point to the ** last element of the write-list that is associated with file handle ** pFile. ** ** If this is a crash simulation, set pFinal to an arbitrarily selected ** element of the write-list. */ WriteBuffer *pFinal = 0; if( !isCrash ){ for(pWrite=g.pWriteList; pWrite; pWrite=pWrite->pNext){ if( pWrite->pFile==pFile ){ pFinal = pWrite; } } }else if( iDc&(SQLITE_IOCAP_SEQUENTIAL|SQLITE_IOCAP_SAFE_APPEND) ){ int nWrite = 0; int iFinal; for(pWrite=g.pWriteList; pWrite; pWrite=pWrite->pNext) nWrite++; sqlite3_randomness(sizeof(int), &iFinal); iFinal = ((iFinal<0)?-1*iFinal:iFinal)%nWrite; for(pWrite=g.pWriteList; iFinal>0; pWrite=pWrite->pNext) iFinal--; pFinal = pWrite; } #ifdef TRACE_CRASHTEST if( pFile ){ printf("Sync %s (is %s crash)\n", pFile->zName, (isCrash?"a":"not a")); } #endif ppPtr = &g.pWriteList; for(pWrite=*ppPtr; rc==SQLITE_OK && pWrite; pWrite=*ppPtr){ sqlite3_file *pRealFile = pWrite->pFile->pRealFile; /* (eAction==1) -> write block out normally, ** (eAction==2) -> do nothing, ** (eAction==3) -> trash sectors. */ int eAction = 0; if( !isCrash ){ eAction = 2; if( (pWrite->pFile==pFile || iDc&SQLITE_IOCAP_SEQUENTIAL) ){ eAction = 1; } }else{ char random; sqlite3_randomness(1, &random); /* Do not select option 3 (sector trashing) if the IOCAP_ATOMIC flag ** is set or this is an OsTruncate(), not an Oswrite(). */ if( (iDc&SQLITE_IOCAP_ATOMIC) || (pWrite->zBuf==0) ){ random &= 0x01; } /* If IOCAP_SEQUENTIAL is set and this is not the final entry ** in the truncated write-list, always select option 1 (write ** out correctly). */ if( (iDc&SQLITE_IOCAP_SEQUENTIAL && pWrite!=pFinal) ){ random = 0; } /* If IOCAP_SAFE_APPEND is set and this OsWrite() operation is ** an append (first byte of the written region is 1 byte past the ** current EOF), always select option 1 (write out correctly). */ if( iDc&SQLITE_IOCAP_SAFE_APPEND && pWrite->zBuf ){ i64 iSize; sqlite3OsFileSize(pRealFile, &iSize); if( iSize==pWrite->iOffset ){ random = 0; } } if( (random&0x06)==0x06 ){ eAction = 3; }else{ eAction = ((random&0x01)?2:1); } } switch( eAction ){ case 1: { /* Write out correctly */ if( pWrite->zBuf ){ rc = writeDbFile( pWrite->pFile, pWrite->zBuf, pWrite->nBuf, pWrite->iOffset ); }else{ rc = sqlite3OsTruncate(pRealFile, pWrite->iOffset); } *ppPtr = pWrite->pNext; #ifdef TRACE_CRASHTEST if( isCrash ){ printf("Writing %d bytes @ %d (%s)\n", pWrite->nBuf, (int)pWrite->iOffset, pWrite->pFile->zName ); } #endif crash_free(pWrite); break; } case 2: { /* Do nothing */ ppPtr = &pWrite->pNext; #ifdef TRACE_CRASHTEST if( isCrash ){ printf("Omiting %d bytes @ %d (%s)\n", pWrite->nBuf, (int)pWrite->iOffset, pWrite->pFile->zName ); } #endif break; } case 3: { /* Trash sectors */ u8 *zGarbage; int iFirst = (int)(pWrite->iOffset/g.iSectorSize); int iLast = (int)((pWrite->iOffset+pWrite->nBuf-1)/g.iSectorSize); assert(pWrite->zBuf); #ifdef TRACE_CRASHTEST printf("Trashing %d sectors (%d bytes) @ %lld (sector %d) (%s)\n", 1+iLast-iFirst, (1+iLast-iFirst)*g.iSectorSize, pWrite->iOffset, iFirst, pWrite->pFile->zName ); #endif zGarbage = crash_malloc(g.iSectorSize); if( zGarbage ){ sqlite3_int64 i; for(i=iFirst; rc==SQLITE_OK && i<=iLast; i++){ sqlite3_randomness(g.iSectorSize, zGarbage); rc = writeDbFile( pWrite->pFile, zGarbage, g.iSectorSize, i*g.iSectorSize ); } crash_free(zGarbage); }else{ rc = SQLITE_NOMEM; } ppPtr = &pWrite->pNext; break; } default: assert(!"Cannot happen"); } if( pWrite==pFinal ) break; } if( rc==SQLITE_OK && isCrash ){ exit(-1); } for(pWrite=g.pWriteList; pWrite && pWrite->pNext; pWrite=pWrite->pNext); g.pWriteListEnd = pWrite; return rc; } /* ** Add an entry to the end of the write-list. */ static int writeListAppend( sqlite3_file *pFile, sqlite3_int64 iOffset, const u8 *zBuf, int nBuf ){ WriteBuffer *pNew; assert((zBuf && nBuf) || (!nBuf && !zBuf)); pNew = (WriteBuffer *)crash_malloc(sizeof(WriteBuffer) + nBuf); if( pNew==0 ){ fprintf(stderr, "out of memory in the crash simulator\n"); } memset(pNew, 0, sizeof(WriteBuffer)+nBuf); pNew->iOffset = iOffset; pNew->nBuf = nBuf; pNew->pFile = (CrashFile *)pFile; if( zBuf ){ pNew->zBuf = (u8 *)&pNew[1]; memcpy(pNew->zBuf, zBuf, nBuf); } if( g.pWriteList ){ assert(g.pWriteListEnd); g.pWriteListEnd->pNext = pNew; }else{ g.pWriteList = pNew; } g.pWriteListEnd = pNew; return SQLITE_OK; } /* ** Close a crash-file. */ static int cfClose(sqlite3_file *pFile){ CrashFile *pCrash = (CrashFile *)pFile; writeListSync(pCrash, 0); sqlite3OsClose(pCrash->pRealFile); return SQLITE_OK; } /* ** Read data from a crash-file. */ static int cfRead( sqlite3_file *pFile, void *zBuf, int iAmt, sqlite_int64 iOfst ){ CrashFile *pCrash = (CrashFile *)pFile; int nCopy = (int)MIN((i64)iAmt, (pCrash->iSize - iOfst)); if( nCopy>0 ){ memcpy(zBuf, &pCrash->zData[iOfst], nCopy); } /* Check the file-size to see if this is a short-read */ if( nCopy<iAmt ){ return SQLITE_IOERR_SHORT_READ; } return SQLITE_OK; } /* ** Write data to a crash-file. */ static int cfWrite( sqlite3_file *pFile, const void *zBuf, int iAmt, sqlite_int64 iOfst ){ CrashFile *pCrash = (CrashFile *)pFile; if( iAmt+iOfst>pCrash->iSize ){ pCrash->iSize = (int)(iAmt+iOfst); } while( pCrash->iSize>pCrash->nData ){ u8 *zNew; int nNew = (pCrash->nData*2) + 4096; zNew = crash_realloc(pCrash->zData, nNew); if( !zNew ){ return SQLITE_NOMEM; } memset(&zNew[pCrash->nData], 0, nNew-pCrash->nData); pCrash->nData = nNew; pCrash->zData = zNew; } memcpy(&pCrash->zData[iOfst], zBuf, iAmt); return writeListAppend(pFile, iOfst, zBuf, iAmt); } /* ** Truncate a crash-file. */ static int cfTruncate(sqlite3_file *pFile, sqlite_int64 size){ CrashFile *pCrash = (CrashFile *)pFile; assert(size>=0); if( pCrash->iSize>size ){ pCrash->iSize = (int)size; } return writeListAppend(pFile, size, 0, 0); } /* ** Sync a crash-file. */ static int cfSync(sqlite3_file *pFile, int flags){ CrashFile *pCrash = (CrashFile *)pFile; int isCrash = 0; const char *zName = pCrash->zName; const char *zCrashFile = g.zCrashFile; int nName = (int)strlen(zName); int nCrashFile = (int)strlen(zCrashFile); if( nCrashFile>0 && zCrashFile[nCrashFile-1]=='*' ){ nCrashFile--; if( nName>nCrashFile ) nName = nCrashFile; } #ifdef TRACE_CRASHTEST printf("cfSync(): nName = %d, nCrashFile = %d, zName = %s, zCrashFile = %s\n", nName, nCrashFile, zName, zCrashFile); #endif if( nName==nCrashFile && 0==memcmp(zName, zCrashFile, nName) ){ #ifdef TRACE_CRASHTEST printf("cfSync(): name matched, g.iCrash = %d\n", g.iCrash); #endif if( (--g.iCrash)==0 ) isCrash = 1; } return writeListSync(pCrash, isCrash); } /* ** Return the current file-size of the crash-file. */ static int cfFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){ CrashFile *pCrash = (CrashFile *)pFile; *pSize = (i64)pCrash->iSize; return SQLITE_OK; } /* ** Calls related to file-locks are passed on to the real file handle. */ static int cfLock(sqlite3_file *pFile, int eLock){ return sqlite3OsLock(((CrashFile *)pFile)->pRealFile, eLock); } static int cfUnlock(sqlite3_file *pFile, int eLock){ return sqlite3OsUnlock(((CrashFile *)pFile)->pRealFile, eLock); } static int cfCheckReservedLock(sqlite3_file *pFile, int *pResOut){ return sqlite3OsCheckReservedLock(((CrashFile *)pFile)->pRealFile, pResOut); } static int cfFileControl(sqlite3_file *pFile, int op, void *pArg){ if( op==SQLITE_FCNTL_SIZE_HINT ){ CrashFile *pCrash = (CrashFile *)pFile; i64 nByte = *(i64 *)pArg; if( nByte>pCrash->iSize ){ if( SQLITE_OK==writeListAppend(pFile, nByte, 0, 0) ){ pCrash->iSize = (int)nByte; } } return SQLITE_OK; } return sqlite3OsFileControl(((CrashFile *)pFile)->pRealFile, op, pArg); } /* ** The xSectorSize() and xDeviceCharacteristics() functions return ** the global values configured by the [sqlite_crashparams] tcl * interface. */ static int cfSectorSize(sqlite3_file *pFile){ return g.iSectorSize; } static int cfDeviceCharacteristics(sqlite3_file *pFile){ return g.iDeviceCharacteristics; } /* ** Pass-throughs for WAL support. */ static int cfShmLock(sqlite3_file *pFile, int ofst, int n, int flags){ sqlite3_file *pReal = ((CrashFile*)pFile)->pRealFile; return pReal->pMethods->xShmLock(pReal, ofst, n, flags); } static void cfShmBarrier(sqlite3_file *pFile){ sqlite3_file *pReal = ((CrashFile*)pFile)->pRealFile; pReal->pMethods->xShmBarrier(pReal); } static int cfShmUnmap(sqlite3_file *pFile, int delFlag){ sqlite3_file *pReal = ((CrashFile*)pFile)->pRealFile; return pReal->pMethods->xShmUnmap(pReal, delFlag); } static int cfShmMap( sqlite3_file *pFile, /* Handle open on database file */ int iRegion, /* Region to retrieve */ int sz, /* Size of regions */ int w, /* True to extend file if necessary */ void volatile **pp /* OUT: Mapped memory */ ){ sqlite3_file *pReal = ((CrashFile*)pFile)->pRealFile; return pReal->pMethods->xShmMap(pReal, iRegion, sz, w, pp); } static const sqlite3_io_methods CrashFileVtab = { 2, /* iVersion */ cfClose, /* xClose */ cfRead, /* xRead */ cfWrite, /* xWrite */ cfTruncate, /* xTruncate */ cfSync, /* xSync */ cfFileSize, /* xFileSize */ cfLock, /* xLock */ cfUnlock, /* xUnlock */ cfCheckReservedLock, /* xCheckReservedLock */ cfFileControl, /* xFileControl */ cfSectorSize, /* xSectorSize */ cfDeviceCharacteristics, /* xDeviceCharacteristics */ cfShmMap, /* xShmMap */ cfShmLock, /* xShmLock */ cfShmBarrier, /* xShmBarrier */ cfShmUnmap /* xShmUnmap */ }; /* ** Application data for the crash VFS */ struct crashAppData { sqlite3_vfs *pOrig; /* Wrapped vfs structure */ }; /* ** Open a crash-file file handle. ** ** The caller will have allocated pVfs->szOsFile bytes of space ** at pFile. This file uses this space for the CrashFile structure ** and allocates space for the "real" file structure using ** sqlite3_malloc(). The assumption here is (pVfs->szOsFile) is ** equal or greater than sizeof(CrashFile). */ static int cfOpen( sqlite3_vfs *pCfVfs, const char *zName, sqlite3_file *pFile, int flags, int *pOutFlags ){ sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData; int rc; CrashFile *pWrapper = (CrashFile *)pFile; sqlite3_file *pReal = (sqlite3_file*)&pWrapper[1]; memset(pWrapper, 0, sizeof(CrashFile)); rc = sqlite3OsOpen(pVfs, zName, pReal, flags, pOutFlags); if( rc==SQLITE_OK ){ i64 iSize; pWrapper->pMethod = &CrashFileVtab; pWrapper->zName = (char *)zName; pWrapper->pRealFile = pReal; rc = sqlite3OsFileSize(pReal, &iSize); pWrapper->iSize = (int)iSize; pWrapper->flags = flags; } if( rc==SQLITE_OK ){ pWrapper->nData = (int)(4096 + pWrapper->iSize); pWrapper->zData = crash_malloc(pWrapper->nData); if( pWrapper->zData ){ /* os_unix.c contains an assert() that fails if the caller attempts ** to read data from the 512-byte locking region of a file opened ** with the SQLITE_OPEN_MAIN_DB flag. This region of a database file ** never contains valid data anyhow. So avoid doing such a read here. ** ** UPDATE: It also contains an assert() verifying that each call ** to the xRead() method reads less than 128KB of data. */ i64 iOff; memset(pWrapper->zData, 0, pWrapper->nData); for(iOff=0; iOff<pWrapper->iSize; iOff += 512){ int nRead = (int)(pWrapper->iSize - iOff); if( nRead>512 ) nRead = 512; rc = sqlite3OsRead(pReal, &pWrapper->zData[iOff], nRead, iOff); } }else{ rc = SQLITE_NOMEM; } } if( rc!=SQLITE_OK && pWrapper->pMethod ){ sqlite3OsClose(pFile); } return rc; } static int cfDelete(sqlite3_vfs *pCfVfs, const char *zPath, int dirSync){ sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData; return pVfs->xDelete(pVfs, zPath, dirSync); } static int cfAccess( sqlite3_vfs *pCfVfs, const char *zPath, int flags, int *pResOut ){ sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData; return pVfs->xAccess(pVfs, zPath, flags, pResOut); } static int cfFullPathname( sqlite3_vfs *pCfVfs, const char *zPath, int nPathOut, char *zPathOut ){ sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData; return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut); } static void *cfDlOpen(sqlite3_vfs *pCfVfs, const char *zPath){ sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData; return pVfs->xDlOpen(pVfs, zPath); } static void cfDlError(sqlite3_vfs *pCfVfs, int nByte, char *zErrMsg){ sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData; pVfs->xDlError(pVfs, nByte, zErrMsg); } static void (*cfDlSym(sqlite3_vfs *pCfVfs, void *pH, const char *zSym))(void){ sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData; return pVfs->xDlSym(pVfs, pH, zSym); } static void cfDlClose(sqlite3_vfs *pCfVfs, void *pHandle){ sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData; pVfs->xDlClose(pVfs, pHandle); } static int cfRandomness(sqlite3_vfs *pCfVfs, int nByte, char *zBufOut){ sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData; return pVfs->xRandomness(pVfs, nByte, zBufOut); } static int cfSleep(sqlite3_vfs *pCfVfs, int nMicro){ sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData; return pVfs->xSleep(pVfs, nMicro); } static int cfCurrentTime(sqlite3_vfs *pCfVfs, double *pTimeOut){ sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData; return pVfs->xCurrentTime(pVfs, pTimeOut); } static int cfGetLastError(sqlite3_vfs *pCfVfs, int n, char *z){ sqlite3_vfs *pVfs = (sqlite3_vfs *)pCfVfs->pAppData; return pVfs->xGetLastError(pVfs, n, z); } static int processDevSymArgs( Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[], int *piDeviceChar, int *piSectorSize ){ struct DeviceFlag { char *zName; int iValue; } aFlag[] = { { "atomic", SQLITE_IOCAP_ATOMIC }, { "atomic512", SQLITE_IOCAP_ATOMIC512 }, { "atomic1k", SQLITE_IOCAP_ATOMIC1K }, { "atomic2k", SQLITE_IOCAP_ATOMIC2K }, { "atomic4k", SQLITE_IOCAP_ATOMIC4K }, { "atomic8k", SQLITE_IOCAP_ATOMIC8K }, { "atomic16k", SQLITE_IOCAP_ATOMIC16K }, { "atomic32k", SQLITE_IOCAP_ATOMIC32K }, { "atomic64k", SQLITE_IOCAP_ATOMIC64K }, { "sequential", SQLITE_IOCAP_SEQUENTIAL }, { "safe_append", SQLITE_IOCAP_SAFE_APPEND }, { "powersafe_overwrite", SQLITE_IOCAP_POWERSAFE_OVERWRITE }, { "batch-atomic", SQLITE_IOCAP_BATCH_ATOMIC }, { 0, 0 } }; int i; int iDc = 0; int iSectorSize = 0; int setSectorsize = 0; int setDeviceChar = 0; for(i=0; i<objc; i+=2){ int nOpt; char *zOpt = Tcl_GetStringFromObj(objv[i], &nOpt); if( (nOpt>11 || nOpt<2 || strncmp("-sectorsize", zOpt, nOpt)) && (nOpt>16 || nOpt<2 || strncmp("-characteristics", zOpt, nOpt)) ){ Tcl_AppendResult(interp, "Bad option: \"", zOpt, "\" - must be \"-characteristics\" or \"-sectorsize\"", 0 ); return TCL_ERROR; } if( i==objc-1 ){ Tcl_AppendResult(interp, "Option requires an argument: \"", zOpt, "\"",0); return TCL_ERROR; } if( zOpt[1]=='s' ){ if( Tcl_GetIntFromObj(interp, objv[i+1], &iSectorSize) ){ return TCL_ERROR; } setSectorsize = 1; }else{ int j; Tcl_Obj **apObj; int nObj; if( Tcl_ListObjGetElements(interp, objv[i+1], &nObj, &apObj) ){ return TCL_ERROR; } for(j=0; j<nObj; j++){ int rc; int iChoice; Tcl_Obj *pFlag = Tcl_DuplicateObj(apObj[j]); Tcl_IncrRefCount(pFlag); Tcl_UtfToLower(Tcl_GetString(pFlag)); rc = Tcl_GetIndexFromObjStruct( interp, pFlag, aFlag, sizeof(aFlag[0]), "no such flag", 0, &iChoice ); Tcl_DecrRefCount(pFlag); if( rc ){ return TCL_ERROR; } iDc |= aFlag[iChoice].iValue; } setDeviceChar = 1; } } if( setDeviceChar ){ *piDeviceChar = iDc; } if( setSectorsize ){ *piSectorSize = iSectorSize; } return TCL_OK; } /* ** tclcmd: sqlite3_crash_now ** ** Simulate a crash immediately. This function does not return ** (writeListSync() calls exit(-1)). */ static int SQLITE_TCLAPI crashNowCmd( void * clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[] ){ if( objc!=1 ){ Tcl_WrongNumArgs(interp, 1, objv, ""); return TCL_ERROR; } writeListSync(0, 1); assert( 0 ); return TCL_OK; } /* ** tclcmd: sqlite_crash_enable ENABLE ?DEFAULT? ** ** Parameter ENABLE must be a boolean value. If true, then the "crash" ** vfs is added to the system. If false, it is removed. */ static int SQLITE_TCLAPI crashEnableCmd( void * clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[] ){ int isEnable; int isDefault = 0; static sqlite3_vfs crashVfs = { 2, /* iVersion */ 0, /* szOsFile */ 0, /* mxPathname */ 0, /* pNext */ "crash", /* zName */ 0, /* pAppData */ cfOpen, /* xOpen */ cfDelete, /* xDelete */ cfAccess, /* xAccess */ cfFullPathname, /* xFullPathname */ cfDlOpen, /* xDlOpen */ cfDlError, /* xDlError */ cfDlSym, /* xDlSym */ cfDlClose, /* xDlClose */ cfRandomness, /* xRandomness */ cfSleep, /* xSleep */ cfCurrentTime, /* xCurrentTime */ cfGetLastError, /* xGetLastError */ 0, /* xCurrentTimeInt64 */ }; if( objc!=2 && objc!=3 ){ Tcl_WrongNumArgs(interp, 1, objv, "ENABLE ?DEFAULT?"); return TCL_ERROR; } if( Tcl_GetBooleanFromObj(interp, objv[1], &isEnable) ){ return TCL_ERROR; } if( objc==3 && Tcl_GetBooleanFromObj(interp, objv[2], &isDefault) ){ return TCL_ERROR; } if( (isEnable && crashVfs.pAppData) || (!isEnable && !crashVfs.pAppData) ){ return TCL_OK; } if( crashVfs.pAppData==0 ){ sqlite3_vfs *pOriginalVfs = sqlite3_vfs_find(0); crashVfs.mxPathname = pOriginalVfs->mxPathname; crashVfs.pAppData = (void *)pOriginalVfs; crashVfs.szOsFile = sizeof(CrashFile) + pOriginalVfs->szOsFile; sqlite3_vfs_register(&crashVfs, isDefault); }else{ crashVfs.pAppData = 0; sqlite3_vfs_unregister(&crashVfs); } return TCL_OK; } /* ** tclcmd: sqlite_crashparams ?OPTIONS? DELAY CRASHFILE ** ** This procedure implements a TCL command that enables crash testing ** in testfixture. Once enabled, crash testing cannot be disabled. ** ** Available options are "-characteristics" and "-sectorsize". Both require ** an argument. For -sectorsize, this is the simulated sector size in ** bytes. For -characteristics, the argument must be a list of io-capability ** flags to simulate. Valid flags are "atomic", "atomic512", "atomic1K", ** "atomic2K", "atomic4K", "atomic8K", "atomic16K", "atomic32K", ** "atomic64K", "sequential" and "safe_append". ** ** Example: ** ** sqlite_crashparams -sect 1024 -char {atomic sequential} ./test.db 1 ** */ static int SQLITE_TCLAPI crashParamsObjCmd( void * clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[] ){ int iDelay; const char *zCrashFile; int nCrashFile, iDc, iSectorSize; iDc = -1; iSectorSize = -1; if( objc<3 ){ Tcl_WrongNumArgs(interp, 1, objv, "?OPTIONS? DELAY CRASHFILE"); goto error; } zCrashFile = Tcl_GetStringFromObj(objv[objc-1], &nCrashFile); if( nCrashFile>=sizeof(g.zCrashFile) ){ Tcl_AppendResult(interp, "Filename is too long: \"", zCrashFile, "\"", 0); goto error; } if( Tcl_GetIntFromObj(interp, objv[objc-2], &iDelay) ){ goto error; } if( processDevSymArgs(interp, objc-3, &objv[1], &iDc, &iSectorSize) ){ return TCL_ERROR; } if( iDc>=0 ){ g.iDeviceCharacteristics = iDc; } if( iSectorSize>=0 ){ g.iSectorSize = iSectorSize; } g.iCrash = iDelay; memcpy(g.zCrashFile, zCrashFile, nCrashFile+1); sqlite3CrashTestEnable = 1; return TCL_OK; error: return TCL_ERROR; } static int SQLITE_TCLAPI devSymObjCmd( void * clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[] ){ void devsym_register(int iDeviceChar, int iSectorSize); int iDc = -1; int iSectorSize = -1; if( processDevSymArgs(interp, objc-1, &objv[1], &iDc, &iSectorSize) ){ return TCL_ERROR; } devsym_register(iDc, iSectorSize); return TCL_OK; } /* ** tclcmd: sqlite3_crash_on_write N */ static int SQLITE_TCLAPI writeCrashObjCmd( void * clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[] ){ void devsym_crash_on_write(int); int nWrite = 0; if( objc!=2 ){ Tcl_WrongNumArgs(interp, 1, objv, "NWRITE"); return TCL_ERROR; } if( Tcl_GetIntFromObj(interp, objv[1], &nWrite) ){ return TCL_ERROR; } devsym_crash_on_write(nWrite); return TCL_OK; } /* ** tclcmd: unregister_devsim */ static int SQLITE_TCLAPI dsUnregisterObjCmd( void * clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[] ){ void devsym_unregister(void); if( objc!=1 ){ Tcl_WrongNumArgs(interp, 1, objv, ""); return TCL_ERROR; } devsym_unregister(); return TCL_OK; } /* ** tclcmd: register_jt_vfs ?-default? PARENT-VFS */ static int SQLITE_TCLAPI jtObjCmd( void * clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[] ){ int jt_register(char *, int); char *zParent = 0; if( objc!=2 && objc!=3 ){ Tcl_WrongNumArgs(interp, 1, objv, "?-default? PARENT-VFS"); return TCL_ERROR; } zParent = Tcl_GetString(objv[1]); if( objc==3 ){ if( strcmp(zParent, "-default") ){ Tcl_AppendResult(interp, "bad option \"", zParent, "\": must be -default", 0 ); return TCL_ERROR; } zParent = Tcl_GetString(objv[2]); } if( !(*zParent) ){ zParent = 0; } if( jt_register(zParent, objc==3) ){ Tcl_AppendResult(interp, "Error in jt_register", 0); return TCL_ERROR; } return TCL_OK; } /* ** tclcmd: unregister_jt_vfs */ static int SQLITE_TCLAPI jtUnregisterObjCmd( void * clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[] ){ void jt_unregister(void); if( objc!=1 ){ Tcl_WrongNumArgs(interp, 1, objv, ""); return TCL_ERROR; } jt_unregister(); return TCL_OK; } #endif /* SQLITE_OMIT_DISKIO */ /* ** This procedure registers the TCL procedures defined in this file. */ int Sqlitetest6_Init(Tcl_Interp *interp){ #ifndef SQLITE_OMIT_DISKIO Tcl_CreateObjCommand(interp, "sqlite3_crash_enable", crashEnableCmd, 0, 0); Tcl_CreateObjCommand(interp, "sqlite3_crashparams", crashParamsObjCmd, 0, 0); Tcl_CreateObjCommand(interp, "sqlite3_crash_now", crashNowCmd, 0, 0); Tcl_CreateObjCommand(interp, "sqlite3_simulate_device", devSymObjCmd, 0, 0); Tcl_CreateObjCommand(interp, "sqlite3_crash_on_write", writeCrashObjCmd,0,0); Tcl_CreateObjCommand(interp, "unregister_devsim", dsUnregisterObjCmd, 0, 0); Tcl_CreateObjCommand(interp, "register_jt_vfs", jtObjCmd, 0, 0); Tcl_CreateObjCommand(interp, "unregister_jt_vfs", jtUnregisterObjCmd, 0, 0); #endif return TCL_OK; } #endif /* SQLITE_TEST */
the_stack_data/875261.c
#include <sys/select.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <stdio.h> #include <fcntl.h> #include <signal.h> #include <errno.h> #include <stdlib.h> #include <assert.h> #define safe(expr, error) do { if (!(expr)) { perror(error); exit(1); } } while (0) static sig_atomic_t exited; static void sighandler(int sig) { if (sig == SIGCHLD) exited = 1; } int main(int argc, char **argv) { pid_t pid; if (argc < 2) { fprintf(stderr, "usage: fdlink bin args...\n"); exit(2); } signal(SIGCHLD, sighandler); if ((pid = fork()) == 0) { close(0); safe(execv(argv[1], argv + 1) != -1, "fdlink execv"); /* NOTREACHED */ } else { assert(pid != -1); safe(fcntl(0, F_SETFL, O_NONBLOCK) != -1, "fdlink fcntl"); int nfds; do { if (exited == 1) { int status; if (waitpid(pid, &status, WNOHANG) != -1) { exit(WEXITSTATUS(status)); }; exited = 0; } fd_set fdset_r; FD_ZERO(&fdset_r); FD_SET(0, &fdset_r); fd_set fdset_e; FD_ZERO(&fdset_e); FD_SET(0, &fdset_e); nfds = select(64, &fdset_r, NULL, &fdset_e, NULL); if (nfds == -1 && (errno == EAGAIN || errno == EINTR)) continue; else if (nfds == -1) { perror("fdlink select"); exit(1); } if (FD_ISSET(0, &fdset_r) || FD_ISSET(0, &fdset_e)) { char buf[1024]; while (1) { int nread = read(0, &buf, sizeof(buf)); if (nread == -1 && errno == EINTR) continue; else if (nread == -1 && errno == EAGAIN) break; else if (nread == -1) { perror("fdlink read"); exit(1); } else if (nread == 0) { kill(pid, SIGHUP); exit(0); } } } } while (1); } return 0; }
the_stack_data/237643286.c
#include <stdio.h> #include <termios.h> #include <unistd.h> static const int speed_map_arr[][2] = { {230400, B230400}, {115200, B115200}, {57600, B57600}, {38400, B38400}, {19200, B19200}, {9600, B9600}, {4800, B4800}, {2400, B2400}, {1800, B1800}, {1200, B1200}, {600, B600}, {300, B300}, {200, B200}, {150, B150}, {134, B134}, {110, B110}, {75, B75}, {50, B50}, {0, B0}, }; static int getSpeed(int baudRate, speed_t *speed) { unsigned i, arr_size = sizeof(speed_map_arr) / sizeof(speed_map_arr[0]) - 1; for (i = 0; i < arr_size; i++) { if (baudRate == speed_map_arr[i][0]) { *speed = (speed_t)speed_map_arr[i][1]; return (0); } } return (-1); } int setupPort(int fd, int baudRate, int dataBits, int stopBits, int parity) { speed_t speed; struct termios options; if (fd == -1) { fprintf(stderr, "Invalid file descriptor, is the serial port open?"); return (-1); } if (getSpeed(baudRate, &speed) != 0) { fprintf(stderr, "Unsupported baudRate %d\n", baudRate); return (-1); } /* Get current serial port settings */ if (tcgetattr(fd, &options) != 0) { perror("tcgetattr(fd, &options) failed"); return (-1); } /* Setting raw mode / no echo / binary */ options.c_cflag |= (CLOCAL | CREAD); options.c_lflag &= ~(ICANON | ECHO | ECHOE | ECHOK | ECHONL | ISIG | IEXTEN); options.c_oflag &= ~(OPOST | ONLCR | OCRNL); #ifdef OLCUC options.c_oflag &= ~OLCUC; #endif options.c_iflag &= ~(INLCR | IGNCR | ICRNL | IGNBRK); #ifdef IUCLC options.c_iflag &= ~IUCLC; #endif #ifdef PARMRK options.c_iflag &= ~PARMRK; #endif /* Setting the baud rate */ #ifdef __USE_MISC cfsetspeed(&options, speed); #else cfsetispeed(&options, speed); cfsetospeed(&options, speed); #endif /* Setting the data bits */ options.c_cflag &= ~CSIZE; /* Mask the character size bits */ switch (dataBits) { case 5: options.c_cflag |= CS5; /* Select 5 data bits */ break; case 6: options.c_cflag |= CS6; /* Select 6 data bits */ break; case 7: options.c_cflag |= CS7; /* Select 7 data bits */ break; case 8: options.c_cflag |= CS8; /* Select 8 data bits */ break; default: fprintf(stderr, "Unsupported data size %d\n", dataBits); return (-1); } /* Setting the stop bits */ switch (stopBits) { case 1: options.c_cflag &= ~CSTOPB; /* 1 stop bit */ break; case 2: options.c_cflag |= CSTOPB; /* 2 stop bits */ break; default: fprintf(stderr, "Unsupported stop bits %d\n", stopBits); return (-1); } /* Setting parity checking */ options.c_iflag &= ~(INPCK | ISTRIP); switch (parity) { case 0: /* No parity */ options.c_cflag &= ~(PARENB | PARODD); break; case 1: /* Odd parity */ options.c_cflag |= (PARENB | PARODD); break; case 2: /* Even parity */ options.c_cflag &= ~(PARODD); options.c_cflag |= (PARENB); break; #ifdef CMSPAR case 3: /* Mark parity */ options.c_cflag |= (PARENB | CMSPAR | PARODD); break; case 4: /* Space parity */ options.c_cflag |= (PARENB | CMSPAR); options.c_cflag &= ~(PARODD); break; #else case 3: case 4: #endif default: /* invalid parity */ fprintf(stderr, "Unsupported parity %d\n", parity); return (-1); } /* Software flow control is disabled */ options.c_iflag &= ~(IXON | IXOFF | IXANY); /* 15 seconds timeout */ options.c_cc[VMIN] = 0; options.c_cc[VTIME] = 150; tcflush(fd, TCIFLUSH); /* Update the options and do it NOW */ if (tcsetattr(fd, TCSANOW, &options) != 0) { perror("tcsetattr(fd, TCSANOW, &options) failed"); return (-1); } return (0); }
the_stack_data/526791.c
#include<stdio.h> //Pozitif tamsayı girildiği zaman çözüm programı /* int main () { int sayi,kalan; printf("Bir sayı giriniz:"); scanf("%d",&sayi); kalan=sayi%2; if (kalan==1) printf("Girilen sayı tektir"); else printf("Girilen sayı çifttir"); getchar(); getchar(); } */ //Girilen üç tam sayıdan en büyüğünü bulan program /* int main() { int sayi1,sayi2,sayi3; printf ("3 Sayı giriniz:"); scanf("%d%d%d",&sayi1,&sayi2,&sayi3); if (sayi1>=sayi2 && sayi1>=sayi3) printf ("En büyük sayı = %d", sayi2); else printf ("En büyük sayı = %d", sayi3); getchar(); getchar(); } */ //1OO Üzerinden geçme ve kalma durumu hesaplayan program /* int main() { int puan; printf("0-100 Arası bir sayı giriniz:"); scanf("%d", &puan); if (puan>=0 && puan<=44) printf("Başarısız"); if (puan>=45 && puan<=54) printf("Geçer"); if (puan>=55 && puan<=69) printf("Orta"); if (puan >=70 && puan<=84) printf("İyi"); if (puan >=85 && puan<=100) printf("Pekiyi"); getchar(); getchar(); } */
the_stack_data/97306.c
#include <stdio.h> void ProizvoljniBit(unsigned long long* n, unsigned int pos, unsigned int v); void PrintBin64(unsigned long long n, int k) { unsigned long long m = 0x8000000000000000ull; for(int i = 1; i <= 64; ++i) { unsigned long long b = n & m; b >>= (64-i); 64-i == k ? printf("\x1b[32m%llu\x1b[0m", b) : printf("%llu", b); if(i % 8 == 0) { printf(" "); } m >>= 1; } } int main() { unsigned long long n; unsigned int pos, v; printf("Unesite broj: "); scanf("%llu", &n); printf("Pozicija bita (0-63): "); scanf("%u", &pos); printf("Vrednost bita (0/1): "); scanf("%u", &v); printf("Pre: \n"); PrintBin64(n, -1); ProizvoljniBit(&n, pos, v); printf("\n\nPosle: \n"); PrintBin64(n, pos); printf("\n"); return 0; }
the_stack_data/9389.c
struct X; main () { struct X { int y; }; return 0; }
the_stack_data/154826694.c
#include <stdio.h> #include <stdlib.h> char ***insere_resultado(int numero_jogos) { int i,j; char ***resultados = (char ***) malloc(numero_jogos*sizeof(char *)); for ( i = 0; i < numero_jogos; i += 1 ) { resultados[i] = (char **)malloc(4*sizeof(char)); for ( j = 0; j < 4; j += 1 ) { resultados[i][j] = (char *)malloc(10*sizeof(char)); scanf("%s", resultados[i][j]); } } return(resultados); }
the_stack_data/1008055.c
/* * Copyright 2010 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /* * Stub routine for `setgid' for porting support. */ #include <unistd.h> #include <sys/types.h> #include <errno.h> int setgid(gid_t gid) { errno = ENOSYS; return -1; }
the_stack_data/167330211.c
/* This testcase exposed the same bug as PR 15342. */ /* { dg-options "-O2 -frename-registers -fno-schedule-insns" } */ void *memcpy (void *, const void *, __SIZE_TYPE__); void f (int n, int (*x)[4]) { while (n--) { int f = x[0][0]; if (f <= 0) memcpy (&x[1], &x[0], sizeof (x[0])); else memcpy (&x[f], &x[0], sizeof (x[0])); f = x[0][2]; x[0][1] = f; } }
the_stack_data/8001.c
/* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code to implement the "sqlite" command line ** utility for accessing SQLite databases. */ #if (defined(_WIN32) || defined(WIN32)) && !defined(_CRT_SECURE_NO_WARNINGS) /* This needs to come before any includes for MSVC compiler */ #define _CRT_SECURE_NO_WARNINGS #endif /* ** If requested, include the SQLite compiler options file for MSVC. */ #if defined(INCLUDE_MSVC_H) #include "msvc.h" #endif /* ** No support for loadable extensions in VxWorks. */ #if (defined(__RTP__) || defined(_WRS_KERNEL)) && !SQLITE_OMIT_LOAD_EXTENSION # define SQLITE_OMIT_LOAD_EXTENSION 1 #endif /* ** Enable large-file support for fopen() and friends on unix. */ #ifndef SQLITE_DISABLE_LFS # define _LARGE_FILE 1 # ifndef _FILE_OFFSET_BITS # define _FILE_OFFSET_BITS 64 # endif # define _LARGEFILE_SOURCE 1 #endif #include <stdlib.h> #include <string.h> #include <stdio.h> #include <assert.h> #include "sqlite3.h" #if SQLITE_USER_AUTHENTICATION # include "sqlite3userauth.h" #endif #include <ctype.h> #include <stdarg.h> #if !defined(_WIN32) && !defined(WIN32) # include <signal.h> # if !defined(__RTP__) && !defined(_WRS_KERNEL) # include <pwd.h> # endif # include <unistd.h> # include <sys/types.h> #endif #if HAVE_READLINE # include <readline/readline.h> # include <readline/history.h> #endif #if HAVE_EDITLINE # include <editline/readline.h> #endif #if HAVE_EDITLINE || HAVE_READLINE # define shell_add_history(X) add_history(X) # define shell_read_history(X) read_history(X) # define shell_write_history(X) write_history(X) # define shell_stifle_history(X) stifle_history(X) # define shell_readline(X) readline(X) #elif HAVE_LINENOISE # include "linenoise.h" # define shell_add_history(X) linenoiseHistoryAdd(X) # define shell_read_history(X) linenoiseHistoryLoad(X) # define shell_write_history(X) linenoiseHistorySave(X) # define shell_stifle_history(X) linenoiseHistorySetMaxLen(X) # define shell_readline(X) linenoise(X) #else # define shell_read_history(X) # define shell_write_history(X) # define shell_stifle_history(X) # define SHELL_USE_LOCAL_GETLINE 1 #endif #if defined(_WIN32) || defined(WIN32) # include <io.h> # include <fcntl.h> # define isatty(h) _isatty(h) # ifndef access # define access(f,m) _access((f),(m)) # endif # undef popen # define popen _popen # undef pclose # define pclose _pclose #else /* Make sure isatty() has a prototype. */ extern int isatty(int); # if !defined(__RTP__) && !defined(_WRS_KERNEL) /* popen and pclose are not C89 functions and so are ** sometimes omitted from the <stdio.h> header */ extern FILE *popen(const char*,const char*); extern int pclose(FILE*); # else # define SQLITE_OMIT_POPEN 1 # endif #endif #if defined(_WIN32_WCE) /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty() * thus we always assume that we have a console. That can be * overridden with the -batch command line option. */ #define isatty(x) 1 #endif /* ctype macros that work with signed characters */ #define IsSpace(X) isspace((unsigned char)X) #define IsDigit(X) isdigit((unsigned char)X) #define ToLower(X) (char)tolower((unsigned char)X) #if defined(_WIN32) || defined(WIN32) #include <windows.h> /* string conversion routines only needed on Win32 */ extern char *sqlite3_win32_unicode_to_utf8(LPCWSTR); extern char *sqlite3_win32_mbcs_to_utf8_v2(const char *, int); extern char *sqlite3_win32_utf8_to_mbcs_v2(const char *, int); #endif /* On Windows, we normally run with output mode of TEXT so that \n characters ** are automatically translated into \r\n. However, this behavior needs ** to be disabled in some cases (ex: when generating CSV output and when ** rendering quoted strings that contain \n characters). The following ** routines take care of that. */ #if defined(_WIN32) || defined(WIN32) static void setBinaryMode(FILE *file, int isOutput){ if( isOutput ) fflush(file); _setmode(_fileno(file), _O_BINARY); } static void setTextMode(FILE *file, int isOutput){ if( isOutput ) fflush(file); _setmode(_fileno(file), _O_TEXT); } #else # define setBinaryMode(X,Y) # define setTextMode(X,Y) #endif /* True if the timer is enabled */ static int enableTimer = 0; /* Return the current wall-clock time */ static sqlite3_int64 timeOfDay(void){ static sqlite3_vfs *clockVfs = 0; sqlite3_int64 t; if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0); if( clockVfs->iVersion>=2 && clockVfs->xCurrentTimeInt64!=0 ){ clockVfs->xCurrentTimeInt64(clockVfs, &t); }else{ double r; clockVfs->xCurrentTime(clockVfs, &r); t = (sqlite3_int64)(r*86400000.0); } return t; } #if !defined(_WIN32) && !defined(WIN32) && !defined(__minux) #include <sys/time.h> #include <sys/resource.h> /* VxWorks does not support getrusage() as far as we can determine */ #if defined(_WRS_KERNEL) || defined(__RTP__) struct rusage { struct timeval ru_utime; /* user CPU time used */ struct timeval ru_stime; /* system CPU time used */ }; #define getrusage(A,B) memset(B,0,sizeof(*B)) #endif /* Saved resource information for the beginning of an operation */ static struct rusage sBegin; /* CPU time at start */ static sqlite3_int64 iBegin; /* Wall-clock time at start */ /* ** Begin timing an operation */ static void beginTimer(void){ if( enableTimer ){ getrusage(RUSAGE_SELF, &sBegin); iBegin = timeOfDay(); } } /* Return the difference of two time_structs in seconds */ static double timeDiff(struct timeval *pStart, struct timeval *pEnd){ return (pEnd->tv_usec - pStart->tv_usec)*0.000001 + (double)(pEnd->tv_sec - pStart->tv_sec); } /* ** Print the timing results. */ static void endTimer(void){ if( enableTimer ){ sqlite3_int64 iEnd = timeOfDay(); struct rusage sEnd; getrusage(RUSAGE_SELF, &sEnd); printf("Run Time: real %.3f user %f sys %f\n", (iEnd - iBegin)*0.001, timeDiff(&sBegin.ru_utime, &sEnd.ru_utime), timeDiff(&sBegin.ru_stime, &sEnd.ru_stime)); } } #define BEGIN_TIMER beginTimer() #define END_TIMER endTimer() #define HAS_TIMER 1 #elif (defined(_WIN32) || defined(WIN32)) /* Saved resource information for the beginning of an operation */ static HANDLE hProcess; static FILETIME ftKernelBegin; static FILETIME ftUserBegin; static sqlite3_int64 ftWallBegin; typedef BOOL (WINAPI *GETPROCTIMES)(HANDLE, LPFILETIME, LPFILETIME, LPFILETIME, LPFILETIME); static GETPROCTIMES getProcessTimesAddr = NULL; /* ** Check to see if we have timer support. Return 1 if necessary ** support found (or found previously). */ static int hasTimer(void){ if( getProcessTimesAddr ){ return 1; } else { /* GetProcessTimes() isn't supported in WIN95 and some other Windows ** versions. See if the version we are running on has it, and if it ** does, save off a pointer to it and the current process handle. */ hProcess = GetCurrentProcess(); if( hProcess ){ HINSTANCE hinstLib = LoadLibrary(TEXT("Kernel32.dll")); if( NULL != hinstLib ){ getProcessTimesAddr = (GETPROCTIMES) GetProcAddress(hinstLib, "GetProcessTimes"); if( NULL != getProcessTimesAddr ){ return 1; } FreeLibrary(hinstLib); } } } return 0; } /* ** Begin timing an operation */ static void beginTimer(void){ if( enableTimer && getProcessTimesAddr ){ FILETIME ftCreation, ftExit; getProcessTimesAddr(hProcess,&ftCreation,&ftExit, &ftKernelBegin,&ftUserBegin); ftWallBegin = timeOfDay(); } } /* Return the difference of two FILETIME structs in seconds */ static double timeDiff(FILETIME *pStart, FILETIME *pEnd){ sqlite_int64 i64Start = *((sqlite_int64 *) pStart); sqlite_int64 i64End = *((sqlite_int64 *) pEnd); return (double) ((i64End - i64Start) / 10000000.0); } /* ** Print the timing results. */ static void endTimer(void){ if( enableTimer && getProcessTimesAddr){ FILETIME ftCreation, ftExit, ftKernelEnd, ftUserEnd; sqlite3_int64 ftWallEnd = timeOfDay(); getProcessTimesAddr(hProcess,&ftCreation,&ftExit,&ftKernelEnd,&ftUserEnd); printf("Run Time: real %.3f user %f sys %f\n", (ftWallEnd - ftWallBegin)*0.001, timeDiff(&ftUserBegin, &ftUserEnd), timeDiff(&ftKernelBegin, &ftKernelEnd)); } } #define BEGIN_TIMER beginTimer() #define END_TIMER endTimer() #define HAS_TIMER hasTimer() #else #define BEGIN_TIMER #define END_TIMER #define HAS_TIMER 0 #endif /* ** Used to prevent warnings about unused parameters */ #define UNUSED_PARAMETER(x) (void)(x) /* ** If the following flag is set, then command execution stops ** at an error if we are not interactive. */ static int bail_on_error = 0; /* ** Threat stdin as an interactive input if the following variable ** is true. Otherwise, assume stdin is connected to a file or pipe. */ static int stdin_is_interactive = 1; /* ** On Windows systems we have to know if standard output is a console ** in order to translate UTF-8 into MBCS. The following variable is ** true if translation is required. */ static int stdout_is_console = 1; /* ** The following is the open SQLite database. We make a pointer ** to this database a static variable so that it can be accessed ** by the SIGINT handler to interrupt database processing. */ static sqlite3 *globalDb = 0; /* ** True if an interrupt (Control-C) has been received. */ static volatile int seenInterrupt = 0; /* ** This is the name of our program. It is set in main(), used ** in a number of other places, mostly for error messages. */ static char *Argv0; /* ** Prompt strings. Initialized in main. Settable with ** .prompt main continue */ static char mainPrompt[20]; /* First line prompt. default: "sqlite> "*/ static char continuePrompt[20]; /* Continuation prompt. default: " ...> " */ /* ** Render output like fprintf(). Except, if the output is going to the ** console and if this is running on a Windows machine, translate the ** output from UTF-8 into MBCS. */ #if defined(_WIN32) || defined(WIN32) void utf8_printf(FILE *out, const char *zFormat, ...){ va_list ap; va_start(ap, zFormat); if( stdout_is_console && (out==stdout || out==stderr) ){ char *z1 = sqlite3_vmprintf(zFormat, ap); char *z2 = sqlite3_win32_utf8_to_mbcs_v2(z1, 0); sqlite3_free(z1); fputs(z2, out); sqlite3_free(z2); }else{ vfprintf(out, zFormat, ap); } va_end(ap); } #elif !defined(utf8_printf) # define utf8_printf fprintf #endif /* ** Render output like fprintf(). This should not be used on anything that ** includes string formatting (e.g. "%s"). */ #if !defined(raw_printf) # define raw_printf fprintf #endif /* ** Write I/O traces to the following stream. */ #ifdef SQLITE_ENABLE_IOTRACE static FILE *iotrace = 0; #endif /* ** This routine works like printf in that its first argument is a ** format string and subsequent arguments are values to be substituted ** in place of % fields. The result of formatting this string ** is written to iotrace. */ #ifdef SQLITE_ENABLE_IOTRACE static void SQLITE_CDECL iotracePrintf(const char *zFormat, ...){ va_list ap; char *z; if( iotrace==0 ) return; va_start(ap, zFormat); z = sqlite3_vmprintf(zFormat, ap); va_end(ap); utf8_printf(iotrace, "%s", z); sqlite3_free(z); } #endif /* ** Determines if a string is a number of not. */ static int isNumber(const char *z, int *realnum){ if( *z=='-' || *z=='+' ) z++; if( !IsDigit(*z) ){ return 0; } z++; if( realnum ) *realnum = 0; while( IsDigit(*z) ){ z++; } if( *z=='.' ){ z++; if( !IsDigit(*z) ) return 0; while( IsDigit(*z) ){ z++; } if( realnum ) *realnum = 1; } if( *z=='e' || *z=='E' ){ z++; if( *z=='+' || *z=='-' ) z++; if( !IsDigit(*z) ) return 0; while( IsDigit(*z) ){ z++; } if( realnum ) *realnum = 1; } return *z==0; } /* ** A global char* and an SQL function to access its current value ** from within an SQL statement. This program used to use the ** sqlite_exec_printf() API to substitue a string into an SQL statement. ** The correct way to do this with sqlite3 is to use the bind API, but ** since the shell is built around the callback paradigm it would be a lot ** of work. Instead just use this hack, which is quite harmless. */ static const char *zShellStatic = 0; static void shellstaticFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ assert( 0==argc ); assert( zShellStatic ); UNUSED_PARAMETER(argc); UNUSED_PARAMETER(argv); sqlite3_result_text(context, zShellStatic, -1, SQLITE_STATIC); } /* ** Compute a string length that is limited to what can be stored in ** lower 30 bits of a 32-bit signed integer. */ static int strlen30(const char *z){ const char *z2 = z; while( *z2 ){ z2++; } return 0x3fffffff & (int)(z2 - z); } /* ** This routine reads a line of text from FILE in, stores ** the text in memory obtained from malloc() and returns a pointer ** to the text. NULL is returned at end of file, or if malloc() ** fails. ** ** If zLine is not NULL then it is a malloced buffer returned from ** a previous call to this routine that may be reused. */ static char *local_getline(char *zLine, FILE *in){ int nLine = zLine==0 ? 0 : 100; int n = 0; while( 1 ){ if( n+100>nLine ){ nLine = nLine*2 + 100; zLine = realloc(zLine, nLine); if( zLine==0 ) return 0; } if( fgets(&zLine[n], nLine - n, in)==0 ){ if( n==0 ){ free(zLine); return 0; } zLine[n] = 0; break; } while( zLine[n] ) n++; if( n>0 && zLine[n-1]=='\n' ){ n--; if( n>0 && zLine[n-1]=='\r' ) n--; zLine[n] = 0; break; } } #if defined(_WIN32) || defined(WIN32) /* For interactive input on Windows systems, translate the ** multi-byte characterset characters into UTF-8. */ if( stdin_is_interactive && in==stdin ){ char *zTrans = sqlite3_win32_mbcs_to_utf8_v2(zLine, 0); if( zTrans ){ int nTrans = strlen30(zTrans)+1; if( nTrans>nLine ){ zLine = realloc(zLine, nTrans); if( zLine==0 ){ sqlite3_free(zTrans); return 0; } } memcpy(zLine, zTrans, nTrans); sqlite3_free(zTrans); } } #endif /* defined(_WIN32) || defined(WIN32) */ return zLine; } /* ** Retrieve a single line of input text. ** ** If in==0 then read from standard input and prompt before each line. ** If isContinuation is true, then a continuation prompt is appropriate. ** If isContinuation is zero, then the main prompt should be used. ** ** If zPrior is not NULL then it is a buffer from a prior call to this ** routine that can be reused. ** ** The result is stored in space obtained from malloc() and must either ** be freed by the caller or else passed back into this routine via the ** zPrior argument for reuse. */ static char *one_input_line(FILE *in, char *zPrior, int isContinuation){ char *zPrompt; char *zResult; if( in!=0 ){ zResult = local_getline(zPrior, in); }else{ zPrompt = isContinuation ? continuePrompt : mainPrompt; #if SHELL_USE_LOCAL_GETLINE printf("%s", zPrompt); fflush(stdout); zResult = local_getline(zPrior, stdin); #else free(zPrior); zResult = shell_readline(zPrompt); if( zResult && *zResult ) shell_add_history(zResult); #endif } return zResult; } #if defined(SQLITE_ENABLE_SESSION) /* ** State information for a single open session */ typedef struct OpenSession OpenSession; struct OpenSession { char *zName; /* Symbolic name for this session */ int nFilter; /* Number of xFilter rejection GLOB patterns */ char **azFilter; /* Array of xFilter rejection GLOB patterns */ sqlite3_session *p; /* The open session */ }; #endif /* ** Shell output mode information from before ".explain on", ** saved so that it can be restored by ".explain off" */ typedef struct SavedModeInfo SavedModeInfo; struct SavedModeInfo { int valid; /* Is there legit data in here? */ int mode; /* Mode prior to ".explain on" */ int showHeader; /* The ".header" setting prior to ".explain on" */ int colWidth[100]; /* Column widths prior to ".explain on" */ }; /* ** State information about the database connection is contained in an ** instance of the following structure. */ typedef struct ShellState ShellState; struct ShellState { sqlite3 *db; /* The database */ int echoOn; /* True to echo input commands */ int autoExplain; /* Automatically turn on .explain mode */ int autoEQP; /* Run EXPLAIN QUERY PLAN prior to seach SQL stmt */ int statsOn; /* True to display memory stats before each finalize */ int scanstatsOn; /* True to display scan stats before each finalize */ int countChanges; /* True to display change counts */ int backslashOn; /* Resolve C-style \x escapes in SQL input text */ int outCount; /* Revert to stdout when reaching zero */ int cnt; /* Number of records displayed so far */ FILE *out; /* Write results here */ FILE *traceOut; /* Output for sqlite3_trace() */ int nErr; /* Number of errors seen */ int mode; /* An output mode setting */ int cMode; /* temporary output mode for the current query */ int normalMode; /* Output mode before ".explain on" */ int writableSchema; /* True if PRAGMA writable_schema=ON */ int showHeader; /* True to show column names in List or Column mode */ unsigned shellFlgs; /* Various flags */ char *zDestTable; /* Name of destination table when MODE_Insert */ char colSeparator[20]; /* Column separator character for several modes */ char rowSeparator[20]; /* Row separator character for MODE_Ascii */ int colWidth[100]; /* Requested width of each column when in column mode*/ int actualWidth[100]; /* Actual width of each column */ char nullValue[20]; /* The text to print when a NULL comes back from ** the database */ char outfile[FILENAME_MAX]; /* Filename for *out */ const char *zDbFilename; /* name of the database file */ char *zFreeOnClose; /* Filename to free when closing */ const char *zVfs; /* Name of VFS to use */ sqlite3_stmt *pStmt; /* Current statement if any. */ FILE *pLog; /* Write log output here */ int *aiIndent; /* Array of indents used in MODE_Explain */ int nIndent; /* Size of array aiIndent[] */ int iIndent; /* Index of current op in aiIndent[] */ #if defined(SQLITE_ENABLE_SESSION) int nSession; /* Number of active sessions */ OpenSession aSession[4]; /* Array of sessions. [0] is in focus. */ #endif }; /* ** These are the allowed shellFlgs values */ #define SHFLG_Scratch 0x00001 /* The --scratch option is used */ #define SHFLG_Pagecache 0x00002 /* The --pagecache option is used */ #define SHFLG_Lookaside 0x00004 /* Lookaside memory is used */ /* ** These are the allowed modes. */ #define MODE_Line 0 /* One column per line. Blank line between records */ #define MODE_Column 1 /* One record per line in neat columns */ #define MODE_List 2 /* One record per line with a separator */ #define MODE_Semi 3 /* Same as MODE_List but append ";" to each line */ #define MODE_Html 4 /* Generate an XHTML table */ #define MODE_Insert 5 /* Generate SQL "insert" statements */ #define MODE_Tcl 6 /* Generate ANSI-C or TCL quoted elements */ #define MODE_Csv 7 /* Quote strings, numbers are plain */ #define MODE_Explain 8 /* Like MODE_Column, but do not truncate data */ #define MODE_Ascii 9 /* Use ASCII unit and record separators (0x1F/0x1E) */ #define MODE_Pretty 10 /* Pretty-print schemas */ static const char *modeDescr[] = { "line", "column", "list", "semi", "html", "insert", "tcl", "csv", "explain", "ascii", "prettyprint", }; /* ** These are the column/row/line separators used by the various ** import/export modes. */ #define SEP_Column "|" #define SEP_Row "\n" #define SEP_Tab "\t" #define SEP_Space " " #define SEP_Comma "," #define SEP_CrLf "\r\n" #define SEP_Unit "\x1F" #define SEP_Record "\x1E" /* ** Number of elements in an array */ #define ArraySize(X) (int)(sizeof(X)/sizeof(X[0])) /* ** A callback for the sqlite3_log() interface. */ static void shellLog(void *pArg, int iErrCode, const char *zMsg){ ShellState *p = (ShellState*)pArg; if( p->pLog==0 ) return; utf8_printf(p->pLog, "(%d) %s\n", iErrCode, zMsg); fflush(p->pLog); } /* ** Output the given string as a hex-encoded blob (eg. X'1234' ) */ static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){ int i; char *zBlob = (char *)pBlob; raw_printf(out,"X'"); for(i=0; i<nBlob; i++){ raw_printf(out,"%02x",zBlob[i]&0xff); } raw_printf(out,"'"); } /* ** Output the given string as a quoted string using SQL quoting conventions. */ static void output_quoted_string(FILE *out, const char *z){ int i; int nSingle = 0; setBinaryMode(out, 1); for(i=0; z[i]; i++){ if( z[i]=='\'' ) nSingle++; } if( nSingle==0 ){ utf8_printf(out,"'%s'",z); }else{ raw_printf(out,"'"); while( *z ){ for(i=0; z[i] && z[i]!='\''; i++){} if( i==0 ){ raw_printf(out,"''"); z++; }else if( z[i]=='\'' ){ utf8_printf(out,"%.*s''",i,z); z += i+1; }else{ utf8_printf(out,"%s",z); break; } } raw_printf(out,"'"); } setTextMode(out, 1); } /* ** Output the given string as a quoted according to C or TCL quoting rules. */ static void output_c_string(FILE *out, const char *z){ unsigned int c; fputc('"', out); while( (c = *(z++))!=0 ){ if( c=='\\' ){ fputc(c, out); fputc(c, out); }else if( c=='"' ){ fputc('\\', out); fputc('"', out); }else if( c=='\t' ){ fputc('\\', out); fputc('t', out); }else if( c=='\n' ){ fputc('\\', out); fputc('n', out); }else if( c=='\r' ){ fputc('\\', out); fputc('r', out); }else if( !isprint(c&0xff) ){ raw_printf(out, "\\%03o", c&0xff); }else{ fputc(c, out); } } fputc('"', out); } /* ** Output the given string with characters that are special to ** HTML escaped. */ static void output_html_string(FILE *out, const char *z){ int i; if( z==0 ) z = ""; while( *z ){ for(i=0; z[i] && z[i]!='<' && z[i]!='&' && z[i]!='>' && z[i]!='\"' && z[i]!='\''; i++){} if( i>0 ){ utf8_printf(out,"%.*s",i,z); } if( z[i]=='<' ){ raw_printf(out,"&lt;"); }else if( z[i]=='&' ){ raw_printf(out,"&amp;"); }else if( z[i]=='>' ){ raw_printf(out,"&gt;"); }else if( z[i]=='\"' ){ raw_printf(out,"&quot;"); }else if( z[i]=='\'' ){ raw_printf(out,"&#39;"); }else{ break; } z += i + 1; } } /* ** If a field contains any character identified by a 1 in the following ** array, then the string must be quoted for CSV. */ static const char needCsvQuote[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, }; /* ** Output a single term of CSV. Actually, p->colSeparator is used for ** the separator, which may or may not be a comma. p->nullValue is ** the null value. Strings are quoted if necessary. The separator ** is only issued if bSep is true. */ static void output_csv(ShellState *p, const char *z, int bSep){ FILE *out = p->out; if( z==0 ){ utf8_printf(out,"%s",p->nullValue); }else{ int i; int nSep = strlen30(p->colSeparator); for(i=0; z[i]; i++){ if( needCsvQuote[((unsigned char*)z)[i]] || (z[i]==p->colSeparator[0] && (nSep==1 || memcmp(z, p->colSeparator, nSep)==0)) ){ i = 0; break; } } if( i==0 ){ putc('"', out); for(i=0; z[i]; i++){ if( z[i]=='"' ) putc('"', out); putc(z[i], out); } putc('"', out); }else{ utf8_printf(out, "%s", z); } } if( bSep ){ utf8_printf(p->out, "%s", p->colSeparator); } } #ifdef SIGINT /* ** This routine runs when the user presses Ctrl-C */ static void interrupt_handler(int NotUsed){ UNUSED_PARAMETER(NotUsed); seenInterrupt++; if( seenInterrupt>2 ) exit(1); if( globalDb ) sqlite3_interrupt(globalDb); } #endif /* ** When the ".auth ON" is set, the following authorizer callback is ** invoked. It always returns SQLITE_OK. */ static int shellAuth( void *pClientData, int op, const char *zA1, const char *zA2, const char *zA3, const char *zA4 ){ ShellState *p = (ShellState*)pClientData; static const char *azAction[] = { 0, "CREATE_INDEX", "CREATE_TABLE", "CREATE_TEMP_INDEX", "CREATE_TEMP_TABLE", "CREATE_TEMP_TRIGGER", "CREATE_TEMP_VIEW", "CREATE_TRIGGER", "CREATE_VIEW", "DELETE", "DROP_INDEX", "DROP_TABLE", "DROP_TEMP_INDEX", "DROP_TEMP_TABLE", "DROP_TEMP_TRIGGER", "DROP_TEMP_VIEW", "DROP_TRIGGER", "DROP_VIEW", "INSERT", "PRAGMA", "READ", "SELECT", "TRANSACTION", "UPDATE", "ATTACH", "DETACH", "ALTER_TABLE", "REINDEX", "ANALYZE", "CREATE_VTABLE", "DROP_VTABLE", "FUNCTION", "SAVEPOINT", "RECURSIVE" }; int i; const char *az[4]; az[0] = zA1; az[1] = zA2; az[2] = zA3; az[3] = zA4; raw_printf(p->out, "authorizer: %s", azAction[op]); for(i=0; i<4; i++){ raw_printf(p->out, " "); if( az[i] ){ output_c_string(p->out, az[i]); }else{ raw_printf(p->out, "NULL"); } } raw_printf(p->out, "\n"); return SQLITE_OK; } /* ** This is the callback routine that the shell ** invokes for each row of a query result. */ static int shell_callback( void *pArg, int nArg, /* Number of result columns */ char **azArg, /* Text of each result column */ char **azCol, /* Column names */ int *aiType /* Column types */ ){ int i; ShellState *p = (ShellState*)pArg; switch( p->cMode ){ case MODE_Line: { int w = 5; if( azArg==0 ) break; for(i=0; i<nArg; i++){ int len = strlen30(azCol[i] ? azCol[i] : ""); if( len>w ) w = len; } if( p->cnt++>0 ) utf8_printf(p->out, "%s", p->rowSeparator); for(i=0; i<nArg; i++){ utf8_printf(p->out,"%*s = %s%s", w, azCol[i], azArg[i] ? azArg[i] : p->nullValue, p->rowSeparator); } break; } case MODE_Explain: case MODE_Column: { static const int aExplainWidths[] = {4, 13, 4, 4, 4, 13, 2, 13}; const int *colWidth; int showHdr; char *rowSep; if( p->cMode==MODE_Column ){ colWidth = p->colWidth; showHdr = p->showHeader; rowSep = p->rowSeparator; }else{ colWidth = aExplainWidths; showHdr = 1; rowSep = SEP_Row; } if( p->cnt++==0 ){ for(i=0; i<nArg; i++){ int w, n; if( i<ArraySize(p->colWidth) ){ w = colWidth[i]; }else{ w = 0; } if( w==0 ){ w = strlen30(azCol[i] ? azCol[i] : ""); if( w<10 ) w = 10; n = strlen30(azArg && azArg[i] ? azArg[i] : p->nullValue); if( w<n ) w = n; } if( i<ArraySize(p->actualWidth) ){ p->actualWidth[i] = w; } if( showHdr ){ if( w<0 ){ utf8_printf(p->out,"%*.*s%s",-w,-w,azCol[i], i==nArg-1 ? rowSep : " "); }else{ utf8_printf(p->out,"%-*.*s%s",w,w,azCol[i], i==nArg-1 ? rowSep : " "); } } } if( showHdr ){ for(i=0; i<nArg; i++){ int w; if( i<ArraySize(p->actualWidth) ){ w = p->actualWidth[i]; if( w<0 ) w = -w; }else{ w = 10; } utf8_printf(p->out,"%-*.*s%s",w,w, "----------------------------------------------------------" "----------------------------------------------------------", i==nArg-1 ? rowSep : " "); } } } if( azArg==0 ) break; for(i=0; i<nArg; i++){ int w; if( i<ArraySize(p->actualWidth) ){ w = p->actualWidth[i]; }else{ w = 10; } if( p->cMode==MODE_Explain && azArg[i] && strlen30(azArg[i])>w ){ w = strlen30(azArg[i]); } if( i==1 && p->aiIndent && p->pStmt ){ if( p->iIndent<p->nIndent ){ utf8_printf(p->out, "%*.s", p->aiIndent[p->iIndent], ""); } p->iIndent++; } if( w<0 ){ utf8_printf(p->out,"%*.*s%s",-w,-w, azArg[i] ? azArg[i] : p->nullValue, i==nArg-1 ? rowSep : " "); }else{ utf8_printf(p->out,"%-*.*s%s",w,w, azArg[i] ? azArg[i] : p->nullValue, i==nArg-1 ? rowSep : " "); } } break; } case MODE_Semi: { /* .schema and .fullschema output */ utf8_printf(p->out, "%s;\n", azArg[0]); break; } case MODE_Pretty: { /* .schema and .fullschema with --indent */ char *z; int j; int nParen = 0; char cEnd = 0; char c; int nLine = 0; assert( nArg==1 ); if( azArg[0]==0 ) break; if( sqlite3_strlike("CREATE VIEW%", azArg[0], 0)==0 || sqlite3_strlike("CREATE TRIG%", azArg[0], 0)==0 ){ utf8_printf(p->out, "%s;\n", azArg[0]); break; } z = sqlite3_mprintf("%s", azArg[0]); j = 0; for(i=0; IsSpace(z[i]); i++){} for(; (c = z[i])!=0; i++){ if( IsSpace(c) ){ if( IsSpace(z[j-1]) || z[j-1]=='(' ) continue; }else if( (c=='(' || c==')') && j>0 && IsSpace(z[j-1]) ){ j--; } z[j++] = c; } while( j>0 && IsSpace(z[j-1]) ){ j--; } z[j] = 0; if( strlen30(z)>=79 ){ for(i=j=0; (c = z[i])!=0; i++){ if( c==cEnd ){ cEnd = 0; }else if( c=='"' || c=='\'' || c=='`' ){ cEnd = c; }else if( c=='[' ){ cEnd = ']'; }else if( c=='(' ){ nParen++; }else if( c==')' ){ nParen--; if( nLine>0 && nParen==0 && j>0 ){ utf8_printf(p->out, "%.*s\n", j, z); j = 0; } } z[j++] = c; if( nParen==1 && (c=='(' || c==',' || c=='\n') ){ if( c=='\n' ) j--; utf8_printf(p->out, "%.*s\n ", j, z); j = 0; nLine++; while( IsSpace(z[i+1]) ){ i++; } } } z[j] = 0; } utf8_printf(p->out, "%s;\n", z); sqlite3_free(z); break; } case MODE_List: { if( p->cnt++==0 && p->showHeader ){ for(i=0; i<nArg; i++){ utf8_printf(p->out,"%s%s",azCol[i], i==nArg-1 ? p->rowSeparator : p->colSeparator); } } if( azArg==0 ) break; for(i=0; i<nArg; i++){ char *z = azArg[i]; if( z==0 ) z = p->nullValue; utf8_printf(p->out, "%s", z); if( i<nArg-1 ){ utf8_printf(p->out, "%s", p->colSeparator); }else{ utf8_printf(p->out, "%s", p->rowSeparator); } } break; } case MODE_Html: { if( p->cnt++==0 && p->showHeader ){ raw_printf(p->out,"<TR>"); for(i=0; i<nArg; i++){ raw_printf(p->out,"<TH>"); output_html_string(p->out, azCol[i]); raw_printf(p->out,"</TH>\n"); } raw_printf(p->out,"</TR>\n"); } if( azArg==0 ) break; raw_printf(p->out,"<TR>"); for(i=0; i<nArg; i++){ raw_printf(p->out,"<TD>"); output_html_string(p->out, azArg[i] ? azArg[i] : p->nullValue); raw_printf(p->out,"</TD>\n"); } raw_printf(p->out,"</TR>\n"); break; } case MODE_Tcl: { if( p->cnt++==0 && p->showHeader ){ for(i=0; i<nArg; i++){ output_c_string(p->out,azCol[i] ? azCol[i] : ""); if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator); } utf8_printf(p->out, "%s", p->rowSeparator); } if( azArg==0 ) break; for(i=0; i<nArg; i++){ output_c_string(p->out, azArg[i] ? azArg[i] : p->nullValue); if(i<nArg-1) utf8_printf(p->out, "%s", p->colSeparator); } utf8_printf(p->out, "%s", p->rowSeparator); break; } case MODE_Csv: { setBinaryMode(p->out, 1); if( p->cnt++==0 && p->showHeader ){ for(i=0; i<nArg; i++){ output_csv(p, azCol[i] ? azCol[i] : "", i<nArg-1); } utf8_printf(p->out, "%s", p->rowSeparator); } if( nArg>0 ){ for(i=0; i<nArg; i++){ output_csv(p, azArg[i], i<nArg-1); } utf8_printf(p->out, "%s", p->rowSeparator); } setTextMode(p->out, 1); break; } case MODE_Insert: { p->cnt++; if( azArg==0 ) break; utf8_printf(p->out,"INSERT INTO %s",p->zDestTable); if( p->showHeader ){ raw_printf(p->out,"("); for(i=0; i<nArg; i++){ char *zSep = i>0 ? ",": ""; utf8_printf(p->out, "%s%s", zSep, azCol[i]); } raw_printf(p->out,")"); } raw_printf(p->out," VALUES("); for(i=0; i<nArg; i++){ char *zSep = i>0 ? ",": ""; if( (azArg[i]==0) || (aiType && aiType[i]==SQLITE_NULL) ){ utf8_printf(p->out,"%sNULL",zSep); }else if( aiType && aiType[i]==SQLITE_TEXT ){ if( zSep[0] ) utf8_printf(p->out,"%s",zSep); output_quoted_string(p->out, azArg[i]); }else if( aiType && (aiType[i]==SQLITE_INTEGER || aiType[i]==SQLITE_FLOAT) ){ utf8_printf(p->out,"%s%s",zSep, azArg[i]); }else if( aiType && aiType[i]==SQLITE_BLOB && p->pStmt ){ const void *pBlob = sqlite3_column_blob(p->pStmt, i); int nBlob = sqlite3_column_bytes(p->pStmt, i); if( zSep[0] ) utf8_printf(p->out,"%s",zSep); output_hex_blob(p->out, pBlob, nBlob); }else if( isNumber(azArg[i], 0) ){ utf8_printf(p->out,"%s%s",zSep, azArg[i]); }else{ if( zSep[0] ) utf8_printf(p->out,"%s",zSep); output_quoted_string(p->out, azArg[i]); } } raw_printf(p->out,");\n"); break; } case MODE_Ascii: { if( p->cnt++==0 && p->showHeader ){ for(i=0; i<nArg; i++){ if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator); utf8_printf(p->out,"%s",azCol[i] ? azCol[i] : ""); } utf8_printf(p->out, "%s", p->rowSeparator); } if( azArg==0 ) break; for(i=0; i<nArg; i++){ if( i>0 ) utf8_printf(p->out, "%s", p->colSeparator); utf8_printf(p->out,"%s",azArg[i] ? azArg[i] : p->nullValue); } utf8_printf(p->out, "%s", p->rowSeparator); break; } } return 0; } /* ** This is the callback routine that the SQLite library ** invokes for each row of a query result. */ static int callback(void *pArg, int nArg, char **azArg, char **azCol){ /* since we don't have type info, call the shell_callback with a NULL value */ return shell_callback(pArg, nArg, azArg, azCol, NULL); } /* ** Set the destination table field of the ShellState structure to ** the name of the table given. Escape any quote characters in the ** table name. */ static void set_table_name(ShellState *p, const char *zName){ int i, n; int needQuote; char *z; if( p->zDestTable ){ free(p->zDestTable); p->zDestTable = 0; } if( zName==0 ) return; needQuote = !isalpha((unsigned char)*zName) && *zName!='_'; for(i=n=0; zName[i]; i++, n++){ if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ){ needQuote = 1; if( zName[i]=='\'' ) n++; } } if( needQuote ) n += 2; z = p->zDestTable = malloc( n+1 ); if( z==0 ){ raw_printf(stderr,"Error: out of memory\n"); exit(1); } n = 0; if( needQuote ) z[n++] = '\''; for(i=0; zName[i]; i++){ z[n++] = zName[i]; if( zName[i]=='\'' ) z[n++] = '\''; } if( needQuote ) z[n++] = '\''; z[n] = 0; } /* zIn is either a pointer to a NULL-terminated string in memory obtained ** from malloc(), or a NULL pointer. The string pointed to by zAppend is ** added to zIn, and the result returned in memory obtained from malloc(). ** zIn, if it was not NULL, is freed. ** ** If the third argument, quote, is not '\0', then it is used as a ** quote character for zAppend. */ static char *appendText(char *zIn, char const *zAppend, char quote){ int len; int i; int nAppend = strlen30(zAppend); int nIn = (zIn?strlen30(zIn):0); len = nAppend+nIn+1; if( quote ){ len += 2; for(i=0; i<nAppend; i++){ if( zAppend[i]==quote ) len++; } } zIn = (char *)realloc(zIn, len); if( !zIn ){ return 0; } if( quote ){ char *zCsr = &zIn[nIn]; *zCsr++ = quote; for(i=0; i<nAppend; i++){ *zCsr++ = zAppend[i]; if( zAppend[i]==quote ) *zCsr++ = quote; } *zCsr++ = quote; *zCsr++ = '\0'; assert( (zCsr-zIn)==len ); }else{ memcpy(&zIn[nIn], zAppend, nAppend); zIn[len-1] = '\0'; } return zIn; } /* ** Execute a query statement that will generate SQL output. Print ** the result columns, comma-separated, on a line and then add a ** semicolon terminator to the end of that line. ** ** If the number of columns is 1 and that column contains text "--" ** then write the semicolon on a separate line. That way, if a ** "--" comment occurs at the end of the statement, the comment ** won't consume the semicolon terminator. */ static int run_table_dump_query( ShellState *p, /* Query context */ const char *zSelect, /* SELECT statement to extract content */ const char *zFirstRow /* Print before first row, if not NULL */ ){ sqlite3_stmt *pSelect; int rc; int nResult; int i; const char *z; rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0); if( rc!=SQLITE_OK || !pSelect ){ utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db)); if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; return rc; } rc = sqlite3_step(pSelect); nResult = sqlite3_column_count(pSelect); while( rc==SQLITE_ROW ){ if( zFirstRow ){ utf8_printf(p->out, "%s", zFirstRow); zFirstRow = 0; } z = (const char*)sqlite3_column_text(pSelect, 0); utf8_printf(p->out, "%s", z); for(i=1; i<nResult; i++){ utf8_printf(p->out, ",%s", sqlite3_column_text(pSelect, i)); } if( z==0 ) z = ""; while( z[0] && (z[0]!='-' || z[1]!='-') ) z++; if( z[0] ){ raw_printf(p->out, "\n;\n"); }else{ raw_printf(p->out, ";\n"); } rc = sqlite3_step(pSelect); } rc = sqlite3_finalize(pSelect); if( rc!=SQLITE_OK ){ utf8_printf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db)); if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; } return rc; } /* ** Allocate space and save off current error string. */ static char *save_err_msg( sqlite3 *db /* Database to query */ ){ int nErrMsg = 1+strlen30(sqlite3_errmsg(db)); char *zErrMsg = sqlite3_malloc64(nErrMsg); if( zErrMsg ){ memcpy(zErrMsg, sqlite3_errmsg(db), nErrMsg); } return zErrMsg; } #ifdef __linux__ /* ** Attempt to display I/O stats on Linux using /proc/PID/io */ static void displayLinuxIoStats(FILE *out){ FILE *in; char z[200]; sqlite3_snprintf(sizeof(z), z, "/proc/%d/io", getpid()); in = fopen(z, "rb"); if( in==0 ) return; while( fgets(z, sizeof(z), in)!=0 ){ static const struct { const char *zPattern; const char *zDesc; } aTrans[] = { { "rchar: ", "Bytes received by read():" }, { "wchar: ", "Bytes sent to write():" }, { "syscr: ", "Read() system calls:" }, { "syscw: ", "Write() system calls:" }, { "read_bytes: ", "Bytes read from storage:" }, { "write_bytes: ", "Bytes written to storage:" }, { "cancelled_write_bytes: ", "Cancelled write bytes:" }, }; int i; for(i=0; i<ArraySize(aTrans); i++){ int n = (int)strlen(aTrans[i].zPattern); if( strncmp(aTrans[i].zPattern, z, n)==0 ){ raw_printf(out, "%-36s %s", aTrans[i].zDesc, &z[n]); break; } } } fclose(in); } #endif /* ** Display memory stats. */ static int display_stats( sqlite3 *db, /* Database to query */ ShellState *pArg, /* Pointer to ShellState */ int bReset /* True to reset the stats */ ){ int iCur; int iHiwtr; if( pArg && pArg->out ){ iHiwtr = iCur = -1; sqlite3_status(SQLITE_STATUS_MEMORY_USED, &iCur, &iHiwtr, bReset); raw_printf(pArg->out, "Memory Used: %d (max %d) bytes\n", iCur, iHiwtr); iHiwtr = iCur = -1; sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &iCur, &iHiwtr, bReset); raw_printf(pArg->out, "Number of Outstanding Allocations: %d (max %d)\n", iCur, iHiwtr); if( pArg->shellFlgs & SHFLG_Pagecache ){ iHiwtr = iCur = -1; sqlite3_status(SQLITE_STATUS_PAGECACHE_USED, &iCur, &iHiwtr, bReset); raw_printf(pArg->out, "Number of Pcache Pages Used: %d (max %d) pages\n", iCur, iHiwtr); } iHiwtr = iCur = -1; sqlite3_status(SQLITE_STATUS_PAGECACHE_OVERFLOW, &iCur, &iHiwtr, bReset); raw_printf(pArg->out, "Number of Pcache Overflow Bytes: %d (max %d) bytes\n", iCur, iHiwtr); if( pArg->shellFlgs & SHFLG_Scratch ){ iHiwtr = iCur = -1; sqlite3_status(SQLITE_STATUS_SCRATCH_USED, &iCur, &iHiwtr, bReset); raw_printf(pArg->out, "Number of Scratch Allocations Used: %d (max %d)\n", iCur, iHiwtr); } iHiwtr = iCur = -1; sqlite3_status(SQLITE_STATUS_SCRATCH_OVERFLOW, &iCur, &iHiwtr, bReset); raw_printf(pArg->out, "Number of Scratch Overflow Bytes: %d (max %d) bytes\n", iCur, iHiwtr); iHiwtr = iCur = -1; sqlite3_status(SQLITE_STATUS_MALLOC_SIZE, &iCur, &iHiwtr, bReset); raw_printf(pArg->out, "Largest Allocation: %d bytes\n", iHiwtr); iHiwtr = iCur = -1; sqlite3_status(SQLITE_STATUS_PAGECACHE_SIZE, &iCur, &iHiwtr, bReset); raw_printf(pArg->out, "Largest Pcache Allocation: %d bytes\n", iHiwtr); iHiwtr = iCur = -1; sqlite3_status(SQLITE_STATUS_SCRATCH_SIZE, &iCur, &iHiwtr, bReset); raw_printf(pArg->out, "Largest Scratch Allocation: %d bytes\n", iHiwtr); #ifdef YYTRACKMAXSTACKDEPTH iHiwtr = iCur = -1; sqlite3_status(SQLITE_STATUS_PARSER_STACK, &iCur, &iHiwtr, bReset); raw_printf(pArg->out, "Deepest Parser Stack: %d (max %d)\n", iCur, iHiwtr); #endif } if( pArg && pArg->out && db ){ if( pArg->shellFlgs & SHFLG_Lookaside ){ iHiwtr = iCur = -1; sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED, &iCur, &iHiwtr, bReset); raw_printf(pArg->out, "Lookaside Slots Used: %d (max %d)\n", iCur, iHiwtr); sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT, &iCur, &iHiwtr, bReset); raw_printf(pArg->out, "Successful lookaside attempts: %d\n", iHiwtr); sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE, &iCur, &iHiwtr, bReset); raw_printf(pArg->out, "Lookaside failures due to size: %d\n", iHiwtr); sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL, &iCur, &iHiwtr, bReset); raw_printf(pArg->out, "Lookaside failures due to OOM: %d\n", iHiwtr); } iHiwtr = iCur = -1; sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, bReset); raw_printf(pArg->out, "Pager Heap Usage: %d bytes\n", iCur); iHiwtr = iCur = -1; sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1); raw_printf(pArg->out, "Page cache hits: %d\n", iCur); iHiwtr = iCur = -1; sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1); raw_printf(pArg->out, "Page cache misses: %d\n", iCur); iHiwtr = iCur = -1; sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1); raw_printf(pArg->out, "Page cache writes: %d\n", iCur); iHiwtr = iCur = -1; sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, bReset); raw_printf(pArg->out, "Schema Heap Usage: %d bytes\n", iCur); iHiwtr = iCur = -1; sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, bReset); raw_printf(pArg->out, "Statement Heap/Lookaside Usage: %d bytes\n", iCur); } if( pArg && pArg->out && db && pArg->pStmt ){ iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_FULLSCAN_STEP, bReset); raw_printf(pArg->out, "Fullscan Steps: %d\n", iCur); iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_SORT, bReset); raw_printf(pArg->out, "Sort Operations: %d\n", iCur); iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_AUTOINDEX,bReset); raw_printf(pArg->out, "Autoindex Inserts: %d\n", iCur); iCur = sqlite3_stmt_status(pArg->pStmt, SQLITE_STMTSTATUS_VM_STEP, bReset); raw_printf(pArg->out, "Virtual Machine Steps: %d\n", iCur); } #ifdef __linux__ displayLinuxIoStats(pArg->out); #endif /* Do not remove this machine readable comment: extra-stats-output-here */ return 0; } /* ** Display scan stats. */ static void display_scanstats( sqlite3 *db, /* Database to query */ ShellState *pArg /* Pointer to ShellState */ ){ #ifndef SQLITE_ENABLE_STMT_SCANSTATUS UNUSED_PARAMETER(db); UNUSED_PARAMETER(pArg); #else int i, k, n, mx; raw_printf(pArg->out, "-------- scanstats --------\n"); mx = 0; for(k=0; k<=mx; k++){ double rEstLoop = 1.0; for(i=n=0; 1; i++){ sqlite3_stmt *p = pArg->pStmt; sqlite3_int64 nLoop, nVisit; double rEst; int iSid; const char *zExplain; if( sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NLOOP, (void*)&nLoop) ){ break; } sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_SELECTID, (void*)&iSid); if( iSid>mx ) mx = iSid; if( iSid!=k ) continue; if( n==0 ){ rEstLoop = (double)nLoop; if( k>0 ) raw_printf(pArg->out, "-------- subquery %d -------\n", k); } n++; sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_NVISIT, (void*)&nVisit); sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EST, (void*)&rEst); sqlite3_stmt_scanstatus(p, i, SQLITE_SCANSTAT_EXPLAIN, (void*)&zExplain); utf8_printf(pArg->out, "Loop %2d: %s\n", n, zExplain); rEstLoop *= rEst; raw_printf(pArg->out, " nLoop=%-8lld nRow=%-8lld estRow=%-8lld estRow/Loop=%-8g\n", nLoop, nVisit, (sqlite3_int64)(rEstLoop+0.5), rEst ); } } raw_printf(pArg->out, "---------------------------\n"); #endif } /* ** Parameter azArray points to a zero-terminated array of strings. zStr ** points to a single nul-terminated string. Return non-zero if zStr ** is equal, according to strcmp(), to any of the strings in the array. ** Otherwise, return zero. */ static int str_in_array(const char *zStr, const char **azArray){ int i; for(i=0; azArray[i]; i++){ if( 0==strcmp(zStr, azArray[i]) ) return 1; } return 0; } /* ** If compiled statement pSql appears to be an EXPLAIN statement, allocate ** and populate the ShellState.aiIndent[] array with the number of ** spaces each opcode should be indented before it is output. ** ** The indenting rules are: ** ** * For each "Next", "Prev", "VNext" or "VPrev" instruction, indent ** all opcodes that occur between the p2 jump destination and the opcode ** itself by 2 spaces. ** ** * For each "Goto", if the jump destination is earlier in the program ** and ends on one of: ** Yield SeekGt SeekLt RowSetRead Rewind ** or if the P1 parameter is one instead of zero, ** then indent all opcodes between the earlier instruction ** and "Goto" by 2 spaces. */ static void explain_data_prepare(ShellState *p, sqlite3_stmt *pSql){ const char *zSql; /* The text of the SQL statement */ const char *z; /* Used to check if this is an EXPLAIN */ int *abYield = 0; /* True if op is an OP_Yield */ int nAlloc = 0; /* Allocated size of p->aiIndent[], abYield */ int iOp; /* Index of operation in p->aiIndent[] */ const char *azNext[] = { "Next", "Prev", "VPrev", "VNext", "SorterNext", "NextIfOpen", "PrevIfOpen", 0 }; const char *azYield[] = { "Yield", "SeekLT", "SeekGT", "RowSetRead", "Rewind", 0 }; const char *azGoto[] = { "Goto", 0 }; /* Try to figure out if this is really an EXPLAIN statement. If this ** cannot be verified, return early. */ if( sqlite3_column_count(pSql)!=8 ){ p->cMode = p->mode; return; } zSql = sqlite3_sql(pSql); if( zSql==0 ) return; for(z=zSql; *z==' ' || *z=='\t' || *z=='\n' || *z=='\f' || *z=='\r'; z++); if( sqlite3_strnicmp(z, "explain", 7) ){ p->cMode = p->mode; return; } for(iOp=0; SQLITE_ROW==sqlite3_step(pSql); iOp++){ int i; int iAddr = sqlite3_column_int(pSql, 0); const char *zOp = (const char*)sqlite3_column_text(pSql, 1); /* Set p2 to the P2 field of the current opcode. Then, assuming that ** p2 is an instruction address, set variable p2op to the index of that ** instruction in the aiIndent[] array. p2 and p2op may be different if ** the current instruction is part of a sub-program generated by an ** SQL trigger or foreign key. */ int p2 = sqlite3_column_int(pSql, 3); int p2op = (p2 + (iOp-iAddr)); /* Grow the p->aiIndent array as required */ if( iOp>=nAlloc ){ if( iOp==0 ){ /* Do further verfication that this is explain output. Abort if ** it is not */ static const char *explainCols[] = { "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment" }; int jj; for(jj=0; jj<ArraySize(explainCols); jj++){ if( strcmp(sqlite3_column_name(pSql,jj),explainCols[jj])!=0 ){ p->cMode = p->mode; sqlite3_reset(pSql); return; } } } nAlloc += 100; p->aiIndent = (int*)sqlite3_realloc64(p->aiIndent, nAlloc*sizeof(int)); abYield = (int*)sqlite3_realloc64(abYield, nAlloc*sizeof(int)); } abYield[iOp] = str_in_array(zOp, azYield); p->aiIndent[iOp] = 0; p->nIndent = iOp+1; if( str_in_array(zOp, azNext) ){ for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2; } if( str_in_array(zOp, azGoto) && p2op<p->nIndent && (abYield[p2op] || sqlite3_column_int(pSql, 2)) ){ for(i=p2op; i<iOp; i++) p->aiIndent[i] += 2; } } p->iIndent = 0; sqlite3_free(abYield); sqlite3_reset(pSql); } /* ** Free the array allocated by explain_data_prepare(). */ static void explain_data_delete(ShellState *p){ sqlite3_free(p->aiIndent); p->aiIndent = 0; p->nIndent = 0; p->iIndent = 0; } /* ** Disable and restore .wheretrace and .selecttrace settings. */ #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE) extern int sqlite3SelectTrace; static int savedSelectTrace; #endif #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE) extern int sqlite3WhereTrace; static int savedWhereTrace; #endif static void disable_debug_trace_modes(void){ #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE) savedSelectTrace = sqlite3SelectTrace; sqlite3SelectTrace = 0; #endif #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE) savedWhereTrace = sqlite3WhereTrace; sqlite3WhereTrace = 0; #endif } static void restore_debug_trace_modes(void){ #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE) sqlite3SelectTrace = savedSelectTrace; #endif #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE) sqlite3WhereTrace = savedWhereTrace; #endif } /* ** Run a prepared statement */ static void exec_prepared_stmt( ShellState *pArg, /* Pointer to ShellState */ sqlite3_stmt *pStmt, /* Statment to run */ int (*xCallback)(void*,int,char**,char**,int*) /* Callback function */ ){ int rc; /* perform the first step. this will tell us if we ** have a result set or not and how wide it is. */ rc = sqlite3_step(pStmt); /* if we have a result set... */ if( SQLITE_ROW == rc ){ /* if we have a callback... */ if( xCallback ){ /* allocate space for col name ptr, value ptr, and type */ int nCol = sqlite3_column_count(pStmt); void *pData = sqlite3_malloc64(3*nCol*sizeof(const char*) + 1); if( !pData ){ rc = SQLITE_NOMEM; }else{ char **azCols = (char **)pData; /* Names of result columns */ char **azVals = &azCols[nCol]; /* Results */ int *aiTypes = (int *)&azVals[nCol]; /* Result types */ int i, x; assert(sizeof(int) <= sizeof(char *)); /* save off ptrs to column names */ for(i=0; i<nCol; i++){ azCols[i] = (char *)sqlite3_column_name(pStmt, i); } do{ /* extract the data and data types */ for(i=0; i<nCol; i++){ aiTypes[i] = x = sqlite3_column_type(pStmt, i); if( x==SQLITE_BLOB && pArg && pArg->cMode==MODE_Insert ){ azVals[i] = ""; }else{ azVals[i] = (char*)sqlite3_column_text(pStmt, i); } if( !azVals[i] && (aiTypes[i]!=SQLITE_NULL) ){ rc = SQLITE_NOMEM; break; /* from for */ } } /* end for */ /* if data and types extracted successfully... */ if( SQLITE_ROW == rc ){ /* call the supplied callback with the result row data */ if( xCallback(pArg, nCol, azVals, azCols, aiTypes) ){ rc = SQLITE_ABORT; }else{ rc = sqlite3_step(pStmt); } } } while( SQLITE_ROW == rc ); sqlite3_free(pData); } }else{ do{ rc = sqlite3_step(pStmt); } while( rc == SQLITE_ROW ); } } } /* ** Execute a statement or set of statements. Print ** any result rows/columns depending on the current mode ** set via the supplied callback. ** ** This is very similar to SQLite's built-in sqlite3_exec() ** function except it takes a slightly different callback ** and callback data argument. */ static int shell_exec( sqlite3 *db, /* An open database */ const char *zSql, /* SQL to be evaluated */ int (*xCallback)(void*,int,char**,char**,int*), /* Callback function */ /* (not the same as sqlite3_exec) */ ShellState *pArg, /* Pointer to ShellState */ char **pzErrMsg /* Error msg written here */ ){ sqlite3_stmt *pStmt = NULL; /* Statement to execute. */ int rc = SQLITE_OK; /* Return Code */ int rc2; const char *zLeftover; /* Tail of unprocessed SQL */ if( pzErrMsg ){ *pzErrMsg = NULL; } while( zSql[0] && (SQLITE_OK == rc) ){ static const char *zStmtSql; rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover); if( SQLITE_OK != rc ){ if( pzErrMsg ){ *pzErrMsg = save_err_msg(db); } }else{ if( !pStmt ){ /* this happens for a comment or white-space */ zSql = zLeftover; while( IsSpace(zSql[0]) ) zSql++; continue; } zStmtSql = sqlite3_sql(pStmt); while( IsSpace(zStmtSql[0]) ) zStmtSql++; /* save off the prepared statment handle and reset row count */ if( pArg ){ pArg->pStmt = pStmt; pArg->cnt = 0; } /* echo the sql statement if echo on */ if( pArg && pArg->echoOn ){ utf8_printf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql); } /* Show the EXPLAIN QUERY PLAN if .eqp is on */ if( pArg && pArg->autoEQP && sqlite3_strlike("EXPLAIN%",zStmtSql,0)!=0 ){ sqlite3_stmt *pExplain; char *zEQP; disable_debug_trace_modes(); zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", zStmtSql); rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); if( rc==SQLITE_OK ){ while( sqlite3_step(pExplain)==SQLITE_ROW ){ raw_printf(pArg->out,"--EQP-- %d,",sqlite3_column_int(pExplain, 0)); raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 1)); raw_printf(pArg->out,"%d,", sqlite3_column_int(pExplain, 2)); utf8_printf(pArg->out,"%s\n", sqlite3_column_text(pExplain, 3)); } } sqlite3_finalize(pExplain); sqlite3_free(zEQP); if( pArg->autoEQP>=2 ){ /* Also do an EXPLAIN for ".eqp full" mode */ zEQP = sqlite3_mprintf("EXPLAIN %s", zStmtSql); rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0); if( rc==SQLITE_OK ){ pArg->cMode = MODE_Explain; explain_data_prepare(pArg, pExplain); exec_prepared_stmt(pArg, pExplain, xCallback); explain_data_delete(pArg); } sqlite3_finalize(pExplain); sqlite3_free(zEQP); } restore_debug_trace_modes(); } if( pArg ){ pArg->cMode = pArg->mode; if( pArg->autoExplain && sqlite3_column_count(pStmt)==8 && sqlite3_strlike("EXPLAIN%", zStmtSql,0)==0 ){ pArg->cMode = MODE_Explain; } /* If the shell is currently in ".explain" mode, gather the extra ** data required to add indents to the output.*/ if( pArg->cMode==MODE_Explain ){ explain_data_prepare(pArg, pStmt); } } exec_prepared_stmt(pArg, pStmt, xCallback); explain_data_delete(pArg); /* print usage stats if stats on */ if( pArg && pArg->statsOn ){ display_stats(db, pArg, 0); } /* print loop-counters if required */ if( pArg && pArg->scanstatsOn ){ display_scanstats(db, pArg); } /* Finalize the statement just executed. If this fails, save a ** copy of the error message. Otherwise, set zSql to point to the ** next statement to execute. */ rc2 = sqlite3_finalize(pStmt); if( rc!=SQLITE_NOMEM ) rc = rc2; if( rc==SQLITE_OK ){ zSql = zLeftover; while( IsSpace(zSql[0]) ) zSql++; }else if( pzErrMsg ){ *pzErrMsg = save_err_msg(db); } /* clear saved stmt handle */ if( pArg ){ pArg->pStmt = NULL; } } } /* end while */ return rc; } /* ** This is a different callback routine used for dumping the database. ** Each row received by this callback consists of a table name, ** the table type ("index" or "table") and SQL to create the table. ** This routine should print text sufficient to recreate the table. */ static int dump_callback(void *pArg, int nArg, char **azArg, char **azCol){ int rc; const char *zTable; const char *zType; const char *zSql; const char *zPrepStmt = 0; ShellState *p = (ShellState *)pArg; UNUSED_PARAMETER(azCol); if( nArg!=3 ) return 1; zTable = azArg[0]; zType = azArg[1]; zSql = azArg[2]; if( strcmp(zTable, "sqlite_sequence")==0 ){ zPrepStmt = "DELETE FROM sqlite_sequence;\n"; }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){ raw_printf(p->out, "ANALYZE sqlite_master;\n"); }else if( strncmp(zTable, "sqlite_", 7)==0 ){ return 0; }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){ char *zIns; if( !p->writableSchema ){ raw_printf(p->out, "PRAGMA writable_schema=ON;\n"); p->writableSchema = 1; } zIns = sqlite3_mprintf( "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)" "VALUES('table','%q','%q',0,'%q');", zTable, zTable, zSql); utf8_printf(p->out, "%s\n", zIns); sqlite3_free(zIns); return 0; }else{ utf8_printf(p->out, "%s;\n", zSql); } if( strcmp(zType, "table")==0 ){ sqlite3_stmt *pTableInfo = 0; char *zSelect = 0; char *zTableInfo = 0; char *zTmp = 0; int nRow = 0; zTableInfo = appendText(zTableInfo, "PRAGMA table_info(", 0); zTableInfo = appendText(zTableInfo, zTable, '"'); zTableInfo = appendText(zTableInfo, ");", 0); rc = sqlite3_prepare_v2(p->db, zTableInfo, -1, &pTableInfo, 0); free(zTableInfo); if( rc!=SQLITE_OK || !pTableInfo ){ return 1; } zSelect = appendText(zSelect, "SELECT 'INSERT INTO ' || ", 0); /* Always quote the table name, even if it appears to be pure ascii, ** in case it is a keyword. Ex: INSERT INTO "table" ... */ zTmp = appendText(zTmp, zTable, '"'); if( zTmp ){ zSelect = appendText(zSelect, zTmp, '\''); free(zTmp); } zSelect = appendText(zSelect, " || ' VALUES(' || ", 0); rc = sqlite3_step(pTableInfo); while( rc==SQLITE_ROW ){ const char *zText = (const char *)sqlite3_column_text(pTableInfo, 1); zSelect = appendText(zSelect, "quote(", 0); zSelect = appendText(zSelect, zText, '"'); rc = sqlite3_step(pTableInfo); if( rc==SQLITE_ROW ){ zSelect = appendText(zSelect, "), ", 0); }else{ zSelect = appendText(zSelect, ") ", 0); } nRow++; } rc = sqlite3_finalize(pTableInfo); if( rc!=SQLITE_OK || nRow==0 ){ free(zSelect); return 1; } zSelect = appendText(zSelect, "|| ')' FROM ", 0); zSelect = appendText(zSelect, zTable, '"'); rc = run_table_dump_query(p, zSelect, zPrepStmt); if( rc==SQLITE_CORRUPT ){ zSelect = appendText(zSelect, " ORDER BY rowid DESC", 0); run_table_dump_query(p, zSelect, 0); } free(zSelect); } return 0; } /* ** Run zQuery. Use dump_callback() as the callback routine so that ** the contents of the query are output as SQL statements. ** ** If we get a SQLITE_CORRUPT error, rerun the query after appending ** "ORDER BY rowid DESC" to the end. */ static int run_schema_dump_query( ShellState *p, const char *zQuery ){ int rc; char *zErr = 0; rc = sqlite3_exec(p->db, zQuery, dump_callback, p, &zErr); if( rc==SQLITE_CORRUPT ){ char *zQ2; int len = strlen30(zQuery); raw_printf(p->out, "/****** CORRUPTION ERROR *******/\n"); if( zErr ){ utf8_printf(p->out, "/****** %s ******/\n", zErr); sqlite3_free(zErr); zErr = 0; } zQ2 = malloc( len+100 ); if( zQ2==0 ) return rc; sqlite3_snprintf(len+100, zQ2, "%s ORDER BY rowid DESC", zQuery); rc = sqlite3_exec(p->db, zQ2, dump_callback, p, &zErr); if( rc ){ utf8_printf(p->out, "/****** ERROR: %s ******/\n", zErr); }else{ rc = SQLITE_CORRUPT; } sqlite3_free(zErr); free(zQ2); } return rc; } /* ** Text of a help message */ static char zHelp[] = ".auth ON|OFF Show authorizer callbacks\n" ".backup ?DB? FILE Backup DB (default \"main\") to FILE\n" ".bail on|off Stop after hitting an error. Default OFF\n" ".binary on|off Turn binary output on or off. Default OFF\n" ".changes on|off Show number of rows changed by SQL\n" ".clone NEWDB Clone data into NEWDB from the existing database\n" ".databases List names and files of attached databases\n" ".dbinfo ?DB? Show status information about the database\n" ".dump ?TABLE? ... Dump the database in an SQL text format\n" " If TABLE specified, only dump tables matching\n" " LIKE pattern TABLE.\n" ".echo on|off Turn command echo on or off\n" ".eqp on|off|full Enable or disable automatic EXPLAIN QUERY PLAN\n" ".exit Exit this program\n" ".explain ?on|off|auto? Turn EXPLAIN output mode on or off or to automatic\n" ".fullschema ?--indent? Show schema and the content of sqlite_stat tables\n" ".headers on|off Turn display of headers on or off\n" ".help Show this message\n" ".import FILE TABLE Import data from FILE into TABLE\n" ".indexes ?TABLE? Show names of all indexes\n" " If TABLE specified, only show indexes for tables\n" " matching LIKE pattern TABLE.\n" #ifdef SQLITE_ENABLE_IOTRACE ".iotrace FILE Enable I/O diagnostic logging to FILE\n" #endif ".limit ?LIMIT? ?VAL? Display or change the value of an SQLITE_LIMIT\n" #ifndef SQLITE_OMIT_LOAD_EXTENSION ".load FILE ?ENTRY? Load an extension library\n" #endif ".log FILE|off Turn logging on or off. FILE can be stderr/stdout\n" ".mode MODE ?TABLE? Set output mode where MODE is one of:\n" " ascii Columns/rows delimited by 0x1F and 0x1E\n" " csv Comma-separated values\n" " column Left-aligned columns. (See .width)\n" " html HTML <table> code\n" " insert SQL insert statements for TABLE\n" " line One value per line\n" " list Values delimited by .separator strings\n" " tabs Tab-separated values\n" " tcl TCL list elements\n" ".nullvalue STRING Use STRING in place of NULL values\n" ".once FILENAME Output for the next SQL command only to FILENAME\n" ".open ?FILENAME? Close existing database and reopen FILENAME\n" ".output ?FILENAME? Send output to FILENAME or stdout\n" ".print STRING... Print literal STRING\n" ".prompt MAIN CONTINUE Replace the standard prompts\n" ".quit Exit this program\n" ".read FILENAME Execute SQL in FILENAME\n" ".restore ?DB? FILE Restore content of DB (default \"main\") from FILE\n" ".save FILE Write in-memory database into FILE\n" ".scanstats on|off Turn sqlite3_stmt_scanstatus() metrics on or off\n" ".schema ?PATTERN? Show the CREATE statements matching PATTERN\n" " Add --indent for pretty-printing\n" ".separator COL ?ROW? Change the column separator and optionally the row\n" " separator for both the output mode and .import\n" #if defined(SQLITE_ENABLE_SESSION) ".session CMD ... Create or control sessions\n" #endif ".shell CMD ARGS... Run CMD ARGS... in a system shell\n" ".show Show the current values for various settings\n" ".stats ?on|off? Show stats or turn stats on or off\n" ".system CMD ARGS... Run CMD ARGS... in a system shell\n" ".tables ?TABLE? List names of tables\n" " If TABLE specified, only list tables matching\n" " LIKE pattern TABLE.\n" ".timeout MS Try opening locked tables for MS milliseconds\n" ".timer on|off Turn SQL timer on or off\n" ".trace FILE|off Output each SQL statement as it is run\n" ".vfsinfo ?AUX? Information about the top-level VFS\n" ".vfslist List all available VFSes\n" ".vfsname ?AUX? Print the name of the VFS stack\n" ".width NUM1 NUM2 ... Set column widths for \"column\" mode\n" " Negative values right-justify\n" ; #if defined(SQLITE_ENABLE_SESSION) /* ** Print help information for the ".sessions" command */ void session_help(ShellState *p){ raw_printf(p->out, ".session ?NAME? SUBCOMMAND ?ARGS...?\n" "If ?NAME? is omitted, the first defined session is used.\n" "Subcommands:\n" " attach TABLE Attach TABLE\n" " changeset FILE Write a changeset into FILE\n" " close Close one session\n" " enable ?BOOLEAN? Set or query the enable bit\n" " filter GLOB... Reject tables matching GLOBs\n" " indirect ?BOOLEAN? Mark or query the indirect status\n" " isempty Query whether the session is empty\n" " list List currently open session names\n" " open DB NAME Open a new session on DB\n" " patchset FILE Write a patchset into FILE\n" ); } #endif /* Forward reference */ static int process_input(ShellState *p, FILE *in); /* ** Implementation of the "readfile(X)" SQL function. The entire content ** of the file named X is read and returned as a BLOB. NULL is returned ** if the file does not exist or is unreadable. */ static void readfileFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ const char *zName; FILE *in; long nIn; void *pBuf; UNUSED_PARAMETER(argc); zName = (const char*)sqlite3_value_text(argv[0]); if( zName==0 ) return; in = fopen(zName, "rb"); if( in==0 ) return; fseek(in, 0, SEEK_END); nIn = ftell(in); rewind(in); pBuf = sqlite3_malloc64( nIn ); if( pBuf && 1==fread(pBuf, nIn, 1, in) ){ sqlite3_result_blob(context, pBuf, nIn, sqlite3_free); }else{ sqlite3_free(pBuf); } fclose(in); } /* ** Implementation of the "writefile(X,Y)" SQL function. The argument Y ** is written into file X. The number of bytes written is returned. Or ** NULL is returned if something goes wrong, such as being unable to open ** file X for writing. */ static void writefileFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ FILE *out; const char *z; sqlite3_int64 rc; const char *zFile; UNUSED_PARAMETER(argc); zFile = (const char*)sqlite3_value_text(argv[0]); if( zFile==0 ) return; out = fopen(zFile, "wb"); if( out==0 ) return; z = (const char*)sqlite3_value_blob(argv[1]); if( z==0 ){ rc = 0; }else{ rc = fwrite(z, 1, sqlite3_value_bytes(argv[1]), out); } fclose(out); sqlite3_result_int64(context, rc); } #if defined(SQLITE_ENABLE_SESSION) /* ** Close a single OpenSession object and release all of its associated ** resources. */ static void session_close(OpenSession *pSession){ int i; sqlite3session_delete(pSession->p); sqlite3_free(pSession->zName); for(i=0; i<pSession->nFilter; i++){ sqlite3_free(pSession->azFilter[i]); } sqlite3_free(pSession->azFilter); memset(pSession, 0, sizeof(OpenSession)); } #endif /* ** Close all OpenSession objects and release all associated resources. */ #if defined(SQLITE_ENABLE_SESSION) static void session_close_all(ShellState *p){ int i; for(i=0; i<p->nSession; i++){ session_close(&p->aSession[i]); } p->nSession = 0; } #else # define session_close_all(X) #endif /* ** Implementation of the xFilter function for an open session. Omit ** any tables named by ".session filter" but let all other table through. */ #if defined(SQLITE_ENABLE_SESSION) static int session_filter(void *pCtx, const char *zTab){ OpenSession *pSession = (OpenSession*)pCtx; int i; for(i=0; i<pSession->nFilter; i++){ if( sqlite3_strglob(pSession->azFilter[i], zTab)==0 ) return 0; } return 1; } #endif /* ** Make sure the database is open. If it is not, then open it. If ** the database fails to open, print an error message and exit. */ static void open_db(ShellState *p, int keepAlive){ if( p->db==0 ){ sqlite3_initialize(); sqlite3_open(p->zDbFilename, &p->db); globalDb = p->db; if( p->db && sqlite3_errcode(p->db)==SQLITE_OK ){ sqlite3_create_function(p->db, "shellstatic", 0, SQLITE_UTF8, 0, shellstaticFunc, 0, 0); } if( p->db==0 || SQLITE_OK!=sqlite3_errcode(p->db) ){ utf8_printf(stderr,"Error: unable to open database \"%s\": %s\n", p->zDbFilename, sqlite3_errmsg(p->db)); if( keepAlive ) return; exit(1); } #ifndef SQLITE_OMIT_LOAD_EXTENSION sqlite3_enable_load_extension(p->db, 1); #endif sqlite3_create_function(p->db, "readfile", 1, SQLITE_UTF8, 0, readfileFunc, 0, 0); sqlite3_create_function(p->db, "writefile", 2, SQLITE_UTF8, 0, writefileFunc, 0, 0); } } /* ** Do C-language style dequoting. ** ** \a -> alarm ** \b -> backspace ** \t -> tab ** \n -> newline ** \v -> vertical tab ** \f -> form feed ** \r -> carriage return ** \s -> space ** \" -> " ** \' -> ' ** \\ -> backslash ** \NNN -> ascii character NNN in octal */ static void resolve_backslashes(char *z){ int i, j; char c; while( *z && *z!='\\' ) z++; for(i=j=0; (c = z[i])!=0; i++, j++){ if( c=='\\' && z[i+1]!=0 ){ c = z[++i]; if( c=='a' ){ c = '\a'; }else if( c=='b' ){ c = '\b'; }else if( c=='t' ){ c = '\t'; }else if( c=='n' ){ c = '\n'; }else if( c=='v' ){ c = '\v'; }else if( c=='f' ){ c = '\f'; }else if( c=='r' ){ c = '\r'; }else if( c=='"' ){ c = '"'; }else if( c=='\'' ){ c = '\''; }else if( c=='\\' ){ c = '\\'; }else if( c>='0' && c<='7' ){ c -= '0'; if( z[i+1]>='0' && z[i+1]<='7' ){ i++; c = (c<<3) + z[i] - '0'; if( z[i+1]>='0' && z[i+1]<='7' ){ i++; c = (c<<3) + z[i] - '0'; } } } } z[j] = c; } if( j<i ) z[j] = 0; } /* ** Return the value of a hexadecimal digit. Return -1 if the input ** is not a hex digit. */ static int hexDigitValue(char c){ if( c>='0' && c<='9' ) return c - '0'; if( c>='a' && c<='f' ) return c - 'a' + 10; if( c>='A' && c<='F' ) return c - 'A' + 10; return -1; } /* ** Interpret zArg as an integer value, possibly with suffixes. */ static sqlite3_int64 integerValue(const char *zArg){ sqlite3_int64 v = 0; static const struct { char *zSuffix; int iMult; } aMult[] = { { "KiB", 1024 }, { "MiB", 1024*1024 }, { "GiB", 1024*1024*1024 }, { "KB", 1000 }, { "MB", 1000000 }, { "GB", 1000000000 }, { "K", 1000 }, { "M", 1000000 }, { "G", 1000000000 }, }; int i; int isNeg = 0; if( zArg[0]=='-' ){ isNeg = 1; zArg++; }else if( zArg[0]=='+' ){ zArg++; } if( zArg[0]=='0' && zArg[1]=='x' ){ int x; zArg += 2; while( (x = hexDigitValue(zArg[0]))>=0 ){ v = (v<<4) + x; zArg++; } }else{ while( IsDigit(zArg[0]) ){ v = v*10 + zArg[0] - '0'; zArg++; } } for(i=0; i<ArraySize(aMult); i++){ if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){ v *= aMult[i].iMult; break; } } return isNeg? -v : v; } /* ** Interpret zArg as either an integer or a boolean value. Return 1 or 0 ** for TRUE and FALSE. Return the integer value if appropriate. */ static int booleanValue(char *zArg){ int i; if( zArg[0]=='0' && zArg[1]=='x' ){ for(i=2; hexDigitValue(zArg[i])>=0; i++){} }else{ for(i=0; zArg[i]>='0' && zArg[i]<='9'; i++){} } if( i>0 && zArg[i]==0 ) return (int)(integerValue(zArg) & 0xffffffff); if( sqlite3_stricmp(zArg, "on")==0 || sqlite3_stricmp(zArg,"yes")==0 ){ return 1; } if( sqlite3_stricmp(zArg, "off")==0 || sqlite3_stricmp(zArg,"no")==0 ){ return 0; } utf8_printf(stderr, "ERROR: Not a boolean value: \"%s\". Assuming \"no\".\n", zArg); return 0; } /* ** Close an output file, assuming it is not stderr or stdout */ static void output_file_close(FILE *f){ if( f && f!=stdout && f!=stderr ) fclose(f); } /* ** Try to open an output file. The names "stdout" and "stderr" are ** recognized and do the right thing. NULL is returned if the output ** filename is "off". */ static FILE *output_file_open(const char *zFile){ FILE *f; if( strcmp(zFile,"stdout")==0 ){ f = stdout; }else if( strcmp(zFile, "stderr")==0 ){ f = stderr; }else if( strcmp(zFile, "off")==0 ){ f = 0; }else{ f = fopen(zFile, "wb"); if( f==0 ){ utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile); } } return f; } /* ** A routine for handling output from sqlite3_trace(). */ static int sql_trace_callback( unsigned mType, void *pArg, void *pP, void *pX ){ FILE *f = (FILE*)pArg; UNUSED_PARAMETER(mType); UNUSED_PARAMETER(pP); if( f ){ const char *z = (const char*)pX; int i = (int)strlen(z); while( i>0 && z[i-1]==';' ){ i--; } utf8_printf(f, "%.*s;\n", i, z); } return 0; } /* ** A no-op routine that runs with the ".breakpoint" doc-command. This is ** a useful spot to set a debugger breakpoint. */ static void test_breakpoint(void){ static int nCall = 0; nCall++; } /* ** An object used to read a CSV and other files for import. */ typedef struct ImportCtx ImportCtx; struct ImportCtx { const char *zFile; /* Name of the input file */ FILE *in; /* Read the CSV text from this input stream */ char *z; /* Accumulated text for a field */ int n; /* Number of bytes in z */ int nAlloc; /* Space allocated for z[] */ int nLine; /* Current line number */ int cTerm; /* Character that terminated the most recent field */ int cColSep; /* The column separator character. (Usually ",") */ int cRowSep; /* The row separator character. (Usually "\n") */ }; /* Append a single byte to z[] */ static void import_append_char(ImportCtx *p, int c){ if( p->n+1>=p->nAlloc ){ p->nAlloc += p->nAlloc + 100; p->z = sqlite3_realloc64(p->z, p->nAlloc); if( p->z==0 ){ raw_printf(stderr, "out of memory\n"); exit(1); } } p->z[p->n++] = (char)c; } /* Read a single field of CSV text. Compatible with rfc4180 and extended ** with the option of having a separator other than ",". ** ** + Input comes from p->in. ** + Store results in p->z of length p->n. Space to hold p->z comes ** from sqlite3_malloc64(). ** + Use p->cSep as the column separator. The default is ",". ** + Use p->rSep as the row separator. The default is "\n". ** + Keep track of the line number in p->nLine. ** + Store the character that terminates the field in p->cTerm. Store ** EOF on end-of-file. ** + Report syntax errors on stderr */ static char *SQLITE_CDECL csv_read_one_field(ImportCtx *p){ int c; int cSep = p->cColSep; int rSep = p->cRowSep; p->n = 0; c = fgetc(p->in); if( c==EOF || seenInterrupt ){ p->cTerm = EOF; return 0; } if( c=='"' ){ int pc, ppc; int startLine = p->nLine; int cQuote = c; pc = ppc = 0; while( 1 ){ c = fgetc(p->in); if( c==rSep ) p->nLine++; if( c==cQuote ){ if( pc==cQuote ){ pc = 0; continue; } } if( (c==cSep && pc==cQuote) || (c==rSep && pc==cQuote) || (c==rSep && pc=='\r' && ppc==cQuote) || (c==EOF && pc==cQuote) ){ do{ p->n--; }while( p->z[p->n]!=cQuote ); p->cTerm = c; break; } if( pc==cQuote && c!='\r' ){ utf8_printf(stderr, "%s:%d: unescaped %c character\n", p->zFile, p->nLine, cQuote); } if( c==EOF ){ utf8_printf(stderr, "%s:%d: unterminated %c-quoted field\n", p->zFile, startLine, cQuote); p->cTerm = c; break; } import_append_char(p, c); ppc = pc; pc = c; } }else{ while( c!=EOF && c!=cSep && c!=rSep ){ import_append_char(p, c); c = fgetc(p->in); } if( c==rSep ){ p->nLine++; if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--; } p->cTerm = c; } if( p->z ) p->z[p->n] = 0; return p->z; } /* Read a single field of ASCII delimited text. ** ** + Input comes from p->in. ** + Store results in p->z of length p->n. Space to hold p->z comes ** from sqlite3_malloc64(). ** + Use p->cSep as the column separator. The default is "\x1F". ** + Use p->rSep as the row separator. The default is "\x1E". ** + Keep track of the row number in p->nLine. ** + Store the character that terminates the field in p->cTerm. Store ** EOF on end-of-file. ** + Report syntax errors on stderr */ static char *SQLITE_CDECL ascii_read_one_field(ImportCtx *p){ int c; int cSep = p->cColSep; int rSep = p->cRowSep; p->n = 0; c = fgetc(p->in); if( c==EOF || seenInterrupt ){ p->cTerm = EOF; return 0; } while( c!=EOF && c!=cSep && c!=rSep ){ import_append_char(p, c); c = fgetc(p->in); } if( c==rSep ){ p->nLine++; } p->cTerm = c; if( p->z ) p->z[p->n] = 0; return p->z; } /* ** Try to transfer data for table zTable. If an error is seen while ** moving forward, try to go backwards. The backwards movement won't ** work for WITHOUT ROWID tables. */ static void tryToCloneData( ShellState *p, sqlite3 *newDb, const char *zTable ){ sqlite3_stmt *pQuery = 0; sqlite3_stmt *pInsert = 0; char *zQuery = 0; char *zInsert = 0; int rc; int i, j, n; int nTable = (int)strlen(zTable); int k = 0; int cnt = 0; const int spinRate = 10000; zQuery = sqlite3_mprintf("SELECT * FROM \"%w\"", zTable); rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); if( rc ){ utf8_printf(stderr, "Error %d: %s on [%s]\n", sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery); goto end_data_xfer; } n = sqlite3_column_count(pQuery); zInsert = sqlite3_malloc64(200 + nTable + n*3); if( zInsert==0 ){ raw_printf(stderr, "out of memory\n"); goto end_data_xfer; } sqlite3_snprintf(200+nTable,zInsert, "INSERT OR IGNORE INTO \"%s\" VALUES(?", zTable); i = (int)strlen(zInsert); for(j=1; j<n; j++){ memcpy(zInsert+i, ",?", 2); i += 2; } memcpy(zInsert+i, ");", 3); rc = sqlite3_prepare_v2(newDb, zInsert, -1, &pInsert, 0); if( rc ){ utf8_printf(stderr, "Error %d: %s on [%s]\n", sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb), zQuery); goto end_data_xfer; } for(k=0; k<2; k++){ while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ for(i=0; i<n; i++){ switch( sqlite3_column_type(pQuery, i) ){ case SQLITE_NULL: { sqlite3_bind_null(pInsert, i+1); break; } case SQLITE_INTEGER: { sqlite3_bind_int64(pInsert, i+1, sqlite3_column_int64(pQuery,i)); break; } case SQLITE_FLOAT: { sqlite3_bind_double(pInsert, i+1, sqlite3_column_double(pQuery,i)); break; } case SQLITE_TEXT: { sqlite3_bind_text(pInsert, i+1, (const char*)sqlite3_column_text(pQuery,i), -1, SQLITE_STATIC); break; } case SQLITE_BLOB: { sqlite3_bind_blob(pInsert, i+1, sqlite3_column_blob(pQuery,i), sqlite3_column_bytes(pQuery,i), SQLITE_STATIC); break; } } } /* End for */ rc = sqlite3_step(pInsert); if( rc!=SQLITE_OK && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){ utf8_printf(stderr, "Error %d: %s\n", sqlite3_extended_errcode(newDb), sqlite3_errmsg(newDb)); } sqlite3_reset(pInsert); cnt++; if( (cnt%spinRate)==0 ){ printf("%c\b", "|/-\\"[(cnt/spinRate)%4]); fflush(stdout); } } /* End while */ if( rc==SQLITE_DONE ) break; sqlite3_finalize(pQuery); sqlite3_free(zQuery); zQuery = sqlite3_mprintf("SELECT * FROM \"%w\" ORDER BY rowid DESC;", zTable); rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); if( rc ){ utf8_printf(stderr, "Warning: cannot step \"%s\" backwards", zTable); break; } } /* End for(k=0...) */ end_data_xfer: sqlite3_finalize(pQuery); sqlite3_finalize(pInsert); sqlite3_free(zQuery); sqlite3_free(zInsert); } /* ** Try to transfer all rows of the schema that match zWhere. For ** each row, invoke xForEach() on the object defined by that row. ** If an error is encountered while moving forward through the ** sqlite_master table, try again moving backwards. */ static void tryToCloneSchema( ShellState *p, sqlite3 *newDb, const char *zWhere, void (*xForEach)(ShellState*,sqlite3*,const char*) ){ sqlite3_stmt *pQuery = 0; char *zQuery = 0; int rc; const unsigned char *zName; const unsigned char *zSql; char *zErrMsg = 0; zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master" " WHERE %s", zWhere); rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); if( rc ){ utf8_printf(stderr, "Error: (%d) %s on [%s]\n", sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery); goto end_schema_xfer; } while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ zName = sqlite3_column_text(pQuery, 0); zSql = sqlite3_column_text(pQuery, 1); printf("%s... ", zName); fflush(stdout); sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg); if( zErrMsg ){ utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql); sqlite3_free(zErrMsg); zErrMsg = 0; } if( xForEach ){ xForEach(p, newDb, (const char*)zName); } printf("done\n"); } if( rc!=SQLITE_DONE ){ sqlite3_finalize(pQuery); sqlite3_free(zQuery); zQuery = sqlite3_mprintf("SELECT name, sql FROM sqlite_master" " WHERE %s ORDER BY rowid DESC", zWhere); rc = sqlite3_prepare_v2(p->db, zQuery, -1, &pQuery, 0); if( rc ){ utf8_printf(stderr, "Error: (%d) %s on [%s]\n", sqlite3_extended_errcode(p->db), sqlite3_errmsg(p->db), zQuery); goto end_schema_xfer; } while( (rc = sqlite3_step(pQuery))==SQLITE_ROW ){ zName = sqlite3_column_text(pQuery, 0); zSql = sqlite3_column_text(pQuery, 1); printf("%s... ", zName); fflush(stdout); sqlite3_exec(newDb, (const char*)zSql, 0, 0, &zErrMsg); if( zErrMsg ){ utf8_printf(stderr, "Error: %s\nSQL: [%s]\n", zErrMsg, zSql); sqlite3_free(zErrMsg); zErrMsg = 0; } if( xForEach ){ xForEach(p, newDb, (const char*)zName); } printf("done\n"); } } end_schema_xfer: sqlite3_finalize(pQuery); sqlite3_free(zQuery); } /* ** Open a new database file named "zNewDb". Try to recover as much information ** as possible out of the main database (which might be corrupt) and write it ** into zNewDb. */ static void tryToClone(ShellState *p, const char *zNewDb){ int rc; sqlite3 *newDb = 0; if( access(zNewDb,0)==0 ){ utf8_printf(stderr, "File \"%s\" already exists.\n", zNewDb); return; } rc = sqlite3_open(zNewDb, &newDb); if( rc ){ utf8_printf(stderr, "Cannot create output database: %s\n", sqlite3_errmsg(newDb)); }else{ sqlite3_exec(p->db, "PRAGMA writable_schema=ON;", 0, 0, 0); sqlite3_exec(newDb, "BEGIN EXCLUSIVE;", 0, 0, 0); tryToCloneSchema(p, newDb, "type='table'", tryToCloneData); tryToCloneSchema(p, newDb, "type!='table'", 0); sqlite3_exec(newDb, "COMMIT;", 0, 0, 0); sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); } sqlite3_close(newDb); } /* ** Change the output file back to stdout */ static void output_reset(ShellState *p){ if( p->outfile[0]=='|' ){ #ifndef SQLITE_OMIT_POPEN pclose(p->out); #endif }else{ output_file_close(p->out); } p->outfile[0] = 0; p->out = stdout; } /* ** Run an SQL command and return the single integer result. */ static int db_int(ShellState *p, const char *zSql){ sqlite3_stmt *pStmt; int res = 0; sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){ res = sqlite3_column_int(pStmt,0); } sqlite3_finalize(pStmt); return res; } /* ** Convert a 2-byte or 4-byte big-endian integer into a native integer */ static unsigned int get2byteInt(unsigned char *a){ return (a[0]<<8) + a[1]; } static unsigned int get4byteInt(unsigned char *a){ return (a[0]<<24) + (a[1]<<16) + (a[2]<<8) + a[3]; } /* ** Implementation of the ".info" command. ** ** Return 1 on error, 2 to exit, and 0 otherwise. */ static int shell_dbinfo_command(ShellState *p, int nArg, char **azArg){ static const struct { const char *zName; int ofst; } aField[] = { { "file change counter:", 24 }, { "database page count:", 28 }, { "freelist page count:", 36 }, { "schema cookie:", 40 }, { "schema format:", 44 }, { "default cache size:", 48 }, { "autovacuum top root:", 52 }, { "incremental vacuum:", 64 }, { "text encoding:", 56 }, { "user version:", 60 }, { "application id:", 68 }, { "software version:", 96 }, }; static const struct { const char *zName; const char *zSql; } aQuery[] = { { "number of tables:", "SELECT count(*) FROM %s WHERE type='table'" }, { "number of indexes:", "SELECT count(*) FROM %s WHERE type='index'" }, { "number of triggers:", "SELECT count(*) FROM %s WHERE type='trigger'" }, { "number of views:", "SELECT count(*) FROM %s WHERE type='view'" }, { "schema size:", "SELECT total(length(sql)) FROM %s" }, }; sqlite3_file *pFile = 0; int i; char *zSchemaTab; char *zDb = nArg>=2 ? azArg[1] : "main"; unsigned char aHdr[100]; open_db(p, 0); if( p->db==0 ) return 1; sqlite3_file_control(p->db, zDb, SQLITE_FCNTL_FILE_POINTER, &pFile); if( pFile==0 || pFile->pMethods==0 || pFile->pMethods->xRead==0 ){ return 1; } i = pFile->pMethods->xRead(pFile, aHdr, 100, 0); if( i!=SQLITE_OK ){ raw_printf(stderr, "unable to read database header\n"); return 1; } i = get2byteInt(aHdr+16); if( i==1 ) i = 65536; utf8_printf(p->out, "%-20s %d\n", "database page size:", i); utf8_printf(p->out, "%-20s %d\n", "write format:", aHdr[18]); utf8_printf(p->out, "%-20s %d\n", "read format:", aHdr[19]); utf8_printf(p->out, "%-20s %d\n", "reserved bytes:", aHdr[20]); for(i=0; i<ArraySize(aField); i++){ int ofst = aField[i].ofst; unsigned int val = get4byteInt(aHdr + ofst); utf8_printf(p->out, "%-20s %u", aField[i].zName, val); switch( ofst ){ case 56: { if( val==1 ) raw_printf(p->out, " (utf8)"); if( val==2 ) raw_printf(p->out, " (utf16le)"); if( val==3 ) raw_printf(p->out, " (utf16be)"); } } raw_printf(p->out, "\n"); } if( zDb==0 ){ zSchemaTab = sqlite3_mprintf("main.sqlite_master"); }else if( strcmp(zDb,"temp")==0 ){ zSchemaTab = sqlite3_mprintf("%s", "sqlite_temp_master"); }else{ zSchemaTab = sqlite3_mprintf("\"%w\".sqlite_master", zDb); } for(i=0; i<ArraySize(aQuery); i++){ char *zSql = sqlite3_mprintf(aQuery[i].zSql, zSchemaTab); int val = db_int(p, zSql); sqlite3_free(zSql); utf8_printf(p->out, "%-20s %d\n", aQuery[i].zName, val); } sqlite3_free(zSchemaTab); return 0; } /* ** Print the current sqlite3_errmsg() value to stderr and return 1. */ static int shellDatabaseError(sqlite3 *db){ const char *zErr = sqlite3_errmsg(db); utf8_printf(stderr, "Error: %s\n", zErr); return 1; } /* ** Print an out-of-memory message to stderr and return 1. */ static int shellNomemError(void){ raw_printf(stderr, "Error: out of memory\n"); return 1; } /* ** Compare the string as a command-line option with either one or two ** initial "-" characters. */ static int optionMatch(const char *zStr, const char *zOpt){ if( zStr[0]!='-' ) return 0; zStr++; if( zStr[0]=='-' ) zStr++; return strcmp(zStr, zOpt)==0; } /* ** If an input line begins with "." then invoke this routine to ** process that line. ** ** Return 1 on error, 2 to exit, and 0 otherwise. */ static int do_meta_command(char *zLine, ShellState *p){ int h = 1; int nArg = 0; int n, c; int rc = 0; char *azArg[50]; /* Parse the input line into tokens. */ while( zLine[h] && nArg<ArraySize(azArg) ){ while( IsSpace(zLine[h]) ){ h++; } if( zLine[h]==0 ) break; if( zLine[h]=='\'' || zLine[h]=='"' ){ int delim = zLine[h++]; azArg[nArg++] = &zLine[h]; while( zLine[h] && zLine[h]!=delim ){ if( zLine[h]=='\\' && delim=='"' && zLine[h+1]!=0 ) h++; h++; } if( zLine[h]==delim ){ zLine[h++] = 0; } if( delim=='"' ) resolve_backslashes(azArg[nArg-1]); }else{ azArg[nArg++] = &zLine[h]; while( zLine[h] && !IsSpace(zLine[h]) ){ h++; } if( zLine[h] ) zLine[h++] = 0; resolve_backslashes(azArg[nArg-1]); } } /* Process the input line. */ if( nArg==0 ) return 0; /* no tokens, no error */ n = strlen30(azArg[0]); c = azArg[0][0]; if( c=='a' && strncmp(azArg[0], "auth", n)==0 ){ if( nArg!=2 ){ raw_printf(stderr, "Usage: .auth ON|OFF\n"); rc = 1; goto meta_command_exit; } open_db(p, 0); if( booleanValue(azArg[1]) ){ sqlite3_set_authorizer(p->db, shellAuth, p); }else{ sqlite3_set_authorizer(p->db, 0, 0); } }else if( (c=='b' && n>=3 && strncmp(azArg[0], "backup", n)==0) || (c=='s' && n>=3 && strncmp(azArg[0], "save", n)==0) ){ const char *zDestFile = 0; const char *zDb = 0; sqlite3 *pDest; sqlite3_backup *pBackup; int j; for(j=1; j<nArg; j++){ const char *z = azArg[j]; if( z[0]=='-' ){ while( z[0]=='-' ) z++; /* No options to process at this time */ { utf8_printf(stderr, "unknown option: %s\n", azArg[j]); return 1; } }else if( zDestFile==0 ){ zDestFile = azArg[j]; }else if( zDb==0 ){ zDb = zDestFile; zDestFile = azArg[j]; }else{ raw_printf(stderr, "too many arguments to .backup\n"); return 1; } } if( zDestFile==0 ){ raw_printf(stderr, "missing FILENAME argument on .backup\n"); return 1; } if( zDb==0 ) zDb = "main"; rc = sqlite3_open(zDestFile, &pDest); if( rc!=SQLITE_OK ){ utf8_printf(stderr, "Error: cannot open \"%s\"\n", zDestFile); sqlite3_close(pDest); return 1; } open_db(p, 0); pBackup = sqlite3_backup_init(pDest, "main", p->db, zDb); if( pBackup==0 ){ utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest)); sqlite3_close(pDest); return 1; } while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){} sqlite3_backup_finish(pBackup); if( rc==SQLITE_DONE ){ rc = 0; }else{ utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(pDest)); rc = 1; } sqlite3_close(pDest); }else if( c=='b' && n>=3 && strncmp(azArg[0], "bail", n)==0 ){ if( nArg==2 ){ bail_on_error = booleanValue(azArg[1]); }else{ raw_printf(stderr, "Usage: .bail on|off\n"); rc = 1; } }else if( c=='b' && n>=3 && strncmp(azArg[0], "binary", n)==0 ){ if( nArg==2 ){ if( booleanValue(azArg[1]) ){ setBinaryMode(p->out, 1); }else{ setTextMode(p->out, 1); } }else{ raw_printf(stderr, "Usage: .binary on|off\n"); rc = 1; } }else /* The undocumented ".breakpoint" command causes a call to the no-op ** routine named test_breakpoint(). */ if( c=='b' && n>=3 && strncmp(azArg[0], "breakpoint", n)==0 ){ test_breakpoint(); }else if( c=='c' && n>=3 && strncmp(azArg[0], "changes", n)==0 ){ if( nArg==2 ){ p->countChanges = booleanValue(azArg[1]); }else{ raw_printf(stderr, "Usage: .changes on|off\n"); rc = 1; } }else if( c=='c' && strncmp(azArg[0], "clone", n)==0 ){ if( nArg==2 ){ tryToClone(p, azArg[1]); }else{ raw_printf(stderr, "Usage: .clone FILENAME\n"); rc = 1; } }else if( c=='d' && n>1 && strncmp(azArg[0], "databases", n)==0 ){ ShellState data; char *zErrMsg = 0; open_db(p, 0); memcpy(&data, p, sizeof(data)); data.showHeader = 1; data.cMode = data.mode = MODE_Column; data.colWidth[0] = 3; data.colWidth[1] = 15; data.colWidth[2] = 58; data.cnt = 0; sqlite3_exec(p->db, "PRAGMA database_list; ", callback, &data, &zErrMsg); if( zErrMsg ){ utf8_printf(stderr,"Error: %s\n", zErrMsg); sqlite3_free(zErrMsg); rc = 1; } }else if( c=='d' && strncmp(azArg[0], "dbinfo", n)==0 ){ rc = shell_dbinfo_command(p, nArg, azArg); }else if( c=='d' && strncmp(azArg[0], "dump", n)==0 ){ open_db(p, 0); /* When playing back a "dump", the content might appear in an order ** which causes immediate foreign key constraints to be violated. ** So disable foreign-key constraint enforcement to prevent problems. */ if( nArg!=1 && nArg!=2 ){ raw_printf(stderr, "Usage: .dump ?LIKE-PATTERN?\n"); rc = 1; goto meta_command_exit; } raw_printf(p->out, "PRAGMA foreign_keys=OFF;\n"); raw_printf(p->out, "BEGIN TRANSACTION;\n"); p->writableSchema = 0; sqlite3_exec(p->db, "SAVEPOINT dump; PRAGMA writable_schema=ON", 0, 0, 0); p->nErr = 0; if( nArg==1 ){ run_schema_dump_query(p, "SELECT name, type, sql FROM sqlite_master " "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'" ); run_schema_dump_query(p, "SELECT name, type, sql FROM sqlite_master " "WHERE name=='sqlite_sequence'" ); run_table_dump_query(p, "SELECT sql FROM sqlite_master " "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0 ); }else{ int i; for(i=1; i<nArg; i++){ zShellStatic = azArg[i]; run_schema_dump_query(p, "SELECT name, type, sql FROM sqlite_master " "WHERE tbl_name LIKE shellstatic() AND type=='table'" " AND sql NOT NULL"); run_table_dump_query(p, "SELECT sql FROM sqlite_master " "WHERE sql NOT NULL" " AND type IN ('index','trigger','view')" " AND tbl_name LIKE shellstatic()", 0 ); zShellStatic = 0; } } if( p->writableSchema ){ raw_printf(p->out, "PRAGMA writable_schema=OFF;\n"); p->writableSchema = 0; } sqlite3_exec(p->db, "PRAGMA writable_schema=OFF;", 0, 0, 0); sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0); raw_printf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n"); }else if( c=='e' && strncmp(azArg[0], "echo", n)==0 ){ if( nArg==2 ){ p->echoOn = booleanValue(azArg[1]); }else{ raw_printf(stderr, "Usage: .echo on|off\n"); rc = 1; } }else if( c=='e' && strncmp(azArg[0], "eqp", n)==0 ){ if( nArg==2 ){ if( strcmp(azArg[1],"full")==0 ){ p->autoEQP = 2; }else{ p->autoEQP = booleanValue(azArg[1]); } }else{ raw_printf(stderr, "Usage: .eqp on|off|full\n"); rc = 1; } }else if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){ if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc); rc = 2; }else if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){ int val = 1; if( nArg>=2 ){ if( strcmp(azArg[1],"auto")==0 ){ val = 99; }else{ val = booleanValue(azArg[1]); } } if( val==1 && p->mode!=MODE_Explain ){ p->normalMode = p->mode; p->mode = MODE_Explain; p->autoExplain = 0; }else if( val==0 ){ if( p->mode==MODE_Explain ) p->mode = p->normalMode; p->autoExplain = 0; }else if( val==99 ){ if( p->mode==MODE_Explain ) p->mode = p->normalMode; p->autoExplain = 1; } }else if( c=='f' && strncmp(azArg[0], "fullschema", n)==0 ){ ShellState data; char *zErrMsg = 0; int doStats = 0; memcpy(&data, p, sizeof(data)); data.showHeader = 0; data.cMode = data.mode = MODE_Semi; if( nArg==2 && optionMatch(azArg[1], "indent") ){ data.cMode = data.mode = MODE_Pretty; nArg = 1; } if( nArg!=1 ){ raw_printf(stderr, "Usage: .fullschema ?--indent?\n"); rc = 1; goto meta_command_exit; } open_db(p, 0); rc = sqlite3_exec(p->db, "SELECT sql FROM" " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x" " FROM sqlite_master UNION ALL" " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) " "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' " "ORDER BY rowid", callback, &data, &zErrMsg ); if( rc==SQLITE_OK ){ sqlite3_stmt *pStmt; rc = sqlite3_prepare_v2(p->db, "SELECT rowid FROM sqlite_master" " WHERE name GLOB 'sqlite_stat[134]'", -1, &pStmt, 0); doStats = sqlite3_step(pStmt)==SQLITE_ROW; sqlite3_finalize(pStmt); } if( doStats==0 ){ raw_printf(p->out, "/* No STAT tables available */\n"); }else{ raw_printf(p->out, "ANALYZE sqlite_master;\n"); sqlite3_exec(p->db, "SELECT 'ANALYZE sqlite_master'", callback, &data, &zErrMsg); data.cMode = data.mode = MODE_Insert; data.zDestTable = "sqlite_stat1"; shell_exec(p->db, "SELECT * FROM sqlite_stat1", shell_callback, &data,&zErrMsg); data.zDestTable = "sqlite_stat3"; shell_exec(p->db, "SELECT * FROM sqlite_stat3", shell_callback, &data,&zErrMsg); data.zDestTable = "sqlite_stat4"; shell_exec(p->db, "SELECT * FROM sqlite_stat4", shell_callback, &data, &zErrMsg); raw_printf(p->out, "ANALYZE sqlite_master;\n"); } }else if( c=='h' && strncmp(azArg[0], "headers", n)==0 ){ if( nArg==2 ){ p->showHeader = booleanValue(azArg[1]); }else{ raw_printf(stderr, "Usage: .headers on|off\n"); rc = 1; } }else if( c=='h' && strncmp(azArg[0], "help", n)==0 ){ utf8_printf(p->out, "%s", zHelp); }else if( c=='i' && strncmp(azArg[0], "import", n)==0 ){ char *zTable; /* Insert data into this table */ char *zFile; /* Name of file to extra content from */ sqlite3_stmt *pStmt = NULL; /* A statement */ int nCol; /* Number of columns in the table */ int nByte; /* Number of bytes in an SQL string */ int i, j; /* Loop counters */ int needCommit; /* True to COMMIT or ROLLBACK at end */ int nSep; /* Number of bytes in p->colSeparator[] */ char *zSql; /* An SQL statement */ ImportCtx sCtx; /* Reader context */ char *(SQLITE_CDECL *xRead)(ImportCtx*); /* Func to read one value */ int (SQLITE_CDECL *xCloser)(FILE*); /* Func to close file */ if( nArg!=3 ){ raw_printf(stderr, "Usage: .import FILE TABLE\n"); goto meta_command_exit; } zFile = azArg[1]; zTable = azArg[2]; seenInterrupt = 0; memset(&sCtx, 0, sizeof(sCtx)); open_db(p, 0); nSep = strlen30(p->colSeparator); if( nSep==0 ){ raw_printf(stderr, "Error: non-null column separator required for import\n"); return 1; } if( nSep>1 ){ raw_printf(stderr, "Error: multi-character column separators not allowed" " for import\n"); return 1; } nSep = strlen30(p->rowSeparator); if( nSep==0 ){ raw_printf(stderr, "Error: non-null row separator required for import\n"); return 1; } if( nSep==2 && p->mode==MODE_Csv && strcmp(p->rowSeparator, SEP_CrLf)==0 ){ /* When importing CSV (only), if the row separator is set to the ** default output row separator, change it to the default input ** row separator. This avoids having to maintain different input ** and output row separators. */ sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Row); nSep = strlen30(p->rowSeparator); } if( nSep>1 ){ raw_printf(stderr, "Error: multi-character row separators not allowed" " for import\n"); return 1; } sCtx.zFile = zFile; sCtx.nLine = 1; if( sCtx.zFile[0]=='|' ){ #ifdef SQLITE_OMIT_POPEN raw_printf(stderr, "Error: pipes are not supported in this OS\n"); return 1; #else sCtx.in = popen(sCtx.zFile+1, "r"); sCtx.zFile = "<pipe>"; xCloser = pclose; #endif }else{ sCtx.in = fopen(sCtx.zFile, "rb"); xCloser = fclose; } if( p->mode==MODE_Ascii ){ xRead = ascii_read_one_field; }else{ xRead = csv_read_one_field; } if( sCtx.in==0 ){ utf8_printf(stderr, "Error: cannot open \"%s\"\n", zFile); return 1; } sCtx.cColSep = p->colSeparator[0]; sCtx.cRowSep = p->rowSeparator[0]; zSql = sqlite3_mprintf("SELECT * FROM %s", zTable); if( zSql==0 ){ raw_printf(stderr, "Error: out of memory\n"); xCloser(sCtx.in); return 1; } nByte = strlen30(zSql); rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); import_append_char(&sCtx, 0); /* To ensure sCtx.z is allocated */ if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(p->db))==0 ){ char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable); char cSep = '('; while( xRead(&sCtx) ){ zCreate = sqlite3_mprintf("%z%c\n \"%w\" TEXT", zCreate, cSep, sCtx.z); cSep = ','; if( sCtx.cTerm!=sCtx.cColSep ) break; } if( cSep=='(' ){ sqlite3_free(zCreate); sqlite3_free(sCtx.z); xCloser(sCtx.in); utf8_printf(stderr,"%s: empty file\n", sCtx.zFile); return 1; } zCreate = sqlite3_mprintf("%z\n)", zCreate); rc = sqlite3_exec(p->db, zCreate, 0, 0, 0); sqlite3_free(zCreate); if( rc ){ utf8_printf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable, sqlite3_errmsg(p->db)); sqlite3_free(sCtx.z); xCloser(sCtx.in); return 1; } rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); } sqlite3_free(zSql); if( rc ){ if (pStmt) sqlite3_finalize(pStmt); utf8_printf(stderr,"Error: %s\n", sqlite3_errmsg(p->db)); xCloser(sCtx.in); return 1; } nCol = sqlite3_column_count(pStmt); sqlite3_finalize(pStmt); pStmt = 0; if( nCol==0 ) return 0; /* no columns, no error */ zSql = sqlite3_malloc64( nByte*2 + 20 + nCol*2 ); if( zSql==0 ){ raw_printf(stderr, "Error: out of memory\n"); xCloser(sCtx.in); return 1; } sqlite3_snprintf(nByte+20, zSql, "INSERT INTO \"%w\" VALUES(?", zTable); j = strlen30(zSql); for(i=1; i<nCol; i++){ zSql[j++] = ','; zSql[j++] = '?'; } zSql[j++] = ')'; zSql[j] = 0; rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); sqlite3_free(zSql); if( rc ){ utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); if (pStmt) sqlite3_finalize(pStmt); xCloser(sCtx.in); return 1; } needCommit = sqlite3_get_autocommit(p->db); if( needCommit ) sqlite3_exec(p->db, "BEGIN", 0, 0, 0); do{ int startLine = sCtx.nLine; for(i=0; i<nCol; i++){ char *z = xRead(&sCtx); /* ** Did we reach end-of-file before finding any columns? ** If so, stop instead of NULL filling the remaining columns. */ if( z==0 && i==0 ) break; /* ** Did we reach end-of-file OR end-of-line before finding any ** columns in ASCII mode? If so, stop instead of NULL filling ** the remaining columns. */ if( p->mode==MODE_Ascii && (z==0 || z[0]==0) && i==0 ) break; sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT); if( i<nCol-1 && sCtx.cTerm!=sCtx.cColSep ){ utf8_printf(stderr, "%s:%d: expected %d columns but found %d - " "filling the rest with NULL\n", sCtx.zFile, startLine, nCol, i+1); i += 2; while( i<=nCol ){ sqlite3_bind_null(pStmt, i); i++; } } } if( sCtx.cTerm==sCtx.cColSep ){ do{ xRead(&sCtx); i++; }while( sCtx.cTerm==sCtx.cColSep ); utf8_printf(stderr, "%s:%d: expected %d columns but found %d - " "extras ignored\n", sCtx.zFile, startLine, nCol, i); } if( i>=nCol ){ sqlite3_step(pStmt); rc = sqlite3_reset(pStmt); if( rc!=SQLITE_OK ){ utf8_printf(stderr, "%s:%d: INSERT failed: %s\n", sCtx.zFile, startLine, sqlite3_errmsg(p->db)); } } }while( sCtx.cTerm!=EOF ); xCloser(sCtx.in); sqlite3_free(sCtx.z); sqlite3_finalize(pStmt); if( needCommit ) sqlite3_exec(p->db, "COMMIT", 0, 0, 0); }else if( c=='i' && (strncmp(azArg[0], "indices", n)==0 || strncmp(azArg[0], "indexes", n)==0) ){ ShellState data; char *zErrMsg = 0; open_db(p, 0); memcpy(&data, p, sizeof(data)); data.showHeader = 0; data.cMode = data.mode = MODE_List; if( nArg==1 ){ rc = sqlite3_exec(p->db, "SELECT name FROM sqlite_master " "WHERE type='index' AND name NOT LIKE 'sqlite_%' " "UNION ALL " "SELECT name FROM sqlite_temp_master " "WHERE type='index' " "ORDER BY 1", callback, &data, &zErrMsg ); }else if( nArg==2 ){ zShellStatic = azArg[1]; rc = sqlite3_exec(p->db, "SELECT name FROM sqlite_master " "WHERE type='index' AND tbl_name LIKE shellstatic() " "UNION ALL " "SELECT name FROM sqlite_temp_master " "WHERE type='index' AND tbl_name LIKE shellstatic() " "ORDER BY 1", callback, &data, &zErrMsg ); zShellStatic = 0; }else{ raw_printf(stderr, "Usage: .indexes ?LIKE-PATTERN?\n"); rc = 1; goto meta_command_exit; } if( zErrMsg ){ utf8_printf(stderr,"Error: %s\n", zErrMsg); sqlite3_free(zErrMsg); rc = 1; }else if( rc != SQLITE_OK ){ raw_printf(stderr, "Error: querying sqlite_master and sqlite_temp_master\n"); rc = 1; } }else #ifdef SQLITE_ENABLE_IOTRACE if( c=='i' && strncmp(azArg[0], "iotrace", n)==0 ){ SQLITE_API extern void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...); if( iotrace && iotrace!=stdout ) fclose(iotrace); iotrace = 0; if( nArg<2 ){ sqlite3IoTrace = 0; }else if( strcmp(azArg[1], "-")==0 ){ sqlite3IoTrace = iotracePrintf; iotrace = stdout; }else{ iotrace = fopen(azArg[1], "w"); if( iotrace==0 ){ utf8_printf(stderr, "Error: cannot open \"%s\"\n", azArg[1]); sqlite3IoTrace = 0; rc = 1; }else{ sqlite3IoTrace = iotracePrintf; } } }else #endif if( c=='l' && n>=5 && strncmp(azArg[0], "limits", n)==0 ){ static const struct { const char *zLimitName; /* Name of a limit */ int limitCode; /* Integer code for that limit */ } aLimit[] = { { "length", SQLITE_LIMIT_LENGTH }, { "sql_length", SQLITE_LIMIT_SQL_LENGTH }, { "column", SQLITE_LIMIT_COLUMN }, { "expr_depth", SQLITE_LIMIT_EXPR_DEPTH }, { "compound_select", SQLITE_LIMIT_COMPOUND_SELECT }, { "vdbe_op", SQLITE_LIMIT_VDBE_OP }, { "function_arg", SQLITE_LIMIT_FUNCTION_ARG }, { "attached", SQLITE_LIMIT_ATTACHED }, { "like_pattern_length", SQLITE_LIMIT_LIKE_PATTERN_LENGTH }, { "variable_number", SQLITE_LIMIT_VARIABLE_NUMBER }, { "trigger_depth", SQLITE_LIMIT_TRIGGER_DEPTH }, { "worker_threads", SQLITE_LIMIT_WORKER_THREADS }, }; int i, n2; open_db(p, 0); if( nArg==1 ){ for(i=0; i<ArraySize(aLimit); i++){ printf("%20s %d\n", aLimit[i].zLimitName, sqlite3_limit(p->db, aLimit[i].limitCode, -1)); } }else if( nArg>3 ){ raw_printf(stderr, "Usage: .limit NAME ?NEW-VALUE?\n"); rc = 1; goto meta_command_exit; }else{ int iLimit = -1; n2 = strlen30(azArg[1]); for(i=0; i<ArraySize(aLimit); i++){ if( sqlite3_strnicmp(aLimit[i].zLimitName, azArg[1], n2)==0 ){ if( iLimit<0 ){ iLimit = i; }else{ utf8_printf(stderr, "ambiguous limit: \"%s\"\n", azArg[1]); rc = 1; goto meta_command_exit; } } } if( iLimit<0 ){ utf8_printf(stderr, "unknown limit: \"%s\"\n" "enter \".limits\" with no arguments for a list.\n", azArg[1]); rc = 1; goto meta_command_exit; } if( nArg==3 ){ sqlite3_limit(p->db, aLimit[iLimit].limitCode, (int)integerValue(azArg[2])); } printf("%20s %d\n", aLimit[iLimit].zLimitName, sqlite3_limit(p->db, aLimit[iLimit].limitCode, -1)); } }else #ifndef SQLITE_OMIT_LOAD_EXTENSION if( c=='l' && strncmp(azArg[0], "load", n)==0 ){ const char *zFile, *zProc; char *zErrMsg = 0; if( nArg<2 ){ raw_printf(stderr, "Usage: .load FILE ?ENTRYPOINT?\n"); rc = 1; goto meta_command_exit; } zFile = azArg[1]; zProc = nArg>=3 ? azArg[2] : 0; open_db(p, 0); rc = sqlite3_load_extension(p->db, zFile, zProc, &zErrMsg); if( rc!=SQLITE_OK ){ utf8_printf(stderr, "Error: %s\n", zErrMsg); sqlite3_free(zErrMsg); rc = 1; } }else #endif if( c=='l' && strncmp(azArg[0], "log", n)==0 ){ if( nArg!=2 ){ raw_printf(stderr, "Usage: .log FILENAME\n"); rc = 1; }else{ const char *zFile = azArg[1]; output_file_close(p->pLog); p->pLog = output_file_open(zFile); } }else if( c=='m' && strncmp(azArg[0], "mode", n)==0 ){ const char *zMode = nArg>=2 ? azArg[1] : ""; int n2 = (int)strlen(zMode); int c2 = zMode[0]; if( c2=='l' && n2>2 && strncmp(azArg[1],"lines",n2)==0 ){ p->mode = MODE_Line; }else if( c2=='c' && strncmp(azArg[1],"columns",n2)==0 ){ p->mode = MODE_Column; }else if( c2=='l' && n2>2 && strncmp(azArg[1],"list",n2)==0 ){ p->mode = MODE_List; }else if( c2=='h' && strncmp(azArg[1],"html",n2)==0 ){ p->mode = MODE_Html; }else if( c2=='t' && strncmp(azArg[1],"tcl",n2)==0 ){ p->mode = MODE_Tcl; sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Space); }else if( c2=='c' && strncmp(azArg[1],"csv",n2)==0 ){ p->mode = MODE_Csv; sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Comma); sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_CrLf); }else if( c2=='t' && strncmp(azArg[1],"tabs",n2)==0 ){ p->mode = MODE_List; sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Tab); }else if( c2=='i' && strncmp(azArg[1],"insert",n2)==0 ){ p->mode = MODE_Insert; set_table_name(p, nArg>=3 ? azArg[2] : "table"); }else if( c2=='a' && strncmp(azArg[1],"ascii",n2)==0 ){ p->mode = MODE_Ascii; sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, SEP_Unit); sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, SEP_Record); }else { raw_printf(stderr, "Error: mode should be one of: " "ascii column csv html insert line list tabs tcl\n"); rc = 1; } p->cMode = p->mode; }else if( c=='n' && strncmp(azArg[0], "nullvalue", n)==0 ){ if( nArg==2 ){ sqlite3_snprintf(sizeof(p->nullValue), p->nullValue, "%.*s", (int)ArraySize(p->nullValue)-1, azArg[1]); }else{ raw_printf(stderr, "Usage: .nullvalue STRING\n"); rc = 1; } }else if( c=='o' && strncmp(azArg[0], "open", n)==0 && n>=2 ){ sqlite3 *savedDb = p->db; const char *zSavedFilename = p->zDbFilename; char *zNewFilename = 0; p->db = 0; if( nArg>=2 ) zNewFilename = sqlite3_mprintf("%s", azArg[1]); p->zDbFilename = zNewFilename; open_db(p, 1); if( p->db!=0 ){ session_close_all(p); sqlite3_close(savedDb); sqlite3_free(p->zFreeOnClose); p->zFreeOnClose = zNewFilename; }else{ sqlite3_free(zNewFilename); p->db = savedDb; p->zDbFilename = zSavedFilename; } }else if( c=='o' && (strncmp(azArg[0], "output", n)==0 || strncmp(azArg[0], "once", n)==0) ){ const char *zFile = nArg>=2 ? azArg[1] : "stdout"; if( nArg>2 ){ utf8_printf(stderr, "Usage: .%s FILE\n", azArg[0]); rc = 1; goto meta_command_exit; } if( n>1 && strncmp(azArg[0], "once", n)==0 ){ if( nArg<2 ){ raw_printf(stderr, "Usage: .once FILE\n"); rc = 1; goto meta_command_exit; } p->outCount = 2; }else{ p->outCount = 0; } output_reset(p); if( zFile[0]=='|' ){ #ifdef SQLITE_OMIT_POPEN raw_printf(stderr, "Error: pipes are not supported in this OS\n"); rc = 1; p->out = stdout; #else p->out = popen(zFile + 1, "w"); if( p->out==0 ){ utf8_printf(stderr,"Error: cannot open pipe \"%s\"\n", zFile + 1); p->out = stdout; rc = 1; }else{ sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); } #endif }else{ p->out = output_file_open(zFile); if( p->out==0 ){ if( strcmp(zFile,"off")!=0 ){ utf8_printf(stderr,"Error: cannot write to \"%s\"\n", zFile); } p->out = stdout; rc = 1; } else { sqlite3_snprintf(sizeof(p->outfile), p->outfile, "%s", zFile); } } }else if( c=='p' && n>=3 && strncmp(azArg[0], "print", n)==0 ){ int i; for(i=1; i<nArg; i++){ if( i>1 ) raw_printf(p->out, " "); utf8_printf(p->out, "%s", azArg[i]); } raw_printf(p->out, "\n"); }else if( c=='p' && strncmp(azArg[0], "prompt", n)==0 ){ if( nArg >= 2) { strncpy(mainPrompt,azArg[1],(int)ArraySize(mainPrompt)-1); } if( nArg >= 3) { strncpy(continuePrompt,azArg[2],(int)ArraySize(continuePrompt)-1); } }else if( c=='q' && strncmp(azArg[0], "quit", n)==0 ){ rc = 2; }else if( c=='r' && n>=3 && strncmp(azArg[0], "read", n)==0 ){ FILE *alt; if( nArg!=2 ){ raw_printf(stderr, "Usage: .read FILE\n"); rc = 1; goto meta_command_exit; } alt = fopen(azArg[1], "rb"); if( alt==0 ){ utf8_printf(stderr,"Error: cannot open \"%s\"\n", azArg[1]); rc = 1; }else{ rc = process_input(p, alt); fclose(alt); } }else if( c=='r' && n>=3 && strncmp(azArg[0], "restore", n)==0 ){ const char *zSrcFile; const char *zDb; sqlite3 *pSrc; sqlite3_backup *pBackup; int nTimeout = 0; if( nArg==2 ){ zSrcFile = azArg[1]; zDb = "main"; }else if( nArg==3 ){ zSrcFile = azArg[2]; zDb = azArg[1]; }else{ raw_printf(stderr, "Usage: .restore ?DB? FILE\n"); rc = 1; goto meta_command_exit; } rc = sqlite3_open(zSrcFile, &pSrc); if( rc!=SQLITE_OK ){ utf8_printf(stderr, "Error: cannot open \"%s\"\n", zSrcFile); sqlite3_close(pSrc); return 1; } open_db(p, 0); pBackup = sqlite3_backup_init(p->db, zDb, pSrc, "main"); if( pBackup==0 ){ utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); sqlite3_close(pSrc); return 1; } while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK || rc==SQLITE_BUSY ){ if( rc==SQLITE_BUSY ){ if( nTimeout++ >= 3 ) break; sqlite3_sleep(100); } } sqlite3_backup_finish(pBackup); if( rc==SQLITE_DONE ){ rc = 0; }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){ raw_printf(stderr, "Error: source database is busy\n"); rc = 1; }else{ utf8_printf(stderr, "Error: %s\n", sqlite3_errmsg(p->db)); rc = 1; } sqlite3_close(pSrc); }else if( c=='s' && strncmp(azArg[0], "scanstats", n)==0 ){ if( nArg==2 ){ p->scanstatsOn = booleanValue(azArg[1]); #ifndef SQLITE_ENABLE_STMT_SCANSTATUS raw_printf(stderr, "Warning: .scanstats not available in this build.\n"); #endif }else{ raw_printf(stderr, "Usage: .scanstats on|off\n"); rc = 1; } }else if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){ ShellState data; char *zErrMsg = 0; open_db(p, 0); memcpy(&data, p, sizeof(data)); data.showHeader = 0; data.cMode = data.mode = MODE_Semi; if( nArg>=2 && optionMatch(azArg[1], "indent") ){ data.cMode = data.mode = MODE_Pretty; nArg--; if( nArg==2 ) azArg[1] = azArg[2]; } if( nArg==2 && azArg[1][0]!='-' ){ int i; for(i=0; azArg[1][i]; i++) azArg[1][i] = ToLower(azArg[1][i]); if( strcmp(azArg[1],"sqlite_master")==0 ){ char *new_argv[2], *new_colv[2]; new_argv[0] = "CREATE TABLE sqlite_master (\n" " type text,\n" " name text,\n" " tbl_name text,\n" " rootpage integer,\n" " sql text\n" ")"; new_argv[1] = 0; new_colv[0] = "sql"; new_colv[1] = 0; callback(&data, 1, new_argv, new_colv); rc = SQLITE_OK; }else if( strcmp(azArg[1],"sqlite_temp_master")==0 ){ char *new_argv[2], *new_colv[2]; new_argv[0] = "CREATE TEMP TABLE sqlite_temp_master (\n" " type text,\n" " name text,\n" " tbl_name text,\n" " rootpage integer,\n" " sql text\n" ")"; new_argv[1] = 0; new_colv[0] = "sql"; new_colv[1] = 0; callback(&data, 1, new_argv, new_colv); rc = SQLITE_OK; }else{ zShellStatic = azArg[1]; rc = sqlite3_exec(p->db, "SELECT sql FROM " " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x" " FROM sqlite_master UNION ALL" " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) " "WHERE lower(tbl_name) LIKE shellstatic()" " AND type!='meta' AND sql NOTNULL " "ORDER BY rowid", callback, &data, &zErrMsg); zShellStatic = 0; } }else if( nArg==1 ){ rc = sqlite3_exec(p->db, "SELECT sql FROM " " (SELECT sql sql, type type, tbl_name tbl_name, name name, rowid x" " FROM sqlite_master UNION ALL" " SELECT sql, type, tbl_name, name, rowid FROM sqlite_temp_master) " "WHERE type!='meta' AND sql NOTNULL AND name NOT LIKE 'sqlite_%' " "ORDER BY rowid", callback, &data, &zErrMsg ); }else{ raw_printf(stderr, "Usage: .schema ?--indent? ?LIKE-PATTERN?\n"); rc = 1; goto meta_command_exit; } if( zErrMsg ){ utf8_printf(stderr,"Error: %s\n", zErrMsg); sqlite3_free(zErrMsg); rc = 1; }else if( rc != SQLITE_OK ){ raw_printf(stderr,"Error: querying schema information\n"); rc = 1; }else{ rc = 0; } }else #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_SELECTTRACE) if( c=='s' && n==11 && strncmp(azArg[0], "selecttrace", n)==0 ){ sqlite3SelectTrace = integerValue(azArg[1]); }else #endif #if defined(SQLITE_ENABLE_SESSION) if( c=='s' && strncmp(azArg[0],"session",n)==0 && n>=3 ){ OpenSession *pSession = &p->aSession[0]; char **azCmd = &azArg[1]; int iSes = 0; int nCmd = nArg - 1; int i; if( nArg<=1 ) goto session_syntax_error; open_db(p, 0); if( nArg>=3 ){ for(iSes=0; iSes<p->nSession; iSes++){ if( strcmp(p->aSession[iSes].zName, azArg[1])==0 ) break; } if( iSes<p->nSession ){ pSession = &p->aSession[iSes]; azCmd++; nCmd--; }else{ pSession = &p->aSession[0]; iSes = 0; } } /* .session attach TABLE ** Invoke the sqlite3session_attach() interface to attach a particular ** table so that it is never filtered. */ if( strcmp(azCmd[0],"attach")==0 ){ if( nCmd!=2 ) goto session_syntax_error; if( pSession->p==0 ){ session_not_open: raw_printf(stderr, "ERROR: No sessions are open\n"); }else{ rc = sqlite3session_attach(pSession->p, azCmd[1]); if( rc ){ raw_printf(stderr, "ERROR: sqlite3session_attach() returns %d\n", rc); rc = 0; } } }else /* .session changeset FILE ** .session patchset FILE ** Write a changeset or patchset into a file. The file is overwritten. */ if( strcmp(azCmd[0],"changeset")==0 || strcmp(azCmd[0],"patchset")==0 ){ FILE *out = 0; if( nCmd!=2 ) goto session_syntax_error; if( pSession->p==0 ) goto session_not_open; out = fopen(azCmd[1], "wb"); if( out==0 ){ utf8_printf(stderr, "ERROR: cannot open \"%s\" for writing\n", azCmd[1]); }else{ int szChng; void *pChng; if( azCmd[0][0]=='c' ){ rc = sqlite3session_changeset(pSession->p, &szChng, &pChng); }else{ rc = sqlite3session_patchset(pSession->p, &szChng, &pChng); } if( rc ){ printf("Error: error code %d\n", rc); rc = 0; } if( pChng && fwrite(pChng, szChng, 1, out)!=1 ){ raw_printf(stderr, "ERROR: Failed to write entire %d-byte output\n", szChng); } sqlite3_free(pChng); fclose(out); } }else /* .session close ** Close the identified session */ if( strcmp(azCmd[0], "close")==0 ){ if( nCmd!=1 ) goto session_syntax_error; if( p->nSession ){ session_close(pSession); p->aSession[iSes] = p->aSession[--p->nSession]; } }else /* .session enable ?BOOLEAN? ** Query or set the enable flag */ if( strcmp(azCmd[0], "enable")==0 ){ int ii; if( nCmd>2 ) goto session_syntax_error; ii = nCmd==1 ? -1 : booleanValue(azCmd[1]); if( p->nSession ){ ii = sqlite3session_enable(pSession->p, ii); utf8_printf(p->out, "session %s enable flag = %d\n", pSession->zName, ii); } }else /* .session filter GLOB .... ** Set a list of GLOB patterns of table names to be excluded. */ if( strcmp(azCmd[0], "filter")==0 ){ int ii, nByte; if( nCmd<2 ) goto session_syntax_error; if( p->nSession ){ for(ii=0; ii<pSession->nFilter; ii++){ sqlite3_free(pSession->azFilter[ii]); } sqlite3_free(pSession->azFilter); nByte = sizeof(pSession->azFilter[0])*(nCmd-1); pSession->azFilter = sqlite3_malloc( nByte ); if( pSession->azFilter==0 ){ raw_printf(stderr, "Error: out or memory\n"); exit(1); } for(ii=1; ii<nCmd; ii++){ pSession->azFilter[ii-1] = sqlite3_mprintf("%s", azCmd[ii]); } pSession->nFilter = ii-1; } }else /* .session indirect ?BOOLEAN? ** Query or set the indirect flag */ if( strcmp(azCmd[0], "indirect")==0 ){ int ii; if( nCmd>2 ) goto session_syntax_error; ii = nCmd==1 ? -1 : booleanValue(azCmd[1]); if( p->nSession ){ ii = sqlite3session_indirect(pSession->p, ii); utf8_printf(p->out, "session %s indirect flag = %d\n", pSession->zName, ii); } }else /* .session isempty ** Determine if the session is empty */ if( strcmp(azCmd[0], "isempty")==0 ){ int ii; if( nCmd!=1 ) goto session_syntax_error; if( p->nSession ){ ii = sqlite3session_isempty(pSession->p); utf8_printf(p->out, "session %s isempty flag = %d\n", pSession->zName, ii); } }else /* .session list ** List all currently open sessions */ if( strcmp(azCmd[0],"list")==0 ){ for(i=0; i<p->nSession; i++){ utf8_printf(p->out, "%d %s\n", i, p->aSession[i].zName); } }else /* .session open DB NAME ** Open a new session called NAME on the attached database DB. ** DB is normally "main". */ if( strcmp(azCmd[0],"open")==0 ){ char *zName; if( nCmd!=3 ) goto session_syntax_error; zName = azCmd[2]; if( zName[0]==0 ) goto session_syntax_error; for(i=0; i<p->nSession; i++){ if( strcmp(p->aSession[i].zName,zName)==0 ){ utf8_printf(stderr, "Session \"%s\" already exists\n", zName); goto meta_command_exit; } } if( p->nSession>=ArraySize(p->aSession) ){ raw_printf(stderr, "Maximum of %d sessions\n", ArraySize(p->aSession)); goto meta_command_exit; } pSession = &p->aSession[p->nSession]; rc = sqlite3session_create(p->db, azCmd[1], &pSession->p); if( rc ){ raw_printf(stderr, "Cannot open session: error code=%d\n", rc); rc = 0; goto meta_command_exit; } pSession->nFilter = 0; sqlite3session_table_filter(pSession->p, session_filter, pSession); p->nSession++; pSession->zName = sqlite3_mprintf("%s", zName); }else /* If no command name matches, show a syntax error */ session_syntax_error: session_help(p); }else #endif #ifdef SQLITE_DEBUG /* Undocumented commands for internal testing. Subject to change ** without notice. */ if( c=='s' && n>=10 && strncmp(azArg[0], "selftest-", 9)==0 ){ if( strncmp(azArg[0]+9, "boolean", n-9)==0 ){ int i, v; for(i=1; i<nArg; i++){ v = booleanValue(azArg[i]); utf8_printf(p->out, "%s: %d 0x%x\n", azArg[i], v, v); } } if( strncmp(azArg[0]+9, "integer", n-9)==0 ){ int i; sqlite3_int64 v; for(i=1; i<nArg; i++){ char zBuf[200]; v = integerValue(azArg[i]); sqlite3_snprintf(sizeof(zBuf),zBuf,"%s: %lld 0x%llx\n", azArg[i],v,v); utf8_printf(p->out, "%s", zBuf); } } }else #endif if( c=='s' && strncmp(azArg[0], "separator", n)==0 ){ if( nArg<2 || nArg>3 ){ raw_printf(stderr, "Usage: .separator COL ?ROW?\n"); rc = 1; } if( nArg>=2 ){ sqlite3_snprintf(sizeof(p->colSeparator), p->colSeparator, "%.*s", (int)ArraySize(p->colSeparator)-1, azArg[1]); } if( nArg>=3 ){ sqlite3_snprintf(sizeof(p->rowSeparator), p->rowSeparator, "%.*s", (int)ArraySize(p->rowSeparator)-1, azArg[2]); } }else if( c=='s' && (strncmp(azArg[0], "shell", n)==0 || strncmp(azArg[0],"system",n)==0) ){ char *zCmd; int i, x; if( nArg<2 ){ raw_printf(stderr, "Usage: .system COMMAND\n"); rc = 1; goto meta_command_exit; } zCmd = sqlite3_mprintf(strchr(azArg[1],' ')==0?"%s":"\"%s\"", azArg[1]); for(i=2; i<nArg; i++){ zCmd = sqlite3_mprintf(strchr(azArg[i],' ')==0?"%z %s":"%z \"%s\"", zCmd, azArg[i]); } x = system(zCmd); sqlite3_free(zCmd); if( x ) raw_printf(stderr, "System command returns %d\n", x); }else if( c=='s' && strncmp(azArg[0], "show", n)==0 ){ static const char *azBool[] = { "off", "on", "full", "unk" }; int i; if( nArg!=1 ){ raw_printf(stderr, "Usage: .show\n"); rc = 1; goto meta_command_exit; } utf8_printf(p->out, "%12.12s: %s\n","echo", azBool[p->echoOn!=0]); utf8_printf(p->out, "%12.12s: %s\n","eqp", azBool[p->autoEQP&3]); utf8_printf(p->out, "%12.12s: %s\n","explain", p->mode==MODE_Explain ? "on" : p->autoExplain ? "auto" : "off"); utf8_printf(p->out,"%12.12s: %s\n","headers", azBool[p->showHeader!=0]); utf8_printf(p->out, "%12.12s: %s\n","mode", modeDescr[p->mode]); utf8_printf(p->out, "%12.12s: ", "nullvalue"); output_c_string(p->out, p->nullValue); raw_printf(p->out, "\n"); utf8_printf(p->out,"%12.12s: %s\n","output", strlen30(p->outfile) ? p->outfile : "stdout"); utf8_printf(p->out,"%12.12s: ", "colseparator"); output_c_string(p->out, p->colSeparator); raw_printf(p->out, "\n"); utf8_printf(p->out,"%12.12s: ", "rowseparator"); output_c_string(p->out, p->rowSeparator); raw_printf(p->out, "\n"); utf8_printf(p->out, "%12.12s: %s\n","stats", azBool[p->statsOn!=0]); utf8_printf(p->out, "%12.12s: ", "width"); for (i=0;i<(int)ArraySize(p->colWidth) && p->colWidth[i] != 0;i++) { raw_printf(p->out, "%d ", p->colWidth[i]); } raw_printf(p->out, "\n"); }else if( c=='s' && strncmp(azArg[0], "stats", n)==0 ){ if( nArg==2 ){ p->statsOn = booleanValue(azArg[1]); }else if( nArg==1 ){ display_stats(p->db, p, 0); }else{ raw_printf(stderr, "Usage: .stats ?on|off?\n"); rc = 1; } }else if( c=='t' && n>1 && strncmp(azArg[0], "tables", n)==0 ){ sqlite3_stmt *pStmt; char **azResult; int nRow, nAlloc; char *zSql = 0; int ii; open_db(p, 0); rc = sqlite3_prepare_v2(p->db, "PRAGMA database_list", -1, &pStmt, 0); if( rc ) return shellDatabaseError(p->db); /* Create an SQL statement to query for the list of tables in the ** main and all attached databases where the table name matches the ** LIKE pattern bound to variable "?1". */ zSql = sqlite3_mprintf( "SELECT name FROM sqlite_master" " WHERE type IN ('table','view')" " AND name NOT LIKE 'sqlite_%%'" " AND name LIKE ?1"); while( zSql && sqlite3_step(pStmt)==SQLITE_ROW ){ const char *zDbName = (const char*)sqlite3_column_text(pStmt, 1); if( zDbName==0 || strcmp(zDbName,"main")==0 ) continue; if( strcmp(zDbName,"temp")==0 ){ zSql = sqlite3_mprintf( "%z UNION ALL " "SELECT 'temp.' || name FROM sqlite_temp_master" " WHERE type IN ('table','view')" " AND name NOT LIKE 'sqlite_%%'" " AND name LIKE ?1", zSql); }else{ zSql = sqlite3_mprintf( "%z UNION ALL " "SELECT '%q.' || name FROM \"%w\".sqlite_master" " WHERE type IN ('table','view')" " AND name NOT LIKE 'sqlite_%%'" " AND name LIKE ?1", zSql, zDbName, zDbName); } } rc = sqlite3_finalize(pStmt); if( zSql && rc==SQLITE_OK ){ zSql = sqlite3_mprintf("%z ORDER BY 1", zSql); if( zSql ) rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); } sqlite3_free(zSql); if( !zSql ) return shellNomemError(); if( rc ) return shellDatabaseError(p->db); /* Run the SQL statement prepared by the above block. Store the results ** as an array of nul-terminated strings in azResult[]. */ nRow = nAlloc = 0; azResult = 0; if( nArg>1 ){ sqlite3_bind_text(pStmt, 1, azArg[1], -1, SQLITE_TRANSIENT); }else{ sqlite3_bind_text(pStmt, 1, "%", -1, SQLITE_STATIC); } while( sqlite3_step(pStmt)==SQLITE_ROW ){ if( nRow>=nAlloc ){ char **azNew; int n2 = nAlloc*2 + 10; azNew = sqlite3_realloc64(azResult, sizeof(azResult[0])*n2); if( azNew==0 ){ rc = shellNomemError(); break; } nAlloc = n2; azResult = azNew; } azResult[nRow] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0)); if( 0==azResult[nRow] ){ rc = shellNomemError(); break; } nRow++; } if( sqlite3_finalize(pStmt)!=SQLITE_OK ){ rc = shellDatabaseError(p->db); } /* Pretty-print the contents of array azResult[] to the output */ if( rc==0 && nRow>0 ){ int len, maxlen = 0; int i, j; int nPrintCol, nPrintRow; for(i=0; i<nRow; i++){ len = strlen30(azResult[i]); if( len>maxlen ) maxlen = len; } nPrintCol = 80/(maxlen+2); if( nPrintCol<1 ) nPrintCol = 1; nPrintRow = (nRow + nPrintCol - 1)/nPrintCol; for(i=0; i<nPrintRow; i++){ for(j=i; j<nRow; j+=nPrintRow){ char *zSp = j<nPrintRow ? "" : " "; utf8_printf(p->out, "%s%-*s", zSp, maxlen, azResult[j] ? azResult[j]:""); } raw_printf(p->out, "\n"); } } for(ii=0; ii<nRow; ii++) sqlite3_free(azResult[ii]); sqlite3_free(azResult); }else if( c=='t' && n>=8 && strncmp(azArg[0], "testctrl", n)==0 && nArg>=2 ){ static const struct { const char *zCtrlName; /* Name of a test-control option */ int ctrlCode; /* Integer code for that option */ } aCtrl[] = { { "prng_save", SQLITE_TESTCTRL_PRNG_SAVE }, { "prng_restore", SQLITE_TESTCTRL_PRNG_RESTORE }, { "prng_reset", SQLITE_TESTCTRL_PRNG_RESET }, { "bitvec_test", SQLITE_TESTCTRL_BITVEC_TEST }, { "fault_install", SQLITE_TESTCTRL_FAULT_INSTALL }, { "benign_malloc_hooks", SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS }, { "pending_byte", SQLITE_TESTCTRL_PENDING_BYTE }, { "assert", SQLITE_TESTCTRL_ASSERT }, { "always", SQLITE_TESTCTRL_ALWAYS }, { "reserve", SQLITE_TESTCTRL_RESERVE }, { "optimizations", SQLITE_TESTCTRL_OPTIMIZATIONS }, { "iskeyword", SQLITE_TESTCTRL_ISKEYWORD }, { "scratchmalloc", SQLITE_TESTCTRL_SCRATCHMALLOC }, { "byteorder", SQLITE_TESTCTRL_BYTEORDER }, { "never_corrupt", SQLITE_TESTCTRL_NEVER_CORRUPT }, { "imposter", SQLITE_TESTCTRL_IMPOSTER }, }; int testctrl = -1; int rc2 = 0; int i, n2; open_db(p, 0); /* convert testctrl text option to value. allow any unique prefix ** of the option name, or a numerical value. */ n2 = strlen30(azArg[1]); for(i=0; i<ArraySize(aCtrl); i++){ if( strncmp(azArg[1], aCtrl[i].zCtrlName, n2)==0 ){ if( testctrl<0 ){ testctrl = aCtrl[i].ctrlCode; }else{ utf8_printf(stderr, "ambiguous option name: \"%s\"\n", azArg[1]); testctrl = -1; break; } } } if( testctrl<0 ) testctrl = (int)integerValue(azArg[1]); if( (testctrl<SQLITE_TESTCTRL_FIRST) || (testctrl>SQLITE_TESTCTRL_LAST) ){ utf8_printf(stderr,"Error: invalid testctrl option: %s\n", azArg[1]); }else{ switch(testctrl){ /* sqlite3_test_control(int, db, int) */ case SQLITE_TESTCTRL_OPTIMIZATIONS: case SQLITE_TESTCTRL_RESERVE: if( nArg==3 ){ int opt = (int)strtol(azArg[2], 0, 0); rc2 = sqlite3_test_control(testctrl, p->db, opt); raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2); } else { utf8_printf(stderr,"Error: testctrl %s takes a single int option\n", azArg[1]); } break; /* sqlite3_test_control(int) */ case SQLITE_TESTCTRL_PRNG_SAVE: case SQLITE_TESTCTRL_PRNG_RESTORE: case SQLITE_TESTCTRL_PRNG_RESET: case SQLITE_TESTCTRL_BYTEORDER: if( nArg==2 ){ rc2 = sqlite3_test_control(testctrl); raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2); } else { utf8_printf(stderr,"Error: testctrl %s takes no options\n", azArg[1]); } break; /* sqlite3_test_control(int, uint) */ case SQLITE_TESTCTRL_PENDING_BYTE: if( nArg==3 ){ unsigned int opt = (unsigned int)integerValue(azArg[2]); rc2 = sqlite3_test_control(testctrl, opt); raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2); } else { utf8_printf(stderr,"Error: testctrl %s takes a single unsigned" " int option\n", azArg[1]); } break; /* sqlite3_test_control(int, int) */ case SQLITE_TESTCTRL_ASSERT: case SQLITE_TESTCTRL_ALWAYS: case SQLITE_TESTCTRL_NEVER_CORRUPT: if( nArg==3 ){ int opt = booleanValue(azArg[2]); rc2 = sqlite3_test_control(testctrl, opt); raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2); } else { utf8_printf(stderr,"Error: testctrl %s takes a single int option\n", azArg[1]); } break; /* sqlite3_test_control(int, char *) */ #ifdef SQLITE_N_KEYWORD case SQLITE_TESTCTRL_ISKEYWORD: if( nArg==3 ){ const char *opt = azArg[2]; rc2 = sqlite3_test_control(testctrl, opt); raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2); } else { utf8_printf(stderr, "Error: testctrl %s takes a single char * option\n", azArg[1]); } break; #endif case SQLITE_TESTCTRL_IMPOSTER: if( nArg==5 ){ rc2 = sqlite3_test_control(testctrl, p->db, azArg[2], integerValue(azArg[3]), integerValue(azArg[4])); raw_printf(p->out, "%d (0x%08x)\n", rc2, rc2); }else{ raw_printf(stderr,"Usage: .testctrl imposter dbName onoff tnum\n"); } break; case SQLITE_TESTCTRL_BITVEC_TEST: case SQLITE_TESTCTRL_FAULT_INSTALL: case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: case SQLITE_TESTCTRL_SCRATCHMALLOC: default: utf8_printf(stderr, "Error: CLI support for testctrl %s not implemented\n", azArg[1]); break; } } }else if( c=='t' && n>4 && strncmp(azArg[0], "timeout", n)==0 ){ open_db(p, 0); sqlite3_busy_timeout(p->db, nArg>=2 ? (int)integerValue(azArg[1]) : 0); }else if( c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0 ){ if( nArg==2 ){ enableTimer = booleanValue(azArg[1]); if( enableTimer && !HAS_TIMER ){ raw_printf(stderr, "Error: timer not available on this system.\n"); enableTimer = 0; } }else{ raw_printf(stderr, "Usage: .timer on|off\n"); rc = 1; } }else if( c=='t' && strncmp(azArg[0], "trace", n)==0 ){ open_db(p, 0); if( nArg!=2 ){ raw_printf(stderr, "Usage: .trace FILE|off\n"); rc = 1; goto meta_command_exit; } output_file_close(p->traceOut); p->traceOut = output_file_open(azArg[1]); #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) if( p->traceOut==0 ){ sqlite3_trace_v2(p->db, 0, 0, 0); }else{ sqlite3_trace_v2(p->db, SQLITE_TRACE_STMT, sql_trace_callback,p->traceOut); } #endif }else #if SQLITE_USER_AUTHENTICATION if( c=='u' && strncmp(azArg[0], "user", n)==0 ){ if( nArg<2 ){ raw_printf(stderr, "Usage: .user SUBCOMMAND ...\n"); rc = 1; goto meta_command_exit; } open_db(p, 0); if( strcmp(azArg[1],"login")==0 ){ if( nArg!=4 ){ raw_printf(stderr, "Usage: .user login USER PASSWORD\n"); rc = 1; goto meta_command_exit; } rc = sqlite3_user_authenticate(p->db, azArg[2], azArg[3], (int)strlen(azArg[3])); if( rc ){ utf8_printf(stderr, "Authentication failed for user %s\n", azArg[2]); rc = 1; } }else if( strcmp(azArg[1],"add")==0 ){ if( nArg!=5 ){ raw_printf(stderr, "Usage: .user add USER PASSWORD ISADMIN\n"); rc = 1; goto meta_command_exit; } rc = sqlite3_user_add(p->db, azArg[2], azArg[3], (int)strlen(azArg[3]), booleanValue(azArg[4])); if( rc ){ raw_printf(stderr, "User-Add failed: %d\n", rc); rc = 1; } }else if( strcmp(azArg[1],"edit")==0 ){ if( nArg!=5 ){ raw_printf(stderr, "Usage: .user edit USER PASSWORD ISADMIN\n"); rc = 1; goto meta_command_exit; } rc = sqlite3_user_change(p->db, azArg[2], azArg[3], (int)strlen(azArg[3]), booleanValue(azArg[4])); if( rc ){ raw_printf(stderr, "User-Edit failed: %d\n", rc); rc = 1; } }else if( strcmp(azArg[1],"delete")==0 ){ if( nArg!=3 ){ raw_printf(stderr, "Usage: .user delete USER\n"); rc = 1; goto meta_command_exit; } rc = sqlite3_user_delete(p->db, azArg[2]); if( rc ){ raw_printf(stderr, "User-Delete failed: %d\n", rc); rc = 1; } }else{ raw_printf(stderr, "Usage: .user login|add|edit|delete ...\n"); rc = 1; goto meta_command_exit; } }else #endif /* SQLITE_USER_AUTHENTICATION */ if( c=='v' && strncmp(azArg[0], "version", n)==0 ){ utf8_printf(p->out, "SQLite %s %s\n" /*extra-version-info*/, sqlite3_libversion(), sqlite3_sourceid()); }else if( c=='v' && strncmp(azArg[0], "vfsinfo", n)==0 ){ const char *zDbName = nArg==2 ? azArg[1] : "main"; sqlite3_vfs *pVfs; if( p->db ){ sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFS_POINTER, &pVfs); if( pVfs ){ utf8_printf(p->out, "vfs.zName = \"%s\"\n", pVfs->zName); raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion); raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile); raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname); } } }else if( c=='v' && strncmp(azArg[0], "vfslist", n)==0 ){ sqlite3_vfs *pVfs; sqlite3_vfs *pCurrent = 0; if( p->db ){ sqlite3_file_control(p->db, "main", SQLITE_FCNTL_VFS_POINTER, &pCurrent); } for(pVfs=sqlite3_vfs_find(0); pVfs; pVfs=pVfs->pNext){ utf8_printf(p->out, "vfs.zName = \"%s\"%s\n", pVfs->zName, pVfs==pCurrent ? " <--- CURRENT" : ""); raw_printf(p->out, "vfs.iVersion = %d\n", pVfs->iVersion); raw_printf(p->out, "vfs.szOsFile = %d\n", pVfs->szOsFile); raw_printf(p->out, "vfs.mxPathname = %d\n", pVfs->mxPathname); if( pVfs->pNext ){ raw_printf(p->out, "-----------------------------------\n"); } } }else if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){ const char *zDbName = nArg==2 ? azArg[1] : "main"; char *zVfsName = 0; if( p->db ){ sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName); if( zVfsName ){ utf8_printf(p->out, "%s\n", zVfsName); sqlite3_free(zVfsName); } } }else #if defined(SQLITE_DEBUG) && defined(SQLITE_ENABLE_WHERETRACE) if( c=='w' && strncmp(azArg[0], "wheretrace", n)==0 ){ sqlite3WhereTrace = nArg>=2 ? booleanValue(azArg[1]) : 0xff; }else #endif if( c=='w' && strncmp(azArg[0], "width", n)==0 ){ int j; assert( nArg<=ArraySize(azArg) ); for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){ p->colWidth[j-1] = (int)integerValue(azArg[j]); } }else { utf8_printf(stderr, "Error: unknown command or invalid arguments: " " \"%s\". Enter \".help\" for help\n", azArg[0]); rc = 1; } meta_command_exit: if( p->outCount ){ p->outCount--; if( p->outCount==0 ) output_reset(p); } return rc; } /* ** Return TRUE if a semicolon occurs anywhere in the first N characters ** of string z[]. */ static int line_contains_semicolon(const char *z, int N){ int i; for(i=0; i<N; i++){ if( z[i]==';' ) return 1; } return 0; } /* ** Test to see if a line consists entirely of whitespace. */ static int _all_whitespace(const char *z){ for(; *z; z++){ if( IsSpace(z[0]) ) continue; if( *z=='/' && z[1]=='*' ){ z += 2; while( *z && (*z!='*' || z[1]!='/') ){ z++; } if( *z==0 ) return 0; z++; continue; } if( *z=='-' && z[1]=='-' ){ z += 2; while( *z && *z!='\n' ){ z++; } if( *z==0 ) return 1; continue; } return 0; } return 1; } /* ** Return TRUE if the line typed in is an SQL command terminator other ** than a semi-colon. The SQL Server style "go" command is understood ** as is the Oracle "/". */ static int line_is_command_terminator(const char *zLine){ while( IsSpace(zLine[0]) ){ zLine++; }; if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){ return 1; /* Oracle */ } if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o' && _all_whitespace(&zLine[2]) ){ return 1; /* SQL Server */ } return 0; } /* ** Return true if zSql is a complete SQL statement. Return false if it ** ends in the middle of a string literal or C-style comment. */ static int line_is_complete(char *zSql, int nSql){ int rc; if( zSql==0 ) return 1; zSql[nSql] = ';'; zSql[nSql+1] = 0; rc = sqlite3_complete(zSql); zSql[nSql] = 0; return rc; } /* ** Read input from *in and process it. If *in==0 then input ** is interactive - the user is typing it it. Otherwise, input ** is coming from a file or device. A prompt is issued and history ** is saved only if input is interactive. An interrupt signal will ** cause this routine to exit immediately, unless input is interactive. ** ** Return the number of errors. */ static int process_input(ShellState *p, FILE *in){ char *zLine = 0; /* A single input line */ char *zSql = 0; /* Accumulated SQL text */ int nLine; /* Length of current line */ int nSql = 0; /* Bytes of zSql[] used */ int nAlloc = 0; /* Allocated zSql[] space */ int nSqlPrior = 0; /* Bytes of zSql[] used by prior line */ char *zErrMsg; /* Error message returned */ int rc; /* Error code */ int errCnt = 0; /* Number of errors seen */ int lineno = 0; /* Current line number */ int startline = 0; /* Line number for start of current input */ while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){ fflush(p->out); zLine = one_input_line(in, zLine, nSql>0); if( zLine==0 ){ /* End of input */ if( in==0 && stdin_is_interactive ) printf("\n"); break; } if( seenInterrupt ){ if( in!=0 ) break; seenInterrupt = 0; } lineno++; if( nSql==0 && _all_whitespace(zLine) ){ if( p->echoOn ) printf("%s\n", zLine); continue; } if( zLine && zLine[0]=='.' && nSql==0 ){ if( p->echoOn ) printf("%s\n", zLine); rc = do_meta_command(zLine, p); if( rc==2 ){ /* exit requested */ break; }else if( rc ){ errCnt++; } continue; } if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){ memcpy(zLine,";",2); } nLine = strlen30(zLine); if( nSql+nLine+2>=nAlloc ){ nAlloc = nSql+nLine+100; zSql = realloc(zSql, nAlloc); if( zSql==0 ){ raw_printf(stderr, "Error: out of memory\n"); exit(1); } } nSqlPrior = nSql; if( nSql==0 ){ int i; for(i=0; zLine[i] && IsSpace(zLine[i]); i++){} assert( nAlloc>0 && zSql!=0 ); memcpy(zSql, zLine+i, nLine+1-i); startline = lineno; nSql = nLine-i; }else{ zSql[nSql++] = '\n'; memcpy(zSql+nSql, zLine, nLine+1); nSql += nLine; } if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior) && sqlite3_complete(zSql) ){ p->cnt = 0; open_db(p, 0); if( p->backslashOn ) resolve_backslashes(zSql); BEGIN_TIMER; rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg); END_TIMER; if( rc || zErrMsg ){ char zPrefix[100]; if( in!=0 || !stdin_is_interactive ){ sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error: near line %d:", startline); }else{ sqlite3_snprintf(sizeof(zPrefix), zPrefix, "Error:"); } if( zErrMsg!=0 ){ utf8_printf(stderr, "%s %s\n", zPrefix, zErrMsg); sqlite3_free(zErrMsg); zErrMsg = 0; }else{ utf8_printf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db)); } errCnt++; }else if( p->countChanges ){ raw_printf(p->out, "changes: %3d total_changes: %d\n", sqlite3_changes(p->db), sqlite3_total_changes(p->db)); } nSql = 0; if( p->outCount ){ output_reset(p); p->outCount = 0; } }else if( nSql && _all_whitespace(zSql) ){ if( p->echoOn ) printf("%s\n", zSql); nSql = 0; } } if( nSql ){ if( !_all_whitespace(zSql) ){ utf8_printf(stderr, "Error: incomplete SQL: %s\n", zSql); errCnt++; } } free(zSql); free(zLine); return errCnt>0; } /* ** Return a pathname which is the user's home directory. A ** 0 return indicates an error of some kind. */ static char *find_home_dir(void){ static char *home_dir = NULL; if( home_dir ) return home_dir; #if !defined(_WIN32) && !defined(WIN32) && !defined(_WIN32_WCE) \ && !defined(__RTP__) && !defined(_WRS_KERNEL) { struct passwd *pwent; uid_t uid = getuid(); if( (pwent=getpwuid(uid)) != NULL) { home_dir = pwent->pw_dir; } } #endif #if defined(_WIN32_WCE) /* Windows CE (arm-wince-mingw32ce-gcc) does not provide getenv() */ home_dir = "/"; #else #if defined(_WIN32) || defined(WIN32) if (!home_dir) { home_dir = getenv("USERPROFILE"); } #endif if (!home_dir) { home_dir = getenv("HOME"); } #if defined(_WIN32) || defined(WIN32) if (!home_dir) { char *zDrive, *zPath; int n; zDrive = getenv("HOMEDRIVE"); zPath = getenv("HOMEPATH"); if( zDrive && zPath ){ n = strlen30(zDrive) + strlen30(zPath) + 1; home_dir = malloc( n ); if( home_dir==0 ) return 0; sqlite3_snprintf(n, home_dir, "%s%s", zDrive, zPath); return home_dir; } home_dir = "c:\\"; } #endif #endif /* !_WIN32_WCE */ if( home_dir ){ int n = strlen30(home_dir) + 1; char *z = malloc( n ); if( z ) memcpy(z, home_dir, n); home_dir = z; } return home_dir; } /* ** Read input from the file given by sqliterc_override. Or if that ** parameter is NULL, take input from ~/.sqliterc ** ** Returns the number of errors. */ static void process_sqliterc( ShellState *p, /* Configuration data */ const char *sqliterc_override /* Name of config file. NULL to use default */ ){ char *home_dir = NULL; const char *sqliterc = sqliterc_override; char *zBuf = 0; FILE *in = NULL; if (sqliterc == NULL) { home_dir = find_home_dir(); if( home_dir==0 ){ raw_printf(stderr, "-- warning: cannot find home directory;" " cannot read ~/.sqliterc\n"); return; } sqlite3_initialize(); zBuf = sqlite3_mprintf("%s/.sqliterc",home_dir); sqliterc = zBuf; } in = fopen(sqliterc,"rb"); if( in ){ if( stdin_is_interactive ){ utf8_printf(stderr,"-- Loading resources from %s\n",sqliterc); } process_input(p,in); fclose(in); } sqlite3_free(zBuf); } /* ** Show available command line options */ static const char zOptions[] = " -ascii set output mode to 'ascii'\n" " -bail stop after hitting an error\n" " -batch force batch I/O\n" " -column set output mode to 'column'\n" " -cmd COMMAND run \"COMMAND\" before reading stdin\n" " -csv set output mode to 'csv'\n" " -echo print commands before execution\n" " -init FILENAME read/process named file\n" " -[no]header turn headers on or off\n" #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) " -heap SIZE Size of heap for memsys3 or memsys5\n" #endif " -help show this message\n" " -html set output mode to HTML\n" " -interactive force interactive I/O\n" " -line set output mode to 'line'\n" " -list set output mode to 'list'\n" " -lookaside SIZE N use N entries of SZ bytes for lookaside memory\n" " -mmap N default mmap size set to N\n" #ifdef SQLITE_ENABLE_MULTIPLEX " -multiplex enable the multiplexor VFS\n" #endif " -newline SEP set output row separator. Default: '\\n'\n" " -nullvalue TEXT set text string for NULL values. Default ''\n" " -pagecache SIZE N use N slots of SZ bytes each for page cache memory\n" " -scratch SIZE N use N slots of SZ bytes each for scratch memory\n" " -separator SEP set output column separator. Default: '|'\n" " -stats print memory stats before each finalize\n" " -version show SQLite version\n" " -vfs NAME use NAME as the default VFS\n" #ifdef SQLITE_ENABLE_VFSTRACE " -vfstrace enable tracing of all VFS calls\n" #endif ; static void usage(int showDetail){ utf8_printf(stderr, "Usage: %s [OPTIONS] FILENAME [SQL]\n" "FILENAME is the name of an SQLite database. A new database is created\n" "if the file does not previously exist.\n", Argv0); if( showDetail ){ utf8_printf(stderr, "OPTIONS include:\n%s", zOptions); }else{ raw_printf(stderr, "Use the -help option for additional information\n"); } exit(1); } /* ** Initialize the state information in data */ static void main_init(ShellState *data) { memset(data, 0, sizeof(*data)); data->normalMode = data->cMode = data->mode = MODE_List; data->autoExplain = 1; memcpy(data->colSeparator,SEP_Column, 2); memcpy(data->rowSeparator,SEP_Row, 2); data->showHeader = 0; data->shellFlgs = SHFLG_Lookaside; sqlite3_config(SQLITE_CONFIG_URI, 1); sqlite3_config(SQLITE_CONFIG_LOG, shellLog, data); sqlite3_config(SQLITE_CONFIG_MULTITHREAD); sqlite3_snprintf(sizeof(mainPrompt), mainPrompt,"sqlite> "); sqlite3_snprintf(sizeof(continuePrompt), continuePrompt," ...> "); } /* ** Output text to the console in a font that attracts extra attention. */ #ifdef _WIN32 static void printBold(const char *zText){ HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO defaultScreenInfo; GetConsoleScreenBufferInfo(out, &defaultScreenInfo); SetConsoleTextAttribute(out, FOREGROUND_RED|FOREGROUND_INTENSITY ); printf("%s", zText); SetConsoleTextAttribute(out, defaultScreenInfo.wAttributes); } #else static void printBold(const char *zText){ printf("\033[1m%s\033[0m", zText); } #endif /* ** Get the argument to an --option. Throw an error and die if no argument ** is available. */ static char *cmdline_option_value(int argc, char **argv, int i){ if( i==argc ){ utf8_printf(stderr, "%s: Error: missing argument to %s\n", argv[0], argv[argc-1]); exit(1); } return argv[i]; } #ifndef SQLITE_SHELL_IS_UTF8 # if (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER) # define SQLITE_SHELL_IS_UTF8 (0) # else # define SQLITE_SHELL_IS_UTF8 (1) # endif #endif #if SQLITE_SHELL_IS_UTF8 int SQLITE_CDECL main(int argc, char **argv){ #else int SQLITE_CDECL wmain(int argc, wchar_t **wargv){ char **argv; #endif char *zErrMsg = 0; ShellState data; const char *zInitFile = 0; int i; int rc = 0; int warnInmemoryDb = 0; int readStdin = 1; int nCmd = 0; char **azCmd = 0; setBinaryMode(stdin, 0); setvbuf(stderr, 0, _IONBF, 0); /* Make sure stderr is unbuffered */ stdin_is_interactive = isatty(0); stdout_is_console = isatty(1); #if USE_SYSTEM_SQLITE+0!=1 if( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)!=0 ){ utf8_printf(stderr, "SQLite header and source version mismatch\n%s\n%s\n", sqlite3_sourceid(), SQLITE_SOURCE_ID); exit(1); } #endif main_init(&data); #if !SQLITE_SHELL_IS_UTF8 sqlite3_initialize(); argv = sqlite3_malloc64(sizeof(argv[0])*argc); if( argv==0 ){ raw_printf(stderr, "out of memory\n"); exit(1); } for(i=0; i<argc; i++){ argv[i] = sqlite3_win32_unicode_to_utf8(wargv[i]); if( argv[i]==0 ){ raw_printf(stderr, "out of memory\n"); exit(1); } } #endif assert( argc>=1 && argv && argv[0] ); Argv0 = argv[0]; /* Make sure we have a valid signal handler early, before anything ** else is done. */ #ifdef SIGINT signal(SIGINT, interrupt_handler); #endif #ifdef SQLITE_SHELL_DBNAME_PROC { /* If the SQLITE_SHELL_DBNAME_PROC macro is defined, then it is the name ** of a C-function that will provide the name of the database file. Use ** this compile-time option to embed this shell program in larger ** applications. */ extern void SQLITE_SHELL_DBNAME_PROC(const char**); SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename); warnInmemoryDb = 0; } #endif /* Do an initial pass through the command-line argument to locate ** the name of the database file, the name of the initialization file, ** the size of the alternative malloc heap, ** and the first command to execute. */ for(i=1; i<argc; i++){ char *z; z = argv[i]; if( z[0]!='-' ){ if( data.zDbFilename==0 ){ data.zDbFilename = z; }else{ /* Excesss arguments are interpreted as SQL (or dot-commands) and ** mean that nothing is read from stdin */ readStdin = 0; nCmd++; azCmd = realloc(azCmd, sizeof(azCmd[0])*nCmd); if( azCmd==0 ){ raw_printf(stderr, "out of memory\n"); exit(1); } azCmd[nCmd-1] = z; } } if( z[1]=='-' ) z++; if( strcmp(z,"-separator")==0 || strcmp(z,"-nullvalue")==0 || strcmp(z,"-newline")==0 || strcmp(z,"-cmd")==0 ){ (void)cmdline_option_value(argc, argv, ++i); }else if( strcmp(z,"-init")==0 ){ zInitFile = cmdline_option_value(argc, argv, ++i); }else if( strcmp(z,"-batch")==0 ){ /* Need to check for batch mode here to so we can avoid printing ** informational messages (like from process_sqliterc) before ** we do the actual processing of arguments later in a second pass. */ stdin_is_interactive = 0; }else if( strcmp(z,"-heap")==0 ){ #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) const char *zSize; sqlite3_int64 szHeap; zSize = cmdline_option_value(argc, argv, ++i); szHeap = integerValue(zSize); if( szHeap>0x7fff0000 ) szHeap = 0x7fff0000; sqlite3_config(SQLITE_CONFIG_HEAP, malloc((int)szHeap), (int)szHeap, 64); #else (void)cmdline_option_value(argc, argv, ++i); #endif }else if( strcmp(z,"-scratch")==0 ){ int n, sz; sz = (int)integerValue(cmdline_option_value(argc,argv,++i)); if( sz>400000 ) sz = 400000; if( sz<2500 ) sz = 2500; n = (int)integerValue(cmdline_option_value(argc,argv,++i)); if( n>10 ) n = 10; if( n<1 ) n = 1; sqlite3_config(SQLITE_CONFIG_SCRATCH, malloc(n*sz+1), sz, n); data.shellFlgs |= SHFLG_Scratch; }else if( strcmp(z,"-pagecache")==0 ){ int n, sz; sz = (int)integerValue(cmdline_option_value(argc,argv,++i)); if( sz>70000 ) sz = 70000; if( sz<0 ) sz = 0; n = (int)integerValue(cmdline_option_value(argc,argv,++i)); sqlite3_config(SQLITE_CONFIG_PAGECACHE, (n>0 && sz>0) ? malloc(n*sz) : 0, sz, n); data.shellFlgs |= SHFLG_Pagecache; }else if( strcmp(z,"-lookaside")==0 ){ int n, sz; sz = (int)integerValue(cmdline_option_value(argc,argv,++i)); if( sz<0 ) sz = 0; n = (int)integerValue(cmdline_option_value(argc,argv,++i)); if( n<0 ) n = 0; sqlite3_config(SQLITE_CONFIG_LOOKASIDE, sz, n); if( sz*n==0 ) data.shellFlgs &= ~SHFLG_Lookaside; #ifdef SQLITE_ENABLE_VFSTRACE }else if( strcmp(z,"-vfstrace")==0 ){ extern int vfstrace_register( const char *zTraceName, const char *zOldVfsName, int (*xOut)(const char*,void*), void *pOutArg, int makeDefault ); vfstrace_register("trace",0,(int(*)(const char*,void*))fputs,stderr,1); #endif #ifdef SQLITE_ENABLE_MULTIPLEX }else if( strcmp(z,"-multiplex")==0 ){ extern int sqlite3_multiple_initialize(const char*,int); sqlite3_multiplex_initialize(0, 1); #endif }else if( strcmp(z,"-mmap")==0 ){ sqlite3_int64 sz = integerValue(cmdline_option_value(argc,argv,++i)); sqlite3_config(SQLITE_CONFIG_MMAP_SIZE, sz, sz); }else if( strcmp(z,"-vfs")==0 ){ sqlite3_vfs *pVfs = sqlite3_vfs_find(cmdline_option_value(argc,argv,++i)); if( pVfs ){ sqlite3_vfs_register(pVfs, 1); }else{ utf8_printf(stderr, "no such VFS: \"%s\"\n", argv[i]); exit(1); } } } if( data.zDbFilename==0 ){ #ifndef SQLITE_OMIT_MEMORYDB data.zDbFilename = ":memory:"; warnInmemoryDb = argc==1; #else utf8_printf(stderr,"%s: Error: no database filename specified\n", Argv0); return 1; #endif } data.out = stdout; /* Go ahead and open the database file if it already exists. If the ** file does not exist, delay opening it. This prevents empty database ** files from being created if a user mistypes the database name argument ** to the sqlite command-line tool. */ if( access(data.zDbFilename, 0)==0 ){ open_db(&data, 0); } /* Process the initialization file if there is one. If no -init option ** is given on the command line, look for a file named ~/.sqliterc and ** try to process it. */ process_sqliterc(&data,zInitFile); /* Make a second pass through the command-line argument and set ** options. This second pass is delayed until after the initialization ** file is processed so that the command-line arguments will override ** settings in the initialization file. */ for(i=1; i<argc; i++){ char *z = argv[i]; if( z[0]!='-' ) continue; if( z[1]=='-' ){ z++; } if( strcmp(z,"-init")==0 ){ i++; }else if( strcmp(z,"-html")==0 ){ data.mode = MODE_Html; }else if( strcmp(z,"-list")==0 ){ data.mode = MODE_List; }else if( strcmp(z,"-line")==0 ){ data.mode = MODE_Line; }else if( strcmp(z,"-column")==0 ){ data.mode = MODE_Column; }else if( strcmp(z,"-csv")==0 ){ data.mode = MODE_Csv; memcpy(data.colSeparator,",",2); }else if( strcmp(z,"-ascii")==0 ){ data.mode = MODE_Ascii; sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, SEP_Unit); sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, SEP_Record); }else if( strcmp(z,"-separator")==0 ){ sqlite3_snprintf(sizeof(data.colSeparator), data.colSeparator, "%s",cmdline_option_value(argc,argv,++i)); }else if( strcmp(z,"-newline")==0 ){ sqlite3_snprintf(sizeof(data.rowSeparator), data.rowSeparator, "%s",cmdline_option_value(argc,argv,++i)); }else if( strcmp(z,"-nullvalue")==0 ){ sqlite3_snprintf(sizeof(data.nullValue), data.nullValue, "%s",cmdline_option_value(argc,argv,++i)); }else if( strcmp(z,"-header")==0 ){ data.showHeader = 1; }else if( strcmp(z,"-noheader")==0 ){ data.showHeader = 0; }else if( strcmp(z,"-echo")==0 ){ data.echoOn = 1; }else if( strcmp(z,"-eqp")==0 ){ data.autoEQP = 1; }else if( strcmp(z,"-eqpfull")==0 ){ data.autoEQP = 2; }else if( strcmp(z,"-stats")==0 ){ data.statsOn = 1; }else if( strcmp(z,"-scanstats")==0 ){ data.scanstatsOn = 1; }else if( strcmp(z,"-backslash")==0 ){ /* Undocumented command-line option: -backslash ** Causes C-style backslash escapes to be evaluated in SQL statements ** prior to sending the SQL into SQLite. Useful for injecting ** crazy bytes in the middle of SQL statements for testing and debugging. */ data.backslashOn = 1; }else if( strcmp(z,"-bail")==0 ){ bail_on_error = 1; }else if( strcmp(z,"-version")==0 ){ printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid()); return 0; }else if( strcmp(z,"-interactive")==0 ){ stdin_is_interactive = 1; }else if( strcmp(z,"-batch")==0 ){ stdin_is_interactive = 0; }else if( strcmp(z,"-heap")==0 ){ i++; }else if( strcmp(z,"-scratch")==0 ){ i+=2; }else if( strcmp(z,"-pagecache")==0 ){ i+=2; }else if( strcmp(z,"-lookaside")==0 ){ i+=2; }else if( strcmp(z,"-mmap")==0 ){ i++; }else if( strcmp(z,"-vfs")==0 ){ i++; #ifdef SQLITE_ENABLE_VFSTRACE }else if( strcmp(z,"-vfstrace")==0 ){ i++; #endif #ifdef SQLITE_ENABLE_MULTIPLEX }else if( strcmp(z,"-multiplex")==0 ){ i++; #endif }else if( strcmp(z,"-help")==0 ){ usage(1); }else if( strcmp(z,"-cmd")==0 ){ /* Run commands that follow -cmd first and separately from commands ** that simply appear on the command-line. This seems goofy. It would ** be better if all commands ran in the order that they appear. But ** we retain the goofy behavior for historical compatibility. */ if( i==argc-1 ) break; z = cmdline_option_value(argc,argv,++i); if( z[0]=='.' ){ rc = do_meta_command(z, &data); if( rc && bail_on_error ) return rc==2 ? 0 : rc; }else{ open_db(&data, 0); rc = shell_exec(data.db, z, shell_callback, &data, &zErrMsg); if( zErrMsg!=0 ){ utf8_printf(stderr,"Error: %s\n", zErrMsg); if( bail_on_error ) return rc!=0 ? rc : 1; }else if( rc!=0 ){ utf8_printf(stderr,"Error: unable to process SQL \"%s\"\n", z); if( bail_on_error ) return rc; } } }else{ utf8_printf(stderr,"%s: Error: unknown option: %s\n", Argv0, z); raw_printf(stderr,"Use -help for a list of options.\n"); return 1; } data.cMode = data.mode; } if( !readStdin ){ /* Run all arguments that do not begin with '-' as if they were separate ** command-line inputs, except for the argToSkip argument which contains ** the database filename. */ for(i=0; i<nCmd; i++){ if( azCmd[i][0]=='.' ){ rc = do_meta_command(azCmd[i], &data); if( rc ) return rc==2 ? 0 : rc; }else{ open_db(&data, 0); rc = shell_exec(data.db, azCmd[i], shell_callback, &data, &zErrMsg); if( zErrMsg!=0 ){ utf8_printf(stderr,"Error: %s\n", zErrMsg); return rc!=0 ? rc : 1; }else if( rc!=0 ){ utf8_printf(stderr,"Error: unable to process SQL: %s\n", azCmd[i]); return rc; } } } free(azCmd); }else{ /* Run commands received from standard input */ if( stdin_is_interactive ){ char *zHome; char *zHistory = 0; int nHistory; printf( "SQLite version %s %.19s\n" /*extra-version-info*/ "Enter \".help\" for usage hints.\n", sqlite3_libversion(), sqlite3_sourceid() ); if( warnInmemoryDb ){ printf("Connected to a "); printBold("transient in-memory database"); printf(".\nUse \".open FILENAME\" to reopen on a " "persistent database.\n"); } zHome = find_home_dir(); if( zHome ){ nHistory = strlen30(zHome) + 20; if( (zHistory = malloc(nHistory))!=0 ){ sqlite3_snprintf(nHistory, zHistory,"%s/.sqlite_history", zHome); } } if( zHistory ){ shell_read_history(zHistory); } rc = process_input(&data, 0); if( zHistory ){ shell_stifle_history(100); shell_write_history(zHistory); free(zHistory); } }else{ rc = process_input(&data, stdin); } } set_table_name(&data, 0); if( data.db ){ session_close_all(&data); sqlite3_close(data.db); } sqlite3_free(data.zFreeOnClose); #if !SQLITE_SHELL_IS_UTF8 for(i=0; i<argc; i++) sqlite3_free(argv[i]); sqlite3_free(argv); #endif return rc; }
the_stack_data/691234.c
/* Copyright (C) 1989, 1997 Aladdin Enterprises. All rights reserved. */ /* hacked up by uo to get around automake-1.3-problem */ /*$Id: ansi2knr.c,v 1.5 1998/12/27 16:09:19 uwe Exp $*/ /* Convert ANSI C function definitions to K&R ("traditional C") syntax */ /* ansi2knr is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. No author or distributor accepts responsibility to anyone for the consequences of using it or for whether it serves any particular purpose or works at all, unless he says so in writing. Refer to the GNU General Public License (the "GPL") for full details. Everyone is granted permission to copy, modify and redistribute ansi2knr, but only under the conditions described in the GPL. A copy of this license is supposed to have been given to you along with ansi2knr so you can know your rights and responsibilities. It should be in a file named COPYLEFT, or, if there is no file named COPYLEFT, a file named COPYING. Among other things, the copyright notice and this notice must be preserved on all copies. We explicitly state here what we believe is already implied by the GPL: if the ansi2knr program is distributed as a separate set of sources and a separate executable file which are aggregated on a storage medium together with another program, this in itself does not bring the other program under the GPL, nor does the mere fact that such a program or the procedures for constructing it invoke the ansi2knr executable bring any other part of the program under the GPL. */ /* * ----- not valid at the moment -- uwe ------ * Usage: ansi2knr [--filename FILENAME] [INPUT_FILE [OUTPUT_FILE]] * --filename provides the file name for the #line directive in the output, * overriding input_file (if present). * If no input_file is supplied, input is read from stdin. * If no output_file is supplied, output goes to stdout. * There are no error messages. * * ansi2knr recognizes function definitions by seeing a non-keyword * identifier at the left margin, followed by a left parenthesis, * with a right parenthesis as the last character on the line, * and with a left brace as the first token on the following line * (ignoring possible intervening comments). * It will recognize a multi-line header provided that no intervening * line ends with a left or right brace or a semicolon. * These algorithms ignore whitespace and comments, except that * the function name must be the first thing on the line. * The following constructs will confuse it: * - Any other construct that starts at the left margin and * follows the above syntax (such as a macro or function call). * - Some macros that tinker with the syntax of the function header. */ /* * The original and principal author of ansi2knr is L. Peter Deutsch * <[email protected]>. Other authors are noted in the change history * that follows (in reverse chronological order): lpd 97-12-08 made input_file optional; only closes input and/or output file if not stdin or stdout respectively; prints usage message on stderr rather than stdout; adds --filename switch (changes suggested by <[email protected]>) lpd 96-01-21 added code to cope with not HAVE_CONFIG_H and with compilers that don't understand void, as suggested by Tom Lane lpd 96-01-15 changed to require that the first non-comment token on the line following a function header be a left brace, to reduce sensitivity to macros, as suggested by Tom Lane <[email protected]> lpd 95-06-22 removed #ifndefs whose sole purpose was to define undefined preprocessor symbols as 0; changed all #ifdefs for configuration symbols to #ifs lpd 95-04-05 changed copyright notice to make it clear that including ansi2knr in a program does not bring the entire program under the GPL lpd 94-12-18 added conditionals for systems where ctype macros don't handle 8-bit characters properly, suggested by Francois Pinard <[email protected]>; removed --varargs switch (this is now the default) lpd 94-10-10 removed CONFIG_BROKETS conditional lpd 94-07-16 added some conditionals to help GNU `configure', suggested by Francois Pinard <[email protected]>; properly erase prototype args in function parameters, contributed by Jim Avera <[email protected]>; correct error in writeblanks (it shouldn't erase EOLs) lpd 89-xx-xx original version */ /* Most of the conditionals here are to make ansi2knr work with */ /* or without the GNU configure machinery. */ #if HAVE_CONFIG_H # include <config.h> #endif #include <stdio.h> #include <ctype.h> #if HAVE_CONFIG_H /* For properly autoconfiguring ansi2knr, use AC_CONFIG_HEADER(config.h). This will define HAVE_CONFIG_H and so, activate the following lines. */ # if STDC_HEADERS || HAVE_STRING_H # include <string.h> # else # include <strings.h> # endif #else /* not HAVE_CONFIG_H */ /* Otherwise do it the hard way */ # ifdef BSD # include <strings.h> # else # ifdef VMS extern int strlen(), strncmp(); # else # include <string.h> # endif # endif #endif /* not HAVE_CONFIG_H */ #if STDC_HEADERS # include <stdlib.h> #else /* malloc and free should be declared in stdlib.h, but if you've got a K&R compiler, they probably aren't. */ # ifdef MSDOS # include <malloc.h> # else # ifdef VMS extern char *malloc(); extern void free(); # else extern char *malloc(); extern int free(); # endif # endif #endif /* * The ctype macros don't always handle 8-bit characters correctly. * Compensate for this here. */ #ifdef isascii # undef HAVE_ISASCII /* just in case */ # define HAVE_ISASCII 1 #else #endif #if STDC_HEADERS || !HAVE_ISASCII # define is_ascii(c) 1 #else # define is_ascii(c) isascii(c) #endif #define is_space(c) (is_ascii(c) && isspace(c)) #define is_alpha(c) (is_ascii(c) && isalpha(c)) #define is_alnum(c) (is_ascii(c) && isalnum(c)) /* Scanning macros */ #define isidchar(ch) (is_alnum(ch) || (ch) == '_') #define isidfirstchar(ch) (is_alpha(ch) || (ch) == '_') /* Forward references */ char *skipspace(); int writeblanks(); int test1(); int convert1(); /* The main program */ int main(argc, argv) int argc; char *argv[]; { FILE *in = stdin; FILE *out = stdout; char *filename = 0; #define bufsize 5000 /* arbitrary size */ char *buf; char *line; char *more; char *usage = "Usage: ansi2knr [--filename FILENAME] [INPUT_FILE [OUTPUT_FILE]]\n"; /* * In previous versions, ansi2knr recognized a --varargs switch. * If this switch was supplied, ansi2knr would attempt to convert * a ... argument to va_alist and va_dcl; if this switch was not * supplied, ansi2knr would simply drop any such arguments. * Now, ansi2knr always does this conversion, and we only * check for this switch for backward compatibility. */ int convert_varargs = 0; while ( argc > 1 && argv[1][0] == '-' ) { if ( !strcmp(argv[1], "--varargs") ) { convert_varargs = 1; argc--; argv++; continue; } if ( !strcmp(argv[1], "--filename") && argc > 2 ) { filename = argv[2]; argc -= 2; argv += 2; continue; } fprintf(stderr, "Unrecognized switch: %s\n", argv[1]); fprintf(stderr, usage); exit(1); } switch ( argc ) { default: fprintf(stderr, usage); exit(0); case 2: out = fopen(argv[1], "w"); if ( out == NULL ) { fprintf(stderr, "Cannot open output file %s\n", argv[2]); exit(1); } /* falls through */ case 1: break; } if ( filename ) fprintf(out, "#line 1 \"%s\"\n", filename); buf = malloc(bufsize); line = buf; while ( fgets(line, (unsigned)(buf + bufsize - line), in) != NULL ) { test: line += strlen(line); switch ( test1(buf) ) { case 2: /* a function header */ convert1(buf, out, 1, convert_varargs); break; case 1: /* a function */ /* Check for a { at the start of the next line. */ more = ++line; f: if ( line >= buf + (bufsize - 1) ) /* overflow check */ goto wl; if ( fgets(line, (unsigned)(buf + bufsize - line), in) == NULL ) goto wl; switch ( *skipspace(more, 1) ) { case '{': /* Definitely a function header. */ convert1(buf, out, 0, convert_varargs); fputs(more, out); break; case 0: /* The next line was blank or a comment: */ /* keep scanning for a non-comment. */ line += strlen(line); goto f; default: /* buf isn't a function header, but */ /* more might be. */ fputs(buf, out); strcpy(buf, more); line = buf; goto test; } break; case -1: /* maybe the start of a function */ if ( line != buf + (bufsize - 1) ) /* overflow check */ continue; /* falls through */ default: /* not a function */ wl: fputs(buf, out); break; } line = buf; } if ( line != buf ) fputs(buf, out); free(buf); if ( out != stdout ) fclose(out); if ( in != stdin ) fclose(in); return 0; } /* Skip over space and comments, in either direction. */ char * skipspace(p, dir) register char *p; register int dir; /* 1 for forward, -1 for backward */ { for ( ; ; ) { while ( is_space(*p) ) p += dir; if ( !(*p == '/' && p[dir] == '*') ) break; p += dir; p += dir; while ( !(*p == '*' && p[dir] == '/') ) { if ( *p == 0 ) return p; /* multi-line comment?? */ p += dir; } p += dir; p += dir; } return p; } /* * Write blanks over part of a string. * Don't overwrite end-of-line characters. */ int writeblanks(start, end) char *start; char *end; { char *p; for ( p = start; p < end; p++ ) if ( *p != '\r' && *p != '\n' ) *p = ' '; return 0; } /* * Test whether the string in buf is a function definition. * The string may contain and/or end with a newline. * Return as follows: * 0 - definitely not a function definition; * 1 - definitely a function definition; * 2 - definitely a function prototype (NOT USED); * -1 - may be the beginning of a function definition, * append another line and look again. * The reason we don't attempt to convert function prototypes is that * Ghostscript's declaration-generating macros look too much like * prototypes, and confuse the algorithms. */ int test1(buf) char *buf; { register char *p = buf; char *bend; char *endfn; int contin; if ( !isidfirstchar(*p) ) return 0; /* no name at left margin */ bend = skipspace(buf + strlen(buf) - 1, -1); switch ( *bend ) { case ';': contin = 0 /*2*/; break; case ')': contin = 1; break; case '{': return 0; /* not a function */ case '}': return 0; /* not a function */ default: contin = -1; } while ( isidchar(*p) ) p++; endfn = p; p = skipspace(p, 1); if ( *p++ != '(' ) return 0; /* not a function */ p = skipspace(p, 1); if ( *p == ')' ) return 0; /* no parameters */ /* Check that the apparent function name isn't a keyword. */ /* We only need to check for keywords that could be followed */ /* by a left parenthesis (which, unfortunately, is most of them). */ { static char *words[] = { "asm", "auto", "case", "char", "const", "double", "extern", "float", "for", "if", "int", "long", "register", "return", "short", "signed", "sizeof", "static", "switch", "typedef", "unsigned", "void", "volatile", "while", 0 }; char **key = words; char *kp; int len = endfn - buf; while ( (kp = *key) != 0 ) { if ( strlen(kp) == len && !strncmp(kp, buf, len) ) return 0; /* name is a keyword */ key++; } } return contin; } /* Convert a recognized function definition or header to K&R syntax. */ int convert1(buf, out, header, convert_varargs) char *buf; FILE *out; int header; /* Boolean */ int convert_varargs; /* Boolean */ { char *endfn; register char *p; /* * The breaks table contains pointers to the beginning and end * of each argument. */ char **breaks; unsigned num_breaks = 2; /* for testing */ char **btop; char **bp; char **ap; char *vararg = 0; /* Pre-ANSI implementations don't agree on whether strchr */ /* is called strchr or index, so we open-code it here. */ for ( endfn = buf; *(endfn++) != '('; ) ; top: p = endfn; breaks = (char **)malloc(sizeof(char *) * num_breaks * 2); if ( breaks == 0 ) { /* Couldn't allocate break table, give up */ fprintf(stderr, "Unable to allocate break table!\n"); fputs(buf, out); return -1; } btop = breaks + num_breaks * 2 - 2; bp = breaks; /* Parse the argument list */ do { int level = 0; char *lp = NULL; char *rp; char *end = NULL; if ( bp >= btop ) { /* Filled up break table. */ /* Allocate a bigger one and start over. */ free((char *)breaks); num_breaks <<= 1; goto top; } *bp++ = p; /* Find the end of the argument */ for ( ; end == NULL; p++ ) { switch(*p) { case ',': if ( !level ) end = p; break; case '(': if ( !level ) lp = p; level++; break; case ')': if ( --level < 0 ) end = p; else rp = p; break; case '/': p = skipspace(p, 1) - 1; break; default: ; } } /* Erase any embedded prototype parameters. */ if ( lp ) writeblanks(lp + 1, rp); p--; /* back up over terminator */ /* Find the name being declared. */ /* This is complicated because of procedure and */ /* array modifiers. */ for ( ; ; ) { p = skipspace(p - 1, -1); switch ( *p ) { case ']': /* skip array dimension(s) */ case ')': /* skip procedure args OR name */ { int level = 1; while ( level ) switch ( *--p ) { case ']': case ')': level++; break; case '[': case '(': level--; break; case '/': p = skipspace(p, -1) + 1; break; default: ; } } if ( *p == '(' && *skipspace(p + 1, 1) == '*' ) { /* We found the name being declared */ while ( !isidfirstchar(*p) ) p = skipspace(p, 1) + 1; goto found; } break; default: goto found; } } found: if ( *p == '.' && p[-1] == '.' && p[-2] == '.' ) { if ( convert_varargs ) { *bp++ = "va_alist"; vararg = p-2; } else { p++; if ( bp == breaks + 1 ) /* sole argument */ writeblanks(breaks[0], p); else writeblanks(bp[-1] - 1, p); bp--; } } else { while ( isidchar(*p) ) p--; *bp++ = p+1; } p = end; } while ( *p++ == ',' ); *bp = p; /* Make a special check for 'void' arglist */ if ( bp == breaks+2 ) { p = skipspace(breaks[0], 1); if ( !strncmp(p, "void", 4) ) { p = skipspace(p+4, 1); if ( p == breaks[2] - 1 ) { bp = breaks; /* yup, pretend arglist is empty */ writeblanks(breaks[0], p + 1); } } } /* Put out the function name and left parenthesis. */ p = buf; while ( p != endfn ) putc(*p, out), p++; /* Put out the declaration. */ if ( header ) { fputs(");", out); for ( p = breaks[0]; *p; p++ ) if ( *p == '\r' || *p == '\n' ) putc(*p, out); } else { for ( ap = breaks+1; ap < bp; ap += 2 ) { p = *ap; while ( isidchar(*p) ) putc(*p, out), p++; if ( ap < bp - 1 ) fputs(", ", out); } fputs(") ", out); /* Put out the argument declarations */ for ( ap = breaks+2; ap <= bp; ap += 2 ) (*ap)[-1] = ';'; if ( vararg != 0 ) { *vararg = 0; fputs(breaks[0], out); /* any prior args */ fputs("va_dcl", out); /* the final arg */ fputs(bp[0], out); } else fputs(breaks[0], out); } free((char *)breaks); return 0; }