file
stringlengths
18
26
data
stringlengths
3
1.04M
the_stack_data/102318.c
#include<stdio.h> void main(){ printf("Pares\n"); int vzs=0; for(int i=1;i<=60;i++){ if(vzs%2==0 && i%2==0){ printf("%d\n",i); vzs++; } } }
the_stack_data/90762140.c
/* * This file is part of the coreboot project. * * Copyright (C) 2013 Google, Inc. * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ void udelay(unsigned int n); void udelay(unsigned int n) { /* TODO provide delay here. */ } int init_timer(void); int init_timer(void) { return 0; }
the_stack_data/231394280.c
/* __ __| | | /_) | ___| | | | __ \ _ \ ' / | | / | _ \ __ \ | _` | __ \ __| | | | | __/ . \ | < | | __/ | | | ( | | |\__ \ _| _| |_|\___| _|\_\_|_|\_\\____|\___|_| _| _____|\__,_|_.__/ ____/ ----------------------------------------------------------------------------- TKGL_MPCMAPPER LD_PRELOAD library. This "low-level" library allows you to hijack the MPC/Force application to add your own midi mapping to input and output midi messages. ----------------------------------------------------------------------------- Disclaimer. This work is licensed under the Creative Commons Attribution-NonCommercial 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to Creative Commons, PO Box 1866, Mountain View, CA 94042, USA. NON COMMERCIAL - PERSONAL USE ONLY : You may not use the material for pure commercial closed code solution without the licensor permission. You are free to copy and redistribute the material in any medium or format, adapt, transform, and build upon the material. You must give appropriate credit, a link to the github site https://github.com/TheKikGen/USBMidiKliK4x4 , provide a link to the license, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use. You may not apply legal terms or technological measures that legally restrict others from doing anything the license permits. You do not have to comply with the license for elements of the material in the public domain or where your use is permitted by an applicable exception or limitation. No warranties are given. The license may not give you all of the permissions necessary for your intended use. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ #define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <stdint.h> #include <alsa/asoundlib.h> #include <dlfcn.h> #include <libgen.h> #include <regex.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdbool.h> // MPC Controller names (regexp) #define CTRL_FORCE "Akai Pro Force" #define CTRL_MPC_X "MPC X Controller" #define CTRL_MPC_LIVE "MPC Live Controller" #define CTRL_MPC_ALL ".*(MPC.*Controller|Akai Pro Force).*" // Product code file #define PRODUCT_CODE_PATH "/sys/firmware/devicetree/base/inmusic,product-code" // Colors R G B #define COLOR_FIRE 0xFF0000 #define COLOR_ORANGE 0xFF6D17 #define COLOR_TANGERINE 0xFF4400 #define COLOR_APRICOT 0xFF8800 #define COLOR_YELLOW 0xECEC24 #define COLOR_CANARY 0xFFD500 #define COLOR_LEMON 0xE6FF00 #define COLOR_CHARTREUSE 0xA2FF00 #define COLOR_NEON 0x55FF00 #define COLOR_LIME 0x11FF00 #define COLOR_CLOVER 0x00FF33 #define COLOR_SEA 0x00FF80 #define COLOR_MINT 0x00FFC4 #define COLOR_CYAN 0x00F7FF #define COLOR_SKY 0x00AAFF #define COLOR_AZURE 0x0066FF #define COLOR_GREY 0xA2A9AD #define COLOR_MIDNIGHT 0x0022FF #define COLOR_INDIGO 0x5200FF #define COLOR_VIOLET 0x6F00FF #define COLOR_GRAPPE 0xB200FF #define COLOR_FUSHIA 0xFF00FF #define COLOR_MAGENTA 0xFF00BB #define COLOR_CORAL 0xFF0077 // Mute pads mod button value #define FORCE_ASSIGN_A 123 #define FORCE_ASSIGN_B 124 #define FORCE_MUTE 91 #define FORCE_SOLO 92 #define FORCE_REC_ARM 93 #define FORCE_CLIP_STOP 94 #define FORCE_LEFT 0x72 #define FORCE_RIGHT 0X73 #define FORCE_UP 0X70 #define FORCE_DOWN 0x71 // The shift value is hard coded here because it is equivalent whatever the platform is #define SHIFT_KEY_VALUE 49 // Mapping tables index offset #define MPCPADS_TABLE_IDX_OFFSET 0X24 #define FORCEPADS_TABLE_IDX_OFFSET 0X36 // Function prototypes --------------------------------------------------------- // Globals --------------------------------------------------------------------- // Raw midi dump flag (for debugging purpose) uint8_t rawMidiDumpFlag = 0 ; // Before transformation uint8_t rawMidiDumpPostFlag = 0 ; // After our tranformation // Config file name static char *configFileName = NULL; // Buttons and controls Mapping tables // SHIFT values have bit 7 set static int map_ButtonsLeds[256]; static int map_ButtonsLeds_Inv[256]; // Inverted table static int map_Ctrl[256]; static int map_Ctrl_Inv[256]; // Inverted table // To navigate in matrix quadran when MPC spoofing a Force static int MPCPad_OffsetL = 0; static int MPCPad_OffsetC = 0; static int MPCPad_OffsetLLast = 0; // Force Pads Color cache typedef struct { uint8_t r; uint8_t g; uint8_t b; } ForceMPCPadColor_t; static ForceMPCPadColor_t ForcePadColorsCache[256]; // End user virtual port name static char *user_virtual_portname = NULL; // End user virtual port handles static snd_rawmidi_t *rawvirt_user_in = NULL ; static snd_rawmidi_t *rawvirt_user_out = NULL ; // Device info block typedef typedef struct { char * productCode; uint8_t sysexId; char * productString; char * productStringShort; uint8_t qlinkKnobsCount; uint8_t sysexIdReply[7]; } DeviceInfo_t; // Internal MPC product sysex id ( a struct may be better....) enum MPCIds { MPC_X, MPC_LIVE, MPC_FORCE, MPC_ONE, MPC_LIVE_MK2, _END_MPCID }; // Declare in the same order that enums above const static DeviceInfo_t DeviceInfoBloc[] = { { .productCode = "ACV5", .sysexId = 0x3a, .productString = "MPC X", .productStringShort = "X", .qlinkKnobsCount = 16, .sysexIdReply = {0x3A,0x00,0x19,0x00,0x01,0x01,0x01} }, { .productCode = "ACV8", .sysexId = 0x3b, .productString = "MPC Live", .productStringShort = "LIVE", .qlinkKnobsCount = 4, .sysexIdReply = {0x3B,0x00,0x19,0x00,0x01,0x01,0x01} }, { .productCode = "ADA2", .sysexId = 0x40, .productString = "Force", .productStringShort = "FORCE", .qlinkKnobsCount = 8, .sysexIdReply = {0x40,0x00,0x19,0x00,0x00,0x04,0x03} }, { .productCode = "ACVA", .sysexId = 0x46, .productString = "MPC One", .productStringShort = "ONE", .qlinkKnobsCount = 4, .sysexIdReply = {0x46,0x00,0x19,0x00,0x01,0x01,0x01} }, { .productCode = "ACVB", .sysexId = 0x47, .productString = "MPC Live 2", .productStringShort = "LIVE2", .qlinkKnobsCount = 4, .sysexIdReply = {0x47,0x00,0x19,0x00,0x01,0x01,0x01} }, }; // Columns pads //F0 47 7F 40 65 00 04 40 00 00 06 F7 F0 47 7F 40 | .G.@[email protected].@ //[tkgl] 65 00 04 41 00 00 06 F7 // F0 47 7F [3B] 65 00 04 [Pad #] [R] [G] [B] F7 // Sysex patterns. static const uint8_t AkaiSysex[] = {0xF0,0x47, 0x7F}; const uint8_t MPCSysexPadColorFn[] = {0x65,0x00,0x04}; static const uint8_t IdentityReplySysexHeader[] = {0xF0,0x7E,0x00,0x06,0x02,0x47}; // MPC Current pad bank. A-H = 0-7 static int MPC_PadBank = -1 ; // SHIFT Holded mode // Holding shift will activate the shift mode static bool shiftHoldedMode=false; // Qlink knobs shift mode static bool QlinkKnobsShiftMode=false; // Columns modes in Force simulated on a MPC static int ForceColumnMode = -1 ; // MPC hardware pads : a totally anarchic numbering! // Force is orered from 0x36. Top left enum MPCPads { MPC_PAD1, MPC_PAD2, MPC_PAD3, MPC_PAD4, MPC_PAD5,MPC_PAD6,MPC_PAD7, MPC_PAD8, MPC_PAD9, MPC_PAD10, MPC_PAD11, MPC_PAD12, MPC_PAD13, MPC_PAD14, MPC_PAD15, MPC_PAD16 }; // MPC --------------------- FORCE------------------ // Press = 99 [pad#] [00-7F] idem // Release = 89 [pad#] 00 idem // AFT A9 [pad#] [00-7F] idem // MPC PAd # from left bottom Force pad# from up left to right bottom // to up right (hexa) = // 31 37 33 35 36 37 38 39 3A 3B 3C 3D // 30 2F 2D 2B 3E 3F 40 41 42 43 44 45 // 28 26 2E 2C ... // 25 24 2A 52 // wtf !! // // (13)31 (14)37 (15)33 (16)35 // (9) 30 (10)2F (11)2D (12)2B // (5) 28 (6) 26 (7) 2E (8) 2C // (1) 25 (2) 24 (3) 2A (4) 52 static const uint8_t MPCPadsTable[] = { MPC_PAD2, MPC_PAD1, MPC_PAD6, 0xff, MPC_PAD5, 0xff, MPC_PAD3, MPC_PAD12, // 0x24, 0x25, 0x26, (0x27), 0x28, (0x29), 0x2A, 0x2B, MPC_PAD8, MPC_PAD11, MPC_PAD7, MPC_PAD10, MPC_PAD9, MPC_PAD13, 0xff, MPC_PAD15, // 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, (0x32) 0x33, 0xff, MPC_PAD16, 0xff, MPC_PAD14, // (0x34), 0x35, (0x36) 0x37, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff, // 0x38 - 0x51 MPC_PAD4 }; // 0x52 static const uint8_t MPCPadsTable2[] = { 0x25,0x24,0x2A,0x52, 0x28,0x26,0x2E,0x2C, 0x30,0x2F,0x2D,0x2B, 0x31,0x37,0x33,0x35 }; // Our MPC product id (index in the table) static int MPCOriginalId = -1; // The one used static int MPCId = -1; // and the spoofed one, static int MPCSpoofedID = -1; // Internal product code file handler to change on the fly when the file will be opened static int product_code_file_handler = -1 ; // MPC alsa informations static int mpc_midi_card = -1; static int mpc_seq_client = -1; static char mpc_midi_private_alsa_name[20]; static char mpc_midi_public_alsa_name[20]; // Midi our controller seq client static int seqanyctrl_client=-1; static snd_rawmidi_t *rawmidi_inanyctrl = NULL; static snd_rawmidi_t *rawmidi_outanyctrl = NULL; static int anyctrl_midi_card = -1; static char * anyctrl_name = NULL; // Virtual rawmidi pointers to fake the MPC app static snd_rawmidi_t *rawvirt_inpriv = NULL; static snd_rawmidi_t *rawvirt_outpriv = NULL ; static snd_rawmidi_t *rawvirt_outpub = NULL ; // Sequencers virtual client addresses static int seqvirt_client_inpriv = -1; static int seqvirt_client_outpriv = -1; static int seqvirt_client_outpub = -1; // Alsa API hooks declaration static typeof(&snd_rawmidi_open) orig_snd_rawmidi_open; static typeof(&snd_rawmidi_read) orig_snd_rawmidi_read; static typeof(&snd_rawmidi_write) orig_snd_rawmidi_write; static typeof(&snd_seq_create_simple_port) orig_snd_seq_create_simple_port; static typeof(&snd_midi_event_decode) orig_snd_midi_event_decode; static typeof(&snd_seq_open) orig_snd_seq_open; static typeof(&snd_seq_port_info_set_name) orig_snd_seq_port_info_set_name; static typeof(&snd_seq_event_input) orig_snd_seq_event_input; // Globals used to rename a virtual port and get the client id. No other way... static int snd_seq_virtual_port_rename_flag = 0; static char snd_seq_virtual_port_newname [30]; static int snd_seq_virtual_port_clientid=-1; // Other more generic APIs static typeof(&open64) orig_open64; static typeof(&read) orig_read; static typeof(&open) orig_open; /////////////////////////////////////////////////////////////////////////////// // Match string against a regular expression /////////////////////////////////////////////////////////////////////////////// int match(const char *string, const char *pattern) { int status; regex_t re; if (regcomp(&re, pattern, REG_EXTENDED|REG_NOSUB) != 0) { return(0); /* Report error. */ } status = regexec(&re, string, (size_t) 0, NULL, 0); regfree(&re); if (status != 0) { return(0); /* Report error. */ } return(1); } /////////////////////////////////////////////////////////////////////////////// // Read a key,value pair from our config file (INI file format) /////////////////////////////////////////////////////////////////////////////// static int GetKeyValueFromConfFile(const char * confFileName, const char *sectionName,const char* key, char value[]) { FILE *fp = fopen(confFileName, "r"); if ( fp == NULL) return -1; char line [132]; int r = -1; bool sectionFound = false; while (fgets(line, sizeof(line), fp)) { // Remove spaces before char *p = line; while (isspace (*p)) p++; // Empty line or comments if ( p[0] == '\0' || p[0] == '#' || p[0] == ';' ) continue; // Remove spaces after int i; for ( i = strlen (p) - 1; (isspace (p[i])); i--) ; p[i + 1] = '\0'; // A section ? if ( p[0] == '[' && p[strlen(p) - 1 ] == ']' ) { if ( strncmp(p + 1,sectionName,strlen(p)-2 ) == 0 ) { sectionFound = true; } continue; } // Section was already found : read the value of the key if ( sectionFound ) { // Empty section ? if ( p[0] == '[' ) break; if ( strncmp(p,key,strlen(key) ) == 0 && p[strlen(key)] == '=' ) { strcpy(value,&p[strlen(key) + 1 ]); // Empty value return -1 r = ( value[0] == '\0' ? -1 : 0 ); break; } } } fclose(fp); return r; } /////////////////////////////////////////////////////////////////////////////// // Load mapping tables from config file /////////////////////////////////////////////////////////////////////////////// static void LoadMappingFromConfFile(const char * confFileName) { char srcKey[64]; char destKey[64]; char myKey[64]; char myValue[64]; char btLedMapSection[64]; char ctrlMapSection[64]; char btLedSrcSection[64]; char ctrlSrcSection[64]; char btLedDestSection[64]; char ctrlDestSection[64]; sprintf(btLedMapSection,"Map_%s_%s_ButtonsLeds", DeviceInfoBloc[MPCOriginalId].productStringShort,DeviceInfoBloc[MPCId].productStringShort); sprintf(ctrlMapSection,"Map_%s_%s_Controls", DeviceInfoBloc[MPCOriginalId].productStringShort,DeviceInfoBloc[MPCId].productStringShort); sprintf(btLedSrcSection,"%s_ButtonsLeds",DeviceInfoBloc[MPCOriginalId].productStringShort); sprintf(ctrlSrcSection,"%s_Controls", DeviceInfoBloc[MPCOriginalId].productStringShort); sprintf(btLedDestSection,"%s_ButtonsLeds",DeviceInfoBloc[MPCId].productStringShort); sprintf(ctrlDestSection,"%s_Controls", DeviceInfoBloc[MPCId].productStringShort); for ( int i = 0 ; i < 256 ; i++ ) { map_ButtonsLeds[i] = -1; map_ButtonsLeds_Inv[i] = -1; map_Ctrl[i] = -1; map_Ctrl_Inv[i] = -1; } if ( confFileName == NULL ) return ; // No config file // Get Globals within the mapping secton if ( GetKeyValueFromConfFile(confFileName, btLedMapSection,"QlinkKnobsShiftMode",myValue) == 0 ) { QlinkKnobsShiftMode = ( atoi(myValue) == 1 ? true:false ); if ( QlinkKnobsShiftMode) fprintf(stdout,"[tkgl] QlinkKnobsShiftMode was set to 1.\n"); } // Read the mapping table entries for ( int i = 0 ; i < 256 ; i++ ) { // Key of the map section, to scan all mappings sprintf(myKey,"%d",i); // Buttons & Leds mapping if ( GetKeyValueFromConfFile(confFileName, btLedMapSection,myKey,myValue) == 0 ) { // We get the combination as src:dest // Get the src key char * sep = strstr(myValue,":"); if ( sep != NULL ) { *sep = '\0'; strcpy(srcKey, myValue); strcpy(destKey,sep + 1); if ( srcKey[0] != '\0' && destKey[0] != '\0' ) { bool srcShift = false ; bool destShift = false; // fprintf(stdout,"[tkgl] Value %s src key %s => dest key %s\n",myValue,srcKey,destKey); // Look for "SHIFT_" prefix on the source and dest key value if ( strncmp(srcKey,"SHIFT_",6) == 0 ) { srcShift = true; strcpy(srcKey, &srcKey[6] ); } if ( strncmp(destKey,"SHIFT_",6) == 0 ) { destShift = true; strcpy(destKey, destKey + 6); } // Get Src value in the device declaration if ( GetKeyValueFromConfFile(confFileName, btLedSrcSection,srcKey,myValue) == 0 ) { int srcValue = atoi(myValue); if ( srcValue <= 127 ) { // Get Dest value if ( GetKeyValueFromConfFile(confFileName, btLedDestSection,destKey,myValue) == 0 ) { int destValue = atoi(myValue); if ( destValue <= 127 ) { // If shift mapping, set the bit 7 srcValue = ( srcShift ? srcValue + 0x80 : srcValue ); destValue = ( destShift ? destValue + 0x80 : destValue ); map_ButtonsLeds[srcValue] = destValue; map_ButtonsLeds_Inv[destValue] = srcValue; fprintf(stdout,"[tkgl] Button-Led %s%s (%d) mapped to %s%s (%d)\n",srcShift?"(SHIFT) ":"",srcKey,srcValue,destShift?"(SHIFT) ":"",destKey,map_ButtonsLeds[srcValue]); } } } } } // != '\0' } // sep } } // for } /////////////////////////////////////////////////////////////////////////////// // Set pad colors /////////////////////////////////////////////////////////////////////////////// // 2 implementations : call with a 32 bits color int value or with r,g,b values void SetPadColor(const uint8_t mpcId, const uint8_t padNumber, const uint8_t r,const uint8_t g,const uint8_t b ) { uint8_t sysexBuff[128]; int p = 0; // F0 47 7F [3B] 65 00 04 [Pad #] [R] [G] [B] F7 memcpy(sysexBuff, AkaiSysex,sizeof(AkaiSysex)); p += sizeof(AkaiSysex) ; // Add the current product id sysexBuff[p++] = mpcId ; // Add the pad color fn and pad number and color memcpy(&sysexBuff[p], MPCSysexPadColorFn,sizeof(MPCSysexPadColorFn)); sysexBuff[p++] = padNumber ; // #define COLOR_CORAL 00FF0077 sysexBuff[p++] = r ; sysexBuff[p++] = g ; sysexBuff[p++] = b ; sysexBuff[p++] = 0xF7; // Send the sysex to the MPC controller snd_rawmidi_write(rawvirt_outpriv,sysexBuff,p); } void SetPadColorFromColorInt(const uint8_t mpcId, const uint8_t padNumber, const uint32_t rgbColorValue) { SetPadColor(mpcId, padNumber, ( rgbColorValue >> 16 ), ( rgbColorValue >> 8 ) & 0x000000FF,rgbColorValue & 0x000000FF ); } /////////////////////////////////////////////////////////////////////////////// // Get an ALSA sequencer client containing a name /////////////////////////////////////////////////////////////////////////////// int GetSeqClientFromPortName(const char * name) { if ( name == NULL) return -1; char port_name[128]; snd_seq_t *seq; if (orig_snd_seq_open(&seq, "default", SND_SEQ_OPEN_DUPLEX, 0) < 0) { fprintf(stderr,"[tkgl] *** Error : impossible to open default seq\n"); return -1; } snd_seq_client_info_t *cinfo; snd_seq_port_info_t *pinfo; snd_seq_client_info_alloca(&cinfo); snd_seq_port_info_alloca(&pinfo); snd_seq_client_info_set_client(cinfo, -1); while (snd_seq_query_next_client(seq, cinfo) >= 0) { /* reset query info */ snd_seq_port_info_set_client(pinfo, snd_seq_client_info_get_client(cinfo)); snd_seq_port_info_set_port(pinfo, -1); while (snd_seq_query_next_port(seq, pinfo) >= 0) { sprintf(port_name,"%s %s",snd_seq_client_info_get_name(cinfo),snd_seq_port_info_get_name(pinfo)); if (strstr(port_name,name) != NULL) { int r = snd_seq_client_info_get_client(cinfo); snd_seq_close(seq); return r ; } } } snd_seq_close(seq); return -1; } /////////////////////////////////////////////////////////////////////////////// // Get the last port ALSA sequencer client /////////////////////////////////////////////////////////////////////////////// int GetLastPortSeqClient() { int r = -1; snd_seq_t *seq; if (orig_snd_seq_open(&seq, "default", SND_SEQ_OPEN_DUPLEX, 0) < 0) { fprintf(stderr,"[tkgl] *** Error : impossible to open default seq\n"); return -1; } snd_seq_client_info_t *cinfo; snd_seq_port_info_t *pinfo; snd_seq_client_info_alloca(&cinfo); snd_seq_port_info_alloca(&pinfo); snd_seq_client_info_set_client(cinfo, -1); while (snd_seq_query_next_client(seq, cinfo) >= 0) { /* reset query info */ snd_seq_port_info_set_client(pinfo, snd_seq_client_info_get_client(cinfo)); snd_seq_port_info_set_port(pinfo, -1); while (snd_seq_query_next_port(seq, pinfo) >= 0) { r = snd_seq_client_info_get_client(cinfo) ; //fprintf(stdout,"[tkgl] client %s -- %d port %s %d\n",snd_seq_client_info_get_name(cinfo) ,r, snd_seq_port_info_get_name(pinfo), snd_seq_port_info_get_port(pinfo) ); } } snd_seq_close(seq); return r; } /////////////////////////////////////////////////////////////////////////////// // Get an ALSA card from a matching regular expression pattern /////////////////////////////////////////////////////////////////////////////// int GetCardFromShortName(const char *pattern) { int card = -1; char* shortname = NULL; if ( snd_card_next(&card) < 0) return -1; while (card >= 0) { if ( snd_card_get_name(card, &shortname) == 0 && match(shortname,pattern) ) return card; if ( snd_card_next(&card) < 0) break; } return -1; } /////////////////////////////////////////////////////////////////////////////// // ALSA aconnect utility API equivalent /////////////////////////////////////////////////////////////////////////////// int aconnect(int src_client, int src_port, int dest_client, int dest_port) { int queue = 0, convert_time = 0, convert_real = 0, exclusive = 0; snd_seq_port_subscribe_t *subs; snd_seq_addr_t sender, dest; int client; char addr[10]; snd_seq_t *seq; if (orig_snd_seq_open(&seq, "default", SND_SEQ_OPEN_DUPLEX, 0) < 0) { fprintf(stderr,"[tkgl] *** Error : impossible to open default seq\n"); return -1; } if ((client = snd_seq_client_id(seq)) < 0) { fprintf(stderr,"[tkgl] *** Error : impossible to get seq client id\n"); snd_seq_close(seq); return - 1; } /* set client info */ if (snd_seq_set_client_name(seq, "ALSA Connector") < 0) { fprintf(stderr,"[tkgl] *** Error : set client name failed\n"); snd_seq_close(seq); return -1; } /* set subscription */ sprintf(addr,"%d:%d",src_client,src_port); if (snd_seq_parse_address(seq, &sender, addr) < 0) { snd_seq_close(seq); fprintf(stderr,"[tkgl] *** Error : invalid source address %s\n", addr); return -1; } sprintf(addr,"%d:%d",dest_client,dest_port); if (snd_seq_parse_address(seq, &dest, addr) < 0) { snd_seq_close(seq); fprintf(stderr,"[tkgl] *** Error : invalid destination address %s\n", addr); return -1; } snd_seq_port_subscribe_alloca(&subs); snd_seq_port_subscribe_set_sender(subs, &sender); snd_seq_port_subscribe_set_dest(subs, &dest); snd_seq_port_subscribe_set_queue(subs, queue); snd_seq_port_subscribe_set_exclusive(subs, exclusive); snd_seq_port_subscribe_set_time_update(subs, convert_time); snd_seq_port_subscribe_set_time_real(subs, convert_real); fprintf(stdout,"[tkgl] connection %d:%d to %d:%d",src_client,src_port,dest_client,dest_port); if (snd_seq_get_port_subscription(seq, subs) == 0) { snd_seq_close(seq); fprintf(stdout," already subscribed\n"); return 0; } if (snd_seq_subscribe_port(seq, subs) < 0) { snd_seq_close(seq); fprintf(stdout," failed !\n"); return 1; } fprintf(stdout," successfull\n"); snd_seq_close(seq); } /////////////////////////////////////////////////////////////////////////////// // Get MPC hardware name from sysex id /////////////////////////////////////////////////////////////////////////////// static int GetIndexOfMPCId(uint8_t id){ for (int i = 0 ; i < _END_MPCID ; i++ ) if ( DeviceInfoBloc[i].sysexId == id ) return i; return -1; } const char * GetHwNameFromMPCId(uint8_t id){ int i = GetIndexOfMPCId(id); if ( i >= 0) return DeviceInfoBloc[i].productString ; else return NULL; } /////////////////////////////////////////////////////////////////////////////// // Show MPCMAPPER HELP /////////////////////////////////////////////////////////////////////////////// void ShowHelp(void) { fprintf(stdout,"[tkgl]\n") ; fprintf(stdout,"[tkgl] --tgkl_help : Show this help\n") ; fprintf(stdout,"[tkgl] --tkgl_ctrlname=<name> : Use external controller containing <name>\n") ; fprintf(stdout,"[tkgl] --tkgl_iamX : Emulate MPC X\n") ; fprintf(stdout,"[tkgl] --tkgl_iamLive : Emulate MPC Live\n") ; fprintf(stdout,"[tkgl] --tkgl_iamForce : Emulate Force\n") ; fprintf(stdout,"[tkgl] --tkgl_iamOne : Emulate MPC One\n") ; fprintf(stdout,"[tkgl] --tkgl_iamLive2 : Emulate MPC Live Mk II\n") ; fprintf(stdout,"[tkgl] --tkgl_virtualport=<name> : Create end user virtual port <name>\n") ; fprintf(stdout,"[tkgl] --tkgl_mididump : Dump original raw midi flow\n") ; fprintf(stdout,"[tkgl] --tkgl_mididumpPost : Dump raw midi flow after transformation\n") ; fprintf(stdout,"[tkgl] --tkgl_configfile=<name> : Use configuration file <name>\n") ; fprintf(stdout,"[tkgl]\n") ; exit(0); } /////////////////////////////////////////////////////////////////////////////// // Setup tkgl anyctrl /////////////////////////////////////////////////////////////////////////////// static void tkgl_init() { // System call hooks orig_open64 = dlsym(RTLD_NEXT, "open64"); orig_open = dlsym(RTLD_NEXT, "open"); orig_read = dlsym(RTLD_NEXT, "read"); // Alsa hooks orig_snd_rawmidi_open = dlsym(RTLD_NEXT, "snd_rawmidi_open"); orig_snd_rawmidi_read = dlsym(RTLD_NEXT, "snd_rawmidi_read"); orig_snd_rawmidi_write = dlsym(RTLD_NEXT, "snd_rawmidi_write"); orig_snd_seq_create_simple_port = dlsym(RTLD_NEXT, "snd_seq_create_simple_port"); orig_snd_midi_event_decode = dlsym(RTLD_NEXT, "snd_midi_event_decode"); orig_snd_seq_open = dlsym(RTLD_NEXT, "snd_seq_open"); orig_snd_seq_port_info_set_name = dlsym(RTLD_NEXT, "snd_seq_port_info_set_name"); orig_snd_seq_event_input = dlsym(RTLD_NEXT, "snd_seq_event_input"); // Read product code char product_code[4]; int fd = orig_open(PRODUCT_CODE_PATH,O_RDONLY); orig_read(fd,&product_code,4); // Find the id in the product code table for (int i = 0 ; i < _END_MPCID; i++) { if ( strncmp(DeviceInfoBloc[i].productCode,product_code,4) == 0 ) { MPCOriginalId = i; break; } } if ( MPCOriginalId < 0) { fprintf(stdout,"[tkgl] *** Error when reading the product-code file\n"); exit(1); } fprintf(stdout,"[tkgl] Original Product code : %s (%s)\n",DeviceInfoBloc[MPCOriginalId].productCode,DeviceInfoBloc[MPCOriginalId].productString); if ( MPCSpoofedID >= 0 ) { fprintf(stdout,"[tkgl] Product code spoofed to %s (%s)\n",DeviceInfoBloc[MPCSpoofedID].productCode,DeviceInfoBloc[MPCSpoofedID].productString); MPCId = MPCSpoofedID ; } else MPCId = MPCOriginalId ; // read mapping config file if any LoadMappingFromConfFile(configFileName); // Initialize card id for public and private mpc_midi_card = GetCardFromShortName(CTRL_MPC_ALL); if ( mpc_midi_card < 0 ) { fprintf(stderr,"[tkgl] **** Error : MPC controller card not found\n"); exit(1); } // Get MPC seq // Public is port 0, Private is port 1 mpc_seq_client = GetSeqClientFromPortName("Private"); if ( mpc_seq_client < 0 ) { fprintf(stderr,"[tkgl] **** Error : MPC controller seq client not found\n"); exit(1); } sprintf(mpc_midi_private_alsa_name,"hw:%d,0,1",mpc_midi_card); sprintf(mpc_midi_public_alsa_name,"hw:%d,0,0",mpc_midi_card); fprintf(stdout,"[tkgl] MPC controller card id hw:%d found\n",mpc_midi_card); fprintf(stdout,"[tkgl] MPC controller Private port is %s\n",mpc_midi_private_alsa_name); fprintf(stdout,"[tkgl] MPC controller Public port is %s\n",mpc_midi_public_alsa_name); fprintf(stdout,"[tkgl] MPC controller seq client is %d\n",mpc_seq_client); // Get our controller seq port client //const char * port_name = getenv("ANYCTRL_NAME") ; if ( anyctrl_name != NULL) { // Initialize card id for public and private seqanyctrl_client = GetSeqClientFromPortName(anyctrl_name); anyctrl_midi_card = GetCardFromShortName(anyctrl_name); if ( seqanyctrl_client < 0 || anyctrl_midi_card < 0 ) { fprintf(stderr,"[tkgl] **** Error : %s seq client or card not found\n",anyctrl_name); exit(1); } fprintf(stdout,"[tkgl] %s connect port is %d:0\n",anyctrl_name,seqanyctrl_client); fprintf(stdout,"[tkgl] %s card id hw:%d found\n",anyctrl_name,anyctrl_midi_card); } // Create 3 virtuals ports : Private I/O, Public O // This will trig our hacked snd_seq_create_simple_port during the call. // NB : the snd_rawmidi_open is hacked here to return the client id of the virtual port. // So, return is either < 0 if error, or > 0, being the client number if everything is ok. // The port is always 0. This is the standard behaviour. seqvirt_client_inpriv = snd_rawmidi_open(&rawvirt_inpriv, NULL, "[virtual]TKGL Virtual In Private", 2); seqvirt_client_outpriv = snd_rawmidi_open(NULL, &rawvirt_outpriv, "[virtual]TKGL Virtual Out Private", 3); seqvirt_client_outpub = snd_rawmidi_open(NULL, &rawvirt_outpub, "[virtual]TKGL Virtual Out Public", 3); if ( seqvirt_client_inpriv < 0 || seqvirt_client_outpriv < 0 || seqvirt_client_outpub < 0 ) { fprintf(stderr,"[tkgl] **** Error : impossible to create one or many virtual ports\n"); exit(1); } fprintf(stdout,"[tkgl] Virtual private input port %d created.\n",seqvirt_client_inpriv); fprintf(stdout,"[tkgl] Virtual private output port %d created.\n",seqvirt_client_outpriv); fprintf(stdout,"[tkgl] Virtual public output port %d created.\n",seqvirt_client_outpub); // Make connections of our virtuals ports // MPC APP <---> VIRTUAL PORTS <---> MPC CONTROLLER PRIVATE & PUBLIC PORTS // Private MPC controller port 1 out to virtual In priv 0 aconnect( mpc_seq_client, 1, seqvirt_client_inpriv, 0); // Virtual out priv 0 to Private MPC controller port 1 in aconnect( seqvirt_client_outpriv, 0, mpc_seq_client, 1); // Virtual out pub to Public MPC controller port 1 in // No need to cable the out... aconnect( seqvirt_client_outpub, 0, mpc_seq_client, 0); // Connect our controller if used if (seqanyctrl_client >= 0) { // port 0 to virtual In 0, aconnect( seqanyctrl_client, 0, seqvirt_client_inpriv, 0); // Virtual out priv 0 to our controller port 0 aconnect( seqvirt_client_outpriv, 0, seqanyctrl_client, 0); // Virtual out public to our controller port 0 aconnect( seqvirt_client_outpub, 0, seqanyctrl_client, 0); } // Create a user virtual port if asked on the command line if ( user_virtual_portname != NULL) { char temp_portname[64]; sprintf(temp_portname,"[virtual]%s",user_virtual_portname); if ( snd_rawmidi_open(&rawvirt_user_in, &rawvirt_user_out, temp_portname, 0 ) < 0 ) { fprintf(stderr,"[tkgl] **** Error : impossible to create virtual user port %s\n",user_virtual_portname); exit(1); } fprintf(stderr,"[tkgl] Virtual user port %s succesfully created.\n",user_virtual_portname); //snd_rawmidi_open(&read_handle, &write_handle, "virtual", 0); } fflush(stdout); } //////////////////////////////////////////////////////////////////////////////// // Clean DUMP of a buffer to screen //////////////////////////////////////////////////////////////////////////////// static void ShowBufferHexDump(const uint8_t* data, size_t sz, uint8_t nl) { uint8_t b; char asciiBuff[33]; uint8_t c=0; for (uint16_t idx = 0 ; idx < sz; idx++) { if ( c == 0 && idx >= 0) fprintf(stdout,"[tkgl] "); b = (*data++); fprintf(stdout,"%02X ",b); asciiBuff[c++] = ( b >= 0x20 && b< 127? b : '.' ) ; if ( c == nl || idx == sz -1 ) { asciiBuff[c] = 0; for ( ; c < nl; c++ ) fprintf(stdout," "); c = 0; fprintf(stdout," | %s\n", asciiBuff); } } } /////////////////////////////////////////////////////////////////////////////// // MPC Main hook /////////////////////////////////////////////////////////////////////////////// int __libc_start_main( int (*main)(int, char **, char **), int argc, char **argv, int (*init)(int, char **, char **), void (*fini)(void), void (*rtld_fini)(void), void *stack_end) { // Find the real __libc_start_main()... typeof(&__libc_start_main) orig = dlsym(RTLD_NEXT, "__libc_start_main"); // Banner fprintf(stdout,"[tkgl] ------------------------------------------\n"); fprintf(stdout,"[tkgl] TKGL_MPCMAPPER V1.0 by the KikGen Labs\n"); fprintf(stdout,"[tkgl] ------------------------------------------\n"); // Scan command line char * tkgl_SpoofArg = NULL; for ( int i = 1 ; i < argc ; i++ ) { // help if ( ( strcmp("--tkgl_help",argv[i]) == 0 ) ) { ShowHelp(); } else if ( ( strncmp("--tkgl_ctrlname=",argv[i],16) == 0 ) && ( strlen(argv[i]) >16 ) ) { anyctrl_name = argv[i] + 16; fprintf(stdout,"[tkgl] --tgkl_ctrlname specified for %s midi controller\n",anyctrl_name) ; } else // Spoofed product id if ( ( strcmp("--tkgl_iamX",argv[i]) == 0 ) ) { MPCSpoofedID = MPC_X; tkgl_SpoofArg = argv[i]; } else if ( ( strcmp("--tkgl_iamLive",argv[i]) == 0 ) ) { MPCSpoofedID = MPC_LIVE; tkgl_SpoofArg = argv[i]; } else if ( ( strcmp("--tkgl_iamForce",argv[i]) == 0 ) ) { MPCSpoofedID = MPC_FORCE; tkgl_SpoofArg = argv[i]; } else if ( ( strcmp("--tkgl_iamOne",argv[i]) == 0 ) ) { MPCSpoofedID = MPC_ONE; tkgl_SpoofArg = argv[i]; } else if ( ( strcmp("--tkgl_iamLive2",argv[i]) == 0 ) ) { MPCSpoofedID = MPC_LIVE_MK2; tkgl_SpoofArg = argv[i]; } else // End user virtual port visible from the MPC app if ( ( strncmp("--tkgl_virtualport=",argv[i],19) == 0 ) && ( strlen(argv[i]) >19 ) ) { user_virtual_portname = argv[i] + 19; fprintf(stdout,"[tkgl] --tkgl_virtualport specified as %s port name\n",user_virtual_portname) ; } else // Dump rawmidi if ( ( strcmp("--tkgl_mididump",argv[i]) == 0 ) ) { rawMidiDumpFlag = 1 ; fprintf(stdout,"[tkgl] --tkgl_mididump specified : dump original raw midi message (ENTRY)\n") ; } else if ( ( strcmp("--tkgl_mididumpPost",argv[i]) == 0 ) ) { rawMidiDumpPostFlag = 1 ; fprintf(stdout,"[tkgl] --tkgl_mididumpPost specified : dump raw midi message after transformation (POST)\n") ; } else // Config file name if ( ( strncmp("--tkgl_configfile=",argv[i],18) == 0 ) && ( strlen(argv[i]) >18 ) ) { configFileName = argv[i] + 18 ; fprintf(stdout,"[tkgl] --tkgl_configfile specified. File %s will be used for mapping\n",configFileName) ; } } if ( MPCSpoofedID >= 0 ) { fprintf(stdout,"[tkgl] %s specified. %s spoofing.\n",tkgl_SpoofArg,DeviceInfoBloc[MPCSpoofedID].productString ) ; } // Initialize everything tkgl_init(); // ... and call main again return orig(main, argc, argv, init, fini, rtld_fini, stack_end); } /////////////////////////////////////////////////////////////////////////////// // ALSA snd_rawmidi_open hooked /////////////////////////////////////////////////////////////////////////////// // This function allows changing the name of a virtual port, by using the // naming convention "[virtual]port name" // and if creation succesfull, will return the client number. Port is always 0 if virtual. int snd_rawmidi_open(snd_rawmidi_t **inputp, snd_rawmidi_t **outputp, const char *name, int mode) { fprintf(stdout,"[tkgl] snd_rawmidi_open name %s mode %d\n",name,mode); // Rename the virtual port as we need // Port Name must not be emtpy - 30 chars max if ( strncmp(name,"[virtual]",9) == 0 ) { int l = strlen(name); if ( l <= 9 || l > 30 + 9 ) return -1; // Prepare the renaming of the virtual port strcpy(snd_seq_virtual_port_newname,name + 9); snd_seq_virtual_port_rename_flag = 1; // Create the virtual port via the fake Alsa rawmidi virtual open int r = orig_snd_rawmidi_open(inputp, outputp, "virtual", mode); if ( r < 0 ) return r; // Get the port id that was populated in the port creation sub function // and reset it r = snd_seq_virtual_port_clientid; snd_seq_virtual_port_clientid=-1; //fprintf(stdout,"[tkgl] PORT ID IS %d\n",r); return r; } // Substitute the hardware private input port by our input virtual ports else if ( strcmp(mpc_midi_private_alsa_name,name) == 0 ) { // Private In if (inputp) *inputp = rawvirt_inpriv; else if (outputp) *outputp = rawvirt_outpriv ; else return -1; fprintf(stdout,"[tkgl] %s substitution by virtual rawmidi successfull\n",name); return 0; } else if ( strcmp(mpc_midi_public_alsa_name,name) == 0 ) { if (outputp) *outputp = rawvirt_outpub; else return -1; fprintf(stdout,"[tkgl] %s substitution by virtual rawmidi successfull\n",name); return 0; } return orig_snd_rawmidi_open(inputp, outputp, name, mode); } /////////////////////////////////////////////////////////////////////////////// // Refresh MPC pads colors from Force PAD Colors cache /////////////////////////////////////////////////////////////////////////////// void MPC_UpdatePadColor(uint8_t padL, uint8_t padC, uint8_t nbLine) { // Write again the color like a Force. // The midi modification will be done within the corpse of the hooked fn. // Pads from 64 are columns pads uint8_t sysexBuff[12] = { 0xF0, 0x47, 0x7F, 0x40, 0x65, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0xF7}; // [Pad #] [R] [G] [B] for ( int l = 0 ; l< nbLine ; l++ ) { for ( int c = 0 ; c < 4 ; c++ ) { int padF = ( l + padL ) * 8 + c + padC; sysexBuff[7] = padF; sysexBuff[8] = ForcePadColorsCache[padF].r ; sysexBuff[9] = ForcePadColorsCache[padF].g; sysexBuff[10] = ForcePadColorsCache[padF].b; // Send the sysex to the MPC controller snd_rawmidi_write(rawvirt_outpriv,sysexBuff,sizeof(sysexBuff)); } } } // // // /////////////////////////////////////////////////////////////////////////////// // // Show the current MPC quadran within the Force matrix // /////////////////////////////////////////////////////////////////////////////// // void MPC_ShowMatrixQuadran(uint8_t forcePadL, uint8_t forcePadC) { // // uint8_t sysexBuff[12] = { 0xF0, 0x47, 0x7F, 0x40, 0x65, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0xF7}; // // [Pad #] [R] [G] [B] // sysexBuff[3] = DeviceInfoBloc[MPCOriginalId].sysexId; // // uint8_t p = forcePadL*8 + forcePadC ; // //#define COLOR_GREY 0xA2A9AD // //#define COLOR_FIRE 0xFF000 // // for ( int l = 0 ; l < 2 ; l++ ) { // for ( int c = 0 ; c < 2 ; c++ ) { // sysexBuff[7] = l * 4 + c ; // if ( l == forcePadL && c == forcePadC ) { // sysexBuff[8] = 0xFF ; // sysexBuff[9] = 0x00 ; // sysexBuff[10] = 0x00 ; // } else { // sysexBuff[8] = 0xA2 ; // sysexBuff[9] = 0xA9 ; // sysexBuff[10] = 0xAD ; // } // // orig_snd_rawmidi_write(rawvirt_outpriv,sysexBuff,sizeof(sysexBuff)); // } // } // } /////////////////////////////////////////////////////////////////////////////// // Draw a pad line on MPC pads from a Force PAD line in the current Colors cache /////////////////////////////////////////////////////////////////////////////// void MPC_UpdatePadColorLine(uint8_t forcePadL, uint8_t forcePadC, uint8_t mpcPadL) { uint8_t sysexBuff[12] = { 0xF0, 0x47, 0x7F, 0x40, 0x65, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0xF7}; // [Pad #] [R] [G] [B] sysexBuff[3] = DeviceInfoBloc[MPCOriginalId].sysexId; uint8_t p = forcePadL*8 + forcePadC ; for ( int c = 0 ; c < 4 ; c++ ) { sysexBuff[7] = mpcPadL * 4 + c ; p = forcePadL*8 + c + forcePadC ; sysexBuff[8] = ForcePadColorsCache[p].r ; sysexBuff[9] = ForcePadColorsCache[p].g; sysexBuff[10] = ForcePadColorsCache[p].b; fprintf(stdout,"[tkgl] MPC Pad Line refresh : %d r g b %02X %02X %02X\n",sysexBuff[7],sysexBuff[8],sysexBuff[9],sysexBuff[10]); orig_snd_rawmidi_write(rawvirt_outpriv,sysexBuff,sizeof(sysexBuff)); } } /////////////////////////////////////////////////////////////////////////////// // MAP MPC controller hardware midi event to MPC application /////////////////////////////////////////////////////////////////////////////// static size_t Map_AppReadFromMPC(void *midiBuffer, size_t maxSize,size_t size) { uint8_t * myBuff = (uint8_t*)midiBuffer; size_t i = 0 ; while ( i < size ) { // AKAI SYSEX // IDENTITY REQUEST if ( myBuff[i] == 0xF0 && memcmp(&myBuff[i],IdentityReplySysexHeader,sizeof(IdentityReplySysexHeader)) == 0 ) { // If so, substitue sysex identity request by the faked one memcpy(&myBuff[i+sizeof(IdentityReplySysexHeader)],DeviceInfoBloc[MPCId].sysexIdReply, sizeof(DeviceInfoBloc[MPCId].sysexIdReply) ); i += sizeof(IdentityReplySysexHeader) + sizeof(DeviceInfoBloc[MPCId].sysexIdReply) ; } else // KNOBS TURN // If it's a shift + knob turn, add an offset // B0 [10-31] [7F - n] if ( myBuff[i] == 0xB0 ) { if ( shiftHoldedMode && QlinkKnobsShiftMode && DeviceInfoBloc[MPCOriginalId].qlinkKnobsCount < 16 && myBuff[i+1] >= 0x10 && myBuff[i+1] <= 0x31 ) myBuff[i+1] += DeviceInfoBloc[MPCOriginalId].qlinkKnobsCount; i += 3; } else // BUTTONS - LEDS // In that direction, it's a button press/release // Check if we must remap... if ( myBuff[i] == 0x90 ) { //|| myBuff[i] == 0x80 //fprintf(stdout,"[tkgl] %d button pressed/released (%02x) \n",myBuff[i+1], myBuff[i+2]); // Shift is an exception and mapping is ignored (the SHIFT button can't be mapped) // Double click on SHIFT is not managed at all. Avoid it. if ( myBuff[i+1] == SHIFT_KEY_VALUE ) { shiftHoldedMode = ( myBuff[i+2] == 0x7F ? true:false ) ; fprintf(stdout,"[tkgl] %d SHIFT MODE\n", shiftHoldedMode ); } else // SHIFT button is current holded // SHIFT double click on the MPC side is not taken into account for the moment if ( shiftHoldedMode ) { // KNOB TOUCH : If it's a shift + knob "touch", add the offset // 90 [54-63] 7F if ( QlinkKnobsShiftMode && DeviceInfoBloc[MPCOriginalId].qlinkKnobsCount < 16 && myBuff[i+1] >= 0x54 && myBuff[i+1] <= 0x63 ) myBuff[i+1] += DeviceInfoBloc[MPCOriginalId].qlinkKnobsCount; // Look for shift mapping above 0x7F if ( map_ButtonsLeds[ myBuff[i+1] + 0x80 ] >= 0 ) { uint8_t mapValue = map_ButtonsLeds[ myBuff[i+1] + 0x80 ]; fprintf(stdout,"[tkgl] Shift Button %d\n",mapValue); // If the SHIFT mapping is also activated at destination, and as the shift key // is currently holded, we send only the corresponding button, that will generate the shift + button code, // Otherwise, we must release the shift key, by inserting a shift key note off // Shift mapped also at destination if ( mapValue >= 0x80 ) { myBuff[i+1] = mapValue - 0x80; } else { // We are holding shift, but the dest key is not a SHIFT mapping // insert SHIFT BUTTON note off in the midi buffer // (we assume brutally we have room; Should check max size) if ( size > maxSize - 3 ) fprintf(stdout,"[tkgl] Warning : midi buffer overflow when inserting SHIFT note off !!\n"); memcpy( &myBuff[i + 3 ], &myBuff[i], size - i ); size +=3; myBuff[i + 1] = SHIFT_KEY_VALUE ; myBuff[i + 2] = 0x00 ; // Button released i += 3; // Now, map our Key myBuff[ i + 1 ] = mapValue; } } else { // If no shift mapping, use the normal mapping myBuff[i+1] = map_ButtonsLeds[ myBuff[i+1] ]; } } // Shiftmode else if ( map_ButtonsLeds[ myBuff[i+1] ] >= 0 ) { //fprintf(stdout,"[tkgl] MAP %d->%d\n",myBuff[i+1],map_ButtonsLeds[ myBuff[i+1] ]); myBuff[i+1] = map_ButtonsLeds[ myBuff[i+1] ]; } // Check if we must activate the special column mode when Force spoofed on a MPC if ( MPCOriginalId != MPC_FORCE && MPCId == MPC_FORCE) { // Colum mode Button holded if ( myBuff[i+2] == 0x7F ) { uint8_t mapValue = myBuff[i+1] ; fprintf(stdout,"[tkgl] COLUMN MODE ON ?? %d\n",ForceColumnMode); switch (myBuff[i+1]) { case FORCE_ASSIGN_A: case FORCE_ASSIGN_B: case FORCE_MUTE: case FORCE_SOLO: case FORCE_REC_ARM: case FORCE_CLIP_STOP: ForceColumnMode = myBuff[i+1]; break; default: ForceColumnMode = -1 ; } fprintf(stdout,"[tkgl] COLUMN MODE ON %d\n",ForceColumnMode); if ( ForceColumnMode >= 0 ) { MPCPad_OffsetLLast = MPCPad_OffsetL; //MPCPad_OffsetL = 5 ; MPC_UpdatePadColorLine(8, MPCPad_OffsetC, 3); //MPC_UpdatePadColor(MPCPad_OffsetL,MPCPad_OffsetC,1); } } // Button released else { fprintf(stdout,"[tkgl] COLUMN MODE OFF %d\n",ForceColumnMode); ForceColumnMode = -1 ; MPCPad_OffsetL = MPCPad_OffsetLLast; MPC_UpdatePadColor(MPCPad_OffsetL,MPCPad_OffsetC,4); } } i += 3; } else // PADS if ( myBuff[i] == 0x99 || myBuff[i] == 0x89 || myBuff[i] == 0xA9 ) { // Force spoofed on an MPC if ( MPCOriginalId != MPC_FORCE && MPCId == MPC_FORCE) { // Remap MPC hardware pad // Get MPC pad id in the true order uint8_t padM = MPCPadsTable[myBuff[i+1] - MPCPADS_TABLE_IDX_OFFSET ]; uint8_t padL = padM / 4 ; uint8_t padC = padM % 4 ; // Compute the Force pad id without offset uint8_t padF = ( 3 - padL + MPCPad_OffsetL ) * 8 + padC + MPCPad_OffsetC ; //fprintf(stdout,"[tkgl] MPC pad %d (%d,%d) -> Force pad %d\n",padM,padL,padC,padF); // Check if SHIFT is holded for the 0 column if ( shiftHoldedMode ) { //fprintf(stdout,"[tkgl] Pad Shift mode ! \n"); bool buttonSimul = false; // Simulate a Force button uint8_t buttonValue = 0x7F; bool refreshPads = false; if ( padC == 0 ) { // SHIFT + PAD in column 0 = Launch the corresponding line // LAUNCH_1=56 // Replace the midi pad note on by a button on/off buttonValue = padF / 8 + 56; // Launch line buttonSimul = true; } // Navigte in the matrix with shift + Pads // 12 13 ( Up 15 ) 16 // 08 (Left 09 ) ( Down 10) (Right 11) else if (padM == 9 ) { buttonValue = FORCE_LEFT; buttonSimul = true; } else if (padM == 11 ) { buttonValue = 115; // Right buttonSimul = FORCE_RIGHT; } else if (padM == 14 ) { buttonValue = FORCE_UP; // Up buttonSimul = true; } else if (padM == 10 ) { buttonValue = FORCE_DOWN; // Down buttonSimul = true; } // Navigte in the MPC pads // 04 05 (06 Left top quadran ) (07 right top quadran) // 00 01 (02 Left bottom quadran) (03 right bottom quadran) else // Top Left if (padM == 6 ) { MPCPad_OffsetL = MPCPad_OffsetC = 0; refreshPads = true; } else // Top Right if (padM == 7 ) { MPCPad_OffsetL = 0; MPCPad_OffsetC = 4; refreshPads = true; } else // bottom left if (padM == 2 ) { MPCPad_OffsetL = 4; MPCPad_OffsetC = 0; refreshPads = true; } else // bottom right if (padM == 3 ) { MPCPad_OffsetL = 4; MPCPad_OffsetC = 4; refreshPads = true; } // Simulate a button press/release if ( buttonSimul ) { myBuff[i+2] = ( myBuff[i] == 0x99 ? 0x7F:0x00 ) ; myBuff[i] = 0x90; // MPC Button //fprintf(stdout,"[tkgl] remapped to %02x %02x %02x ! \n",myBuff[i],myBuff[i+1],myBuff[i+2]); myBuff[i+1] = buttonValue; } else { // Generate a fake midi message myBuff[i] = 0x8F; myBuff[i+1] = 0x00; myBuff[i+2] = 0x00 ; } // Update the MPC pad colors from Force pad colors cache if ( refreshPads ) MPC_UpdatePadColor(MPCPad_OffsetL,MPCPad_OffsetC,4); } // Shitfmode // Check if columns solo mute... mode else if ( ForceColumnMode >= 0 ) { // Generate the "column" button event press or release myBuff[i+2] = ( myBuff[i] == 0x99 ? 0x7F:0x00 ) ; myBuff[i] = 0x90; // MPC Button // Pads botom line 90 29-30 00/7f myBuff[i+1] = 0x29 + padC + MPCPad_OffsetC; } else myBuff[i+1] = padF + FORCEPADS_TABLE_IDX_OFFSET; } else // MPC spoofed on a Force if ( MPCOriginalId == MPC_FORCE && MPCId != MPC_FORCE) { // Remap Force hardware pad uint8_t *pad = &myBuff[i+1]; uint8_t p = *pad - FORCEPADS_TABLE_IDX_OFFSET; uint8_t padL = p / 8 ; uint8_t padC = p % 8 ; // Use the 8x8 matrix as 4x pad banks // Regarding the pad pressed // C D 2 3 // A B 0 1 int prevMPC_PadBank = MPC_PadBank; if (padL >= 4 ) { if ( padC < 4 ) MPC_PadBank = 0; else MPC_PadBank = 1; } else { if ( padC < 4 ) MPC_PadBank = 2; else MPC_PadBank = 3; } // Keep pads in the 4x4 MPC pad matrix at the left bottom if ( padL >= 4 && padC < 4 ) { // Compute the MPC pad id p = (7 - padL ) * 4 + padC; *pad = MPCPadsTable2[p]; } else { // Implement other functions on Free PADS ? // Or Shows all banks... *pad = 0x7F; // To avoid random pad events... } } i += 3; } else i++; } return size; } /////////////////////////////////////////////////////////////////////////////// // MAP MPC application to MPC controller hardware midi event /////////////////////////////////////////////////////////////////////////////// static void Map_AppWriteToMPC(const void *midiBuffer, size_t size) { uint8_t * myBuff = (uint8_t*)midiBuffer; bool refreshMutePadLine = false; size_t i = 0 ; while ( i < size ) { // AKAI SYSEX // If we detect the Akai sysex header, change the harwware id by our true hardware id. // Messages are compatibles. Some midi msg are not always interpreted (e.g. Oled) if ( myBuff[i] == 0xF0 && memcmp(&myBuff[i],AkaiSysex,sizeof(AkaiSysex)) == 0 ) { // Update the sysex id in the sysex for our original hardware i += sizeof(AkaiSysex) ; myBuff[i] = DeviceInfoBloc[MPCOriginalId].sysexId; i++; // Force spoofed on an MPC if ( MPCOriginalId != MPC_FORCE && MPCId == MPC_FORCE) { // SET PAD COLORS SYSEX FN // F0 47 7F [3B] -> 65 00 04 [Pad #] [R] [G] [B] F7 // F0 47 7F 40 65 00 04 04 46 19 7F F7 if ( memcmp(&myBuff[i],MPCSysexPadColorFn,sizeof(MPCSysexPadColorFn)) == 0 ) { i += sizeof(MPCSysexPadColorFn) ; uint8_t padF = myBuff[i]; uint8_t padL = padF / 8 ; uint8_t padC = padF % 8 ; // Keep pad mutes eventual refresh in memory if ( padF >= 64 ) refreshMutePadLine = true ; // Update Force pad color cache ForcePadColorsCache[padF].r = myBuff[i + 1 ]; ForcePadColorsCache[padF].g = myBuff[i + 2 ]; ForcePadColorsCache[padF].b = myBuff[i + 3 ]; //fprintf(stdout,"[tkgl] Force pads color cache updated : Pad %d/%02x (%02x %02x %02x)\n",padF,padF,ForcePadColorsCache[padF].r,ForcePadColorsCache[padF].g,ForcePadColorsCache[padF].b); // Apply eventulal L,C pad offset if MPC padF = 0x7F; // set the default pad color to an unknow pad # if ( padL >= MPCPad_OffsetL && padL < MPCPad_OffsetL + 4 ) { if ( padC >= MPCPad_OffsetC && padC < MPCPad_OffsetC + 4 ) { //fprintf(stdout,"[tkgl] Pad (%d,%d) In the quadran (%d,%d)\n",padL,padC,MPCPad_OffsetL,MPCPad_OffsetC); padF = ( 3 - ( padL - MPCPad_OffsetL ) ) * 4 + ( padC - MPCPad_OffsetC) ; } } // Update the midi buffer myBuff[i] = padF; i += 5 ; // Next msg } } // MPC spoofed on a Force else if ( MPCOriginalId == MPC_FORCE && MPCId != MPC_FORCE) { // SET PAD COLORS SYSEX FN // F0 47 7F [3B] -> 65 00 04 [Pad #] [R] [G] [B] F7 if ( memcmp(&myBuff[i],MPCSysexPadColorFn,sizeof(MPCSysexPadColorFn)) == 0 ) { i += sizeof(MPCSysexPadColorFn) ; uint8_t *pad = &myBuff[i]; uint8_t padL = *pad / 4 ; uint8_t padC = *pad % 4 ; // 4x4 MPC pad matrix at the left bottom of Force pads *pad = ( 7 - padL ) * 8 + padC; i += 5 ; // Next msg } } } else // Buttons-Leds. In that direction, it's a LED ON / OFF for the button // Check if we must remap... if ( myBuff[i] == 0xB0 ) { if ( map_ButtonsLeds_Inv[ myBuff[i+1] ] >= 0 ) { //fprintf(stdout,"[tkgl] MAP INV %d->%d\n",myBuff[i+1],map_ButtonsLeds_Inv[ myBuff[i+1] ]); myBuff[i+1] = map_ButtonsLeds_Inv[ myBuff[i+1] ]; } i += 3; } else i++; } // Check if we must refresh the pad mutes line on the MPC if ( ForceColumnMode >= 0 && refreshMutePadLine ) { MPC_UpdatePadColorLine(8, MPCPad_OffsetC, 3); } } /////////////////////////////////////////////////////////////////////////////// // Alsa Rawmidi read /////////////////////////////////////////////////////////////////////////////// ssize_t snd_rawmidi_read(snd_rawmidi_t *rawmidi, void *buffer, size_t size) { ssize_t r = orig_snd_rawmidi_read(rawmidi, buffer, size); if ( rawMidiDumpFlag ) { const char *name = snd_rawmidi_name(rawmidi); fprintf(stdout,"[tkgl] ENTRY Dump snd_rawmidi_read from controller %s\n",name); ShowBufferHexDump(buffer, r,16); fprintf(stdout,"[tkgl]\n"); } // Map only if not on the original hardware if ( MPCId != MPCOriginalId && rawmidi == rawvirt_inpriv) { r = Map_AppReadFromMPC(buffer,size,r); } if ( rawMidiDumpPostFlag ) { const char *name = snd_rawmidi_name(rawmidi); fprintf(stdout,"[tkgl] POST Dump snd_rawmidi_read from controller %s\n",name); ShowBufferHexDump(buffer, r,16); fprintf(stdout,"[tkgl]\n"); } return r; } /////////////////////////////////////////////////////////////////////////////// // Alsa Rawmidi write /////////////////////////////////////////////////////////////////////////////// ssize_t snd_rawmidi_write(snd_rawmidi_t * rawmidi,const void * buffer,size_t size) { if ( rawMidiDumpFlag ) { const char *name = snd_rawmidi_name(rawmidi); fprintf(stdout,"[tkgl] ENTRY Dump snd_rawmidi_write to controller %s\n",name); ShowBufferHexDump(buffer, size,16); fprintf(stdout,"[tkgl]\n"); } //const char *name = snd_rawmidi_name(rawmidi); //fprintf(stdout,"[tkgl] Rawmidi_write %s\n",name); // Map only if not on the original hardware if ( MPCId != MPCOriginalId && ( rawmidi == rawvirt_outpriv || rawmidi == rawvirt_outpub ) ) { Map_AppWriteToMPC(buffer,size); } if ( rawMidiDumpPostFlag ) { const char *name = snd_rawmidi_name(rawmidi); fprintf(stdout,"[tkgl] POST Dump snd_rawmidi_write to controller %s\n",name); ShowBufferHexDump(buffer, size,16); fprintf(stdout,"[tkgl]\n"); } return orig_snd_rawmidi_write(rawmidi, buffer, size); } /////////////////////////////////////////////////////////////////////////////// // Alsa open sequencer /////////////////////////////////////////////////////////////////////////////// int snd_seq_open (snd_seq_t **handle, const char *name, int streams, int mode) { fprintf(stdout,"[tkgl] snd_seq_open %s (%p) \n",name,handle); return orig_snd_seq_open(handle, name, streams, mode); } /////////////////////////////////////////////////////////////////////////////// // Alsa set a seq port name /////////////////////////////////////////////////////////////////////////////// void snd_seq_port_info_set_name ( snd_seq_port_info_t * info, const char * name ) { fprintf(stdout,"[tkgl] snd_seq_port_info_set_name %s (%p) \n",name); return snd_seq_port_info_set_name ( info, name ); } /////////////////////////////////////////////////////////////////////////////// // Alsa create a simple seq port /////////////////////////////////////////////////////////////////////////////// int snd_seq_create_simple_port ( snd_seq_t * seq, const char * name, unsigned int caps, unsigned int type ) { //fprintf(stdout,"[tkgl] Port creation of %s\n",name); // Rename virtual port correctly. Impossible with the native Alsa... if ( strncmp (" Virtual RawMIDI",name,16) && snd_seq_virtual_port_rename_flag ) { //fprintf(stdout,"[tkgl] Virtual port renamed to %s \n",snd_seq_virtual_port_newname); snd_seq_virtual_port_rename_flag = 0; int r = orig_snd_seq_create_simple_port(seq,snd_seq_virtual_port_newname,caps,type); if ( r < 0 ) return r; // Get port information snd_seq_port_info_t *pinfo; snd_seq_port_info_alloca(&pinfo); snd_seq_get_port_info(seq, 0, pinfo); snd_seq_virtual_port_clientid = snd_seq_port_info_get_client(pinfo); return r; } // We do not allow ports creation by MPC app for our device or our virtuals ports // Because this could lead to infinite midi loop in the MPC midi end user settings if ( ( seqanyctrl_client >= 0 && strstr(name, anyctrl_name ) ) //|| ( match(name,"^Client-[0-9][0-9][0-9] TKGL.*" ) ) // In some specific cases, public and private ports could appear in the APP when spoofing, // because port names haven't the same prefixes (eg. Force vs MPC). The consequence is // that the MPC App receives midi message of buttons and encoders in midi tracks. // So we mask here Private and Public ports eventually requested by MPC App, which // should be only internal rawmidi ports. // This match will also catch our TKGL virtual ports having Private or Public suffix. || ( ( match(name,".* Public$|.* Private$" )) ) ) { fprintf(stdout,"[tkgl] Port %s creation canceled.\n",name); return -1; } return orig_snd_seq_create_simple_port(seq,name,caps,type); } /////////////////////////////////////////////////////////////////////////////// // Clean dump of a midi seq event /////////////////////////////////////////////////////////////////////////////// static void dump_event(const snd_seq_event_t *ev) { printf("%3d:%-3d ", ev->source.client, ev->source.port); switch (ev->type) { case SND_SEQ_EVENT_NOTEON: printf("Note on %2d %3d %3d\n", ev->data.note.channel, ev->data.note.note, ev->data.note.velocity); break; case SND_SEQ_EVENT_NOTEOFF: printf("Note off %2d %3d %3d\n", ev->data.note.channel, ev->data.note.note, ev->data.note.velocity); break; case SND_SEQ_EVENT_KEYPRESS: printf("Polyphonic aftertouch %2d %3d %3d\n", ev->data.note.channel, ev->data.note.note, ev->data.note.velocity); break; case SND_SEQ_EVENT_CONTROLLER: printf("Control change %2d %3d %3d\n", ev->data.control.channel, ev->data.control.param, ev->data.control.value); break; case SND_SEQ_EVENT_PGMCHANGE: printf("Program change %2d %3d\n", ev->data.control.channel, ev->data.control.value); break; case SND_SEQ_EVENT_CHANPRESS: printf("Channel aftertouch %2d %3d\n", ev->data.control.channel, ev->data.control.value); break; case SND_SEQ_EVENT_PITCHBEND: printf("Pitch bend %2d %6d\n", ev->data.control.channel, ev->data.control.value); break; case SND_SEQ_EVENT_CONTROL14: printf("Control change %2d %3d %5d\n", ev->data.control.channel, ev->data.control.param, ev->data.control.value); break; case SND_SEQ_EVENT_NONREGPARAM: printf("Non-reg. parameter %2d %5d %5d\n", ev->data.control.channel, ev->data.control.param, ev->data.control.value); break; case SND_SEQ_EVENT_REGPARAM: printf("Reg. parameter %2d %5d %5d\n", ev->data.control.channel, ev->data.control.param, ev->data.control.value); break; case SND_SEQ_EVENT_SONGPOS: printf("Song position pointer %5d\n", ev->data.control.value); break; case SND_SEQ_EVENT_SONGSEL: printf("Song select %3d\n", ev->data.control.value); break; case SND_SEQ_EVENT_QFRAME: printf("MTC quarter frame %02xh\n", ev->data.control.value); break; case SND_SEQ_EVENT_TIMESIGN: // XXX how is this encoded? printf("SMF time signature (%#08x)\n", ev->data.control.value); break; case SND_SEQ_EVENT_KEYSIGN: // XXX how is this encoded? printf("SMF key signature (%#08x)\n", ev->data.control.value); break; case SND_SEQ_EVENT_START: if (ev->source.client == SND_SEQ_CLIENT_SYSTEM && ev->source.port == SND_SEQ_PORT_SYSTEM_TIMER) printf("Queue start %d\n", ev->data.queue.queue); else printf("Start\n"); break; case SND_SEQ_EVENT_CONTINUE: if (ev->source.client == SND_SEQ_CLIENT_SYSTEM && ev->source.port == SND_SEQ_PORT_SYSTEM_TIMER) printf("Queue continue %d\n", ev->data.queue.queue); else printf("Continue\n"); break; case SND_SEQ_EVENT_STOP: if (ev->source.client == SND_SEQ_CLIENT_SYSTEM && ev->source.port == SND_SEQ_PORT_SYSTEM_TIMER) printf("Queue stop %d\n", ev->data.queue.queue); else printf("Stop\n"); break; case SND_SEQ_EVENT_SETPOS_TICK: printf("Set tick queue pos. %d\n", ev->data.queue.queue); break; case SND_SEQ_EVENT_SETPOS_TIME: printf("Set rt queue pos. %d\n", ev->data.queue.queue); break; case SND_SEQ_EVENT_TEMPO: printf("Set queue tempo %d\n", ev->data.queue.queue); break; case SND_SEQ_EVENT_CLOCK: printf("Clock\n"); break; case SND_SEQ_EVENT_TICK: printf("Tick\n"); break; case SND_SEQ_EVENT_QUEUE_SKEW: printf("Queue timer skew %d\n", ev->data.queue.queue); break; case SND_SEQ_EVENT_TUNE_REQUEST: /* something's fishy here ... */ printf("Tuna request\n"); break; case SND_SEQ_EVENT_RESET: printf("Reset\n"); break; case SND_SEQ_EVENT_SENSING: printf("Active Sensing\n"); break; case SND_SEQ_EVENT_CLIENT_START: printf("Client start %d\n", ev->data.addr.client); break; case SND_SEQ_EVENT_CLIENT_EXIT: printf("Client exit %d\n", ev->data.addr.client); break; case SND_SEQ_EVENT_CLIENT_CHANGE: printf("Client changed %d\n", ev->data.addr.client); break; case SND_SEQ_EVENT_PORT_START: printf("Port start %d:%d\n", ev->data.addr.client, ev->data.addr.port); break; case SND_SEQ_EVENT_PORT_EXIT: printf("Port exit %d:%d\n", ev->data.addr.client, ev->data.addr.port); break; case SND_SEQ_EVENT_PORT_CHANGE: printf("Port changed %d:%d\n", ev->data.addr.client, ev->data.addr.port); break; case SND_SEQ_EVENT_PORT_SUBSCRIBED: printf("Port subscribed %d:%d -> %d:%d\n", ev->data.connect.sender.client, ev->data.connect.sender.port, ev->data.connect.dest.client, ev->data.connect.dest.port); break; case SND_SEQ_EVENT_PORT_UNSUBSCRIBED: printf("Port unsubscribed %d:%d -> %d:%d\n", ev->data.connect.sender.client, ev->data.connect.sender.port, ev->data.connect.dest.client, ev->data.connect.dest.port); break; case SND_SEQ_EVENT_SYSEX: { unsigned int i; printf("System exclusive "); for (i = 0; i < ev->data.ext.len; ++i) printf(" %02X", ((unsigned char*)ev->data.ext.ptr)[i]); printf("\n"); } break; default: printf("Event type %d\n", ev->type); } } /////////////////////////////////////////////////////////////////////////////// // Process an input midi seq event /////////////////////////////////////////////////////////////////////////////// int snd_seq_event_input( snd_seq_t* handle, snd_seq_event_t** ev ) { int r = orig_snd_seq_event_input(handle,ev); // if ((*ev)->type != SND_SEQ_EVENT_CLOCK ) { // dump_event(*ev); // // // // fprintf(stdout,"[tkgl] Src = %02d:%02d -> Dest = %02d:%02d \n",(*ev)->source.client,(*ev)->source.port,(*ev)->dest.client,(*ev)->dest.port); // // ShowBufferHexDump(buf, r,16); // // fprintf(stdout,"[tkgl] ----------------------------------\n"); // } return r; } /////////////////////////////////////////////////////////////////////////////// // Decode a midi seq event /////////////////////////////////////////////////////////////////////////////// long snd_midi_event_decode ( snd_midi_event_t * dev,unsigned char * buf,long count, const snd_seq_event_t * ev ) { // Disable running status to be a true "raw" midi. Side effect : disabled for all ports... snd_midi_event_no_status(dev,1); long r = orig_snd_midi_event_decode(dev,buf,count,ev); // if (r > 0) { // if (ev->type != SND_SEQ_EVENT_CLOCK ) { // // dump_event(ev); // // // fprintf(stdout,"[tkgl] Src = %02d:%02d -> Dest = %02d:%02d \n",ev->source.client,ev->source.port,ev->dest.client,ev->dest.port); // ShowBufferHexDump(buf, r,16); // fprintf(stdout,"[tkgl] ----------------------------------\n"); // } // // } return r ; } /////////////////////////////////////////////////////////////////////////////// // open64 /////////////////////////////////////////////////////////////////////////////// // We intercept all file opening until we found inmusic,product-code in the path. // We could do the same for serial number, or panel/touch orientaton. int open64(const char *pathname, int flags,...) { int r; // printf("(tkgl) Open64 %s\n",pathname); // If O_CREAT is used to create a file, the file access mode must be given. if (flags & O_CREAT) { va_list args; va_start(args, flags); int mode = va_arg(args, int); va_end(args); r = orig_open64(pathname, flags, mode); } else { r = orig_open64(pathname, flags); } // Specific part if ( product_code_file_handler < 0 && strcmp(pathname,PRODUCT_CODE_PATH) == 0 ) { // Save the product code file descriptor product_code_file_handler = r; } return r ; } /////////////////////////////////////////////////////////////////////////////// // open /////////////////////////////////////////////////////////////////////////////// int open(const char *pathname, int flags,...) { // printf("(tkgl) Open %s\n",pathname); // If O_CREAT is used to create a file, the file access mode must be given. if (flags & O_CREAT) { va_list args; va_start(args, flags); int mode = va_arg(args, int); va_end(args); return orig_open(pathname, flags, mode); } else { return orig_open(pathname, flags); } } /////////////////////////////////////////////////////////////////////////////// // read /////////////////////////////////////////////////////////////////////////////// ssize_t read(int fildes, void *buf, size_t nbyte) { // Not yet if ( product_code_file_handler < 0 ) return orig_read(fildes,buf,nbyte); // If we got the file descriptor, we can swap the product code with the spoofed one. if ( fildes == product_code_file_handler ) { memcpy(buf,DeviceInfoBloc[MPCId].productCode,nbyte ); product_code_file_handler = -1; return nbyte; } }
the_stack_data/103090.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #define NAZIV_MAX 14 #define VRSTA_MAX 10 typedef struct namirnica_st { char naziv[NAZIV_MAX]; unsigned int kolicina_vit; char vrsta[VRSTA_MAX]; struct namirnica_st* levi; struct namirnica_st* desni; } NAMIRNICA; FILE* safe_open(char* f_name, char* mode) { FILE* f = fopen(f_name, mode); if(f == NULL) { printf("Greška pri otvaranju datoteke %s\n", f_name); exit(EXIT_FAILURE); } return f; } NAMIRNICA* napravi_elem(char* n, unsigned int k, char* v) { NAMIRNICA* novi = malloc(sizeof(NAMIRNICA)); strcpy(novi->naziv, n); novi->kolicina_vit = k; strcpy(novi->vrsta, v); novi->levi = NULL; novi->desni = NULL; return novi; } void dodaj_elem(NAMIRNICA** pkoren, NAMIRNICA* novi) { if(*pkoren == NULL) { *pkoren = novi; return; } if((*pkoren)->kolicina_vit > novi->kolicina_vit) { dodaj_elem(&(*pkoren)->levi, novi); } else if((*pkoren)->kolicina_vit <= novi->kolicina_vit) { dodaj_elem(&(*pkoren)->desni, novi); } } void ucitaj(FILE* fin, NAMIRNICA** pkoren) { char n[NAZIV_MAX], v[VRSTA_MAX]; unsigned int k; while(fscanf(fin, "%s %u %s", n, &k, v) != EOF) { NAMIRNICA* novi = napravi_elem(n, k, v); dodaj_elem(pkoren, novi); } } void ispisi(FILE* fout, NAMIRNICA* pkoren) { if(pkoren == NULL) { return; } // Reverse In-order ispisi(fout, pkoren->desni); fprintf(fout, "%3u %-13s %s\n", pkoren->kolicina_vit, pkoren->naziv, pkoren->vrsta); ispisi(fout, pkoren->levi); } void pronadji(FILE* fout, NAMIRNICA* pkoren) { if(pkoren->desni == NULL) { fprintf(fout, "\nNamirnica sa najviše vitamina C je: \n"); fprintf(fout, "%3u %-13s %s\n", pkoren->kolicina_vit, pkoren->naziv, pkoren->vrsta); return; } pronadji(fout, pkoren->desni); } void obrisi_stablo(NAMIRNICA** pkoren) { if(*pkoren == NULL) { return; } obrisi_stablo(&(*pkoren)->levi); obrisi_stablo(&(*pkoren)->desni); free(*pkoren); *pkoren = NULL; } int main(int argc, char* argv[]) { NAMIRNICA* pkoren = NULL; if(argc != 3) { printf("Greška pri unosu sa komandne linije!\n"); exit(EXIT_FAILURE); } FILE* fin = fopen(argv[1], "r"); ucitaj(fin, &pkoren); fclose(fin); FILE* fout = fopen(argv[2], "w"); ispisi(fout, pkoren); pronadji(fout, pkoren); fclose(fout); obrisi_stablo(&pkoren); return 0; }
the_stack_data/51701362.c
/* { dg-do compile } */ /* { dg-options "-fdiagnostics-format=json -Wmisleading-indentation" } */ int test (void) { if (1) return 3; return 4; return 5; } /* Use dg-regexp to consume the JSON output starting with the innermost values, and working outwards. We can't rely on any ordering of the keys. */ /* Verify nested diagnostics. */ /* The nested diagnostic. */ /* { dg-regexp "\"kind\": \"note\"" } */ /* { dg-regexp "\"message\": \"...this statement, but the latter is misleadingly indented as if it were guarded by the 'if'\"" } */ /* { dg-regexp "\"caret\": \{" } */ /* { dg-regexp "\"file\": \"\[^\n\r\"\]*diagnostic-format-json-4.c\"" } */ /* { dg-regexp "\"line\": 8" } */ /* { dg-regexp "\"column\": 5" } */ /* { dg-regexp "\"display-column\": 5" } */ /* { dg-regexp "\"byte-column\": 5" } */ /* { dg-regexp "\"finish\": \{" } */ /* { dg-regexp "\"file\": \"\[^\n\r\"\]*diagnostic-format-json-4.c\"" } */ /* { dg-regexp "\"line\": 8" } */ /* { dg-regexp "\"column\": 10" } */ /* { dg-regexp "\"display-column\": 10" } */ /* { dg-regexp "\"byte-column\": 10" } */ /* The outer diagnostic. */ /* { dg-regexp "\"kind\": \"warning\"" } */ /* { dg-regexp "\"column-origin\": 1" } */ /* { dg-regexp "\"message\": \"this 'if' clause does not guard...\"" } */ /* { dg-regexp "\"option\": \"-Wmisleading-indentation\"" } */ /* { dg-regexp "\"option_url\": \"https:\[^\n\r\"\]*#index-Wmisleading-indentation\"" } */ /* { dg-regexp "\"caret\": \{" } */ /* { dg-regexp "\"file\": \"\[^\n\r\"\]*diagnostic-format-json-4.c\"" } */ /* { dg-regexp "\"line\": 6" } */ /* { dg-regexp "\"column\": 3" } */ /* { dg-regexp "\"display-column\": 3" } */ /* { dg-regexp "\"byte-column\": 3" } */ /* { dg-regexp "\"finish\": \{" } */ /* { dg-regexp "\"file\": \"\[^\n\r\"\]*diagnostic-format-json-4.c\"" } */ /* { dg-regexp "\"line\": 6" } */ /* { dg-regexp "\"column\": 4" } */ /* { dg-regexp "\"display-column\": 4" } */ /* { dg-regexp "\"byte-column\": 4" } */ /* More from the nested diagnostic (we can't guarantee what order the "file" keys are consumed). */ /* { dg-regexp "\"locations\": \[\[\{\}, \]*\]" } */ /* More from the outer diagnostic. */ /* { dg-regexp "\"locations\": \[\[\{\}, \]*\]" } */ /* { dg-regexp "\"children\": \[\[\{\}, \]*\]" } */ /* { dg-regexp "\[\[\{\}, \]*\]" } */
the_stack_data/61230.c
/* * Copyright (C) 2017 XRADIO TECHNOLOGY CO., LTD. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * 3. Neither the name of XRADIO TECHNOLOGY CO., LTD. nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdint.h> #include <stddef.h> #define MEM_UNALIGNED(addr) ((uint32_t)(addr) & 0x3) __attribute__ ((__optimize__ ("-O2"))) void *__wrap_memset(void *s, int c, size_t n) { uint8_t *ptr = (uint8_t *)s; while (MEM_UNALIGNED(ptr)) { if (n--) { *ptr++ = (uint8_t)c; } else { return s; } } if (n >= 4) { uint32_t *ptr_aligned = (uint32_t *)ptr; uint32_t val = c & 0xff; val |= (val << 8); val |= (val << 16); while (n >= 4 * 4) { *ptr_aligned++ = val; *ptr_aligned++ = val; *ptr_aligned++ = val; *ptr_aligned++ = val; n -= 4 * 4; } while (n >= 4) { *ptr_aligned++ = val; n -= 4; } ptr = (uint8_t *)ptr_aligned; } while (n--) { *ptr++ = (uint8_t)c; } return s; }
the_stack_data/46576.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <sys/ioctl.h> #define WR_VALUE _IOW('a', 1,int32_t*) #define RD_VALUE _IOR('a', 2,int32_t*) int main() { int fd; int32_t value, number; printf("\nOpening Driver\n"); fd = open("/dev/killa", O_RDWR); if(fd < 0) { printf("Cannot open device file...\n"); return 0; } printf("Enter the Value to send\n"); scanf("%d",&number); printf("Writing Value to Driver\n"); ioctl(fd, WR_VALUE, (int32_t*) &number); printf("Reading Value from Driver\n"); ioctl(fd, RD_VALUE, (int32_t*) &value); printf("Value is %d\n", value); printf("Closing Driver\n"); close(fd); }
the_stack_data/187643051.c
#include <stdio.h> #include <omp.h> /* If the OMP_NUM_THREADS variable is set to 8 with */ /* export OMP_NUM_THREADS=8 */ /* Q1: Is the execution of the program correct? Add a */ /* data sharing clause to make it correct */ /* Q2: Are the lines always printed in the same order? */ /* Could the messages appear intermixed? */ int main () { int id; #pragma omp parallel { #pragma omp critical { id =omp_get_thread_num(); printf("(%d) Hello ",id); printf("(%d) world!\n",id); } } return 0; }
the_stack_data/126703193.c
#include <stdio.h> #include <stdlib.h> // Exercício 2 void swapM (int *x, int *y) { int temp = *x; *x = *y; *y = temp; } // Exercício 3 void swap (int v[], int i, int j) { int temp = v[i]; v[i] = v[j]; v[j] = temp; } // Exercício 4 int soma (int v[], int N) { int resultado = 0, i; for (i = 0; i < N; i++) { resultado += v[i]; } return resultado; } // Exercício 5 void inverteArray (int v[], int N){ int i; for (i = 0; i < N / 2; i++) { swapM (&v[i], &v[N - i - 1]); } } void inverteArray2 (int v[], int N){ int i; for (i = 0; i < N / 2; i++) { swap (v, i, N - i - 1); } } // Exercício 6 int maximum (int v[], int N, int *m) { if (N <= 0) return 1; else { int i; *m = v[0]; for (i = 0; i < N; i++) { if (v[i] > *m) *m = v[i]; return 0; } } } // Exercício 7 void quadrados (int q[], int N) { int i; for (i = 0; i < N; i++) { q[i] = (i + 1)*(i + 1); } } // Exercício 8 a) void pascal(int v[], int N) { int i,j; for (i = 0; i < N+1; i++) { v[i] = 1; for (j = 1; j < i; j++) { v[i - j] = v[i - j] + v[i - j - 1]; } } } // Exercício 8 b) void desenhaTriangulpP (int N){ int i,j, v[N]; for (i = 0; i < N+1; i++) { v[i] = 1; for (j = 1; j < i; j++) { v[i - j] = v[i - j] + v[i - j - 1]; } for (j = 0; j <= i; j++) { printf("%6d", v[j]); } putchar('\n'); } } main () { }
the_stack_data/168894330.c
/* EX3_2.C ======= Suggested solution to Exercise 3-2 */ #include <stdio.h> void escape(char * s, char * t); void unescape(char * s, char * t); int main(void) { char text1[50] = "\aHello,\n\tWorld! Mistakee\b was \"Extra 'e'\"!\n"; char text2[51]; printf("Original string:\n%s\n", text1); escape(text2, text1); printf("Escaped string:\n%s\n", text2); unescape(text1, text2); printf("Unescaped string:\n%s\n", text1); return 0; } /* Copies string t to string s, converting special characters into their appropriate escape sequences. The "complete set of escape sequences" found in K&R Chapter 2 is used, with the exception of: \? \' \ooo \xhh as these can be typed directly into the source code, (i.e. without using the escape sequences themselves) and translating them is therefore ambiguous. */ void escape(char * s, char * t) { int i, j; i = j = 0; while ( t[i] ) { /* Translate the special character, if we have one */ switch( t[i] ) { case '\n': s[j++] = '\\'; s[j] = 'n'; break; case '\t': s[j++] = '\\'; s[j] = 't'; break; case '\a': s[j++] = '\\'; s[j] = 'a'; break; case '\b': s[j++] = '\\'; s[j] = 'b'; break; case '\f': s[j++] = '\\'; s[j] = 'f'; break; case '\r': s[j++] = '\\'; s[j] = 'r'; break; case '\v': s[j++] = '\\'; s[j] = 'v'; break; case '\\': s[j++] = '\\'; s[j] = '\\'; break; case '\"': s[j++] = '\\'; s[j] = '\"'; break; default: /* This is not a special character, so just copy it */ s[j] = t[i]; break; } ++i; ++j; } s[j] = t[i]; /* Don't forget the null character */ } /* Copies string t to string s, converting escape sequences into their appropriate special characters. See the comment for escape() for remarks regarding which escape sequences are translated. */ void unescape(char * s, char * t) { int i, j; i = j = 0; while ( t[i] ) { switch ( t[i] ) { case '\\': /* We've found an escape sequence, so translate it */ switch( t[++i] ) { case 'n': s[j] = '\n'; break; case 't': s[j] = '\t'; break; case 'a': s[j] = '\a'; break; case 'b': s[j] = '\b'; break; case 'f': s[j] = '\f'; break; case 'r': s[j] = '\r'; break; case 'v': s[j] = '\v'; break; case '\\': s[j] = '\\'; break; case '\"': s[j] = '\"'; break; default: /* We don't translate this escape sequence, so just copy it verbatim */ s[j++] = '\\'; s[j] = t[i]; } break; default: /* Not an escape sequence, so just copy the character */ s[j] = t[i]; } ++i; ++j; } s[j] = t[i]; /* Don't forget the null character */ }
the_stack_data/81776.c
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ____ ___ __ _ // / __// o |,'_/ .' \ // / _/ / _,'/ /_n / o / _ __ _ ___ _ _ __ // /_/ /_/ |__,'/_n_/ / \,' /.' \ ,' _/,' \ / |/ / // / \,' // o /_\ `./ o // || / // /_/ /_//_n_//___,'|_,'/_/|_/ // //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Author : Wesley Taylor-Rendal (WTR) // Design history : Review git logs. // Description : Modify Program 10.7 and 10.8 countWord function. // Concepts : You can change the bounds of what is acceptable before // : reseting a flag //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #include <stdio.h> #include <stdbool.h> bool alphabetic(const char c) { if ( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ) return true; else return false; } bool numeric(const char c) { if (c >= '0' && c <= '9') return true; else return false; } bool special(const char c) { if (c >= '!' && c <= '/') // ascii table 33 to 47, could add :, ;, etc. return true; else return false; } bool wordContinues(const char c) { if (alphabetic(c) || numeric(c) || special(c)) return true; else return false; } void readLine (char buffer[]) { char character; int i=0; do { character = getchar (); buffer[i] = character; ++i; } while (character != '\n'); buffer[i-1] = '\0'; // terminating char } int countWords (const char string[]) { int i, wordCount = 0; bool lookingForWord = true, wordContinues (const char c); for (i = 0; string[i] != '\0'; ++i) if (wordContinues(string[i]) ) { if (lookingForWord) { ++wordCount; lookingForWord = false; } } else lookingForWord = true; return wordCount; } int main(void) { char text[81]; int totalWords = 0; int countWords (const char string[]); void readLine (char buffer[]) ; bool endOfText=false; printf("Type in your text.\n"); printf("When you are done, please press 'RETURN'.\n\n"); while (!endOfText) { readLine(text); if (text[0] == '\0') // null string text="" endOfText = true; else totalWords += countWords(text); // Add words from current line to total. } printf("\n"); printf("There are %i words in the above text. \n", totalWords); return 0; }
the_stack_data/122015774.c
#include<stdio.h> int main(void) { int x = 100, y = 10; printf("Valor inicial de x: %d \n",x); /* x++ equivale a fazer x = x + 1; ++x também equivale a fazer x = x + 1; Então qual a diferença entre os dois comandos? */ printf("\n-------------------- Pos-incremento --------------------- \n\n"); printf("Valor de x na mesma linha do pos-incremento: %d \n",x++); //vai exibir 100 printf("Valor de x na linha seguinte ao pos-incremento: %d \n",x); //vai exibir 101 printf("\n-------------------- Pre-incremento --------------------- \n\n"); printf("Valor de x na mesma linha do pre-incremento: %d \n",++x); //vai exibir 102 printf("Valor inicial de y: %d \n",y);//nesta linha vai exibir 10 printf("\n-------------------- Pos-decremento --------------------- \n\n"); printf("Valor de y na mesma linha do pos-decremento: %d \n",y--); //vai exibir 10 printf("Valor de y na linha seguinte ao pos-decremento: %d \n",y); //vai exibir 9 printf("\n-------------------- Pre-decremento --------------------- \n\n"); printf("Valor de y na mesma linha do pre-decremento: %d \n",--y); //vai exibir 8 return 0; }
the_stack_data/211080020.c
#include <stdio.h> int main(void){ int n, m; int d[251][251] = {0}; for(int i=1;i<=250;i++) for(int j=1;j<=250;j++) if(i!=j) d[i][j] = 99999999; scanf("%d %d", &n, &m); for(int i=0;i<m;i++){ int u, v, b; scanf("%d %d %d", &u, &v, &b); d[u][v] = 1; d[v][u] = 1000; if(b) d[v][u] = 1; } for(int k=1;k<=n;k++) for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) if(d[i][j] > d[i][k]+d[k][j]) d[i][j] = d[i][k] + d[k][j]; int k; scanf("%d", &k); for(int i=0;i<k;i++){ int s, e; scanf("%d %d", &s, &e); printf("%d\n", d[s][e]/1000); } return 0; }
the_stack_data/145453820.c
/* This is third-party software that is distributed with UTILIB. * For licensing information concerning this file, see the UTILIB home page: * http://software.sandia.gov/trac/utilib */ /* gengam.c * */ #ifdef HAVE_FSIGN #include <utilib_config.h> #include <math.h> #include <utilib/Random.h> double gengam(double a,double r) /* ********************************************************************** double gengam(double a,double r) GENerates random deviates from GAMma distribution Function Generates random deviates from the gamma distribution whose density is (A**R)/Gamma(R) * X**(R-1) * Exp(-A*X) Arguments a --> Location parameter of Gamma distribution r --> Shape parameter of Gamma distribution Method Renames SGAMMA from TOMS as slightly modified by BWB to use RANF instead of SUNIF. For details see: (Case R >= 1.0) Ahrens, J.H. and Dieter, U. Generating Gamma Variates by a Modified Rejection Technique. Comm. ACM, 25,1 (Jan. 1982), 47 - 54. Algorithm GD (Case 0.0 <= R <= 1.0) Ahrens, J.H. and Dieter, U. Computer Methods for Sampling from Gamma, Beta, Poisson and Binomial Distributions. Computing, 12 (1974), 223-246/ Adapted algorithm GS. ********************************************************************** */ { static double gengam; gengam = sgamma(r); gengam /= a; return gengam; } #endif
the_stack_data/234516952.c
/* Copyright (C) 2019-2022 Free Software Foundation, Inc. This file is part of GNU Binutils. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. */ /* This file generates a number of DLL (PE/COFF binaries traditionally used on Windows) that we can then utilize in various tests to ensure objdump can parse these file correctly. See: https://www.ecma-international.org/publications/files/ECMA-ST/ECMA-335.pdf */ #include <memory.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #define INCORRECT_USAGE 2 #define IO_ERROR 3 static void write_dos_header_and_stub (FILE* file) { /* See ECMA-335 II.25.2.1. Instead of lfanew, lets just hardcode the offset of the next byte after this header (0x80). */ char buffer[128] = { 0x4d, 0x5a, 0x90, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, /* Last 4 bytes are precomputed lfanew. */ 0x0e, 0x1f, 0xba, 0x0e, 0x00, 0xb4, 0x09, 0xcd, 0x21, 0xb8, 0x01, 0x4c, 0xcd, 0x21, 0x54, 0x68, 0x69, 0x73, 0x20, 0x70, 0x72, 0x6f, 0x67, 0x72, 0x61, 0x6d, 0x20, 0x63, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x20, 0x62, 0x65, 0x20, 0x72, 0x75, 0x6e, 0x20, 0x69, 0x6e, 0x20, 0x44, 0x4f, 0x53, 0x20, 0x6d, 0x6f, 0x64, 0x65, 0x2e, 0x0d, 0x0d, 0x0a, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; fwrite (buffer, 1, 128, file); } static void write_pe_signature (FILE* file) { char buffer[4]; buffer[0] = 'P'; buffer[1] = 'E'; buffer[2] = 0; buffer[3] = 0; fwrite (buffer, 1, 4, file); } static void write_coff_header (FILE* file, uint16_t machine) { char buffer[128]; memset (buffer, 0, sizeof (buffer)); /* Machine. ECMA-335 says this must be 0x14c but that's not true anymore. */ buffer[0] = machine & 0xff; buffer[1] = machine >> 0x8; fwrite (buffer, 2, 1, file); memset (buffer, 0, sizeof (buffer)); /* NumberOfSections = 0. */ fwrite (buffer, 2, 1, file); /* TimeDateStamp = 0. */ fwrite (buffer, 4, 1, file); /* PointerToSymbolTable = 0. */ fwrite (buffer, 4, 1, file); /* NumberOfSymbols = 0. */ fwrite (buffer, 4, 1, file); /* OptionalHeaderSize = 0. */ fwrite (buffer, 2, 1, file); /* Characteristics = 0x2000. */ buffer[0] = 0x00; buffer[1] = 0x20; fwrite (buffer, 2, 1, file); memset (buffer, 0 , sizeof (buffer)); } static void write_simple_dll (const char* name, uint16_t machine) { FILE* file = fopen (name, "w"); if (file == NULL) { fprintf (stderr, "error: unable to open file for writing\n"); exit (IO_ERROR); } write_dos_header_and_stub (file); write_pe_signature (file); write_coff_header (file, machine); fclose (file); file = NULL; printf ("wrote %s\n", name); } int main (int argc, char** argv) { char* program_name = argv[0]; char* output_directory = argv[1]; int i; if (argc < 3) { fprintf (stderr, "usage: %s output-directory format [format ...] \n\n", program_name); fprintf (stderr, "format is an objdump-style format string, like pei-i386\n"); exit (INCORRECT_USAGE); } if (chdir (output_directory) != 0) { fprintf (stderr, "error: unable to change directory to %s\n", output_directory); exit (INCORRECT_USAGE); } /* We generate a simple PEI format files, and then .NET Core on Linux-style PEI files for a number of architectures. As opposed to the more common PEI files that contain bytecode (CIL/MSIL), many .NET Core DLLs are pre-compiled for specific architectures and platforms. See https://github.com/jbevain/cecil/issues/337 for an example of this value being used in practice. */ for (i = 2; i < argc; i++) { char* wanted_format = argv[i]; if (strcmp ("pei-i386", wanted_format) == 0) { write_simple_dll ("simple-pei-i386.dll", 0x14c); write_simple_dll ("linux-pei-i386.dll", 0x14c ^ 0x7b79 /* i386 + Linux */); } else if (strcmp ("pei-x86-64", wanted_format) == 0) { write_simple_dll ("simple-pei-x86-64.dll", 0x8664); write_simple_dll ("linux-pei-x86-64.dll", 0x8664 ^ 0x7b79 /* x86-64 + Linux */); } else { fprintf (stderr, "error: can't handle format %s\n", wanted_format); exit (INCORRECT_USAGE); } } return 0; }
the_stack_data/115766356.c
#include <stdio.h> void convertRoman(int number) { int num[] = {1,4,5,9,10,40,50,90,100,400,500,900,1000}; char* sym[] = {"I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M"}; int i=12; while(number>0) { int div = number/num[i]; number = number%num[i]; while(div--) { printf(sym[i]); } i--; } } int main() { int number; scanf("%d",&number); convertRoman(number); return 0; }
the_stack_data/215768145.c
extern void __VERIFIER_error() __attribute__ ((__noreturn__)); #include <pthread.h> void __VERIFIER_assert(int expression) { if (!expression) { ERROR: __VERIFIER_error();}; return; } int i=1, j=1; #define NUM 11 void * t1(void* arg) { int k = 0; for (k = 0; k < NUM; k++) i+=j; pthread_exit(NULL); } void * t2(void* arg) { int k = 0; for (k = 0; k < NUM; k++) j+=i; pthread_exit(NULL); } int main(int argc, char **argv) { pthread_t id1, id2; pthread_create(&id1, NULL, t1, NULL); pthread_create(&id2, NULL, t2, NULL); pthread_join(id1, NULL); pthread_join(id2, NULL); if (i >= 46368 || j >= 46368) { ERROR: __VERIFIER_error(); } return 0; }
the_stack_data/138841.c
/*************************************** * EECS2031AC – Lab3 * * Author: Rahman, Mahfuz * * Email: [email protected] * * eecs_username: mafu * * York Student #: 217847518 ************************************** **/ #include <stdio.h> #include <stdlib.h> // for atoi #define SIZE 10 int my_atoi(char[], int); int power(int, int); int main(){ int b, base; char arr [SIZE]; printf("Enter a word of positive number and base, or 'quit': " ); scanf("%s %d", arr, &base); while(strcmp("quit", arr)) { printf("%s\n", arr); b = my_atoi(arr, base); printf("my_atoi: %d (%#o, %#X)\t%d\t%d\n", b,b,b, b*2, b*b); printf("\nEnter a word of positive number and base, or 'quit': " ); scanf("%s %d", arr, &base); } return 0; } /* convert an array of digit characters into a decimal int */ /* textbook scans from left to right. Here you should scan from right to left. This is a little complicated but more straightforward (IMHO) */ int my_atoi(char c[], int base) { int digit = 0; int i; int p = 0; int temp = 0; for (i = strlen(c)-1; i >= 0; i--) { temp = c[i] - '0'; digit += power(base, p) * temp; p++; temp = 0; } return digit;; } int power(int b, int p){ int i, j; j = 1; if (p != 0) { for (i = 1; i <= p; i++) { j = j * b; } } return j; }
the_stack_data/863611.c
#include<stdio.h> int main() { int a,i,j=0; long int x; scanf("%d",&a); for(i=0; i<a; i++){ scanf("%d",&x); if(x > 9 && x < 21){ j++; } } printf("%d in\n%d out\n",j,a-j); return 0; }
the_stack_data/844157.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_isascii.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: bgauci <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2013/11/20 16:48:19 by bgauci #+# #+# */ /* Updated: 2013/12/22 19:22:30 by bgauci ### ########.fr */ /* */ /* ************************************************************************** */ int ft_isascii(int c) { if (c >= 0 && c <= 127) return (1); else return (0); }
the_stack_data/29826068.c
// RUN: %clang -no-canonical-prefixes \ // RUN: -target aarch64-pc-freebsd11 %s \ // RUN: --sysroot=%S/Inputs/basic_freebsd64_tree -### 2>&1 \ // RUN: | FileCheck --check-prefix=CHECK-ARM64 %s // CHECK-ARM64: "-cc1" "-triple" "aarch64-pc-freebsd11" // CHECK-ARM64: ld{{.*}}" "--sysroot=[[SYSROOT:[^"]+]]" // CHECK-ARM64: "--eh-frame-hdr" "-dynamic-linker" "{{.*}}ld-elf{{.*}}" "-o" "a.out" "{{.*}}crt1.o" "{{.*}}crti.o" "{{.*}}crtbegin.o" "-L[[SYSROOT]]/usr/lib" "{{.*}}.o" "-lgcc" "--as-needed" "-lgcc_s" "--no-as-needed" "-lc" "-lgcc" "--as-needed" "-lgcc_s" "--no-as-needed" "{{.*}}crtend.o" "{{.*}}crtn.o" // // RUN: %clang -no-canonical-prefixes \ // RUN: -target powerpc-pc-freebsd8 %s \ // RUN: --sysroot=%S/Inputs/basic_freebsd_tree -### 2>&1 \ // RUN: | FileCheck --check-prefix=CHECK-PPC %s // CHECK-PPC: "-cc1" "-triple" "powerpc-pc-freebsd8" // CHECK-PPC: ld{{.*}}" "--sysroot=[[SYSROOT:[^"]+]]" // CHECK-PPC: "--eh-frame-hdr" "-dynamic-linker" "{{.*}}ld-elf{{.*}}" "-o" "a.out" "{{.*}}crt1.o" "{{.*}}crti.o" "{{.*}}crtbegin.o" "-L[[SYSROOT]]/usr/lib" "{{.*}}.o" "-lgcc" "--as-needed" "-lgcc_s" "--no-as-needed" "-lc" "-lgcc" "--as-needed" "-lgcc_s" "--no-as-needed" "{{.*}}crtend.o" "{{.*}}crtn.o" // // RUN: %clang -no-canonical-prefixes \ // RUN: -target powerpc64-pc-freebsd8 %s \ // RUN: --sysroot=%S/Inputs/basic_freebsd64_tree -### 2>&1 \ // RUN: | FileCheck --check-prefix=CHECK-PPC64 %s // CHECK-PPC64: "-cc1" "-triple" "powerpc64-pc-freebsd8" // CHECK-PPC64: ld{{.*}}" "--sysroot=[[SYSROOT:[^"]+]]" // CHECK-PPC64: "--eh-frame-hdr" "-dynamic-linker" "{{.*}}ld-elf{{.*}}" "-o" "a.out" "{{.*}}crt1.o" "{{.*}}crti.o" "{{.*}}crtbegin.o" "-L[[SYSROOT]]/usr/lib" "{{.*}}.o" "-lgcc" "--as-needed" "-lgcc_s" "--no-as-needed" "-lc" "-lgcc" "--as-needed" "-lgcc_s" "--no-as-needed" "{{.*}}crtend.o" "{{.*}}crtn.o" // // // Check that -m32 properly adjusts the toolchain flags. // // RUN: %clang -no-canonical-prefixes -target x86_64-pc-freebsd8 -m32 %s \ // RUN: --sysroot=%S/Inputs/multiarch_freebsd64_tree -### 2>&1 \ // RUN: | FileCheck --check-prefix=CHECK-LIB32 %s // CHECK-LIB32: "-cc1" "-triple" "i386-pc-freebsd8" // CHECK-LIB32: ld{{.*}}" {{.*}} "-m" "elf_i386_fbsd" // // RUN: %clang -target x86_64-pc-freebsd8 -m32 %s 2>&1 \ // RUN: --sysroot=%S/Inputs/multiarch_freebsd64_tree -print-search-dirs 2>&1 \ // RUN: | FileCheck --check-prefix=CHECK-LIB32PATHS %s // CHECK-LIB32PATHS: libraries: ={{.*:?}}/usr/lib32 // // Check that the new linker flags are passed to FreeBSD // RUN: %clang -no-canonical-prefixes -target x86_64-pc-freebsd8 -m32 %s \ // RUN: --sysroot=%S/Inputs/multiarch_freebsd64_tree -### 2>&1 \ // RUN: | FileCheck --check-prefix=CHECK-LDFLAGS8 %s // RUN: %clang -no-canonical-prefixes -target x86_64-pc-freebsd9 -m32 %s \ // RUN: --sysroot=%S/Inputs/multiarch_freebsd64_tree -### 2>&1 \ // RUN: | FileCheck --check-prefix=CHECK-LDFLAGS9 %s // RUN: %clang -no-canonical-prefixes -target x86_64-pc-freebsd10.0 -m32 %s \ // RUN: --sysroot=%S/Inputs/multiarch_freebsd64_tree -### 2>&1 \ // RUN: | FileCheck --check-prefix=CHECK-LDFLAGS9 %s // CHECK-LDFLAGS8-NOT: --hash-style=both // CHECK-LDFLAGS8: --enable-new-dtags // CHECK-LDFLAGS9: --hash-style=both // CHECK-LDFLAGS9: --enable-new-dtags // // Check that we do not pass --hash-style=gnu and --hash-style=both to linker // and provide correct path to the dynamic linker for MIPS platforms. // Also verify that we tell the assembler to target the right ISA and ABI. // RUN: %clang %s -### -o %t.o 2>&1 \ // RUN: -target mips-unknown-freebsd10.0 \ // RUN: | FileCheck --check-prefix=CHECK-MIPS %s // CHECK-MIPS: "{{[^" ]*}}ld{{[^" ]*}}" // CHECK-MIPS: "-dynamic-linker" "{{.*}}/libexec/ld-elf.so.1" // CHECK-MIPS-NOT: "--hash-style={{gnu|both}}" // RUN: %clang %s -### -o %t.o 2>&1 \ // RUN: -target mipsel-unknown-freebsd10.0 \ // RUN: | FileCheck --check-prefix=CHECK-MIPSEL %s // CHECK-MIPSEL: "{{[^" ]*}}ld{{[^" ]*}}" // CHECK-MIPSEL: "-dynamic-linker" "{{.*}}/libexec/ld-elf.so.1" // CHECK-MIPSEL-NOT: "--hash-style={{gnu|both}}" // RUN: %clang %s -### 2>&1 \ // RUN: -target mips64-unknown-freebsd10.0 \ // RUN: | FileCheck --check-prefix=CHECK-MIPS64 %s // CHECK-MIPS64: "{{[^" ]*}}ld{{[^" ]*}}" // CHECK-MIPS64: "-dynamic-linker" "{{.*}}/libexec/ld-elf.so.1" // CHECK-MIPS64-NOT: "--hash-style={{gnu|both}}" // RUN: %clang %s -### 2>&1 \ // RUN: -target mips64el-unknown-freebsd10.0 \ // RUN: | FileCheck --check-prefix=CHECK-MIPS64EL %s // CHECK-MIPS64EL: "{{[^" ]*}}ld{{[^" ]*}}" // CHECK-MIPS64EL: "-dynamic-linker" "{{.*}}/libexec/ld-elf.so.1" // CHECK-MIPS64EL-NOT: "--hash-style={{gnu|both}}" // RUN: %clang -no-canonical-prefixes -target x86_64-pc-freebsd8 -static %s \ // RUN: --sysroot=%S/Inputs/multiarch_freebsd64_tree -### 2>&1 \ // RUN: | FileCheck --check-prefix=CHECK-STATIC %s // CHECK-STATIC: crt1.o // CHECK-STATIC: crtbeginT.o // RUN: %clang -no-canonical-prefixes -target x86_64-pc-freebsd8 -shared %s \ // RUN: --sysroot=%S/Inputs/multiarch_freebsd64_tree -### 2>&1 \ // RUN: | FileCheck --check-prefix=CHECK-SHARED %s // CHECK-SHARED: crti.o // CHECK-SHARED: crtbeginS.o // RUN: %clang -no-canonical-prefixes -target x86_64-pc-freebsd8 -pie %s \ // RUN: --sysroot=%S/Inputs/multiarch_freebsd64_tree -### 2>&1 \ // RUN: | FileCheck --check-prefix=CHECK-PIE %s // CHECK-PIE: pie // CHECK-PIE: Scrt1.o // CHECK-PIE: crtbeginS.o // RUN: %clang -no-canonical-prefixes -target x86_64-pc-freebsd8 %s \ // RUN: --sysroot=%S/Inputs/multiarch_freebsd64_tree -### 2>&1 \ // RUN: | FileCheck --check-prefix=CHECK-NORMAL %s // CHECK-NORMAL: crt1.o // CHECK-NORMAL: crtbegin.o // RUN: %clang %s -### -target arm-unknown-freebsd10.0 -no-integrated-as 2>&1 \ // RUN: | FileCheck --check-prefix=CHECK-ARM %s // CHECK-ARM: "-cc1"{{.*}}" "-fsjlj-exceptions" // CHECK-ARM: as{{.*}}" "-mfpu=softvfp"{{.*}}"-matpcs" // CHECK-ARM-EABI-NOT: as{{.*}}" "-mfpu=vfp" // RUN: %clang %s -### -target arm-gnueabi-freebsd10.0 -no-integrated-as 2>&1 \ // RUN: | FileCheck --check-prefix=CHECK-ARM-EABI %s // CHECK-ARM-EABI-NOT: "-cc1"{{.*}}" "-fsjlj-exceptions" // CHECK-ARM-EABI: as{{.*}}" "-mfpu=softvfp" "-meabi=5" // CHECK-ARM-EABI-NOT: as{{.*}}" "-mfpu=vfp" // CHECK-ARM-EABI-NOT: as{{.*}}" "-matpcs" // RUN: %clang %s -### -target arm-gnueabihf-freebsd10.0 -no-integrated-as 2>&1 \ // RUN: | FileCheck --check-prefix=CHECK-ARM-EABIHF %s // CHECK-ARM-EABIHF-NOT: "-cc1"{{.*}}" "-fsjlj-exceptions" // CHECK-ARM-EABIHF: as{{.*}}" "-mfpu=vfp" "-meabi=5" // CHECK-ARM-EABIHF-NOT: as{{.*}}" "-mfpu=softvfp" // CHECK-ARM-EABIHF-NOT: as{{.*}}" "-matpcs" // RUN: %clang -target x86_64-pc-freebsd8 %s -### -flto 2>&1 \ // RUN: | FileCheck --check-prefix=CHECK-LTO %s // CHECK-LTO: ld{{.*}}" "-plugin{{.*}}LLVMgold.so // RUN: %clang -target sparc-unknown-freebsd8 %s -### -fpic 2>&1 \ // RUN: | FileCheck --check-prefix=CHECK-SPARC-PIE %s // CHECK-SPARC-PIE: as{{.*}}" "-KPIC // RUN: %clang -mcpu=ultrasparc -target sparc64-unknown-freebsd8 %s -### 2>&1 \ // RUN: | FileCheck --check-prefix=CHECK-SPARC-CPU %s // CHECK-SPARC-CPU: cc1{{.*}}" "-target-cpu" "ultrasparc" // CHECK-SPARC-CPU: as{{.*}}" "-Av9a
the_stack_data/150203.c
#include <stdio.h> int main (void){ int img_direita[600][400],img[600][400],i,j; for(i = 0 ; i < 600; i ++){ for( j = 0; j < 400 ; j ++){ img_direita[i][j] = img[399-j][i]; // [0][0] = [399][0] } } }
the_stack_data/54826162.c
// Ogg Vorbis audio decoder - v1.17 - public domain // http://nothings.org/stb_vorbis/ // // Original version written by Sean Barrett in 2007. // // Originally sponsored by RAD Game Tools. Seeking implementation // sponsored by Phillip Bennefall, Marc Andersen, Aaron Baker, // Elias Software, Aras Pranckevicius, and Sean Barrett. // // LICENSE // // See end of file for license information. // // Limitations: // // - floor 0 not supported (used in old ogg vorbis files pre-2004) // - lossless sample-truncation at beginning ignored // - cannot concatenate multiple vorbis streams // - sample positions are 32-bit, limiting seekable 192Khz // files to around 6 hours (Ogg supports 64-bit) // // Feature contributors: // Dougall Johnson (sample-exact seeking) // // Bugfix/warning contributors: // Terje Mathisen Niklas Frykholm Andy Hill // Casey Muratori John Bolton Gargaj // Laurent Gomila Marc LeBlanc Ronny Chevalier // Bernhard Wodo Evan Balster alxprd@github // Tom Beaumont Ingo Leitgeb Nicolas Guillemot // Phillip Bennefall Rohit Thiago Goulart // manxorist@github saga musix github:infatum // Timur Gagiev Maxwell Koo // // Partial history: // 1.17 - 2019-07-08 - fix CVE-2019-13217..CVE-2019-13223 (by ForAllSecure) // 1.16 - 2019-03-04 - fix warnings // 1.15 - 2019-02-07 - explicit failure if Ogg Skeleton data is found // 1.14 - 2018-02-11 - delete bogus dealloca usage // 1.13 - 2018-01-29 - fix truncation of last frame (hopefully) // 1.12 - 2017-11-21 - limit residue begin/end to blocksize/2 to avoid large temp allocs in bad/corrupt files // 1.11 - 2017-07-23 - fix MinGW compilation // 1.10 - 2017-03-03 - more robust seeking; fix negative ilog(); clear error in open_memory // 1.09 - 2016-04-04 - back out 'truncation of last frame' fix from previous version // 1.08 - 2016-04-02 - warnings; setup memory leaks; truncation of last frame // 1.07 - 2015-01-16 - fixes for crashes on invalid files; warning fixes; const // 1.06 - 2015-08-31 - full, correct support for seeking API (Dougall Johnson) // some crash fixes when out of memory or with corrupt files // fix some inappropriately signed shifts // 1.05 - 2015-04-19 - don't define __forceinline if it's redundant // 1.04 - 2014-08-27 - fix missing const-correct case in API // 1.03 - 2014-08-07 - warning fixes // 1.02 - 2014-07-09 - declare qsort comparison as explicitly _cdecl in Windows // 1.01 - 2014-06-18 - fix stb_vorbis_get_samples_float (interleaved was correct) // 1.0 - 2014-05-26 - fix memory leaks; fix warnings; fix bugs in >2-channel; // (API change) report sample rate for decode-full-file funcs // // See end of file for full version history. ////////////////////////////////////////////////////////////////////////////// // // HEADER BEGINS HERE // #ifndef STB_VORBIS_INCLUDE_STB_VORBIS_H #define STB_VORBIS_INCLUDE_STB_VORBIS_H #if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO) #define STB_VORBIS_NO_STDIO 1 #endif #ifndef STB_VORBIS_NO_STDIO #include <stdio.h> #endif #ifdef __cplusplus extern "C" { #endif /////////// THREAD SAFETY // Individual stb_vorbis* handles are not thread-safe; you cannot decode from // them from multiple threads at the same time. However, you can have multiple // stb_vorbis* handles and decode from them independently in multiple thrads. /////////// MEMORY ALLOCATION // normally stb_vorbis uses malloc() to allocate memory at startup, // and alloca() to allocate temporary memory during a frame on the // stack. (Memory consumption will depend on the amount of setup // data in the file and how you set the compile flags for speed // vs. size. In my test files the maximal-size usage is ~150KB.) // // You can modify the wrapper functions in the source (setup_malloc, // setup_temp_malloc, temp_malloc) to change this behavior, or you // can use a simpler allocation model: you pass in a buffer from // which stb_vorbis will allocate _all_ its memory (including the // temp memory). "open" may fail with a VORBIS_outofmem if you // do not pass in enough data; there is no way to determine how // much you do need except to succeed (at which point you can // query get_info to find the exact amount required. yes I know // this is lame). // // If you pass in a non-NULL buffer of the type below, allocation // will occur from it as described above. Otherwise just pass NULL // to use malloc()/alloca() typedef struct { char *alloc_buffer; int alloc_buffer_length_in_bytes; } stb_vorbis_alloc; /////////// FUNCTIONS USEABLE WITH ALL INPUT MODES typedef struct stb_vorbis stb_vorbis; typedef struct { unsigned int sample_rate; int channels; unsigned int setup_memory_required; unsigned int setup_temp_memory_required; unsigned int temp_memory_required; int max_frame_size; } stb_vorbis_info; // get general information about the file extern stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f); // get the last error detected (clears it, too) extern int stb_vorbis_get_error(stb_vorbis *f); // close an ogg vorbis file and free all memory in use extern void stb_vorbis_close(stb_vorbis *f); // this function returns the offset (in samples) from the beginning of the // file that will be returned by the next decode, if it is known, or -1 // otherwise. after a flush_pushdata() call, this may take a while before // it becomes valid again. // NOT WORKING YET after a seek with PULLDATA API extern int stb_vorbis_get_sample_offset(stb_vorbis *f); // returns the current seek point within the file, or offset from the beginning // of the memory buffer. In pushdata mode it returns 0. extern unsigned int stb_vorbis_get_file_offset(stb_vorbis *f); /////////// PUSHDATA API #ifndef STB_VORBIS_NO_PUSHDATA_API // this API allows you to get blocks of data from any source and hand // them to stb_vorbis. you have to buffer them; stb_vorbis will tell // you how much it used, and you have to give it the rest next time; // and stb_vorbis may not have enough data to work with and you will // need to give it the same data again PLUS more. Note that the Vorbis // specification does not bound the size of an individual frame. extern stb_vorbis *stb_vorbis_open_pushdata( const unsigned char * datablock, int datablock_length_in_bytes, int *datablock_memory_consumed_in_bytes, int *error, const stb_vorbis_alloc *alloc_buffer); // create a vorbis decoder by passing in the initial data block containing // the ogg&vorbis headers (you don't need to do parse them, just provide // the first N bytes of the file--you're told if it's not enough, see below) // on success, returns an stb_vorbis *, does not set error, returns the amount of // data parsed/consumed on this call in *datablock_memory_consumed_in_bytes; // on failure, returns NULL on error and sets *error, does not change *datablock_memory_consumed // if returns NULL and *error is VORBIS_need_more_data, then the input block was // incomplete and you need to pass in a larger block from the start of the file extern int stb_vorbis_decode_frame_pushdata( stb_vorbis *f, const unsigned char *datablock, int datablock_length_in_bytes, int *channels, // place to write number of float * buffers float ***output, // place to write float ** array of float * buffers int *samples // place to write number of output samples ); // decode a frame of audio sample data if possible from the passed-in data block // // return value: number of bytes we used from datablock // // possible cases: // 0 bytes used, 0 samples output (need more data) // N bytes used, 0 samples output (resynching the stream, keep going) // N bytes used, M samples output (one frame of data) // note that after opening a file, you will ALWAYS get one N-bytes,0-sample // frame, because Vorbis always "discards" the first frame. // // Note that on resynch, stb_vorbis will rarely consume all of the buffer, // instead only datablock_length_in_bytes-3 or less. This is because it wants // to avoid missing parts of a page header if they cross a datablock boundary, // without writing state-machiney code to record a partial detection. // // The number of channels returned are stored in *channels (which can be // NULL--it is always the same as the number of channels reported by // get_info). *output will contain an array of float* buffers, one per // channel. In other words, (*output)[0][0] contains the first sample from // the first channel, and (*output)[1][0] contains the first sample from // the second channel. extern void stb_vorbis_flush_pushdata(stb_vorbis *f); // inform stb_vorbis that your next datablock will not be contiguous with // previous ones (e.g. you've seeked in the data); future attempts to decode // frames will cause stb_vorbis to resynchronize (as noted above), and // once it sees a valid Ogg page (typically 4-8KB, as large as 64KB), it // will begin decoding the _next_ frame. // // if you want to seek using pushdata, you need to seek in your file, then // call stb_vorbis_flush_pushdata(), then start calling decoding, then once // decoding is returning you data, call stb_vorbis_get_sample_offset, and // if you don't like the result, seek your file again and repeat. #endif ////////// PULLING INPUT API #ifndef STB_VORBIS_NO_PULLDATA_API // This API assumes stb_vorbis is allowed to pull data from a source-- // either a block of memory containing the _entire_ vorbis stream, or a // FILE * that you or it create, or possibly some other reading mechanism // if you go modify the source to replace the FILE * case with some kind // of callback to your code. (But if you don't support seeking, you may // just want to go ahead and use pushdata.) #if !defined(STB_VORBIS_NO_STDIO) && !defined(STB_VORBIS_NO_INTEGER_CONVERSION) extern int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_rate, short **output); #endif #if !defined(STB_VORBIS_NO_INTEGER_CONVERSION) extern int stb_vorbis_decode_memory(const unsigned char *mem, int len, int *channels, int *sample_rate, short **output); #endif // decode an entire file and output the data interleaved into a malloc()ed // buffer stored in *output. The return value is the number of samples // decoded, or -1 if the file could not be opened or was not an ogg vorbis file. // When you're done with it, just free() the pointer returned in *output. extern stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len, int *error, const stb_vorbis_alloc *alloc_buffer); // create an ogg vorbis decoder from an ogg vorbis stream in memory (note // this must be the entire stream!). on failure, returns NULL and sets *error #ifndef STB_VORBIS_NO_STDIO extern stb_vorbis * stb_vorbis_open_filename(const char *filename, int *error, const stb_vorbis_alloc *alloc_buffer); // create an ogg vorbis decoder from a filename via fopen(). on failure, // returns NULL and sets *error (possibly to VORBIS_file_open_failure). extern stb_vorbis * stb_vorbis_open_file(FILE *f, int close_handle_on_close, int *error, const stb_vorbis_alloc *alloc_buffer); // create an ogg vorbis decoder from an open FILE *, looking for a stream at // the _current_ seek point (ftell). on failure, returns NULL and sets *error. // note that stb_vorbis must "own" this stream; if you seek it in between // calls to stb_vorbis, it will become confused. Moreover, if you attempt to // perform stb_vorbis_seek_*() operations on this file, it will assume it // owns the _entire_ rest of the file after the start point. Use the next // function, stb_vorbis_open_file_section(), to limit it. extern stb_vorbis * stb_vorbis_open_file_section(FILE *f, int close_handle_on_close, int *error, const stb_vorbis_alloc *alloc_buffer, unsigned int len); // create an ogg vorbis decoder from an open FILE *, looking for a stream at // the _current_ seek point (ftell); the stream will be of length 'len' bytes. // on failure, returns NULL and sets *error. note that stb_vorbis must "own" // this stream; if you seek it in between calls to stb_vorbis, it will become // confused. #endif extern int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number); extern int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number); // these functions seek in the Vorbis file to (approximately) 'sample_number'. // after calling seek_frame(), the next call to get_frame_*() will include // the specified sample. after calling stb_vorbis_seek(), the next call to // stb_vorbis_get_samples_* will start with the specified sample. If you // do not need to seek to EXACTLY the target sample when using get_samples_*, // you can also use seek_frame(). extern int stb_vorbis_seek_start(stb_vorbis *f); // this function is equivalent to stb_vorbis_seek(f,0) extern unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f); extern float stb_vorbis_stream_length_in_seconds(stb_vorbis *f); // these functions return the total length of the vorbis stream extern int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output); // decode the next frame and return the number of samples. the number of // channels returned are stored in *channels (which can be NULL--it is always // the same as the number of channels reported by get_info). *output will // contain an array of float* buffers, one per channel. These outputs will // be overwritten on the next call to stb_vorbis_get_frame_*. // // You generally should not intermix calls to stb_vorbis_get_frame_*() // and stb_vorbis_get_samples_*(), since the latter calls the former. #ifndef STB_VORBIS_NO_INTEGER_CONVERSION extern int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts); extern int stb_vorbis_get_frame_short (stb_vorbis *f, int num_c, short **buffer, int num_samples); #endif // decode the next frame and return the number of *samples* per channel. // Note that for interleaved data, you pass in the number of shorts (the // size of your array), but the return value is the number of samples per // channel, not the total number of samples. // // The data is coerced to the number of channels you request according to the // channel coercion rules (see below). You must pass in the size of your // buffer(s) so that stb_vorbis will not overwrite the end of the buffer. // The maximum buffer size needed can be gotten from get_info(); however, // the Vorbis I specification implies an absolute maximum of 4096 samples // per channel. // Channel coercion rules: // Let M be the number of channels requested, and N the number of channels present, // and Cn be the nth channel; let stereo L be the sum of all L and center channels, // and stereo R be the sum of all R and center channels (channel assignment from the // vorbis spec). // M N output // 1 k sum(Ck) for all k // 2 * stereo L, stereo R // k l k > l, the first l channels, then 0s // k l k <= l, the first k channels // Note that this is not _good_ surround etc. mixing at all! It's just so // you get something useful. extern int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats); extern int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples); // gets num_samples samples, not necessarily on a frame boundary--this requires // buffering so you have to supply the buffers. DOES NOT APPLY THE COERCION RULES. // Returns the number of samples stored per channel; it may be less than requested // at the end of the file. If there are no more samples in the file, returns 0. #ifndef STB_VORBIS_NO_INTEGER_CONVERSION extern int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts); extern int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int num_samples); #endif // gets num_samples samples, not necessarily on a frame boundary--this requires // buffering so you have to supply the buffers. Applies the coercion rules above // to produce 'channels' channels. Returns the number of samples stored per channel; // it may be less than requested at the end of the file. If there are no more // samples in the file, returns 0. #endif //////// ERROR CODES enum STBVorbisError { VORBIS__no_error, VORBIS_need_more_data=1, // not a real error VORBIS_invalid_api_mixing, // can't mix API modes VORBIS_outofmem, // not enough memory VORBIS_feature_not_supported, // uses floor 0 VORBIS_too_many_channels, // STB_VORBIS_MAX_CHANNELS is too small VORBIS_file_open_failure, // fopen() failed VORBIS_seek_without_length, // can't seek in unknown-length file VORBIS_unexpected_eof=10, // file is truncated? VORBIS_seek_invalid, // seek past EOF // decoding errors (corrupt/invalid stream) -- you probably // don't care about the exact details of these // vorbis errors: VORBIS_invalid_setup=20, VORBIS_invalid_stream, // ogg errors: VORBIS_missing_capture_pattern=30, VORBIS_invalid_stream_structure_version, VORBIS_continued_packet_flag_invalid, VORBIS_incorrect_stream_serial_number, VORBIS_invalid_first_page, VORBIS_bad_packet_type, VORBIS_cant_find_last_page, VORBIS_seek_failed, VORBIS_ogg_skeleton_not_supported }; #ifdef __cplusplus } #endif #endif // STB_VORBIS_INCLUDE_STB_VORBIS_H // // HEADER ENDS HERE // ////////////////////////////////////////////////////////////////////////////// #ifndef STB_VORBIS_HEADER_ONLY // global configuration settings (e.g. set these in the project/makefile), // or just set them in this file at the top (although ideally the first few // should be visible when the header file is compiled too, although it's not // crucial) // STB_VORBIS_NO_PUSHDATA_API // does not compile the code for the various stb_vorbis_*_pushdata() // functions // #define STB_VORBIS_NO_PUSHDATA_API // STB_VORBIS_NO_PULLDATA_API // does not compile the code for the non-pushdata APIs // #define STB_VORBIS_NO_PULLDATA_API // STB_VORBIS_NO_STDIO // does not compile the code for the APIs that use FILE *s internally // or externally (implied by STB_VORBIS_NO_PULLDATA_API) // #define STB_VORBIS_NO_STDIO // STB_VORBIS_NO_INTEGER_CONVERSION // does not compile the code for converting audio sample data from // float to integer (implied by STB_VORBIS_NO_PULLDATA_API) // #define STB_VORBIS_NO_INTEGER_CONVERSION // STB_VORBIS_NO_FAST_SCALED_FLOAT // does not use a fast float-to-int trick to accelerate float-to-int on // most platforms which requires endianness be defined correctly. //#define STB_VORBIS_NO_FAST_SCALED_FLOAT // STB_VORBIS_MAX_CHANNELS [number] // globally define this to the maximum number of channels you need. // The spec does not put a restriction on channels except that // the count is stored in a byte, so 255 is the hard limit. // Reducing this saves about 16 bytes per value, so using 16 saves // (255-16)*16 or around 4KB. Plus anything other memory usage // I forgot to account for. Can probably go as low as 8 (7.1 audio), // 6 (5.1 audio), or 2 (stereo only). #ifndef STB_VORBIS_MAX_CHANNELS #define STB_VORBIS_MAX_CHANNELS 16 // enough for anyone? #endif // STB_VORBIS_PUSHDATA_CRC_COUNT [number] // after a flush_pushdata(), stb_vorbis begins scanning for the // next valid page, without backtracking. when it finds something // that looks like a page, it streams through it and verifies its // CRC32. Should that validation fail, it keeps scanning. But it's // possible that _while_ streaming through to check the CRC32 of // one candidate page, it sees another candidate page. This #define // determines how many "overlapping" candidate pages it can search // at once. Note that "real" pages are typically ~4KB to ~8KB, whereas // garbage pages could be as big as 64KB, but probably average ~16KB. // So don't hose ourselves by scanning an apparent 64KB page and // missing a ton of real ones in the interim; so minimum of 2 #ifndef STB_VORBIS_PUSHDATA_CRC_COUNT #define STB_VORBIS_PUSHDATA_CRC_COUNT 4 #endif // STB_VORBIS_FAST_HUFFMAN_LENGTH [number] // sets the log size of the huffman-acceleration table. Maximum // supported value is 24. with larger numbers, more decodings are O(1), // but the table size is larger so worse cache missing, so you'll have // to probe (and try multiple ogg vorbis files) to find the sweet spot. #ifndef STB_VORBIS_FAST_HUFFMAN_LENGTH #define STB_VORBIS_FAST_HUFFMAN_LENGTH 10 #endif // STB_VORBIS_FAST_BINARY_LENGTH [number] // sets the log size of the binary-search acceleration table. this // is used in similar fashion to the fast-huffman size to set initial // parameters for the binary search // STB_VORBIS_FAST_HUFFMAN_INT // The fast huffman tables are much more efficient if they can be // stored as 16-bit results instead of 32-bit results. This restricts // the codebooks to having only 65535 possible outcomes, though. // (At least, accelerated by the huffman table.) #ifndef STB_VORBIS_FAST_HUFFMAN_INT #define STB_VORBIS_FAST_HUFFMAN_SHORT #endif // STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH // If the 'fast huffman' search doesn't succeed, then stb_vorbis falls // back on binary searching for the correct one. This requires storing // extra tables with the huffman codes in sorted order. Defining this // symbol trades off space for speed by forcing a linear search in the // non-fast case, except for "sparse" codebooks. // #define STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH // STB_VORBIS_DIVIDES_IN_RESIDUE // stb_vorbis precomputes the result of the scalar residue decoding // that would otherwise require a divide per chunk. you can trade off // space for time by defining this symbol. // #define STB_VORBIS_DIVIDES_IN_RESIDUE // STB_VORBIS_DIVIDES_IN_CODEBOOK // vorbis VQ codebooks can be encoded two ways: with every case explicitly // stored, or with all elements being chosen from a small range of values, // and all values possible in all elements. By default, stb_vorbis expands // this latter kind out to look like the former kind for ease of decoding, // because otherwise an integer divide-per-vector-element is required to // unpack the index. If you define STB_VORBIS_DIVIDES_IN_CODEBOOK, you can // trade off storage for speed. //#define STB_VORBIS_DIVIDES_IN_CODEBOOK #ifdef STB_VORBIS_CODEBOOK_SHORTS #error "STB_VORBIS_CODEBOOK_SHORTS is no longer supported as it produced incorrect results for some input formats" #endif // STB_VORBIS_DIVIDE_TABLE // this replaces small integer divides in the floor decode loop with // table lookups. made less than 1% difference, so disabled by default. // STB_VORBIS_NO_INLINE_DECODE // disables the inlining of the scalar codebook fast-huffman decode. // might save a little codespace; useful for debugging // #define STB_VORBIS_NO_INLINE_DECODE // STB_VORBIS_NO_DEFER_FLOOR // Normally we only decode the floor without synthesizing the actual // full curve. We can instead synthesize the curve immediately. This // requires more memory and is very likely slower, so I don't think // you'd ever want to do it except for debugging. // #define STB_VORBIS_NO_DEFER_FLOOR ////////////////////////////////////////////////////////////////////////////// #ifdef STB_VORBIS_NO_PULLDATA_API #define STB_VORBIS_NO_INTEGER_CONVERSION #define STB_VORBIS_NO_STDIO #endif #if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO) #define STB_VORBIS_NO_STDIO 1 #endif #ifndef STB_VORBIS_NO_INTEGER_CONVERSION #ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT // only need endianness for fast-float-to-int, which we don't // use for pushdata #ifndef STB_VORBIS_BIG_ENDIAN #define STB_VORBIS_ENDIAN 0 #else #define STB_VORBIS_ENDIAN 1 #endif #endif #endif #ifndef STB_VORBIS_NO_STDIO #include <stdio.h> #endif #ifndef STB_VORBIS_NO_CRT #include <stdlib.h> #include <string.h> #include <assert.h> #include <math.h> // find definition of alloca if it's not in stdlib.h: #if defined(_MSC_VER) || defined(__MINGW32__) #include <malloc.h> #endif #if defined(__linux__) || defined(__linux) || defined(__EMSCRIPTEN__) #include <alloca.h> #endif #else // STB_VORBIS_NO_CRT #define NULL 0 #define malloc(s) 0 #define free(s) ((void) 0) #define realloc(s) 0 #endif // STB_VORBIS_NO_CRT #include <limits.h> #ifdef __MINGW32__ // eff you mingw: // "fixed": // http://sourceforge.net/p/mingw-w64/mailman/message/32882927/ // "no that broke the build, reverted, who cares about C": // http://sourceforge.net/p/mingw-w64/mailman/message/32890381/ #ifdef __forceinline #undef __forceinline #endif #define __forceinline #define alloca __builtin_alloca #elif !defined(_MSC_VER) #if __GNUC__ #define __forceinline inline #else #define __forceinline #endif #endif #if STB_VORBIS_MAX_CHANNELS > 256 #error "Value of STB_VORBIS_MAX_CHANNELS outside of allowed range" #endif #if STB_VORBIS_FAST_HUFFMAN_LENGTH > 24 #error "Value of STB_VORBIS_FAST_HUFFMAN_LENGTH outside of allowed range" #endif #if 0 #include <crtdbg.h> #define CHECK(f) _CrtIsValidHeapPointer(f->channel_buffers[1]) #else #define CHECK(f) ((void) 0) #endif #define MAX_BLOCKSIZE_LOG 13 // from specification #define MAX_BLOCKSIZE (1 << MAX_BLOCKSIZE_LOG) typedef unsigned char uint8; typedef signed char int8; typedef unsigned short uint16; typedef signed short int16; typedef unsigned int uint32; typedef signed int int32; #ifndef TRUE #define TRUE 1 #define FALSE 0 #endif typedef float codetype; // @NOTE // // Some arrays below are tagged "//varies", which means it's actually // a variable-sized piece of data, but rather than malloc I assume it's // small enough it's better to just allocate it all together with the // main thing // // Most of the variables are specified with the smallest size I could pack // them into. It might give better performance to make them all full-sized // integers. It should be safe to freely rearrange the structures or change // the sizes larger--nothing relies on silently truncating etc., nor the // order of variables. #define FAST_HUFFMAN_TABLE_SIZE (1 << STB_VORBIS_FAST_HUFFMAN_LENGTH) #define FAST_HUFFMAN_TABLE_MASK (FAST_HUFFMAN_TABLE_SIZE - 1) typedef struct { int dimensions, entries; uint8 *codeword_lengths; float minimum_value; float delta_value; uint8 value_bits; uint8 lookup_type; uint8 sequence_p; uint8 sparse; uint32 lookup_values; codetype *multiplicands; uint32 *codewords; #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT int16 fast_huffman[FAST_HUFFMAN_TABLE_SIZE]; #else int32 fast_huffman[FAST_HUFFMAN_TABLE_SIZE]; #endif uint32 *sorted_codewords; int *sorted_values; int sorted_entries; } Codebook; typedef struct { uint8 order; uint16 rate; uint16 bark_map_size; uint8 amplitude_bits; uint8 amplitude_offset; uint8 number_of_books; uint8 book_list[16]; // varies } Floor0; typedef struct { uint8 partitions; uint8 partition_class_list[32]; // varies uint8 class_dimensions[16]; // varies uint8 class_subclasses[16]; // varies uint8 class_masterbooks[16]; // varies int16 subclass_books[16][8]; // varies uint16 Xlist[31*8+2]; // varies uint8 sorted_order[31*8+2]; uint8 neighbors[31*8+2][2]; uint8 floor1_multiplier; uint8 rangebits; int values; } Floor1; typedef union { Floor0 floor0; Floor1 floor1; } Floor; typedef struct { uint32 begin, end; uint32 part_size; uint8 classifications; uint8 classbook; uint8 **classdata; int16 (*residue_books)[8]; } Residue; typedef struct { uint8 magnitude; uint8 angle; uint8 mux; } MappingChannel; typedef struct { uint16 coupling_steps; MappingChannel *chan; uint8 submaps; uint8 submap_floor[15]; // varies uint8 submap_residue[15]; // varies } Mapping; typedef struct { uint8 blockflag; uint8 mapping; uint16 windowtype; uint16 transformtype; } Mode; typedef struct { uint32 goal_crc; // expected crc if match int bytes_left; // bytes left in packet uint32 crc_so_far; // running crc int bytes_done; // bytes processed in _current_ chunk uint32 sample_loc; // granule pos encoded in page } CRCscan; typedef struct { uint32 page_start, page_end; uint32 last_decoded_sample; } ProbedPage; struct stb_vorbis { // user-accessible info unsigned int sample_rate; int channels; unsigned int setup_memory_required; unsigned int temp_memory_required; unsigned int setup_temp_memory_required; // input config #ifndef STB_VORBIS_NO_STDIO FILE *f; uint32 f_start; int close_on_free; #endif uint8 *stream; uint8 *stream_start; uint8 *stream_end; uint32 stream_len; uint8 push_mode; uint32 first_audio_page_offset; ProbedPage p_first, p_last; // memory management stb_vorbis_alloc alloc; int setup_offset; int temp_offset; // run-time results int eof; enum STBVorbisError error; // user-useful data // header info int blocksize[2]; int blocksize_0, blocksize_1; int codebook_count; Codebook *codebooks; int floor_count; uint16 floor_types[64]; // varies Floor *floor_config; int residue_count; uint16 residue_types[64]; // varies Residue *residue_config; int mapping_count; Mapping *mapping; int mode_count; Mode mode_config[64]; // varies uint32 total_samples; // decode buffer float *channel_buffers[STB_VORBIS_MAX_CHANNELS]; float *outputs [STB_VORBIS_MAX_CHANNELS]; float *previous_window[STB_VORBIS_MAX_CHANNELS]; int previous_length; #ifndef STB_VORBIS_NO_DEFER_FLOOR int16 *finalY[STB_VORBIS_MAX_CHANNELS]; #else float *floor_buffers[STB_VORBIS_MAX_CHANNELS]; #endif uint32 current_loc; // sample location of next frame to decode int current_loc_valid; // per-blocksize precomputed data // twiddle factors float *A[2],*B[2],*C[2]; float *window[2]; uint16 *bit_reverse[2]; // current page/packet/segment streaming info uint32 serial; // stream serial number for verification int last_page; int segment_count; uint8 segments[255]; uint8 page_flag; uint8 bytes_in_seg; uint8 first_decode; int next_seg; int last_seg; // flag that we're on the last segment int last_seg_which; // what was the segment number of the last seg? uint32 acc; int valid_bits; int packet_bytes; int end_seg_with_known_loc; uint32 known_loc_for_packet; int discard_samples_deferred; uint32 samples_output; // push mode scanning int page_crc_tests; // only in push_mode: number of tests active; -1 if not searching #ifndef STB_VORBIS_NO_PUSHDATA_API CRCscan scan[STB_VORBIS_PUSHDATA_CRC_COUNT]; #endif // sample-access int channel_buffer_start; int channel_buffer_end; }; #if defined(STB_VORBIS_NO_PUSHDATA_API) #define IS_PUSH_MODE(f) FALSE #elif defined(STB_VORBIS_NO_PULLDATA_API) #define IS_PUSH_MODE(f) TRUE #else #define IS_PUSH_MODE(f) ((f)->push_mode) #endif typedef struct stb_vorbis vorb; static int error(vorb *f, enum STBVorbisError e) { f->error = e; if (!f->eof && e != VORBIS_need_more_data) { f->error=e; // breakpoint for debugging } return 0; } // these functions are used for allocating temporary memory // while decoding. if you can afford the stack space, use // alloca(); otherwise, provide a temp buffer and it will // allocate out of those. #define array_size_required(count,size) (count*(sizeof(void *)+(size))) #define temp_alloc(f,size) (f->alloc.alloc_buffer ? setup_temp_malloc(f,size) : alloca(size)) #define temp_free(f,p) 0 #define temp_alloc_save(f) ((f)->temp_offset) #define temp_alloc_restore(f,p) ((f)->temp_offset = (p)) #define temp_block_array(f,count,size) make_block_array(temp_alloc(f,array_size_required(count,size)), count, size) // given a sufficiently large block of memory, make an array of pointers to subblocks of it static void *make_block_array(void *mem, int count, int size) { int i; void ** p = (void **) mem; char *q = (char *) (p + count); for (i=0; i < count; ++i) { p[i] = q; q += size; } return p; } static void *setup_malloc(vorb *f, int sz) { sz = (sz+3) & ~3; f->setup_memory_required += sz; if (f->alloc.alloc_buffer) { void *p = (char *) f->alloc.alloc_buffer + f->setup_offset; if (f->setup_offset + sz > f->temp_offset) return NULL; f->setup_offset += sz; return p; } return sz ? malloc(sz) : NULL; } static void setup_free(vorb *f, void *p) { if (f->alloc.alloc_buffer) return; // do nothing; setup mem is a stack free(p); } static void *setup_temp_malloc(vorb *f, int sz) { sz = (sz+3) & ~3; if (f->alloc.alloc_buffer) { if (f->temp_offset - sz < f->setup_offset) return NULL; f->temp_offset -= sz; return (char *) f->alloc.alloc_buffer + f->temp_offset; } return malloc(sz); } static void setup_temp_free(vorb *f, void *p, int sz) { if (f->alloc.alloc_buffer) { f->temp_offset += (sz+3)&~3; return; } free(p); } #define CRC32_POLY 0x04c11db7 // from spec static uint32 crc_table[256]; static void crc32_init(void) { int i,j; uint32 s; for(i=0; i < 256; i++) { for (s=(uint32) i << 24, j=0; j < 8; ++j) s = (s << 1) ^ (s >= (1U<<31) ? CRC32_POLY : 0); crc_table[i] = s; } } static __forceinline uint32 crc32_update(uint32 crc, uint8 byte) { return (crc << 8) ^ crc_table[byte ^ (crc >> 24)]; } // used in setup, and for huffman that doesn't go fast path static unsigned int bit_reverse(unsigned int n) { n = ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1); n = ((n & 0xCCCCCCCC) >> 2) | ((n & 0x33333333) << 2); n = ((n & 0xF0F0F0F0) >> 4) | ((n & 0x0F0F0F0F) << 4); n = ((n & 0xFF00FF00) >> 8) | ((n & 0x00FF00FF) << 8); return (n >> 16) | (n << 16); } static float square(float x) { return x*x; } // this is a weird definition of log2() for which log2(1) = 1, log2(2) = 2, log2(4) = 3 // as required by the specification. fast(?) implementation from stb.h // @OPTIMIZE: called multiple times per-packet with "constants"; move to setup static int ilog(int32 n) { static signed char log2_4[16] = { 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4 }; if (n < 0) return 0; // signed n returns 0 // 2 compares if n < 16, 3 compares otherwise (4 if signed or n > 1<<29) if (n < (1 << 14)) if (n < (1 << 4)) return 0 + log2_4[n ]; else if (n < (1 << 9)) return 5 + log2_4[n >> 5]; else return 10 + log2_4[n >> 10]; else if (n < (1 << 24)) if (n < (1 << 19)) return 15 + log2_4[n >> 15]; else return 20 + log2_4[n >> 20]; else if (n < (1 << 29)) return 25 + log2_4[n >> 25]; else return 30 + log2_4[n >> 30]; } #ifndef M_PI #define M_PI 3.14159265358979323846264f // from CRC #endif // code length assigned to a value with no huffman encoding #define NO_CODE 255 /////////////////////// LEAF SETUP FUNCTIONS ////////////////////////// // // these functions are only called at setup, and only a few times // per file static float float32_unpack(uint32 x) { // from the specification uint32 mantissa = x & 0x1fffff; uint32 sign = x & 0x80000000; uint32 exp = (x & 0x7fe00000) >> 21; double res = sign ? -(double)mantissa : (double)mantissa; return (float) ldexp((float)res, exp-788); } // zlib & jpeg huffman tables assume that the output symbols // can either be arbitrarily arranged, or have monotonically // increasing frequencies--they rely on the lengths being sorted; // this makes for a very simple generation algorithm. // vorbis allows a huffman table with non-sorted lengths. This // requires a more sophisticated construction, since symbols in // order do not map to huffman codes "in order". static void add_entry(Codebook *c, uint32 huff_code, int symbol, int count, int len, uint32 *values) { if (!c->sparse) { c->codewords [symbol] = huff_code; } else { c->codewords [count] = huff_code; c->codeword_lengths[count] = len; values [count] = symbol; } } static int compute_codewords(Codebook *c, uint8 *len, int n, uint32 *values) { int i,k,m=0; uint32 available[32]; memset(available, 0, sizeof(available)); // find the first entry for (k=0; k < n; ++k) if (len[k] < NO_CODE) break; if (k == n) { assert(c->sorted_entries == 0); return TRUE; } // add to the list add_entry(c, 0, k, m++, len[k], values); // add all available leaves for (i=1; i <= len[k]; ++i) available[i] = 1U << (32-i); // note that the above code treats the first case specially, // but it's really the same as the following code, so they // could probably be combined (except the initial code is 0, // and I use 0 in available[] to mean 'empty') for (i=k+1; i < n; ++i) { uint32 res; int z = len[i], y; if (z == NO_CODE) continue; // find lowest available leaf (should always be earliest, // which is what the specification calls for) // note that this property, and the fact we can never have // more than one free leaf at a given level, isn't totally // trivial to prove, but it seems true and the assert never // fires, so! while (z > 0 && !available[z]) --z; if (z == 0) { return FALSE; } res = available[z]; assert(z >= 0 && z < 32); available[z] = 0; add_entry(c, bit_reverse(res), i, m++, len[i], values); // propagate availability up the tree if (z != len[i]) { assert(len[i] >= 0 && len[i] < 32); for (y=len[i]; y > z; --y) { assert(available[y] == 0); available[y] = res + (1 << (32-y)); } } } return TRUE; } // accelerated huffman table allows fast O(1) match of all symbols // of length <= STB_VORBIS_FAST_HUFFMAN_LENGTH static void compute_accelerated_huffman(Codebook *c) { int i, len; for (i=0; i < FAST_HUFFMAN_TABLE_SIZE; ++i) c->fast_huffman[i] = -1; len = c->sparse ? c->sorted_entries : c->entries; #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT if (len > 32767) len = 32767; // largest possible value we can encode! #endif for (i=0; i < len; ++i) { if (c->codeword_lengths[i] <= STB_VORBIS_FAST_HUFFMAN_LENGTH) { uint32 z = c->sparse ? bit_reverse(c->sorted_codewords[i]) : c->codewords[i]; // set table entries for all bit combinations in the higher bits while (z < FAST_HUFFMAN_TABLE_SIZE) { c->fast_huffman[z] = i; z += 1 << c->codeword_lengths[i]; } } } } #ifdef _MSC_VER #define STBV_CDECL __cdecl #else #define STBV_CDECL #endif static int STBV_CDECL uint32_compare(const void *p, const void *q) { uint32 x = * (uint32 *) p; uint32 y = * (uint32 *) q; return x < y ? -1 : x > y; } static int include_in_sort(Codebook *c, uint8 len) { if (c->sparse) { assert(len != NO_CODE); return TRUE; } if (len == NO_CODE) return FALSE; if (len > STB_VORBIS_FAST_HUFFMAN_LENGTH) return TRUE; return FALSE; } // if the fast table above doesn't work, we want to binary // search them... need to reverse the bits static void compute_sorted_huffman(Codebook *c, uint8 *lengths, uint32 *values) { int i, len; // build a list of all the entries // OPTIMIZATION: don't include the short ones, since they'll be caught by FAST_HUFFMAN. // this is kind of a frivolous optimization--I don't see any performance improvement, // but it's like 4 extra lines of code, so. if (!c->sparse) { int k = 0; for (i=0; i < c->entries; ++i) if (include_in_sort(c, lengths[i])) c->sorted_codewords[k++] = bit_reverse(c->codewords[i]); assert(k == c->sorted_entries); } else { for (i=0; i < c->sorted_entries; ++i) c->sorted_codewords[i] = bit_reverse(c->codewords[i]); } qsort(c->sorted_codewords, c->sorted_entries, sizeof(c->sorted_codewords[0]), uint32_compare); c->sorted_codewords[c->sorted_entries] = 0xffffffff; len = c->sparse ? c->sorted_entries : c->entries; // now we need to indicate how they correspond; we could either // #1: sort a different data structure that says who they correspond to // #2: for each sorted entry, search the original list to find who corresponds // #3: for each original entry, find the sorted entry // #1 requires extra storage, #2 is slow, #3 can use binary search! for (i=0; i < len; ++i) { int huff_len = c->sparse ? lengths[values[i]] : lengths[i]; if (include_in_sort(c,huff_len)) { uint32 code = bit_reverse(c->codewords[i]); int x=0, n=c->sorted_entries; while (n > 1) { // invariant: sc[x] <= code < sc[x+n] int m = x + (n >> 1); if (c->sorted_codewords[m] <= code) { x = m; n -= (n>>1); } else { n >>= 1; } } assert(c->sorted_codewords[x] == code); if (c->sparse) { c->sorted_values[x] = values[i]; c->codeword_lengths[x] = huff_len; } else { c->sorted_values[x] = i; } } } } // only run while parsing the header (3 times) static int vorbis_validate(uint8 *data) { static uint8 vorbis[6] = { 'v', 'o', 'r', 'b', 'i', 's' }; return memcmp(data, vorbis, 6) == 0; } // called from setup only, once per code book // (formula implied by specification) static int lookup1_values(int entries, int dim) { int r = (int) floor(exp((float) log((float) entries) / dim)); if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning; ++r; // floor() to avoid _ftol() when non-CRT if (pow((float) r+1, dim) <= entries) return -1; if ((int) floor(pow((float) r, dim)) > entries) return -1; return r; } // called twice per file static void compute_twiddle_factors(int n, float *A, float *B, float *C) { int n4 = n >> 2, n8 = n >> 3; int k,k2; for (k=k2=0; k < n4; ++k,k2+=2) { A[k2 ] = (float) cos(4*k*M_PI/n); A[k2+1] = (float) -sin(4*k*M_PI/n); B[k2 ] = (float) cos((k2+1)*M_PI/n/2) * 0.5f; B[k2+1] = (float) sin((k2+1)*M_PI/n/2) * 0.5f; } for (k=k2=0; k < n8; ++k,k2+=2) { C[k2 ] = (float) cos(2*(k2+1)*M_PI/n); C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n); } } static void compute_window(int n, float *window) { int n2 = n >> 1, i; for (i=0; i < n2; ++i) window[i] = (float) sin(0.5 * M_PI * square((float) sin((i - 0 + 0.5) / n2 * 0.5 * M_PI))); } static void compute_bitreverse(int n, uint16 *rev) { int ld = ilog(n) - 1; // ilog is off-by-one from normal definitions int i, n8 = n >> 3; for (i=0; i < n8; ++i) rev[i] = (bit_reverse(i) >> (32-ld+3)) << 2; } static int init_blocksize(vorb *f, int b, int n) { int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3; f->A[b] = (float *) setup_malloc(f, sizeof(float) * n2); f->B[b] = (float *) setup_malloc(f, sizeof(float) * n2); f->C[b] = (float *) setup_malloc(f, sizeof(float) * n4); if (!f->A[b] || !f->B[b] || !f->C[b]) return error(f, VORBIS_outofmem); compute_twiddle_factors(n, f->A[b], f->B[b], f->C[b]); f->window[b] = (float *) setup_malloc(f, sizeof(float) * n2); if (!f->window[b]) return error(f, VORBIS_outofmem); compute_window(n, f->window[b]); f->bit_reverse[b] = (uint16 *) setup_malloc(f, sizeof(uint16) * n8); if (!f->bit_reverse[b]) return error(f, VORBIS_outofmem); compute_bitreverse(n, f->bit_reverse[b]); return TRUE; } static void neighbors(uint16 *x, int n, int *plow, int *phigh) { int low = -1; int high = 65536; int i; for (i=0; i < n; ++i) { if (x[i] > low && x[i] < x[n]) { *plow = i; low = x[i]; } if (x[i] < high && x[i] > x[n]) { *phigh = i; high = x[i]; } } } // this has been repurposed so y is now the original index instead of y typedef struct { uint16 x,id; } stbv__floor_ordering; static int STBV_CDECL point_compare(const void *p, const void *q) { stbv__floor_ordering *a = (stbv__floor_ordering *) p; stbv__floor_ordering *b = (stbv__floor_ordering *) q; return a->x < b->x ? -1 : a->x > b->x; } // /////////////////////// END LEAF SETUP FUNCTIONS ////////////////////////// #if defined(STB_VORBIS_NO_STDIO) #define USE_MEMORY(z) TRUE #else #define USE_MEMORY(z) ((z)->stream) #endif static uint8 get8(vorb *z) { if (USE_MEMORY(z)) { if (z->stream >= z->stream_end) { z->eof = TRUE; return 0; } return *z->stream++; } #ifndef STB_VORBIS_NO_STDIO { int c = fgetc(z->f); if (c == EOF) { z->eof = TRUE; return 0; } return c; } #endif } static uint32 get32(vorb *f) { uint32 x; x = get8(f); x += get8(f) << 8; x += get8(f) << 16; x += (uint32) get8(f) << 24; return x; } static int getn(vorb *z, uint8 *data, int n) { if (USE_MEMORY(z)) { if (z->stream+n > z->stream_end) { z->eof = 1; return 0; } memcpy(data, z->stream, n); z->stream += n; return 1; } #ifndef STB_VORBIS_NO_STDIO if (fread(data, n, 1, z->f) == 1) return 1; else { z->eof = 1; return 0; } #endif } static void skip(vorb *z, int n) { if (USE_MEMORY(z)) { z->stream += n; if (z->stream >= z->stream_end) z->eof = 1; return; } #ifndef STB_VORBIS_NO_STDIO { long x = ftell(z->f); fseek(z->f, x+n, SEEK_SET); } #endif } static int set_file_offset(stb_vorbis *f, unsigned int loc) { #ifndef STB_VORBIS_NO_PUSHDATA_API if (f->push_mode) return 0; #endif f->eof = 0; if (USE_MEMORY(f)) { if (f->stream_start + loc >= f->stream_end || f->stream_start + loc < f->stream_start) { f->stream = f->stream_end; f->eof = 1; return 0; } else { f->stream = f->stream_start + loc; return 1; } } #ifndef STB_VORBIS_NO_STDIO if (loc + f->f_start < loc || loc >= 0x80000000) { loc = 0x7fffffff; f->eof = 1; } else { loc += f->f_start; } if (!fseek(f->f, loc, SEEK_SET)) return 1; f->eof = 1; fseek(f->f, f->f_start, SEEK_END); return 0; #endif } static uint8 ogg_page_header[4] = { 0x4f, 0x67, 0x67, 0x53 }; static int capture_pattern(vorb *f) { if (0x4f != get8(f)) return FALSE; if (0x67 != get8(f)) return FALSE; if (0x67 != get8(f)) return FALSE; if (0x53 != get8(f)) return FALSE; return TRUE; } #define PAGEFLAG_continued_packet 1 #define PAGEFLAG_first_page 2 #define PAGEFLAG_last_page 4 static int start_page_no_capturepattern(vorb *f) { uint32 loc0,loc1,n; // stream structure version if (0 != get8(f)) return error(f, VORBIS_invalid_stream_structure_version); // header flag f->page_flag = get8(f); // absolute granule position loc0 = get32(f); loc1 = get32(f); // @TODO: validate loc0,loc1 as valid positions? // stream serial number -- vorbis doesn't interleave, so discard get32(f); //if (f->serial != get32(f)) return error(f, VORBIS_incorrect_stream_serial_number); // page sequence number n = get32(f); f->last_page = n; // CRC32 get32(f); // page_segments f->segment_count = get8(f); if (!getn(f, f->segments, f->segment_count)) return error(f, VORBIS_unexpected_eof); // assume we _don't_ know any the sample position of any segments f->end_seg_with_known_loc = -2; if (loc0 != ~0U || loc1 != ~0U) { int i; // determine which packet is the last one that will complete for (i=f->segment_count-1; i >= 0; --i) if (f->segments[i] < 255) break; // 'i' is now the index of the _last_ segment of a packet that ends if (i >= 0) { f->end_seg_with_known_loc = i; f->known_loc_for_packet = loc0; } } if (f->first_decode) { int i,len; ProbedPage p; len = 0; for (i=0; i < f->segment_count; ++i) len += f->segments[i]; len += 27 + f->segment_count; p.page_start = f->first_audio_page_offset; p.page_end = p.page_start + len; p.last_decoded_sample = loc0; f->p_first = p; } f->next_seg = 0; return TRUE; } static int start_page(vorb *f) { if (!capture_pattern(f)) return error(f, VORBIS_missing_capture_pattern); return start_page_no_capturepattern(f); } static int start_packet(vorb *f) { while (f->next_seg == -1) { if (!start_page(f)) return FALSE; if (f->page_flag & PAGEFLAG_continued_packet) return error(f, VORBIS_continued_packet_flag_invalid); } f->last_seg = FALSE; f->valid_bits = 0; f->packet_bytes = 0; f->bytes_in_seg = 0; // f->next_seg is now valid return TRUE; } static int maybe_start_packet(vorb *f) { if (f->next_seg == -1) { int x = get8(f); if (f->eof) return FALSE; // EOF at page boundary is not an error! if (0x4f != x ) return error(f, VORBIS_missing_capture_pattern); if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern); if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern); if (0x53 != get8(f)) return error(f, VORBIS_missing_capture_pattern); if (!start_page_no_capturepattern(f)) return FALSE; if (f->page_flag & PAGEFLAG_continued_packet) { // set up enough state that we can read this packet if we want, // e.g. during recovery f->last_seg = FALSE; f->bytes_in_seg = 0; return error(f, VORBIS_continued_packet_flag_invalid); } } return start_packet(f); } static int next_segment(vorb *f) { int len; if (f->last_seg) return 0; if (f->next_seg == -1) { f->last_seg_which = f->segment_count-1; // in case start_page fails if (!start_page(f)) { f->last_seg = 1; return 0; } if (!(f->page_flag & PAGEFLAG_continued_packet)) return error(f, VORBIS_continued_packet_flag_invalid); } len = f->segments[f->next_seg++]; if (len < 255) { f->last_seg = TRUE; f->last_seg_which = f->next_seg-1; } if (f->next_seg >= f->segment_count) f->next_seg = -1; assert(f->bytes_in_seg == 0); f->bytes_in_seg = len; return len; } #define EOP (-1) #define INVALID_BITS (-1) static int get8_packet_raw(vorb *f) { if (!f->bytes_in_seg) { // CLANG! if (f->last_seg) return EOP; else if (!next_segment(f)) return EOP; } assert(f->bytes_in_seg > 0); --f->bytes_in_seg; ++f->packet_bytes; return get8(f); } static int get8_packet(vorb *f) { int x = get8_packet_raw(f); f->valid_bits = 0; return x; } static void flush_packet(vorb *f) { while (get8_packet_raw(f) != EOP); } // @OPTIMIZE: this is the secondary bit decoder, so it's probably not as important // as the huffman decoder? static uint32 get_bits(vorb *f, int n) { uint32 z; if (f->valid_bits < 0) return 0; if (f->valid_bits < n) { if (n > 24) { // the accumulator technique below would not work correctly in this case z = get_bits(f, 24); z += get_bits(f, n-24) << 24; return z; } if (f->valid_bits == 0) f->acc = 0; while (f->valid_bits < n) { int z = get8_packet_raw(f); if (z == EOP) { f->valid_bits = INVALID_BITS; return 0; } f->acc += z << f->valid_bits; f->valid_bits += 8; } } if (f->valid_bits < 0) return 0; z = f->acc & ((1 << n)-1); f->acc >>= n; f->valid_bits -= n; return z; } // @OPTIMIZE: primary accumulator for huffman // expand the buffer to as many bits as possible without reading off end of packet // it might be nice to allow f->valid_bits and f->acc to be stored in registers, // e.g. cache them locally and decode locally static __forceinline void prep_huffman(vorb *f) { if (f->valid_bits <= 24) { if (f->valid_bits == 0) f->acc = 0; do { int z; if (f->last_seg && !f->bytes_in_seg) return; z = get8_packet_raw(f); if (z == EOP) return; f->acc += (unsigned) z << f->valid_bits; f->valid_bits += 8; } while (f->valid_bits <= 24); } } enum { VORBIS_packet_id = 1, VORBIS_packet_comment = 3, VORBIS_packet_setup = 5 }; static int codebook_decode_scalar_raw(vorb *f, Codebook *c) { int i; prep_huffman(f); if (c->codewords == NULL && c->sorted_codewords == NULL) return -1; // cases to use binary search: sorted_codewords && !c->codewords // sorted_codewords && c->entries > 8 if (c->entries > 8 ? c->sorted_codewords!=NULL : !c->codewords) { // binary search uint32 code = bit_reverse(f->acc); int x=0, n=c->sorted_entries, len; while (n > 1) { // invariant: sc[x] <= code < sc[x+n] int m = x + (n >> 1); if (c->sorted_codewords[m] <= code) { x = m; n -= (n>>1); } else { n >>= 1; } } // x is now the sorted index if (!c->sparse) x = c->sorted_values[x]; // x is now sorted index if sparse, or symbol otherwise len = c->codeword_lengths[x]; if (f->valid_bits >= len) { f->acc >>= len; f->valid_bits -= len; return x; } f->valid_bits = 0; return -1; } // if small, linear search assert(!c->sparse); for (i=0; i < c->entries; ++i) { if (c->codeword_lengths[i] == NO_CODE) continue; if (c->codewords[i] == (f->acc & ((1 << c->codeword_lengths[i])-1))) { if (f->valid_bits >= c->codeword_lengths[i]) { f->acc >>= c->codeword_lengths[i]; f->valid_bits -= c->codeword_lengths[i]; return i; } f->valid_bits = 0; return -1; } } error(f, VORBIS_invalid_stream); f->valid_bits = 0; return -1; } #ifndef STB_VORBIS_NO_INLINE_DECODE #define DECODE_RAW(var, f,c) \ if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH) \ prep_huffman(f); \ var = f->acc & FAST_HUFFMAN_TABLE_MASK; \ var = c->fast_huffman[var]; \ if (var >= 0) { \ int n = c->codeword_lengths[var]; \ f->acc >>= n; \ f->valid_bits -= n; \ if (f->valid_bits < 0) { f->valid_bits = 0; var = -1; } \ } else { \ var = codebook_decode_scalar_raw(f,c); \ } #else static int codebook_decode_scalar(vorb *f, Codebook *c) { int i; if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH) prep_huffman(f); // fast huffman table lookup i = f->acc & FAST_HUFFMAN_TABLE_MASK; i = c->fast_huffman[i]; if (i >= 0) { f->acc >>= c->codeword_lengths[i]; f->valid_bits -= c->codeword_lengths[i]; if (f->valid_bits < 0) { f->valid_bits = 0; return -1; } return i; } return codebook_decode_scalar_raw(f,c); } #define DECODE_RAW(var,f,c) var = codebook_decode_scalar(f,c); #endif #define DECODE(var,f,c) \ DECODE_RAW(var,f,c) \ if (c->sparse) var = c->sorted_values[var]; #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK #define DECODE_VQ(var,f,c) DECODE_RAW(var,f,c) #else #define DECODE_VQ(var,f,c) DECODE(var,f,c) #endif // CODEBOOK_ELEMENT_FAST is an optimization for the CODEBOOK_FLOATS case // where we avoid one addition #define CODEBOOK_ELEMENT(c,off) (c->multiplicands[off]) #define CODEBOOK_ELEMENT_FAST(c,off) (c->multiplicands[off]) #define CODEBOOK_ELEMENT_BASE(c) (0) static int codebook_decode_start(vorb *f, Codebook *c) { int z = -1; // type 0 is only legal in a scalar context if (c->lookup_type == 0) error(f, VORBIS_invalid_stream); else { DECODE_VQ(z,f,c); if (c->sparse) assert(z < c->sorted_entries); if (z < 0) { // check for EOP if (!f->bytes_in_seg) if (f->last_seg) return z; error(f, VORBIS_invalid_stream); } } return z; } static int codebook_decode(vorb *f, Codebook *c, float *output, int len) { int i,z = codebook_decode_start(f,c); if (z < 0) return FALSE; if (len > c->dimensions) len = c->dimensions; #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK if (c->lookup_type == 1) { float last = CODEBOOK_ELEMENT_BASE(c); int div = 1; for (i=0; i < len; ++i) { int off = (z / div) % c->lookup_values; float val = CODEBOOK_ELEMENT_FAST(c,off) + last; output[i] += val; if (c->sequence_p) last = val + c->minimum_value; div *= c->lookup_values; } return TRUE; } #endif z *= c->dimensions; if (c->sequence_p) { float last = CODEBOOK_ELEMENT_BASE(c); for (i=0; i < len; ++i) { float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last; output[i] += val; last = val + c->minimum_value; } } else { float last = CODEBOOK_ELEMENT_BASE(c); for (i=0; i < len; ++i) { output[i] += CODEBOOK_ELEMENT_FAST(c,z+i) + last; } } return TRUE; } static int codebook_decode_step(vorb *f, Codebook *c, float *output, int len, int step) { int i,z = codebook_decode_start(f,c); float last = CODEBOOK_ELEMENT_BASE(c); if (z < 0) return FALSE; if (len > c->dimensions) len = c->dimensions; #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK if (c->lookup_type == 1) { int div = 1; for (i=0; i < len; ++i) { int off = (z / div) % c->lookup_values; float val = CODEBOOK_ELEMENT_FAST(c,off) + last; output[i*step] += val; if (c->sequence_p) last = val; div *= c->lookup_values; } return TRUE; } #endif z *= c->dimensions; for (i=0; i < len; ++i) { float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last; output[i*step] += val; if (c->sequence_p) last = val; } return TRUE; } static int codebook_decode_deinterleave_repeat(vorb *f, Codebook *c, float **outputs, int ch, int *c_inter_p, int *p_inter_p, int len, int total_decode) { int c_inter = *c_inter_p; int p_inter = *p_inter_p; int i,z, effective = c->dimensions; // type 0 is only legal in a scalar context if (c->lookup_type == 0) return error(f, VORBIS_invalid_stream); while (total_decode > 0) { float last = CODEBOOK_ELEMENT_BASE(c); DECODE_VQ(z,f,c); #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK assert(!c->sparse || z < c->sorted_entries); #endif if (z < 0) { if (!f->bytes_in_seg) if (f->last_seg) return FALSE; return error(f, VORBIS_invalid_stream); } // if this will take us off the end of the buffers, stop short! // we check by computing the length of the virtual interleaved // buffer (len*ch), our current offset within it (p_inter*ch)+(c_inter), // and the length we'll be using (effective) if (c_inter + p_inter*ch + effective > len * ch) { effective = len*ch - (p_inter*ch - c_inter); } #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK if (c->lookup_type == 1) { int div = 1; for (i=0; i < effective; ++i) { int off = (z / div) % c->lookup_values; float val = CODEBOOK_ELEMENT_FAST(c,off) + last; if (outputs[c_inter]) outputs[c_inter][p_inter] += val; if (++c_inter == ch) { c_inter = 0; ++p_inter; } if (c->sequence_p) last = val; div *= c->lookup_values; } } else #endif { z *= c->dimensions; if (c->sequence_p) { for (i=0; i < effective; ++i) { float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last; if (outputs[c_inter]) outputs[c_inter][p_inter] += val; if (++c_inter == ch) { c_inter = 0; ++p_inter; } last = val; } } else { for (i=0; i < effective; ++i) { float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last; if (outputs[c_inter]) outputs[c_inter][p_inter] += val; if (++c_inter == ch) { c_inter = 0; ++p_inter; } } } } total_decode -= effective; } *c_inter_p = c_inter; *p_inter_p = p_inter; return TRUE; } static int predict_point(int x, int x0, int x1, int y0, int y1) { int dy = y1 - y0; int adx = x1 - x0; // @OPTIMIZE: force int division to round in the right direction... is this necessary on x86? int err = abs(dy) * (x - x0); int off = err / adx; return dy < 0 ? y0 - off : y0 + off; } // the following table is block-copied from the specification static float inverse_db_table[256] = { 1.0649863e-07f, 1.1341951e-07f, 1.2079015e-07f, 1.2863978e-07f, 1.3699951e-07f, 1.4590251e-07f, 1.5538408e-07f, 1.6548181e-07f, 1.7623575e-07f, 1.8768855e-07f, 1.9988561e-07f, 2.1287530e-07f, 2.2670913e-07f, 2.4144197e-07f, 2.5713223e-07f, 2.7384213e-07f, 2.9163793e-07f, 3.1059021e-07f, 3.3077411e-07f, 3.5226968e-07f, 3.7516214e-07f, 3.9954229e-07f, 4.2550680e-07f, 4.5315863e-07f, 4.8260743e-07f, 5.1396998e-07f, 5.4737065e-07f, 5.8294187e-07f, 6.2082472e-07f, 6.6116941e-07f, 7.0413592e-07f, 7.4989464e-07f, 7.9862701e-07f, 8.5052630e-07f, 9.0579828e-07f, 9.6466216e-07f, 1.0273513e-06f, 1.0941144e-06f, 1.1652161e-06f, 1.2409384e-06f, 1.3215816e-06f, 1.4074654e-06f, 1.4989305e-06f, 1.5963394e-06f, 1.7000785e-06f, 1.8105592e-06f, 1.9282195e-06f, 2.0535261e-06f, 2.1869758e-06f, 2.3290978e-06f, 2.4804557e-06f, 2.6416497e-06f, 2.8133190e-06f, 2.9961443e-06f, 3.1908506e-06f, 3.3982101e-06f, 3.6190449e-06f, 3.8542308e-06f, 4.1047004e-06f, 4.3714470e-06f, 4.6555282e-06f, 4.9580707e-06f, 5.2802740e-06f, 5.6234160e-06f, 5.9888572e-06f, 6.3780469e-06f, 6.7925283e-06f, 7.2339451e-06f, 7.7040476e-06f, 8.2047000e-06f, 8.7378876e-06f, 9.3057248e-06f, 9.9104632e-06f, 1.0554501e-05f, 1.1240392e-05f, 1.1970856e-05f, 1.2748789e-05f, 1.3577278e-05f, 1.4459606e-05f, 1.5399272e-05f, 1.6400004e-05f, 1.7465768e-05f, 1.8600792e-05f, 1.9809576e-05f, 2.1096914e-05f, 2.2467911e-05f, 2.3928002e-05f, 2.5482978e-05f, 2.7139006e-05f, 2.8902651e-05f, 3.0780908e-05f, 3.2781225e-05f, 3.4911534e-05f, 3.7180282e-05f, 3.9596466e-05f, 4.2169667e-05f, 4.4910090e-05f, 4.7828601e-05f, 5.0936773e-05f, 5.4246931e-05f, 5.7772202e-05f, 6.1526565e-05f, 6.5524908e-05f, 6.9783085e-05f, 7.4317983e-05f, 7.9147585e-05f, 8.4291040e-05f, 8.9768747e-05f, 9.5602426e-05f, 0.00010181521f, 0.00010843174f, 0.00011547824f, 0.00012298267f, 0.00013097477f, 0.00013948625f, 0.00014855085f, 0.00015820453f, 0.00016848555f, 0.00017943469f, 0.00019109536f, 0.00020351382f, 0.00021673929f, 0.00023082423f, 0.00024582449f, 0.00026179955f, 0.00027881276f, 0.00029693158f, 0.00031622787f, 0.00033677814f, 0.00035866388f, 0.00038197188f, 0.00040679456f, 0.00043323036f, 0.00046138411f, 0.00049136745f, 0.00052329927f, 0.00055730621f, 0.00059352311f, 0.00063209358f, 0.00067317058f, 0.00071691700f, 0.00076350630f, 0.00081312324f, 0.00086596457f, 0.00092223983f, 0.00098217216f, 0.0010459992f, 0.0011139742f, 0.0011863665f, 0.0012634633f, 0.0013455702f, 0.0014330129f, 0.0015261382f, 0.0016253153f, 0.0017309374f, 0.0018434235f, 0.0019632195f, 0.0020908006f, 0.0022266726f, 0.0023713743f, 0.0025254795f, 0.0026895994f, 0.0028643847f, 0.0030505286f, 0.0032487691f, 0.0034598925f, 0.0036847358f, 0.0039241906f, 0.0041792066f, 0.0044507950f, 0.0047400328f, 0.0050480668f, 0.0053761186f, 0.0057254891f, 0.0060975636f, 0.0064938176f, 0.0069158225f, 0.0073652516f, 0.0078438871f, 0.0083536271f, 0.0088964928f, 0.009474637f, 0.010090352f, 0.010746080f, 0.011444421f, 0.012188144f, 0.012980198f, 0.013823725f, 0.014722068f, 0.015678791f, 0.016697687f, 0.017782797f, 0.018938423f, 0.020169149f, 0.021479854f, 0.022875735f, 0.024362330f, 0.025945531f, 0.027631618f, 0.029427276f, 0.031339626f, 0.033376252f, 0.035545228f, 0.037855157f, 0.040315199f, 0.042935108f, 0.045725273f, 0.048696758f, 0.051861348f, 0.055231591f, 0.058820850f, 0.062643361f, 0.066714279f, 0.071049749f, 0.075666962f, 0.080584227f, 0.085821044f, 0.091398179f, 0.097337747f, 0.10366330f, 0.11039993f, 0.11757434f, 0.12521498f, 0.13335215f, 0.14201813f, 0.15124727f, 0.16107617f, 0.17154380f, 0.18269168f, 0.19456402f, 0.20720788f, 0.22067342f, 0.23501402f, 0.25028656f, 0.26655159f, 0.28387361f, 0.30232132f, 0.32196786f, 0.34289114f, 0.36517414f, 0.38890521f, 0.41417847f, 0.44109412f, 0.46975890f, 0.50028648f, 0.53279791f, 0.56742212f, 0.60429640f, 0.64356699f, 0.68538959f, 0.72993007f, 0.77736504f, 0.82788260f, 0.88168307f, 0.9389798f, 1.0f }; // @OPTIMIZE: if you want to replace this bresenham line-drawing routine, // note that you must produce bit-identical output to decode correctly; // this specific sequence of operations is specified in the spec (it's // drawing integer-quantized frequency-space lines that the encoder // expects to be exactly the same) // ... also, isn't the whole point of Bresenham's algorithm to NOT // have to divide in the setup? sigh. #ifndef STB_VORBIS_NO_DEFER_FLOOR #define LINE_OP(a,b) a *= b #else #define LINE_OP(a,b) a = b #endif #ifdef STB_VORBIS_DIVIDE_TABLE #define DIVTAB_NUMER 32 #define DIVTAB_DENOM 64 int8 integer_divide_table[DIVTAB_NUMER][DIVTAB_DENOM]; // 2KB #endif static __forceinline void draw_line(float *output, int x0, int y0, int x1, int y1, int n) { int dy = y1 - y0; int adx = x1 - x0; int ady = abs(dy); int base; int x=x0,y=y0; int err = 0; int sy; #ifdef STB_VORBIS_DIVIDE_TABLE if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) { if (dy < 0) { base = -integer_divide_table[ady][adx]; sy = base-1; } else { base = integer_divide_table[ady][adx]; sy = base+1; } } else { base = dy / adx; if (dy < 0) sy = base - 1; else sy = base+1; } #else base = dy / adx; if (dy < 0) sy = base - 1; else sy = base+1; #endif ady -= abs(base) * adx; if (x1 > n) x1 = n; if (x < x1) { LINE_OP(output[x], inverse_db_table[y&255]); for (++x; x < x1; ++x) { err += ady; if (err >= adx) { err -= adx; y += sy; } else y += base; LINE_OP(output[x], inverse_db_table[y&255]); } } } static int residue_decode(vorb *f, Codebook *book, float *target, int offset, int n, int rtype) { int k; if (rtype == 0) { int step = n / book->dimensions; for (k=0; k < step; ++k) if (!codebook_decode_step(f, book, target+offset+k, n-offset-k, step)) return FALSE; } else { for (k=0; k < n; ) { if (!codebook_decode(f, book, target+offset, n-k)) return FALSE; k += book->dimensions; offset += book->dimensions; } } return TRUE; } // n is 1/2 of the blocksize -- // specification: "Correct per-vector decode length is [n]/2" static void decode_residue(vorb *f, float *residue_buffers[], int ch, int n, int rn, uint8 *do_not_decode) { int i,j,pass; Residue *r = f->residue_config + rn; int rtype = f->residue_types[rn]; int c = r->classbook; int classwords = f->codebooks[c].dimensions; unsigned int actual_size = rtype == 2 ? n*2 : n; unsigned int limit_r_begin = (r->begin < actual_size ? r->begin : actual_size); unsigned int limit_r_end = (r->end < actual_size ? r->end : actual_size); int n_read = limit_r_end - limit_r_begin; int part_read = n_read / r->part_size; int temp_alloc_point = temp_alloc_save(f); #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE uint8 ***part_classdata = (uint8 ***) temp_block_array(f,f->channels, part_read * sizeof(**part_classdata)); #else int **classifications = (int **) temp_block_array(f,f->channels, part_read * sizeof(**classifications)); #endif CHECK(f); for (i=0; i < ch; ++i) if (!do_not_decode[i]) memset(residue_buffers[i], 0, sizeof(float) * n); if (rtype == 2 && ch != 1) { for (j=0; j < ch; ++j) if (!do_not_decode[j]) break; if (j == ch) goto done; for (pass=0; pass < 8; ++pass) { int pcount = 0, class_set = 0; if (ch == 2) { while (pcount < part_read) { int z = r->begin + pcount*r->part_size; int c_inter = (z & 1), p_inter = z>>1; if (pass == 0) { Codebook *c = f->codebooks+r->classbook; int q; DECODE(q,f,c); if (q == EOP) goto done; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE part_classdata[0][class_set] = r->classdata[q]; #else for (i=classwords-1; i >= 0; --i) { classifications[0][i+pcount] = q % r->classifications; q /= r->classifications; } #endif } for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) { int z = r->begin + pcount*r->part_size; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE int c = part_classdata[0][class_set][i]; #else int c = classifications[0][pcount]; #endif int b = r->residue_books[c][pass]; if (b >= 0) { Codebook *book = f->codebooks + b; #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) goto done; #else // saves 1% if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) goto done; #endif } else { z += r->part_size; c_inter = z & 1; p_inter = z >> 1; } } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE ++class_set; #endif } } else if (ch == 1) { while (pcount < part_read) { int z = r->begin + pcount*r->part_size; int c_inter = 0, p_inter = z; if (pass == 0) { Codebook *c = f->codebooks+r->classbook; int q; DECODE(q,f,c); if (q == EOP) goto done; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE part_classdata[0][class_set] = r->classdata[q]; #else for (i=classwords-1; i >= 0; --i) { classifications[0][i+pcount] = q % r->classifications; q /= r->classifications; } #endif } for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) { int z = r->begin + pcount*r->part_size; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE int c = part_classdata[0][class_set][i]; #else int c = classifications[0][pcount]; #endif int b = r->residue_books[c][pass]; if (b >= 0) { Codebook *book = f->codebooks + b; if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) goto done; } else { z += r->part_size; c_inter = 0; p_inter = z; } } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE ++class_set; #endif } } else { while (pcount < part_read) { int z = r->begin + pcount*r->part_size; int c_inter = z % ch, p_inter = z/ch; if (pass == 0) { Codebook *c = f->codebooks+r->classbook; int q; DECODE(q,f,c); if (q == EOP) goto done; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE part_classdata[0][class_set] = r->classdata[q]; #else for (i=classwords-1; i >= 0; --i) { classifications[0][i+pcount] = q % r->classifications; q /= r->classifications; } #endif } for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) { int z = r->begin + pcount*r->part_size; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE int c = part_classdata[0][class_set][i]; #else int c = classifications[0][pcount]; #endif int b = r->residue_books[c][pass]; if (b >= 0) { Codebook *book = f->codebooks + b; if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) goto done; } else { z += r->part_size; c_inter = z % ch; p_inter = z / ch; } } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE ++class_set; #endif } } } goto done; } CHECK(f); for (pass=0; pass < 8; ++pass) { int pcount = 0, class_set=0; while (pcount < part_read) { if (pass == 0) { for (j=0; j < ch; ++j) { if (!do_not_decode[j]) { Codebook *c = f->codebooks+r->classbook; int temp; DECODE(temp,f,c); if (temp == EOP) goto done; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE part_classdata[j][class_set] = r->classdata[temp]; #else for (i=classwords-1; i >= 0; --i) { classifications[j][i+pcount] = temp % r->classifications; temp /= r->classifications; } #endif } } } for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) { for (j=0; j < ch; ++j) { if (!do_not_decode[j]) { #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE int c = part_classdata[j][class_set][i]; #else int c = classifications[j][pcount]; #endif int b = r->residue_books[c][pass]; if (b >= 0) { float *target = residue_buffers[j]; int offset = r->begin + pcount * r->part_size; int n = r->part_size; Codebook *book = f->codebooks + b; if (!residue_decode(f, book, target, offset, n, rtype)) goto done; } } } } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE ++class_set; #endif } } done: CHECK(f); #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE temp_free(f,part_classdata); #else temp_free(f,classifications); #endif temp_alloc_restore(f,temp_alloc_point); } #if 0 // slow way for debugging void inverse_mdct_slow(float *buffer, int n) { int i,j; int n2 = n >> 1; float *x = (float *) malloc(sizeof(*x) * n2); memcpy(x, buffer, sizeof(*x) * n2); for (i=0; i < n; ++i) { float acc = 0; for (j=0; j < n2; ++j) // formula from paper: //acc += n/4.0f * x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1)); // formula from wikipedia //acc += 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5)); // these are equivalent, except the formula from the paper inverts the multiplier! // however, what actually works is NO MULTIPLIER!?! //acc += 64 * 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5)); acc += x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1)); buffer[i] = acc; } free(x); } #elif 0 // same as above, but just barely able to run in real time on modern machines void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype) { float mcos[16384]; int i,j; int n2 = n >> 1, nmask = (n << 2) -1; float *x = (float *) malloc(sizeof(*x) * n2); memcpy(x, buffer, sizeof(*x) * n2); for (i=0; i < 4*n; ++i) mcos[i] = (float) cos(M_PI / 2 * i / n); for (i=0; i < n; ++i) { float acc = 0; for (j=0; j < n2; ++j) acc += x[j] * mcos[(2 * i + 1 + n2)*(2*j+1) & nmask]; buffer[i] = acc; } free(x); } #elif 0 // transform to use a slow dct-iv; this is STILL basically trivial, // but only requires half as many ops void dct_iv_slow(float *buffer, int n) { float mcos[16384]; float x[2048]; int i,j; int n2 = n >> 1, nmask = (n << 3) - 1; memcpy(x, buffer, sizeof(*x) * n); for (i=0; i < 8*n; ++i) mcos[i] = (float) cos(M_PI / 4 * i / n); for (i=0; i < n; ++i) { float acc = 0; for (j=0; j < n; ++j) acc += x[j] * mcos[((2 * i + 1)*(2*j+1)) & nmask]; buffer[i] = acc; } } void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype) { int i, n4 = n >> 2, n2 = n >> 1, n3_4 = n - n4; float temp[4096]; memcpy(temp, buffer, n2 * sizeof(float)); dct_iv_slow(temp, n2); // returns -c'-d, a-b' for (i=0; i < n4 ; ++i) buffer[i] = temp[i+n4]; // a-b' for ( ; i < n3_4; ++i) buffer[i] = -temp[n3_4 - i - 1]; // b-a', c+d' for ( ; i < n ; ++i) buffer[i] = -temp[i - n3_4]; // c'+d } #endif #ifndef LIBVORBIS_MDCT #define LIBVORBIS_MDCT 0 #endif #if LIBVORBIS_MDCT // directly call the vorbis MDCT using an interface documented // by Jeff Roberts... useful for performance comparison typedef struct { int n; int log2n; float *trig; int *bitrev; float scale; } mdct_lookup; extern void mdct_init(mdct_lookup *lookup, int n); extern void mdct_clear(mdct_lookup *l); extern void mdct_backward(mdct_lookup *init, float *in, float *out); mdct_lookup M1,M2; void inverse_mdct(float *buffer, int n, vorb *f, int blocktype) { mdct_lookup *M; if (M1.n == n) M = &M1; else if (M2.n == n) M = &M2; else if (M1.n == 0) { mdct_init(&M1, n); M = &M1; } else { if (M2.n) __asm int 3; mdct_init(&M2, n); M = &M2; } mdct_backward(M, buffer, buffer); } #endif // the following were split out into separate functions while optimizing; // they could be pushed back up but eh. __forceinline showed no change; // they're probably already being inlined. static void imdct_step3_iter0_loop(int n, float *e, int i_off, int k_off, float *A) { float *ee0 = e + i_off; float *ee2 = ee0 + k_off; int i; assert((n & 3) == 0); for (i=(n>>2); i > 0; --i) { float k00_20, k01_21; k00_20 = ee0[ 0] - ee2[ 0]; k01_21 = ee0[-1] - ee2[-1]; ee0[ 0] += ee2[ 0];//ee0[ 0] = ee0[ 0] + ee2[ 0]; ee0[-1] += ee2[-1];//ee0[-1] = ee0[-1] + ee2[-1]; ee2[ 0] = k00_20 * A[0] - k01_21 * A[1]; ee2[-1] = k01_21 * A[0] + k00_20 * A[1]; A += 8; k00_20 = ee0[-2] - ee2[-2]; k01_21 = ee0[-3] - ee2[-3]; ee0[-2] += ee2[-2];//ee0[-2] = ee0[-2] + ee2[-2]; ee0[-3] += ee2[-3];//ee0[-3] = ee0[-3] + ee2[-3]; ee2[-2] = k00_20 * A[0] - k01_21 * A[1]; ee2[-3] = k01_21 * A[0] + k00_20 * A[1]; A += 8; k00_20 = ee0[-4] - ee2[-4]; k01_21 = ee0[-5] - ee2[-5]; ee0[-4] += ee2[-4];//ee0[-4] = ee0[-4] + ee2[-4]; ee0[-5] += ee2[-5];//ee0[-5] = ee0[-5] + ee2[-5]; ee2[-4] = k00_20 * A[0] - k01_21 * A[1]; ee2[-5] = k01_21 * A[0] + k00_20 * A[1]; A += 8; k00_20 = ee0[-6] - ee2[-6]; k01_21 = ee0[-7] - ee2[-7]; ee0[-6] += ee2[-6];//ee0[-6] = ee0[-6] + ee2[-6]; ee0[-7] += ee2[-7];//ee0[-7] = ee0[-7] + ee2[-7]; ee2[-6] = k00_20 * A[0] - k01_21 * A[1]; ee2[-7] = k01_21 * A[0] + k00_20 * A[1]; A += 8; ee0 -= 8; ee2 -= 8; } } static void imdct_step3_inner_r_loop(int lim, float *e, int d0, int k_off, float *A, int k1) { int i; float k00_20, k01_21; float *e0 = e + d0; float *e2 = e0 + k_off; for (i=lim >> 2; i > 0; --i) { k00_20 = e0[-0] - e2[-0]; k01_21 = e0[-1] - e2[-1]; e0[-0] += e2[-0];//e0[-0] = e0[-0] + e2[-0]; e0[-1] += e2[-1];//e0[-1] = e0[-1] + e2[-1]; e2[-0] = (k00_20)*A[0] - (k01_21) * A[1]; e2[-1] = (k01_21)*A[0] + (k00_20) * A[1]; A += k1; k00_20 = e0[-2] - e2[-2]; k01_21 = e0[-3] - e2[-3]; e0[-2] += e2[-2];//e0[-2] = e0[-2] + e2[-2]; e0[-3] += e2[-3];//e0[-3] = e0[-3] + e2[-3]; e2[-2] = (k00_20)*A[0] - (k01_21) * A[1]; e2[-3] = (k01_21)*A[0] + (k00_20) * A[1]; A += k1; k00_20 = e0[-4] - e2[-4]; k01_21 = e0[-5] - e2[-5]; e0[-4] += e2[-4];//e0[-4] = e0[-4] + e2[-4]; e0[-5] += e2[-5];//e0[-5] = e0[-5] + e2[-5]; e2[-4] = (k00_20)*A[0] - (k01_21) * A[1]; e2[-5] = (k01_21)*A[0] + (k00_20) * A[1]; A += k1; k00_20 = e0[-6] - e2[-6]; k01_21 = e0[-7] - e2[-7]; e0[-6] += e2[-6];//e0[-6] = e0[-6] + e2[-6]; e0[-7] += e2[-7];//e0[-7] = e0[-7] + e2[-7]; e2[-6] = (k00_20)*A[0] - (k01_21) * A[1]; e2[-7] = (k01_21)*A[0] + (k00_20) * A[1]; e0 -= 8; e2 -= 8; A += k1; } } static void imdct_step3_inner_s_loop(int n, float *e, int i_off, int k_off, float *A, int a_off, int k0) { int i; float A0 = A[0]; float A1 = A[0+1]; float A2 = A[0+a_off]; float A3 = A[0+a_off+1]; float A4 = A[0+a_off*2+0]; float A5 = A[0+a_off*2+1]; float A6 = A[0+a_off*3+0]; float A7 = A[0+a_off*3+1]; float k00,k11; float *ee0 = e +i_off; float *ee2 = ee0+k_off; for (i=n; i > 0; --i) { k00 = ee0[ 0] - ee2[ 0]; k11 = ee0[-1] - ee2[-1]; ee0[ 0] = ee0[ 0] + ee2[ 0]; ee0[-1] = ee0[-1] + ee2[-1]; ee2[ 0] = (k00) * A0 - (k11) * A1; ee2[-1] = (k11) * A0 + (k00) * A1; k00 = ee0[-2] - ee2[-2]; k11 = ee0[-3] - ee2[-3]; ee0[-2] = ee0[-2] + ee2[-2]; ee0[-3] = ee0[-3] + ee2[-3]; ee2[-2] = (k00) * A2 - (k11) * A3; ee2[-3] = (k11) * A2 + (k00) * A3; k00 = ee0[-4] - ee2[-4]; k11 = ee0[-5] - ee2[-5]; ee0[-4] = ee0[-4] + ee2[-4]; ee0[-5] = ee0[-5] + ee2[-5]; ee2[-4] = (k00) * A4 - (k11) * A5; ee2[-5] = (k11) * A4 + (k00) * A5; k00 = ee0[-6] - ee2[-6]; k11 = ee0[-7] - ee2[-7]; ee0[-6] = ee0[-6] + ee2[-6]; ee0[-7] = ee0[-7] + ee2[-7]; ee2[-6] = (k00) * A6 - (k11) * A7; ee2[-7] = (k11) * A6 + (k00) * A7; ee0 -= k0; ee2 -= k0; } } static __forceinline void iter_54(float *z) { float k00,k11,k22,k33; float y0,y1,y2,y3; k00 = z[ 0] - z[-4]; y0 = z[ 0] + z[-4]; y2 = z[-2] + z[-6]; k22 = z[-2] - z[-6]; z[-0] = y0 + y2; // z0 + z4 + z2 + z6 z[-2] = y0 - y2; // z0 + z4 - z2 - z6 // done with y0,y2 k33 = z[-3] - z[-7]; z[-4] = k00 + k33; // z0 - z4 + z3 - z7 z[-6] = k00 - k33; // z0 - z4 - z3 + z7 // done with k33 k11 = z[-1] - z[-5]; y1 = z[-1] + z[-5]; y3 = z[-3] + z[-7]; z[-1] = y1 + y3; // z1 + z5 + z3 + z7 z[-3] = y1 - y3; // z1 + z5 - z3 - z7 z[-5] = k11 - k22; // z1 - z5 + z2 - z6 z[-7] = k11 + k22; // z1 - z5 - z2 + z6 } static void imdct_step3_inner_s_loop_ld654(int n, float *e, int i_off, float *A, int base_n) { int a_off = base_n >> 3; float A2 = A[0+a_off]; float *z = e + i_off; float *base = z - 16 * n; while (z > base) { float k00,k11; k00 = z[-0] - z[-8]; k11 = z[-1] - z[-9]; z[-0] = z[-0] + z[-8]; z[-1] = z[-1] + z[-9]; z[-8] = k00; z[-9] = k11 ; k00 = z[ -2] - z[-10]; k11 = z[ -3] - z[-11]; z[ -2] = z[ -2] + z[-10]; z[ -3] = z[ -3] + z[-11]; z[-10] = (k00+k11) * A2; z[-11] = (k11-k00) * A2; k00 = z[-12] - z[ -4]; // reverse to avoid a unary negation k11 = z[ -5] - z[-13]; z[ -4] = z[ -4] + z[-12]; z[ -5] = z[ -5] + z[-13]; z[-12] = k11; z[-13] = k00; k00 = z[-14] - z[ -6]; // reverse to avoid a unary negation k11 = z[ -7] - z[-15]; z[ -6] = z[ -6] + z[-14]; z[ -7] = z[ -7] + z[-15]; z[-14] = (k00+k11) * A2; z[-15] = (k00-k11) * A2; iter_54(z); iter_54(z-8); z -= 16; } } static void inverse_mdct(float *buffer, int n, vorb *f, int blocktype) { int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l; int ld; // @OPTIMIZE: reduce register pressure by using fewer variables? int save_point = temp_alloc_save(f); float *buf2 = (float *) temp_alloc(f, n2 * sizeof(*buf2)); float *u=NULL,*v=NULL; // twiddle factors float *A = f->A[blocktype]; // IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio" // See notes about bugs in that paper in less-optimal implementation 'inverse_mdct_old' after this function. // kernel from paper // merged: // copy and reflect spectral data // step 0 // note that it turns out that the items added together during // this step are, in fact, being added to themselves (as reflected // by step 0). inexplicable inefficiency! this became obvious // once I combined the passes. // so there's a missing 'times 2' here (for adding X to itself). // this propagates through linearly to the end, where the numbers // are 1/2 too small, and need to be compensated for. { float *d,*e, *AA, *e_stop; d = &buf2[n2-2]; AA = A; e = &buffer[0]; e_stop = &buffer[n2]; while (e != e_stop) { d[1] = (e[0] * AA[0] - e[2]*AA[1]); d[0] = (e[0] * AA[1] + e[2]*AA[0]); d -= 2; AA += 2; e += 4; } e = &buffer[n2-3]; while (d >= buf2) { d[1] = (-e[2] * AA[0] - -e[0]*AA[1]); d[0] = (-e[2] * AA[1] + -e[0]*AA[0]); d -= 2; AA += 2; e -= 4; } } // now we use symbolic names for these, so that we can // possibly swap their meaning as we change which operations // are in place u = buffer; v = buf2; // step 2 (paper output is w, now u) // this could be in place, but the data ends up in the wrong // place... _somebody_'s got to swap it, so this is nominated { float *AA = &A[n2-8]; float *d0,*d1, *e0, *e1; e0 = &v[n4]; e1 = &v[0]; d0 = &u[n4]; d1 = &u[0]; while (AA >= A) { float v40_20, v41_21; v41_21 = e0[1] - e1[1]; v40_20 = e0[0] - e1[0]; d0[1] = e0[1] + e1[1]; d0[0] = e0[0] + e1[0]; d1[1] = v41_21*AA[4] - v40_20*AA[5]; d1[0] = v40_20*AA[4] + v41_21*AA[5]; v41_21 = e0[3] - e1[3]; v40_20 = e0[2] - e1[2]; d0[3] = e0[3] + e1[3]; d0[2] = e0[2] + e1[2]; d1[3] = v41_21*AA[0] - v40_20*AA[1]; d1[2] = v40_20*AA[0] + v41_21*AA[1]; AA -= 8; d0 += 4; d1 += 4; e0 += 4; e1 += 4; } } // step 3 ld = ilog(n) - 1; // ilog is off-by-one from normal definitions // optimized step 3: // the original step3 loop can be nested r inside s or s inside r; // it's written originally as s inside r, but this is dumb when r // iterates many times, and s few. So I have two copies of it and // switch between them halfway. // this is iteration 0 of step 3 imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*0, -(n >> 3), A); imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*1, -(n >> 3), A); // this is iteration 1 of step 3 imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*0, -(n >> 4), A, 16); imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*1, -(n >> 4), A, 16); imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*2, -(n >> 4), A, 16); imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*3, -(n >> 4), A, 16); l=2; for (; l < (ld-3)>>1; ++l) { int k0 = n >> (l+2), k0_2 = k0>>1; int lim = 1 << (l+1); int i; for (i=0; i < lim; ++i) imdct_step3_inner_r_loop(n >> (l+4), u, n2-1 - k0*i, -k0_2, A, 1 << (l+3)); } for (; l < ld-6; ++l) { int k0 = n >> (l+2), k1 = 1 << (l+3), k0_2 = k0>>1; int rlim = n >> (l+6), r; int lim = 1 << (l+1); int i_off; float *A0 = A; i_off = n2-1; for (r=rlim; r > 0; --r) { imdct_step3_inner_s_loop(lim, u, i_off, -k0_2, A0, k1, k0); A0 += k1*4; i_off -= 8; } } // iterations with count: // ld-6,-5,-4 all interleaved together // the big win comes from getting rid of needless flops // due to the constants on pass 5 & 4 being all 1 and 0; // combining them to be simultaneous to improve cache made little difference imdct_step3_inner_s_loop_ld654(n >> 5, u, n2-1, A, n); // output is u // step 4, 5, and 6 // cannot be in-place because of step 5 { uint16 *bitrev = f->bit_reverse[blocktype]; // weirdly, I'd have thought reading sequentially and writing // erratically would have been better than vice-versa, but in // fact that's not what my testing showed. (That is, with // j = bitreverse(i), do you read i and write j, or read j and write i.) float *d0 = &v[n4-4]; float *d1 = &v[n2-4]; while (d0 >= v) { int k4; k4 = bitrev[0]; d1[3] = u[k4+0]; d1[2] = u[k4+1]; d0[3] = u[k4+2]; d0[2] = u[k4+3]; k4 = bitrev[1]; d1[1] = u[k4+0]; d1[0] = u[k4+1]; d0[1] = u[k4+2]; d0[0] = u[k4+3]; d0 -= 4; d1 -= 4; bitrev += 2; } } // (paper output is u, now v) // data must be in buf2 assert(v == buf2); // step 7 (paper output is v, now v) // this is now in place { float *C = f->C[blocktype]; float *d, *e; d = v; e = v + n2 - 4; while (d < e) { float a02,a11,b0,b1,b2,b3; a02 = d[0] - e[2]; a11 = d[1] + e[3]; b0 = C[1]*a02 + C[0]*a11; b1 = C[1]*a11 - C[0]*a02; b2 = d[0] + e[ 2]; b3 = d[1] - e[ 3]; d[0] = b2 + b0; d[1] = b3 + b1; e[2] = b2 - b0; e[3] = b1 - b3; a02 = d[2] - e[0]; a11 = d[3] + e[1]; b0 = C[3]*a02 + C[2]*a11; b1 = C[3]*a11 - C[2]*a02; b2 = d[2] + e[ 0]; b3 = d[3] - e[ 1]; d[2] = b2 + b0; d[3] = b3 + b1; e[0] = b2 - b0; e[1] = b1 - b3; C += 4; d += 4; e -= 4; } } // data must be in buf2 // step 8+decode (paper output is X, now buffer) // this generates pairs of data a la 8 and pushes them directly through // the decode kernel (pushing rather than pulling) to avoid having // to make another pass later // this cannot POSSIBLY be in place, so we refer to the buffers directly { float *d0,*d1,*d2,*d3; float *B = f->B[blocktype] + n2 - 8; float *e = buf2 + n2 - 8; d0 = &buffer[0]; d1 = &buffer[n2-4]; d2 = &buffer[n2]; d3 = &buffer[n-4]; while (e >= v) { float p0,p1,p2,p3; p3 = e[6]*B[7] - e[7]*B[6]; p2 = -e[6]*B[6] - e[7]*B[7]; d0[0] = p3; d1[3] = - p3; d2[0] = p2; d3[3] = p2; p1 = e[4]*B[5] - e[5]*B[4]; p0 = -e[4]*B[4] - e[5]*B[5]; d0[1] = p1; d1[2] = - p1; d2[1] = p0; d3[2] = p0; p3 = e[2]*B[3] - e[3]*B[2]; p2 = -e[2]*B[2] - e[3]*B[3]; d0[2] = p3; d1[1] = - p3; d2[2] = p2; d3[1] = p2; p1 = e[0]*B[1] - e[1]*B[0]; p0 = -e[0]*B[0] - e[1]*B[1]; d0[3] = p1; d1[0] = - p1; d2[3] = p0; d3[0] = p0; B -= 8; e -= 8; d0 += 4; d2 += 4; d1 -= 4; d3 -= 4; } } temp_free(f,buf2); temp_alloc_restore(f,save_point); } #if 0 // this is the original version of the above code, if you want to optimize it from scratch void inverse_mdct_naive(float *buffer, int n) { float s; float A[1 << 12], B[1 << 12], C[1 << 11]; int i,k,k2,k4, n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l; int n3_4 = n - n4, ld; // how can they claim this only uses N words?! // oh, because they're only used sparsely, whoops float u[1 << 13], X[1 << 13], v[1 << 13], w[1 << 13]; // set up twiddle factors for (k=k2=0; k < n4; ++k,k2+=2) { A[k2 ] = (float) cos(4*k*M_PI/n); A[k2+1] = (float) -sin(4*k*M_PI/n); B[k2 ] = (float) cos((k2+1)*M_PI/n/2); B[k2+1] = (float) sin((k2+1)*M_PI/n/2); } for (k=k2=0; k < n8; ++k,k2+=2) { C[k2 ] = (float) cos(2*(k2+1)*M_PI/n); C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n); } // IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio" // Note there are bugs in that pseudocode, presumably due to them attempting // to rename the arrays nicely rather than representing the way their actual // implementation bounces buffers back and forth. As a result, even in the // "some formulars corrected" version, a direct implementation fails. These // are noted below as "paper bug". // copy and reflect spectral data for (k=0; k < n2; ++k) u[k] = buffer[k]; for ( ; k < n ; ++k) u[k] = -buffer[n - k - 1]; // kernel from paper // step 1 for (k=k2=k4=0; k < n4; k+=1, k2+=2, k4+=4) { v[n-k4-1] = (u[k4] - u[n-k4-1]) * A[k2] - (u[k4+2] - u[n-k4-3])*A[k2+1]; v[n-k4-3] = (u[k4] - u[n-k4-1]) * A[k2+1] + (u[k4+2] - u[n-k4-3])*A[k2]; } // step 2 for (k=k4=0; k < n8; k+=1, k4+=4) { w[n2+3+k4] = v[n2+3+k4] + v[k4+3]; w[n2+1+k4] = v[n2+1+k4] + v[k4+1]; w[k4+3] = (v[n2+3+k4] - v[k4+3])*A[n2-4-k4] - (v[n2+1+k4]-v[k4+1])*A[n2-3-k4]; w[k4+1] = (v[n2+1+k4] - v[k4+1])*A[n2-4-k4] + (v[n2+3+k4]-v[k4+3])*A[n2-3-k4]; } // step 3 ld = ilog(n) - 1; // ilog is off-by-one from normal definitions for (l=0; l < ld-3; ++l) { int k0 = n >> (l+2), k1 = 1 << (l+3); int rlim = n >> (l+4), r4, r; int s2lim = 1 << (l+2), s2; for (r=r4=0; r < rlim; r4+=4,++r) { for (s2=0; s2 < s2lim; s2+=2) { u[n-1-k0*s2-r4] = w[n-1-k0*s2-r4] + w[n-1-k0*(s2+1)-r4]; u[n-3-k0*s2-r4] = w[n-3-k0*s2-r4] + w[n-3-k0*(s2+1)-r4]; u[n-1-k0*(s2+1)-r4] = (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1] - (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1+1]; u[n-3-k0*(s2+1)-r4] = (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1] + (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1+1]; } } if (l+1 < ld-3) { // paper bug: ping-ponging of u&w here is omitted memcpy(w, u, sizeof(u)); } } // step 4 for (i=0; i < n8; ++i) { int j = bit_reverse(i) >> (32-ld+3); assert(j < n8); if (i == j) { // paper bug: original code probably swapped in place; if copying, // need to directly copy in this case int i8 = i << 3; v[i8+1] = u[i8+1]; v[i8+3] = u[i8+3]; v[i8+5] = u[i8+5]; v[i8+7] = u[i8+7]; } else if (i < j) { int i8 = i << 3, j8 = j << 3; v[j8+1] = u[i8+1], v[i8+1] = u[j8 + 1]; v[j8+3] = u[i8+3], v[i8+3] = u[j8 + 3]; v[j8+5] = u[i8+5], v[i8+5] = u[j8 + 5]; v[j8+7] = u[i8+7], v[i8+7] = u[j8 + 7]; } } // step 5 for (k=0; k < n2; ++k) { w[k] = v[k*2+1]; } // step 6 for (k=k2=k4=0; k < n8; ++k, k2 += 2, k4 += 4) { u[n-1-k2] = w[k4]; u[n-2-k2] = w[k4+1]; u[n3_4 - 1 - k2] = w[k4+2]; u[n3_4 - 2 - k2] = w[k4+3]; } // step 7 for (k=k2=0; k < n8; ++k, k2 += 2) { v[n2 + k2 ] = ( u[n2 + k2] + u[n-2-k2] + C[k2+1]*(u[n2+k2]-u[n-2-k2]) + C[k2]*(u[n2+k2+1]+u[n-2-k2+1]))/2; v[n-2 - k2] = ( u[n2 + k2] + u[n-2-k2] - C[k2+1]*(u[n2+k2]-u[n-2-k2]) - C[k2]*(u[n2+k2+1]+u[n-2-k2+1]))/2; v[n2+1+ k2] = ( u[n2+1+k2] - u[n-1-k2] + C[k2+1]*(u[n2+1+k2]+u[n-1-k2]) - C[k2]*(u[n2+k2]-u[n-2-k2]))/2; v[n-1 - k2] = (-u[n2+1+k2] + u[n-1-k2] + C[k2+1]*(u[n2+1+k2]+u[n-1-k2]) - C[k2]*(u[n2+k2]-u[n-2-k2]))/2; } // step 8 for (k=k2=0; k < n4; ++k,k2 += 2) { X[k] = v[k2+n2]*B[k2 ] + v[k2+1+n2]*B[k2+1]; X[n2-1-k] = v[k2+n2]*B[k2+1] - v[k2+1+n2]*B[k2 ]; } // decode kernel to output // determined the following value experimentally // (by first figuring out what made inverse_mdct_slow work); then matching that here // (probably vorbis encoder premultiplies by n or n/2, to save it on the decoder?) s = 0.5; // theoretically would be n4 // [[[ note! the s value of 0.5 is compensated for by the B[] in the current code, // so it needs to use the "old" B values to behave correctly, or else // set s to 1.0 ]]] for (i=0; i < n4 ; ++i) buffer[i] = s * X[i+n4]; for ( ; i < n3_4; ++i) buffer[i] = -s * X[n3_4 - i - 1]; for ( ; i < n ; ++i) buffer[i] = -s * X[i - n3_4]; } #endif static float *get_window(vorb *f, int len) { len <<= 1; if (len == f->blocksize_0) return f->window[0]; if (len == f->blocksize_1) return f->window[1]; return NULL; } #ifndef STB_VORBIS_NO_DEFER_FLOOR typedef int16 YTYPE; #else typedef int YTYPE; #endif static int do_floor(vorb *f, Mapping *map, int i, int n, float *target, YTYPE *finalY, uint8 *step2_flag) { int n2 = n >> 1; int s = map->chan[i].mux, floor; floor = map->submap_floor[s]; if (f->floor_types[floor] == 0) { return error(f, VORBIS_invalid_stream); } else { Floor1 *g = &f->floor_config[floor].floor1; int j,q; int lx = 0, ly = finalY[0] * g->floor1_multiplier; for (q=1; q < g->values; ++q) { j = g->sorted_order[q]; #ifndef STB_VORBIS_NO_DEFER_FLOOR if (finalY[j] >= 0) #else if (step2_flag[j]) #endif { int hy = finalY[j] * g->floor1_multiplier; int hx = g->Xlist[j]; if (lx != hx) draw_line(target, lx,ly, hx,hy, n2); CHECK(f); lx = hx, ly = hy; } } if (lx < n2) { // optimization of: draw_line(target, lx,ly, n,ly, n2); for (j=lx; j < n2; ++j) LINE_OP(target[j], inverse_db_table[ly]); CHECK(f); } } return TRUE; } // The meaning of "left" and "right" // // For a given frame: // we compute samples from 0..n // window_center is n/2 // we'll window and mix the samples from left_start to left_end with data from the previous frame // all of the samples from left_end to right_start can be output without mixing; however, // this interval is 0-length except when transitioning between short and long frames // all of the samples from right_start to right_end need to be mixed with the next frame, // which we don't have, so those get saved in a buffer // frame N's right_end-right_start, the number of samples to mix with the next frame, // has to be the same as frame N+1's left_end-left_start (which they are by // construction) static int vorbis_decode_initial(vorb *f, int *p_left_start, int *p_left_end, int *p_right_start, int *p_right_end, int *mode) { Mode *m; int i, n, prev, next, window_center; f->channel_buffer_start = f->channel_buffer_end = 0; retry: if (f->eof) return FALSE; if (!maybe_start_packet(f)) return FALSE; // check packet type if (get_bits(f,1) != 0) { if (IS_PUSH_MODE(f)) return error(f,VORBIS_bad_packet_type); while (EOP != get8_packet(f)); goto retry; } if (f->alloc.alloc_buffer) assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); i = get_bits(f, ilog(f->mode_count-1)); if (i == EOP) return FALSE; if (i >= f->mode_count) return FALSE; *mode = i; m = f->mode_config + i; if (m->blockflag) { n = f->blocksize_1; prev = get_bits(f,1); next = get_bits(f,1); } else { prev = next = 0; n = f->blocksize_0; } // WINDOWING window_center = n >> 1; if (m->blockflag && !prev) { *p_left_start = (n - f->blocksize_0) >> 2; *p_left_end = (n + f->blocksize_0) >> 2; } else { *p_left_start = 0; *p_left_end = window_center; } if (m->blockflag && !next) { *p_right_start = (n*3 - f->blocksize_0) >> 2; *p_right_end = (n*3 + f->blocksize_0) >> 2; } else { *p_right_start = window_center; *p_right_end = n; } return TRUE; } static int vorbis_decode_packet_rest(vorb *f, int *len, Mode *m, int left_start, int left_end, int right_start, int right_end, int *p_left) { Mapping *map; int i,j,k,n,n2; int zero_channel[256]; int really_zero_channel[256]; // WINDOWING n = f->blocksize[m->blockflag]; map = &f->mapping[m->mapping]; // FLOORS n2 = n >> 1; CHECK(f); for (i=0; i < f->channels; ++i) { int s = map->chan[i].mux, floor; zero_channel[i] = FALSE; floor = map->submap_floor[s]; if (f->floor_types[floor] == 0) { return error(f, VORBIS_invalid_stream); } else { Floor1 *g = &f->floor_config[floor].floor1; if (get_bits(f, 1)) { short *finalY; uint8 step2_flag[256]; static int range_list[4] = { 256, 128, 86, 64 }; int range = range_list[g->floor1_multiplier-1]; int offset = 2; finalY = f->finalY[i]; finalY[0] = get_bits(f, ilog(range)-1); finalY[1] = get_bits(f, ilog(range)-1); for (j=0; j < g->partitions; ++j) { int pclass = g->partition_class_list[j]; int cdim = g->class_dimensions[pclass]; int cbits = g->class_subclasses[pclass]; int csub = (1 << cbits)-1; int cval = 0; if (cbits) { Codebook *c = f->codebooks + g->class_masterbooks[pclass]; DECODE(cval,f,c); } for (k=0; k < cdim; ++k) { int book = g->subclass_books[pclass][cval & csub]; cval = cval >> cbits; if (book >= 0) { int temp; Codebook *c = f->codebooks + book; DECODE(temp,f,c); finalY[offset++] = temp; } else finalY[offset++] = 0; } } if (f->valid_bits == INVALID_BITS) goto error; // behavior according to spec step2_flag[0] = step2_flag[1] = 1; for (j=2; j < g->values; ++j) { int low, high, pred, highroom, lowroom, room, val; low = g->neighbors[j][0]; high = g->neighbors[j][1]; //neighbors(g->Xlist, j, &low, &high); pred = predict_point(g->Xlist[j], g->Xlist[low], g->Xlist[high], finalY[low], finalY[high]); val = finalY[j]; highroom = range - pred; lowroom = pred; if (highroom < lowroom) room = highroom * 2; else room = lowroom * 2; if (val) { step2_flag[low] = step2_flag[high] = 1; step2_flag[j] = 1; if (val >= room) if (highroom > lowroom) finalY[j] = val - lowroom + pred; else finalY[j] = pred - val + highroom - 1; else if (val & 1) finalY[j] = pred - ((val+1)>>1); else finalY[j] = pred + (val>>1); } else { step2_flag[j] = 0; finalY[j] = pred; } } #ifdef STB_VORBIS_NO_DEFER_FLOOR do_floor(f, map, i, n, f->floor_buffers[i], finalY, step2_flag); #else // defer final floor computation until _after_ residue for (j=0; j < g->values; ++j) { if (!step2_flag[j]) finalY[j] = -1; } #endif } else { error: zero_channel[i] = TRUE; } // So we just defer everything else to later // at this point we've decoded the floor into buffer } } CHECK(f); // at this point we've decoded all floors if (f->alloc.alloc_buffer) assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); // re-enable coupled channels if necessary memcpy(really_zero_channel, zero_channel, sizeof(really_zero_channel[0]) * f->channels); for (i=0; i < map->coupling_steps; ++i) if (!zero_channel[map->chan[i].magnitude] || !zero_channel[map->chan[i].angle]) { zero_channel[map->chan[i].magnitude] = zero_channel[map->chan[i].angle] = FALSE; } CHECK(f); // RESIDUE DECODE for (i=0; i < map->submaps; ++i) { float *residue_buffers[STB_VORBIS_MAX_CHANNELS]; int r; uint8 do_not_decode[256]; int ch = 0; for (j=0; j < f->channels; ++j) { if (map->chan[j].mux == i) { if (zero_channel[j]) { do_not_decode[ch] = TRUE; residue_buffers[ch] = NULL; } else { do_not_decode[ch] = FALSE; residue_buffers[ch] = f->channel_buffers[j]; } ++ch; } } r = map->submap_residue[i]; decode_residue(f, residue_buffers, ch, n2, r, do_not_decode); } if (f->alloc.alloc_buffer) assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); CHECK(f); // INVERSE COUPLING for (i = map->coupling_steps-1; i >= 0; --i) { int n2 = n >> 1; float *m = f->channel_buffers[map->chan[i].magnitude]; float *a = f->channel_buffers[map->chan[i].angle ]; for (j=0; j < n2; ++j) { float a2,m2; if (m[j] > 0) if (a[j] > 0) m2 = m[j], a2 = m[j] - a[j]; else a2 = m[j], m2 = m[j] + a[j]; else if (a[j] > 0) m2 = m[j], a2 = m[j] + a[j]; else a2 = m[j], m2 = m[j] - a[j]; m[j] = m2; a[j] = a2; } } CHECK(f); // finish decoding the floors #ifndef STB_VORBIS_NO_DEFER_FLOOR for (i=0; i < f->channels; ++i) { if (really_zero_channel[i]) { memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2); } else { do_floor(f, map, i, n, f->channel_buffers[i], f->finalY[i], NULL); } } #else for (i=0; i < f->channels; ++i) { if (really_zero_channel[i]) { memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2); } else { for (j=0; j < n2; ++j) f->channel_buffers[i][j] *= f->floor_buffers[i][j]; } } #endif // INVERSE MDCT CHECK(f); for (i=0; i < f->channels; ++i) inverse_mdct(f->channel_buffers[i], n, f, m->blockflag); CHECK(f); // this shouldn't be necessary, unless we exited on an error // and want to flush to get to the next packet flush_packet(f); if (f->first_decode) { // assume we start so first non-discarded sample is sample 0 // this isn't to spec, but spec would require us to read ahead // and decode the size of all current frames--could be done, // but presumably it's not a commonly used feature f->current_loc = -n2; // start of first frame is positioned for discard // we might have to discard samples "from" the next frame too, // if we're lapping a large block then a small at the start? f->discard_samples_deferred = n - right_end; f->current_loc_valid = TRUE; f->first_decode = FALSE; } else if (f->discard_samples_deferred) { if (f->discard_samples_deferred >= right_start - left_start) { f->discard_samples_deferred -= (right_start - left_start); left_start = right_start; *p_left = left_start; } else { left_start += f->discard_samples_deferred; *p_left = left_start; f->discard_samples_deferred = 0; } } else if (f->previous_length == 0 && f->current_loc_valid) { // we're recovering from a seek... that means we're going to discard // the samples from this packet even though we know our position from // the last page header, so we need to update the position based on // the discarded samples here // but wait, the code below is going to add this in itself even // on a discard, so we don't need to do it here... } // check if we have ogg information about the sample # for this packet if (f->last_seg_which == f->end_seg_with_known_loc) { // if we have a valid current loc, and this is final: if (f->current_loc_valid && (f->page_flag & PAGEFLAG_last_page)) { uint32 current_end = f->known_loc_for_packet; // then let's infer the size of the (probably) short final frame if (current_end < f->current_loc + (right_end-left_start)) { if (current_end < f->current_loc) { // negative truncation, that's impossible! *len = 0; } else { *len = current_end - f->current_loc; } *len += left_start; // this doesn't seem right, but has no ill effect on my test files if (*len > right_end) *len = right_end; // this should never happen f->current_loc += *len; return TRUE; } } // otherwise, just set our sample loc // guess that the ogg granule pos refers to the _middle_ of the // last frame? // set f->current_loc to the position of left_start f->current_loc = f->known_loc_for_packet - (n2-left_start); f->current_loc_valid = TRUE; } if (f->current_loc_valid) f->current_loc += (right_start - left_start); if (f->alloc.alloc_buffer) assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); *len = right_end; // ignore samples after the window goes to 0 CHECK(f); return TRUE; } static int vorbis_decode_packet(vorb *f, int *len, int *p_left, int *p_right) { int mode, left_end, right_end; if (!vorbis_decode_initial(f, p_left, &left_end, p_right, &right_end, &mode)) return 0; return vorbis_decode_packet_rest(f, len, f->mode_config + mode, *p_left, left_end, *p_right, right_end, p_left); } static int vorbis_finish_frame(stb_vorbis *f, int len, int left, int right) { int prev,i,j; // we use right&left (the start of the right- and left-window sin()-regions) // to determine how much to return, rather than inferring from the rules // (same result, clearer code); 'left' indicates where our sin() window // starts, therefore where the previous window's right edge starts, and // therefore where to start mixing from the previous buffer. 'right' // indicates where our sin() ending-window starts, therefore that's where // we start saving, and where our returned-data ends. // mixin from previous window if (f->previous_length) { int i,j, n = f->previous_length; float *w = get_window(f, n); if (w == NULL) return 0; for (i=0; i < f->channels; ++i) { for (j=0; j < n; ++j) f->channel_buffers[i][left+j] = f->channel_buffers[i][left+j]*w[ j] + f->previous_window[i][ j]*w[n-1-j]; } } prev = f->previous_length; // last half of this data becomes previous window f->previous_length = len - right; // @OPTIMIZE: could avoid this copy by double-buffering the // output (flipping previous_window with channel_buffers), but // then previous_window would have to be 2x as large, and // channel_buffers couldn't be temp mem (although they're NOT // currently temp mem, they could be (unless we want to level // performance by spreading out the computation)) for (i=0; i < f->channels; ++i) for (j=0; right+j < len; ++j) f->previous_window[i][j] = f->channel_buffers[i][right+j]; if (!prev) // there was no previous packet, so this data isn't valid... // this isn't entirely true, only the would-have-overlapped data // isn't valid, but this seems to be what the spec requires return 0; // truncate a short frame if (len < right) right = len; f->samples_output += right-left; return right - left; } static int vorbis_pump_first_frame(stb_vorbis *f) { int len, right, left, res; res = vorbis_decode_packet(f, &len, &left, &right); if (res) vorbis_finish_frame(f, len, left, right); return res; } #ifndef STB_VORBIS_NO_PUSHDATA_API static int is_whole_packet_present(stb_vorbis *f, int end_page) { // make sure that we have the packet available before continuing... // this requires a full ogg parse, but we know we can fetch from f->stream // instead of coding this out explicitly, we could save the current read state, // read the next packet with get8() until end-of-packet, check f->eof, then // reset the state? but that would be slower, esp. since we'd have over 256 bytes // of state to restore (primarily the page segment table) int s = f->next_seg, first = TRUE; uint8 *p = f->stream; if (s != -1) { // if we're not starting the packet with a 'continue on next page' flag for (; s < f->segment_count; ++s) { p += f->segments[s]; if (f->segments[s] < 255) // stop at first short segment break; } // either this continues, or it ends it... if (end_page) if (s < f->segment_count-1) return error(f, VORBIS_invalid_stream); if (s == f->segment_count) s = -1; // set 'crosses page' flag if (p > f->stream_end) return error(f, VORBIS_need_more_data); first = FALSE; } for (; s == -1;) { uint8 *q; int n; // check that we have the page header ready if (p + 26 >= f->stream_end) return error(f, VORBIS_need_more_data); // validate the page if (memcmp(p, ogg_page_header, 4)) return error(f, VORBIS_invalid_stream); if (p[4] != 0) return error(f, VORBIS_invalid_stream); if (first) { // the first segment must NOT have 'continued_packet', later ones MUST if (f->previous_length) if ((p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream); // if no previous length, we're resynching, so we can come in on a continued-packet, // which we'll just drop } else { if (!(p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream); } n = p[26]; // segment counts q = p+27; // q points to segment table p = q + n; // advance past header // make sure we've read the segment table if (p > f->stream_end) return error(f, VORBIS_need_more_data); for (s=0; s < n; ++s) { p += q[s]; if (q[s] < 255) break; } if (end_page) if (s < n-1) return error(f, VORBIS_invalid_stream); if (s == n) s = -1; // set 'crosses page' flag if (p > f->stream_end) return error(f, VORBIS_need_more_data); first = FALSE; } return TRUE; } #endif // !STB_VORBIS_NO_PUSHDATA_API static int start_decoder(vorb *f) { uint8 header[6], x,y; int len,i,j,k, max_submaps = 0; int longest_floorlist=0; // first page, first packet if (!start_page(f)) return FALSE; // validate page flag if (!(f->page_flag & PAGEFLAG_first_page)) return error(f, VORBIS_invalid_first_page); if (f->page_flag & PAGEFLAG_last_page) return error(f, VORBIS_invalid_first_page); if (f->page_flag & PAGEFLAG_continued_packet) return error(f, VORBIS_invalid_first_page); // check for expected packet length if (f->segment_count != 1) return error(f, VORBIS_invalid_first_page); if (f->segments[0] != 30) { // check for the Ogg skeleton fishead identifying header to refine our error if (f->segments[0] == 64 && getn(f, header, 6) && header[0] == 'f' && header[1] == 'i' && header[2] == 's' && header[3] == 'h' && header[4] == 'e' && header[5] == 'a' && get8(f) == 'd' && get8(f) == '\0') return error(f, VORBIS_ogg_skeleton_not_supported); else return error(f, VORBIS_invalid_first_page); } // read packet // check packet header if (get8(f) != VORBIS_packet_id) return error(f, VORBIS_invalid_first_page); if (!getn(f, header, 6)) return error(f, VORBIS_unexpected_eof); if (!vorbis_validate(header)) return error(f, VORBIS_invalid_first_page); // vorbis_version if (get32(f) != 0) return error(f, VORBIS_invalid_first_page); f->channels = get8(f); if (!f->channels) return error(f, VORBIS_invalid_first_page); if (f->channels > STB_VORBIS_MAX_CHANNELS) return error(f, VORBIS_too_many_channels); f->sample_rate = get32(f); if (!f->sample_rate) return error(f, VORBIS_invalid_first_page); get32(f); // bitrate_maximum get32(f); // bitrate_nominal get32(f); // bitrate_minimum x = get8(f); { int log0,log1; log0 = x & 15; log1 = x >> 4; f->blocksize_0 = 1 << log0; f->blocksize_1 = 1 << log1; if (log0 < 6 || log0 > 13) return error(f, VORBIS_invalid_setup); if (log1 < 6 || log1 > 13) return error(f, VORBIS_invalid_setup); if (log0 > log1) return error(f, VORBIS_invalid_setup); } // framing_flag x = get8(f); if (!(x & 1)) return error(f, VORBIS_invalid_first_page); // second packet! if (!start_page(f)) return FALSE; if (!start_packet(f)) return FALSE; do { len = next_segment(f); skip(f, len); f->bytes_in_seg = 0; } while (len); // third packet! if (!start_packet(f)) return FALSE; #ifndef STB_VORBIS_NO_PUSHDATA_API if (IS_PUSH_MODE(f)) { if (!is_whole_packet_present(f, TRUE)) { // convert error in ogg header to write type if (f->error == VORBIS_invalid_stream) f->error = VORBIS_invalid_setup; return FALSE; } } #endif crc32_init(); // always init it, to avoid multithread race conditions if (get8_packet(f) != VORBIS_packet_setup) return error(f, VORBIS_invalid_setup); for (i=0; i < 6; ++i) header[i] = get8_packet(f); if (!vorbis_validate(header)) return error(f, VORBIS_invalid_setup); // codebooks f->codebook_count = get_bits(f,8) + 1; f->codebooks = (Codebook *) setup_malloc(f, sizeof(*f->codebooks) * f->codebook_count); if (f->codebooks == NULL) return error(f, VORBIS_outofmem); memset(f->codebooks, 0, sizeof(*f->codebooks) * f->codebook_count); for (i=0; i < f->codebook_count; ++i) { uint32 *values; int ordered, sorted_count; int total=0; uint8 *lengths; Codebook *c = f->codebooks+i; CHECK(f); x = get_bits(f, 8); if (x != 0x42) return error(f, VORBIS_invalid_setup); x = get_bits(f, 8); if (x != 0x43) return error(f, VORBIS_invalid_setup); x = get_bits(f, 8); if (x != 0x56) return error(f, VORBIS_invalid_setup); x = get_bits(f, 8); c->dimensions = (get_bits(f, 8)<<8) + x; x = get_bits(f, 8); y = get_bits(f, 8); c->entries = (get_bits(f, 8)<<16) + (y<<8) + x; ordered = get_bits(f,1); c->sparse = ordered ? 0 : get_bits(f,1); if (c->dimensions == 0 && c->entries != 0) return error(f, VORBIS_invalid_setup); if (c->sparse) lengths = (uint8 *) setup_temp_malloc(f, c->entries); else lengths = c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries); if (!lengths) return error(f, VORBIS_outofmem); if (ordered) { int current_entry = 0; int current_length = get_bits(f,5) + 1; while (current_entry < c->entries) { int limit = c->entries - current_entry; int n = get_bits(f, ilog(limit)); if (current_length >= 32) return error(f, VORBIS_invalid_setup); if (current_entry + n > (int) c->entries) { return error(f, VORBIS_invalid_setup); } memset(lengths + current_entry, current_length, n); current_entry += n; ++current_length; } } else { for (j=0; j < c->entries; ++j) { int present = c->sparse ? get_bits(f,1) : 1; if (present) { lengths[j] = get_bits(f, 5) + 1; ++total; if (lengths[j] == 32) return error(f, VORBIS_invalid_setup); } else { lengths[j] = NO_CODE; } } } if (c->sparse && total >= c->entries >> 2) { // convert sparse items to non-sparse! if (c->entries > (int) f->setup_temp_memory_required) f->setup_temp_memory_required = c->entries; c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries); if (c->codeword_lengths == NULL) return error(f, VORBIS_outofmem); memcpy(c->codeword_lengths, lengths, c->entries); setup_temp_free(f, lengths, c->entries); // note this is only safe if there have been no intervening temp mallocs! lengths = c->codeword_lengths; c->sparse = 0; } // compute the size of the sorted tables if (c->sparse) { sorted_count = total; } else { sorted_count = 0; #ifndef STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH for (j=0; j < c->entries; ++j) if (lengths[j] > STB_VORBIS_FAST_HUFFMAN_LENGTH && lengths[j] != NO_CODE) ++sorted_count; #endif } c->sorted_entries = sorted_count; values = NULL; CHECK(f); if (!c->sparse) { c->codewords = (uint32 *) setup_malloc(f, sizeof(c->codewords[0]) * c->entries); if (!c->codewords) return error(f, VORBIS_outofmem); } else { unsigned int size; if (c->sorted_entries) { c->codeword_lengths = (uint8 *) setup_malloc(f, c->sorted_entries); if (!c->codeword_lengths) return error(f, VORBIS_outofmem); c->codewords = (uint32 *) setup_temp_malloc(f, sizeof(*c->codewords) * c->sorted_entries); if (!c->codewords) return error(f, VORBIS_outofmem); values = (uint32 *) setup_temp_malloc(f, sizeof(*values) * c->sorted_entries); if (!values) return error(f, VORBIS_outofmem); } size = c->entries + (sizeof(*c->codewords) + sizeof(*values)) * c->sorted_entries; if (size > f->setup_temp_memory_required) f->setup_temp_memory_required = size; } if (!compute_codewords(c, lengths, c->entries, values)) { if (c->sparse) setup_temp_free(f, values, 0); return error(f, VORBIS_invalid_setup); } if (c->sorted_entries) { // allocate an extra slot for sentinels c->sorted_codewords = (uint32 *) setup_malloc(f, sizeof(*c->sorted_codewords) * (c->sorted_entries+1)); if (c->sorted_codewords == NULL) return error(f, VORBIS_outofmem); // allocate an extra slot at the front so that c->sorted_values[-1] is defined // so that we can catch that case without an extra if c->sorted_values = ( int *) setup_malloc(f, sizeof(*c->sorted_values ) * (c->sorted_entries+1)); if (c->sorted_values == NULL) return error(f, VORBIS_outofmem); ++c->sorted_values; c->sorted_values[-1] = -1; compute_sorted_huffman(c, lengths, values); } if (c->sparse) { setup_temp_free(f, values, sizeof(*values)*c->sorted_entries); setup_temp_free(f, c->codewords, sizeof(*c->codewords)*c->sorted_entries); setup_temp_free(f, lengths, c->entries); c->codewords = NULL; } compute_accelerated_huffman(c); CHECK(f); c->lookup_type = get_bits(f, 4); if (c->lookup_type > 2) return error(f, VORBIS_invalid_setup); if (c->lookup_type > 0) { uint16 *mults; c->minimum_value = float32_unpack(get_bits(f, 32)); c->delta_value = float32_unpack(get_bits(f, 32)); c->value_bits = get_bits(f, 4)+1; c->sequence_p = get_bits(f,1); if (c->lookup_type == 1) { int values = lookup1_values(c->entries, c->dimensions); if (values < 0) return error(f, VORBIS_invalid_setup); c->lookup_values = (uint32) values; } else { c->lookup_values = c->entries * c->dimensions; } if (c->lookup_values == 0) return error(f, VORBIS_invalid_setup); mults = (uint16 *) setup_temp_malloc(f, sizeof(mults[0]) * c->lookup_values); if (mults == NULL) return error(f, VORBIS_outofmem); for (j=0; j < (int) c->lookup_values; ++j) { int q = get_bits(f, c->value_bits); if (q == EOP) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_invalid_setup); } mults[j] = q; } #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK if (c->lookup_type == 1) { int len, sparse = c->sparse; float last=0; // pre-expand the lookup1-style multiplicands, to avoid a divide in the inner loop if (sparse) { if (c->sorted_entries == 0) goto skip; c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->sorted_entries * c->dimensions); } else c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->entries * c->dimensions); if (c->multiplicands == NULL) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); } len = sparse ? c->sorted_entries : c->entries; for (j=0; j < len; ++j) { unsigned int z = sparse ? c->sorted_values[j] : j; unsigned int div=1; for (k=0; k < c->dimensions; ++k) { int off = (z / div) % c->lookup_values; float val = mults[off]; val = mults[off]*c->delta_value + c->minimum_value + last; c->multiplicands[j*c->dimensions + k] = val; if (c->sequence_p) last = val; if (k+1 < c->dimensions) { if (div > UINT_MAX / (unsigned int) c->lookup_values) { setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_invalid_setup); } div *= c->lookup_values; } } } c->lookup_type = 2; } else #endif { float last=0; CHECK(f); c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->lookup_values); if (c->multiplicands == NULL) { setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); } for (j=0; j < (int) c->lookup_values; ++j) { float val = mults[j] * c->delta_value + c->minimum_value + last; c->multiplicands[j] = val; if (c->sequence_p) last = val; } } #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK skip:; #endif setup_temp_free(f, mults, sizeof(mults[0])*c->lookup_values); CHECK(f); } CHECK(f); } // time domain transfers (notused) x = get_bits(f, 6) + 1; for (i=0; i < x; ++i) { uint32 z = get_bits(f, 16); if (z != 0) return error(f, VORBIS_invalid_setup); } // Floors f->floor_count = get_bits(f, 6)+1; f->floor_config = (Floor *) setup_malloc(f, f->floor_count * sizeof(*f->floor_config)); if (f->floor_config == NULL) return error(f, VORBIS_outofmem); for (i=0; i < f->floor_count; ++i) { f->floor_types[i] = get_bits(f, 16); if (f->floor_types[i] > 1) return error(f, VORBIS_invalid_setup); if (f->floor_types[i] == 0) { Floor0 *g = &f->floor_config[i].floor0; g->order = get_bits(f,8); g->rate = get_bits(f,16); g->bark_map_size = get_bits(f,16); g->amplitude_bits = get_bits(f,6); g->amplitude_offset = get_bits(f,8); g->number_of_books = get_bits(f,4) + 1; for (j=0; j < g->number_of_books; ++j) g->book_list[j] = get_bits(f,8); return error(f, VORBIS_feature_not_supported); } else { stbv__floor_ordering p[31*8+2]; Floor1 *g = &f->floor_config[i].floor1; int max_class = -1; g->partitions = get_bits(f, 5); for (j=0; j < g->partitions; ++j) { g->partition_class_list[j] = get_bits(f, 4); if (g->partition_class_list[j] > max_class) max_class = g->partition_class_list[j]; } for (j=0; j <= max_class; ++j) { g->class_dimensions[j] = get_bits(f, 3)+1; g->class_subclasses[j] = get_bits(f, 2); if (g->class_subclasses[j]) { g->class_masterbooks[j] = get_bits(f, 8); if (g->class_masterbooks[j] >= f->codebook_count) return error(f, VORBIS_invalid_setup); } for (k=0; k < 1 << g->class_subclasses[j]; ++k) { g->subclass_books[j][k] = get_bits(f,8)-1; if (g->subclass_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup); } } g->floor1_multiplier = get_bits(f,2)+1; g->rangebits = get_bits(f,4); g->Xlist[0] = 0; g->Xlist[1] = 1 << g->rangebits; g->values = 2; for (j=0; j < g->partitions; ++j) { int c = g->partition_class_list[j]; for (k=0; k < g->class_dimensions[c]; ++k) { g->Xlist[g->values] = get_bits(f, g->rangebits); ++g->values; } } // precompute the sorting for (j=0; j < g->values; ++j) { p[j].x = g->Xlist[j]; p[j].id = j; } qsort(p, g->values, sizeof(p[0]), point_compare); for (j=0; j < g->values-1; ++j) if (p[j].x == p[j+1].x) return error(f, VORBIS_invalid_setup); for (j=0; j < g->values; ++j) g->sorted_order[j] = (uint8) p[j].id; // precompute the neighbors for (j=2; j < g->values; ++j) { int low,hi; neighbors(g->Xlist, j, &low,&hi); g->neighbors[j][0] = low; g->neighbors[j][1] = hi; } if (g->values > longest_floorlist) longest_floorlist = g->values; } } // Residue f->residue_count = get_bits(f, 6)+1; f->residue_config = (Residue *) setup_malloc(f, f->residue_count * sizeof(f->residue_config[0])); if (f->residue_config == NULL) return error(f, VORBIS_outofmem); memset(f->residue_config, 0, f->residue_count * sizeof(f->residue_config[0])); for (i=0; i < f->residue_count; ++i) { uint8 residue_cascade[64]; Residue *r = f->residue_config+i; f->residue_types[i] = get_bits(f, 16); if (f->residue_types[i] > 2) return error(f, VORBIS_invalid_setup); r->begin = get_bits(f, 24); r->end = get_bits(f, 24); if (r->end < r->begin) return error(f, VORBIS_invalid_setup); r->part_size = get_bits(f,24)+1; r->classifications = get_bits(f,6)+1; r->classbook = get_bits(f,8); if (r->classbook >= f->codebook_count) return error(f, VORBIS_invalid_setup); for (j=0; j < r->classifications; ++j) { uint8 high_bits=0; uint8 low_bits=get_bits(f,3); if (get_bits(f,1)) high_bits = get_bits(f,5); residue_cascade[j] = high_bits*8 + low_bits; } r->residue_books = (short (*)[8]) setup_malloc(f, sizeof(r->residue_books[0]) * r->classifications); if (r->residue_books == NULL) return error(f, VORBIS_outofmem); for (j=0; j < r->classifications; ++j) { for (k=0; k < 8; ++k) { if (residue_cascade[j] & (1 << k)) { r->residue_books[j][k] = get_bits(f, 8); if (r->residue_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup); } else { r->residue_books[j][k] = -1; } } } // precompute the classifications[] array to avoid inner-loop mod/divide // call it 'classdata' since we already have r->classifications r->classdata = (uint8 **) setup_malloc(f, sizeof(*r->classdata) * f->codebooks[r->classbook].entries); if (!r->classdata) return error(f, VORBIS_outofmem); memset(r->classdata, 0, sizeof(*r->classdata) * f->codebooks[r->classbook].entries); for (j=0; j < f->codebooks[r->classbook].entries; ++j) { int classwords = f->codebooks[r->classbook].dimensions; int temp = j; r->classdata[j] = (uint8 *) setup_malloc(f, sizeof(r->classdata[j][0]) * classwords); if (r->classdata[j] == NULL) return error(f, VORBIS_outofmem); for (k=classwords-1; k >= 0; --k) { r->classdata[j][k] = temp % r->classifications; temp /= r->classifications; } } } f->mapping_count = get_bits(f,6)+1; f->mapping = (Mapping *) setup_malloc(f, f->mapping_count * sizeof(*f->mapping)); if (f->mapping == NULL) return error(f, VORBIS_outofmem); memset(f->mapping, 0, f->mapping_count * sizeof(*f->mapping)); for (i=0; i < f->mapping_count; ++i) { Mapping *m = f->mapping + i; int mapping_type = get_bits(f,16); if (mapping_type != 0) return error(f, VORBIS_invalid_setup); m->chan = (MappingChannel *) setup_malloc(f, f->channels * sizeof(*m->chan)); if (m->chan == NULL) return error(f, VORBIS_outofmem); if (get_bits(f,1)) m->submaps = get_bits(f,4)+1; else m->submaps = 1; if (m->submaps > max_submaps) max_submaps = m->submaps; if (get_bits(f,1)) { m->coupling_steps = get_bits(f,8)+1; if (m->coupling_steps > f->channels) return error(f, VORBIS_invalid_setup); for (k=0; k < m->coupling_steps; ++k) { m->chan[k].magnitude = get_bits(f, ilog(f->channels-1)); m->chan[k].angle = get_bits(f, ilog(f->channels-1)); if (m->chan[k].magnitude >= f->channels) return error(f, VORBIS_invalid_setup); if (m->chan[k].angle >= f->channels) return error(f, VORBIS_invalid_setup); if (m->chan[k].magnitude == m->chan[k].angle) return error(f, VORBIS_invalid_setup); } } else m->coupling_steps = 0; // reserved field if (get_bits(f,2)) return error(f, VORBIS_invalid_setup); if (m->submaps > 1) { for (j=0; j < f->channels; ++j) { m->chan[j].mux = get_bits(f, 4); if (m->chan[j].mux >= m->submaps) return error(f, VORBIS_invalid_setup); } } else // @SPECIFICATION: this case is missing from the spec for (j=0; j < f->channels; ++j) m->chan[j].mux = 0; for (j=0; j < m->submaps; ++j) { get_bits(f,8); // discard m->submap_floor[j] = get_bits(f,8); m->submap_residue[j] = get_bits(f,8); if (m->submap_floor[j] >= f->floor_count) return error(f, VORBIS_invalid_setup); if (m->submap_residue[j] >= f->residue_count) return error(f, VORBIS_invalid_setup); } } // Modes f->mode_count = get_bits(f, 6)+1; for (i=0; i < f->mode_count; ++i) { Mode *m = f->mode_config+i; m->blockflag = get_bits(f,1); m->windowtype = get_bits(f,16); m->transformtype = get_bits(f,16); m->mapping = get_bits(f,8); if (m->windowtype != 0) return error(f, VORBIS_invalid_setup); if (m->transformtype != 0) return error(f, VORBIS_invalid_setup); if (m->mapping >= f->mapping_count) return error(f, VORBIS_invalid_setup); } flush_packet(f); f->previous_length = 0; for (i=0; i < f->channels; ++i) { f->channel_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1); f->previous_window[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2); f->finalY[i] = (int16 *) setup_malloc(f, sizeof(int16) * longest_floorlist); if (f->channel_buffers[i] == NULL || f->previous_window[i] == NULL || f->finalY[i] == NULL) return error(f, VORBIS_outofmem); memset(f->channel_buffers[i], 0, sizeof(float) * f->blocksize_1); #ifdef STB_VORBIS_NO_DEFER_FLOOR f->floor_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2); if (f->floor_buffers[i] == NULL) return error(f, VORBIS_outofmem); #endif } if (!init_blocksize(f, 0, f->blocksize_0)) return FALSE; if (!init_blocksize(f, 1, f->blocksize_1)) return FALSE; f->blocksize[0] = f->blocksize_0; f->blocksize[1] = f->blocksize_1; #ifdef STB_VORBIS_DIVIDE_TABLE if (integer_divide_table[1][1]==0) for (i=0; i < DIVTAB_NUMER; ++i) for (j=1; j < DIVTAB_DENOM; ++j) integer_divide_table[i][j] = i / j; #endif // compute how much temporary memory is needed // 1. { uint32 imdct_mem = (f->blocksize_1 * sizeof(float) >> 1); uint32 classify_mem; int i,max_part_read=0; for (i=0; i < f->residue_count; ++i) { Residue *r = f->residue_config + i; unsigned int actual_size = f->blocksize_1 / 2; unsigned int limit_r_begin = r->begin < actual_size ? r->begin : actual_size; unsigned int limit_r_end = r->end < actual_size ? r->end : actual_size; int n_read = limit_r_end - limit_r_begin; int part_read = n_read / r->part_size; if (part_read > max_part_read) max_part_read = part_read; } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(uint8 *)); #else classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(int *)); #endif // maximum reasonable partition size is f->blocksize_1 f->temp_memory_required = classify_mem; if (imdct_mem > f->temp_memory_required) f->temp_memory_required = imdct_mem; } f->first_decode = TRUE; if (f->alloc.alloc_buffer) { assert(f->temp_offset == f->alloc.alloc_buffer_length_in_bytes); // check if there's enough temp memory so we don't error later if (f->setup_offset + sizeof(*f) + f->temp_memory_required > (unsigned) f->temp_offset) return error(f, VORBIS_outofmem); } f->first_audio_page_offset = stb_vorbis_get_file_offset(f); return TRUE; } static void vorbis_deinit(stb_vorbis *p) { int i,j; if (p->residue_config) { for (i=0; i < p->residue_count; ++i) { Residue *r = p->residue_config+i; if (r->classdata) { for (j=0; j < p->codebooks[r->classbook].entries; ++j) setup_free(p, r->classdata[j]); setup_free(p, r->classdata); } setup_free(p, r->residue_books); } } if (p->codebooks) { CHECK(p); for (i=0; i < p->codebook_count; ++i) { Codebook *c = p->codebooks + i; setup_free(p, c->codeword_lengths); setup_free(p, c->multiplicands); setup_free(p, c->codewords); setup_free(p, c->sorted_codewords); // c->sorted_values[-1] is the first entry in the array setup_free(p, c->sorted_values ? c->sorted_values-1 : NULL); } setup_free(p, p->codebooks); } setup_free(p, p->floor_config); setup_free(p, p->residue_config); if (p->mapping) { for (i=0; i < p->mapping_count; ++i) setup_free(p, p->mapping[i].chan); setup_free(p, p->mapping); } CHECK(p); for (i=0; i < p->channels && i < STB_VORBIS_MAX_CHANNELS; ++i) { setup_free(p, p->channel_buffers[i]); setup_free(p, p->previous_window[i]); #ifdef STB_VORBIS_NO_DEFER_FLOOR setup_free(p, p->floor_buffers[i]); #endif setup_free(p, p->finalY[i]); } for (i=0; i < 2; ++i) { setup_free(p, p->A[i]); setup_free(p, p->B[i]); setup_free(p, p->C[i]); setup_free(p, p->window[i]); setup_free(p, p->bit_reverse[i]); } #ifndef STB_VORBIS_NO_STDIO if (p->close_on_free) fclose(p->f); #endif } void stb_vorbis_close(stb_vorbis *p) { if (p == NULL) return; vorbis_deinit(p); setup_free(p,p); } static void vorbis_init(stb_vorbis *p, const stb_vorbis_alloc *z) { memset(p, 0, sizeof(*p)); // NULL out all malloc'd pointers to start if (z) { p->alloc = *z; p->alloc.alloc_buffer_length_in_bytes = (p->alloc.alloc_buffer_length_in_bytes+3) & ~3; p->temp_offset = p->alloc.alloc_buffer_length_in_bytes; } p->eof = 0; p->error = VORBIS__no_error; p->stream = NULL; p->codebooks = NULL; p->page_crc_tests = -1; #ifndef STB_VORBIS_NO_STDIO p->close_on_free = FALSE; p->f = NULL; #endif } int stb_vorbis_get_sample_offset(stb_vorbis *f) { if (f->current_loc_valid) return f->current_loc; else return -1; } stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f) { stb_vorbis_info d; d.channels = f->channels; d.sample_rate = f->sample_rate; d.setup_memory_required = f->setup_memory_required; d.setup_temp_memory_required = f->setup_temp_memory_required; d.temp_memory_required = f->temp_memory_required; d.max_frame_size = f->blocksize_1 >> 1; return d; } int stb_vorbis_get_error(stb_vorbis *f) { int e = f->error; f->error = VORBIS__no_error; return e; } static stb_vorbis * vorbis_alloc(stb_vorbis *f) { stb_vorbis *p = (stb_vorbis *) setup_malloc(f, sizeof(*p)); return p; } #ifndef STB_VORBIS_NO_PUSHDATA_API void stb_vorbis_flush_pushdata(stb_vorbis *f) { f->previous_length = 0; f->page_crc_tests = 0; f->discard_samples_deferred = 0; f->current_loc_valid = FALSE; f->first_decode = FALSE; f->samples_output = 0; f->channel_buffer_start = 0; f->channel_buffer_end = 0; } static int vorbis_search_for_page_pushdata(vorb *f, uint8 *data, int data_len) { int i,n; for (i=0; i < f->page_crc_tests; ++i) f->scan[i].bytes_done = 0; // if we have room for more scans, search for them first, because // they may cause us to stop early if their header is incomplete if (f->page_crc_tests < STB_VORBIS_PUSHDATA_CRC_COUNT) { if (data_len < 4) return 0; data_len -= 3; // need to look for 4-byte sequence, so don't miss // one that straddles a boundary for (i=0; i < data_len; ++i) { if (data[i] == 0x4f) { if (0==memcmp(data+i, ogg_page_header, 4)) { int j,len; uint32 crc; // make sure we have the whole page header if (i+26 >= data_len || i+27+data[i+26] >= data_len) { // only read up to this page start, so hopefully we'll // have the whole page header start next time data_len = i; break; } // ok, we have it all; compute the length of the page len = 27 + data[i+26]; for (j=0; j < data[i+26]; ++j) len += data[i+27+j]; // scan everything up to the embedded crc (which we must 0) crc = 0; for (j=0; j < 22; ++j) crc = crc32_update(crc, data[i+j]); // now process 4 0-bytes for ( ; j < 26; ++j) crc = crc32_update(crc, 0); // len is the total number of bytes we need to scan n = f->page_crc_tests++; f->scan[n].bytes_left = len-j; f->scan[n].crc_so_far = crc; f->scan[n].goal_crc = data[i+22] + (data[i+23] << 8) + (data[i+24]<<16) + (data[i+25]<<24); // if the last frame on a page is continued to the next, then // we can't recover the sample_loc immediately if (data[i+27+data[i+26]-1] == 255) f->scan[n].sample_loc = ~0; else f->scan[n].sample_loc = data[i+6] + (data[i+7] << 8) + (data[i+ 8]<<16) + (data[i+ 9]<<24); f->scan[n].bytes_done = i+j; if (f->page_crc_tests == STB_VORBIS_PUSHDATA_CRC_COUNT) break; // keep going if we still have room for more } } } } for (i=0; i < f->page_crc_tests;) { uint32 crc; int j; int n = f->scan[i].bytes_done; int m = f->scan[i].bytes_left; if (m > data_len - n) m = data_len - n; // m is the bytes to scan in the current chunk crc = f->scan[i].crc_so_far; for (j=0; j < m; ++j) crc = crc32_update(crc, data[n+j]); f->scan[i].bytes_left -= m; f->scan[i].crc_so_far = crc; if (f->scan[i].bytes_left == 0) { // does it match? if (f->scan[i].crc_so_far == f->scan[i].goal_crc) { // Houston, we have page data_len = n+m; // consumption amount is wherever that scan ended f->page_crc_tests = -1; // drop out of page scan mode f->previous_length = 0; // decode-but-don't-output one frame f->next_seg = -1; // start a new page f->current_loc = f->scan[i].sample_loc; // set the current sample location // to the amount we'd have decoded had we decoded this page f->current_loc_valid = f->current_loc != ~0U; return data_len; } // delete entry f->scan[i] = f->scan[--f->page_crc_tests]; } else { ++i; } } return data_len; } // return value: number of bytes we used int stb_vorbis_decode_frame_pushdata( stb_vorbis *f, // the file we're decoding const uint8 *data, int data_len, // the memory available for decoding int *channels, // place to write number of float * buffers float ***output, // place to write float ** array of float * buffers int *samples // place to write number of output samples ) { int i; int len,right,left; if (!IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); if (f->page_crc_tests >= 0) { *samples = 0; return vorbis_search_for_page_pushdata(f, (uint8 *) data, data_len); } f->stream = (uint8 *) data; f->stream_end = (uint8 *) data + data_len; f->error = VORBIS__no_error; // check that we have the entire packet in memory if (!is_whole_packet_present(f, FALSE)) { *samples = 0; return 0; } if (!vorbis_decode_packet(f, &len, &left, &right)) { // save the actual error we encountered enum STBVorbisError error = f->error; if (error == VORBIS_bad_packet_type) { // flush and resynch f->error = VORBIS__no_error; while (get8_packet(f) != EOP) if (f->eof) break; *samples = 0; return (int) (f->stream - data); } if (error == VORBIS_continued_packet_flag_invalid) { if (f->previous_length == 0) { // we may be resynching, in which case it's ok to hit one // of these; just discard the packet f->error = VORBIS__no_error; while (get8_packet(f) != EOP) if (f->eof) break; *samples = 0; return (int) (f->stream - data); } } // if we get an error while parsing, what to do? // well, it DEFINITELY won't work to continue from where we are! stb_vorbis_flush_pushdata(f); // restore the error that actually made us bail f->error = error; *samples = 0; return 1; } // success! len = vorbis_finish_frame(f, len, left, right); for (i=0; i < f->channels; ++i) f->outputs[i] = f->channel_buffers[i] + left; if (channels) *channels = f->channels; *samples = len; *output = f->outputs; return (int) (f->stream - data); } stb_vorbis *stb_vorbis_open_pushdata( const unsigned char *data, int data_len, // the memory available for decoding int *data_used, // only defined if result is not NULL int *error, const stb_vorbis_alloc *alloc) { stb_vorbis *f, p; vorbis_init(&p, alloc); p.stream = (uint8 *) data; p.stream_end = (uint8 *) data + data_len; p.push_mode = TRUE; if (!start_decoder(&p)) { if (p.eof) *error = VORBIS_need_more_data; else *error = p.error; return NULL; } f = vorbis_alloc(&p); if (f) { *f = p; *data_used = (int) (f->stream - data); *error = 0; return f; } else { vorbis_deinit(&p); return NULL; } } #endif // STB_VORBIS_NO_PUSHDATA_API unsigned int stb_vorbis_get_file_offset(stb_vorbis *f) { #ifndef STB_VORBIS_NO_PUSHDATA_API if (f->push_mode) return 0; #endif if (USE_MEMORY(f)) return (unsigned int) (f->stream - f->stream_start); #ifndef STB_VORBIS_NO_STDIO return (unsigned int) (ftell(f->f) - f->f_start); #endif } #ifndef STB_VORBIS_NO_PULLDATA_API // // DATA-PULLING API // static uint32 vorbis_find_page(stb_vorbis *f, uint32 *end, uint32 *last) { for(;;) { int n; if (f->eof) return 0; n = get8(f); if (n == 0x4f) { // page header candidate unsigned int retry_loc = stb_vorbis_get_file_offset(f); int i; // check if we're off the end of a file_section stream if (retry_loc - 25 > f->stream_len) return 0; // check the rest of the header for (i=1; i < 4; ++i) if (get8(f) != ogg_page_header[i]) break; if (f->eof) return 0; if (i == 4) { uint8 header[27]; uint32 i, crc, goal, len; for (i=0; i < 4; ++i) header[i] = ogg_page_header[i]; for (; i < 27; ++i) header[i] = get8(f); if (f->eof) return 0; if (header[4] != 0) goto invalid; goal = header[22] + (header[23] << 8) + (header[24]<<16) + (header[25]<<24); for (i=22; i < 26; ++i) header[i] = 0; crc = 0; for (i=0; i < 27; ++i) crc = crc32_update(crc, header[i]); len = 0; for (i=0; i < header[26]; ++i) { int s = get8(f); crc = crc32_update(crc, s); len += s; } if (len && f->eof) return 0; for (i=0; i < len; ++i) crc = crc32_update(crc, get8(f)); // finished parsing probable page if (crc == goal) { // we could now check that it's either got the last // page flag set, OR it's followed by the capture // pattern, but I guess TECHNICALLY you could have // a file with garbage between each ogg page and recover // from it automatically? So even though that paranoia // might decrease the chance of an invalid decode by // another 2^32, not worth it since it would hose those // invalid-but-useful files? if (end) *end = stb_vorbis_get_file_offset(f); if (last) { if (header[5] & 0x04) *last = 1; else *last = 0; } set_file_offset(f, retry_loc-1); return 1; } } invalid: // not a valid page, so rewind and look for next one set_file_offset(f, retry_loc); } } } #define SAMPLE_unknown 0xffffffff // seeking is implemented with a binary search, which narrows down the range to // 64K, before using a linear search (because finding the synchronization // pattern can be expensive, and the chance we'd find the end page again is // relatively high for small ranges) // // two initial interpolation-style probes are used at the start of the search // to try to bound either side of the binary search sensibly, while still // working in O(log n) time if they fail. static int get_seek_page_info(stb_vorbis *f, ProbedPage *z) { uint8 header[27], lacing[255]; int i,len; // record where the page starts z->page_start = stb_vorbis_get_file_offset(f); // parse the header getn(f, header, 27); if (header[0] != 'O' || header[1] != 'g' || header[2] != 'g' || header[3] != 'S') return 0; getn(f, lacing, header[26]); // determine the length of the payload len = 0; for (i=0; i < header[26]; ++i) len += lacing[i]; // this implies where the page ends z->page_end = z->page_start + 27 + header[26] + len; // read the last-decoded sample out of the data z->last_decoded_sample = header[6] + (header[7] << 8) + (header[8] << 16) + (header[9] << 24); // restore file state to where we were set_file_offset(f, z->page_start); return 1; } // rarely used function to seek back to the preceding page while finding the // start of a packet static int go_to_page_before(stb_vorbis *f, unsigned int limit_offset) { unsigned int previous_safe, end; // now we want to seek back 64K from the limit if (limit_offset >= 65536 && limit_offset-65536 >= f->first_audio_page_offset) previous_safe = limit_offset - 65536; else previous_safe = f->first_audio_page_offset; set_file_offset(f, previous_safe); while (vorbis_find_page(f, &end, NULL)) { if (end >= limit_offset && stb_vorbis_get_file_offset(f) < limit_offset) return 1; set_file_offset(f, end); } return 0; } // implements the search logic for finding a page and starting decoding. if // the function succeeds, current_loc_valid will be true and current_loc will // be less than or equal to the provided sample number (the closer the // better). static int seek_to_sample_coarse(stb_vorbis *f, uint32 sample_number) { ProbedPage left, right, mid; int i, start_seg_with_known_loc, end_pos, page_start; uint32 delta, stream_length, padding; double offset, bytes_per_sample; int probe = 0; // find the last page and validate the target sample stream_length = stb_vorbis_stream_length_in_samples(f); if (stream_length == 0) return error(f, VORBIS_seek_without_length); if (sample_number > stream_length) return error(f, VORBIS_seek_invalid); // this is the maximum difference between the window-center (which is the // actual granule position value), and the right-start (which the spec // indicates should be the granule position (give or take one)). padding = ((f->blocksize_1 - f->blocksize_0) >> 2); if (sample_number < padding) sample_number = 0; else sample_number -= padding; left = f->p_first; while (left.last_decoded_sample == ~0U) { // (untested) the first page does not have a 'last_decoded_sample' set_file_offset(f, left.page_end); if (!get_seek_page_info(f, &left)) goto error; } right = f->p_last; assert(right.last_decoded_sample != ~0U); // starting from the start is handled differently if (sample_number <= left.last_decoded_sample) { if (stb_vorbis_seek_start(f)) return 1; return 0; } while (left.page_end != right.page_start) { assert(left.page_end < right.page_start); // search range in bytes delta = right.page_start - left.page_end; if (delta <= 65536) { // there's only 64K left to search - handle it linearly set_file_offset(f, left.page_end); } else { if (probe < 2) { if (probe == 0) { // first probe (interpolate) double data_bytes = right.page_end - left.page_start; bytes_per_sample = data_bytes / right.last_decoded_sample; offset = left.page_start + bytes_per_sample * (sample_number - left.last_decoded_sample); } else { // second probe (try to bound the other side) double error = ((double) sample_number - mid.last_decoded_sample) * bytes_per_sample; if (error >= 0 && error < 8000) error = 8000; if (error < 0 && error > -8000) error = -8000; offset += error * 2; } // ensure the offset is valid if (offset < left.page_end) offset = left.page_end; if (offset > right.page_start - 65536) offset = right.page_start - 65536; set_file_offset(f, (unsigned int) offset); } else { // binary search for large ranges (offset by 32K to ensure // we don't hit the right page) set_file_offset(f, left.page_end + (delta / 2) - 32768); } if (!vorbis_find_page(f, NULL, NULL)) goto error; } for (;;) { if (!get_seek_page_info(f, &mid)) goto error; if (mid.last_decoded_sample != ~0U) break; // (untested) no frames end on this page set_file_offset(f, mid.page_end); assert(mid.page_start < right.page_start); } // if we've just found the last page again then we're in a tricky file, // and we're close enough. if (mid.page_start == right.page_start) break; if (sample_number < mid.last_decoded_sample) right = mid; else left = mid; ++probe; } // seek back to start of the last packet page_start = left.page_start; set_file_offset(f, page_start); if (!start_page(f)) return error(f, VORBIS_seek_failed); end_pos = f->end_seg_with_known_loc; assert(end_pos >= 0); for (;;) { for (i = end_pos; i > 0; --i) if (f->segments[i-1] != 255) break; start_seg_with_known_loc = i; if (start_seg_with_known_loc > 0 || !(f->page_flag & PAGEFLAG_continued_packet)) break; // (untested) the final packet begins on an earlier page if (!go_to_page_before(f, page_start)) goto error; page_start = stb_vorbis_get_file_offset(f); if (!start_page(f)) goto error; end_pos = f->segment_count - 1; } // prepare to start decoding f->current_loc_valid = FALSE; f->last_seg = FALSE; f->valid_bits = 0; f->packet_bytes = 0; f->bytes_in_seg = 0; f->previous_length = 0; f->next_seg = start_seg_with_known_loc; for (i = 0; i < start_seg_with_known_loc; i++) skip(f, f->segments[i]); // start decoding (optimizable - this frame is generally discarded) if (!vorbis_pump_first_frame(f)) return 0; if (f->current_loc > sample_number) return error(f, VORBIS_seek_failed); return 1; error: // try to restore the file to a valid state stb_vorbis_seek_start(f); return error(f, VORBIS_seek_failed); } // the same as vorbis_decode_initial, but without advancing static int peek_decode_initial(vorb *f, int *p_left_start, int *p_left_end, int *p_right_start, int *p_right_end, int *mode) { int bits_read, bytes_read; if (!vorbis_decode_initial(f, p_left_start, p_left_end, p_right_start, p_right_end, mode)) return 0; // either 1 or 2 bytes were read, figure out which so we can rewind bits_read = 1 + ilog(f->mode_count-1); if (f->mode_config[*mode].blockflag) bits_read += 2; bytes_read = (bits_read + 7) / 8; f->bytes_in_seg += bytes_read; f->packet_bytes -= bytes_read; skip(f, -bytes_read); if (f->next_seg == -1) f->next_seg = f->segment_count - 1; else f->next_seg--; f->valid_bits = 0; return 1; } int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number) { uint32 max_frame_samples; if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); // fast page-level search if (!seek_to_sample_coarse(f, sample_number)) return 0; assert(f->current_loc_valid); assert(f->current_loc <= sample_number); // linear search for the relevant packet max_frame_samples = (f->blocksize_1*3 - f->blocksize_0) >> 2; while (f->current_loc < sample_number) { int left_start, left_end, right_start, right_end, mode, frame_samples; if (!peek_decode_initial(f, &left_start, &left_end, &right_start, &right_end, &mode)) return error(f, VORBIS_seek_failed); // calculate the number of samples returned by the next frame frame_samples = right_start - left_start; if (f->current_loc + frame_samples > sample_number) { return 1; // the next frame will contain the sample } else if (f->current_loc + frame_samples + max_frame_samples > sample_number) { // there's a chance the frame after this could contain the sample vorbis_pump_first_frame(f); } else { // this frame is too early to be relevant f->current_loc += frame_samples; f->previous_length = 0; maybe_start_packet(f); flush_packet(f); } } // the next frame will start with the sample assert(f->current_loc == sample_number); return 1; } int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number) { if (!stb_vorbis_seek_frame(f, sample_number)) return 0; if (sample_number != f->current_loc) { int n; uint32 frame_start = f->current_loc; stb_vorbis_get_frame_float(f, &n, NULL); assert(sample_number > frame_start); assert(f->channel_buffer_start + (int) (sample_number-frame_start) <= f->channel_buffer_end); f->channel_buffer_start += (sample_number - frame_start); } return 1; } int stb_vorbis_seek_start(stb_vorbis *f) { if (IS_PUSH_MODE(f)) { return error(f, VORBIS_invalid_api_mixing); } set_file_offset(f, f->first_audio_page_offset); f->previous_length = 0; f->first_decode = TRUE; f->next_seg = -1; return vorbis_pump_first_frame(f); } unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f) { unsigned int restore_offset, previous_safe; unsigned int end, last_page_loc; if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); if (!f->total_samples) { unsigned int last; uint32 lo,hi; char header[6]; // first, store the current decode position so we can restore it restore_offset = stb_vorbis_get_file_offset(f); // now we want to seek back 64K from the end (the last page must // be at most a little less than 64K, but let's allow a little slop) if (f->stream_len >= 65536 && f->stream_len-65536 >= f->first_audio_page_offset) previous_safe = f->stream_len - 65536; else previous_safe = f->first_audio_page_offset; set_file_offset(f, previous_safe); // previous_safe is now our candidate 'earliest known place that seeking // to will lead to the final page' if (!vorbis_find_page(f, &end, &last)) { // if we can't find a page, we're hosed! f->error = VORBIS_cant_find_last_page; f->total_samples = 0xffffffff; goto done; } // check if there are more pages last_page_loc = stb_vorbis_get_file_offset(f); // stop when the last_page flag is set, not when we reach eof; // this allows us to stop short of a 'file_section' end without // explicitly checking the length of the section while (!last) { set_file_offset(f, end); if (!vorbis_find_page(f, &end, &last)) { // the last page we found didn't have the 'last page' flag // set. whoops! break; } previous_safe = last_page_loc+1; last_page_loc = stb_vorbis_get_file_offset(f); } set_file_offset(f, last_page_loc); // parse the header getn(f, (unsigned char *)header, 6); // extract the absolute granule position lo = get32(f); hi = get32(f); if (lo == 0xffffffff && hi == 0xffffffff) { f->error = VORBIS_cant_find_last_page; f->total_samples = SAMPLE_unknown; goto done; } if (hi) lo = 0xfffffffe; // saturate f->total_samples = lo; f->p_last.page_start = last_page_loc; f->p_last.page_end = end; f->p_last.last_decoded_sample = lo; done: set_file_offset(f, restore_offset); } return f->total_samples == SAMPLE_unknown ? 0 : f->total_samples; } float stb_vorbis_stream_length_in_seconds(stb_vorbis *f) { return stb_vorbis_stream_length_in_samples(f) / (float) f->sample_rate; } int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output) { int len, right,left,i; if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); if (!vorbis_decode_packet(f, &len, &left, &right)) { f->channel_buffer_start = f->channel_buffer_end = 0; return 0; } len = vorbis_finish_frame(f, len, left, right); for (i=0; i < f->channels; ++i) f->outputs[i] = f->channel_buffers[i] + left; f->channel_buffer_start = left; f->channel_buffer_end = left+len; if (channels) *channels = f->channels; if (output) *output = f->outputs; return len; } #ifndef STB_VORBIS_NO_STDIO stb_vorbis * stb_vorbis_open_file_section(FILE *file, int close_on_free, int *error, const stb_vorbis_alloc *alloc, unsigned int length) { stb_vorbis *f, p; vorbis_init(&p, alloc); p.f = file; p.f_start = (uint32) ftell(file); p.stream_len = length; p.close_on_free = close_on_free; if (start_decoder(&p)) { f = vorbis_alloc(&p); if (f) { *f = p; vorbis_pump_first_frame(f); return f; } } if (error) *error = p.error; vorbis_deinit(&p); return NULL; } stb_vorbis * stb_vorbis_open_file(FILE *file, int close_on_free, int *error, const stb_vorbis_alloc *alloc) { unsigned int len, start; start = (unsigned int) ftell(file); fseek(file, 0, SEEK_END); len = (unsigned int) (ftell(file) - start); fseek(file, start, SEEK_SET); return stb_vorbis_open_file_section(file, close_on_free, error, alloc, len); } stb_vorbis * stb_vorbis_open_filename(const char *filename, int *error, const stb_vorbis_alloc *alloc) { FILE *f; #if defined(_WIN32) && defined(__STDC_WANT_SECURE_LIB__) if (0 != fopen_s(&f, filename, "rb")) f = NULL; #else f = fopen(filename, "rb"); #endif if (f) return stb_vorbis_open_file(f, TRUE, error, alloc); if (error) *error = VORBIS_file_open_failure; return NULL; } #endif // STB_VORBIS_NO_STDIO stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len, int *error, const stb_vorbis_alloc *alloc) { stb_vorbis *f, p; if (data == NULL) return NULL; vorbis_init(&p, alloc); p.stream = (uint8 *) data; p.stream_end = (uint8 *) data + len; p.stream_start = (uint8 *) p.stream; p.stream_len = len; p.push_mode = FALSE; if (start_decoder(&p)) { f = vorbis_alloc(&p); if (f) { *f = p; vorbis_pump_first_frame(f); if (error) *error = VORBIS__no_error; return f; } } if (error) *error = p.error; vorbis_deinit(&p); return NULL; } #ifndef STB_VORBIS_NO_INTEGER_CONVERSION #define PLAYBACK_MONO 1 #define PLAYBACK_LEFT 2 #define PLAYBACK_RIGHT 4 #define L (PLAYBACK_LEFT | PLAYBACK_MONO) #define C (PLAYBACK_LEFT | PLAYBACK_RIGHT | PLAYBACK_MONO) #define R (PLAYBACK_RIGHT | PLAYBACK_MONO) static int8 channel_position[7][6] = { { 0 }, { C }, { L, R }, { L, C, R }, { L, R, L, R }, { L, C, R, L, R }, { L, C, R, L, R, C }, }; #ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT typedef union { float f; int i; } float_conv; typedef char stb_vorbis_float_size_test[sizeof(float)==4 && sizeof(int) == 4]; #define FASTDEF(x) float_conv x // add (1<<23) to convert to int, then divide by 2^SHIFT, then add 0.5/2^SHIFT to round #define MAGIC(SHIFT) (1.5f * (1 << (23-SHIFT)) + 0.5f/(1 << SHIFT)) #define ADDEND(SHIFT) (((150-SHIFT) << 23) + (1 << 22)) #define FAST_SCALED_FLOAT_TO_INT(temp,x,s) (temp.f = (x) + MAGIC(s), temp.i - ADDEND(s)) #define check_endianness() #else #define FAST_SCALED_FLOAT_TO_INT(temp,x,s) ((int) ((x) * (1 << (s)))) #define check_endianness() #define FASTDEF(x) #endif static void copy_samples(short *dest, float *src, int len) { int i; check_endianness(); for (i=0; i < len; ++i) { FASTDEF(temp); int v = FAST_SCALED_FLOAT_TO_INT(temp, src[i],15); if ((unsigned int) (v + 32768) > 65535) v = v < 0 ? -32768 : 32767; dest[i] = v; } } static void compute_samples(int mask, short *output, int num_c, float **data, int d_offset, int len) { #define BUFFER_SIZE 32 float buffer[BUFFER_SIZE]; int i,j,o,n = BUFFER_SIZE; check_endianness(); for (o = 0; o < len; o += BUFFER_SIZE) { memset(buffer, 0, sizeof(buffer)); if (o + n > len) n = len - o; for (j=0; j < num_c; ++j) { if (channel_position[num_c][j] & mask) { for (i=0; i < n; ++i) buffer[i] += data[j][d_offset+o+i]; } } for (i=0; i < n; ++i) { FASTDEF(temp); int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15); if ((unsigned int) (v + 32768) > 65535) v = v < 0 ? -32768 : 32767; output[o+i] = v; } } } static void compute_stereo_samples(short *output, int num_c, float **data, int d_offset, int len) { #define BUFFER_SIZE 32 float buffer[BUFFER_SIZE]; int i,j,o,n = BUFFER_SIZE >> 1; // o is the offset in the source data check_endianness(); for (o = 0; o < len; o += BUFFER_SIZE >> 1) { // o2 is the offset in the output data int o2 = o << 1; memset(buffer, 0, sizeof(buffer)); if (o + n > len) n = len - o; for (j=0; j < num_c; ++j) { int m = channel_position[num_c][j] & (PLAYBACK_LEFT | PLAYBACK_RIGHT); if (m == (PLAYBACK_LEFT | PLAYBACK_RIGHT)) { for (i=0; i < n; ++i) { buffer[i*2+0] += data[j][d_offset+o+i]; buffer[i*2+1] += data[j][d_offset+o+i]; } } else if (m == PLAYBACK_LEFT) { for (i=0; i < n; ++i) { buffer[i*2+0] += data[j][d_offset+o+i]; } } else if (m == PLAYBACK_RIGHT) { for (i=0; i < n; ++i) { buffer[i*2+1] += data[j][d_offset+o+i]; } } } for (i=0; i < (n<<1); ++i) { FASTDEF(temp); int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15); if ((unsigned int) (v + 32768) > 65535) v = v < 0 ? -32768 : 32767; output[o2+i] = v; } } } static void convert_samples_short(int buf_c, short **buffer, int b_offset, int data_c, float **data, int d_offset, int samples) { int i; if (buf_c != data_c && buf_c <= 2 && data_c <= 6) { static int channel_selector[3][2] = { {0}, {PLAYBACK_MONO}, {PLAYBACK_LEFT, PLAYBACK_RIGHT} }; for (i=0; i < buf_c; ++i) compute_samples(channel_selector[buf_c][i], buffer[i]+b_offset, data_c, data, d_offset, samples); } else { int limit = buf_c < data_c ? buf_c : data_c; for (i=0; i < limit; ++i) copy_samples(buffer[i]+b_offset, data[i]+d_offset, samples); for ( ; i < buf_c; ++i) memset(buffer[i]+b_offset, 0, sizeof(short) * samples); } } int stb_vorbis_get_frame_short(stb_vorbis *f, int num_c, short **buffer, int num_samples) { float **output; int len = stb_vorbis_get_frame_float(f, NULL, &output); if (len > num_samples) len = num_samples; if (len) convert_samples_short(num_c, buffer, 0, f->channels, output, 0, len); return len; } static void convert_channels_short_interleaved(int buf_c, short *buffer, int data_c, float **data, int d_offset, int len) { int i; check_endianness(); if (buf_c != data_c && buf_c <= 2 && data_c <= 6) { assert(buf_c == 2); for (i=0; i < buf_c; ++i) compute_stereo_samples(buffer, data_c, data, d_offset, len); } else { int limit = buf_c < data_c ? buf_c : data_c; int j; for (j=0; j < len; ++j) { for (i=0; i < limit; ++i) { FASTDEF(temp); float f = data[i][d_offset+j]; int v = FAST_SCALED_FLOAT_TO_INT(temp, f,15);//data[i][d_offset+j],15); if ((unsigned int) (v + 32768) > 65535) v = v < 0 ? -32768 : 32767; *buffer++ = v; } for ( ; i < buf_c; ++i) *buffer++ = 0; } } } int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts) { float **output; int len; if (num_c == 1) return stb_vorbis_get_frame_short(f,num_c,&buffer, num_shorts); len = stb_vorbis_get_frame_float(f, NULL, &output); if (len) { if (len*num_c > num_shorts) len = num_shorts / num_c; convert_channels_short_interleaved(num_c, buffer, f->channels, output, 0, len); } return len; } int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts) { float **outputs; int len = num_shorts / channels; int n=0; int z = f->channels; if (z > channels) z = channels; while (n < len) { int k = f->channel_buffer_end - f->channel_buffer_start; if (n+k >= len) k = len - n; if (k) convert_channels_short_interleaved(channels, buffer, f->channels, f->channel_buffers, f->channel_buffer_start, k); buffer += k*channels; n += k; f->channel_buffer_start += k; if (n == len) break; if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; } return n; } int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int len) { float **outputs; int n=0; int z = f->channels; if (z > channels) z = channels; while (n < len) { int k = f->channel_buffer_end - f->channel_buffer_start; if (n+k >= len) k = len - n; if (k) convert_samples_short(channels, buffer, n, f->channels, f->channel_buffers, f->channel_buffer_start, k); n += k; f->channel_buffer_start += k; if (n == len) break; if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; } return n; } #ifndef STB_VORBIS_NO_STDIO int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_rate, short **output) { int data_len, offset, total, limit, error; short *data; stb_vorbis *v = stb_vorbis_open_filename(filename, &error, NULL); if (v == NULL) return -1; limit = v->channels * 4096; *channels = v->channels; if (sample_rate) *sample_rate = v->sample_rate; offset = data_len = 0; total = limit; data = (short *) malloc(total * sizeof(*data)); if (data == NULL) { stb_vorbis_close(v); return -2; } for (;;) { int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset); if (n == 0) break; data_len += n; offset += n * v->channels; if (offset + limit > total) { short *data2; total *= 2; data2 = (short *) realloc(data, total * sizeof(*data)); if (data2 == NULL) { free(data); stb_vorbis_close(v); return -2; } data = data2; } } *output = data; stb_vorbis_close(v); return data_len; } #endif // NO_STDIO int stb_vorbis_decode_memory(const uint8 *mem, int len, int *channels, int *sample_rate, short **output) { int data_len, offset, total, limit, error; short *data; stb_vorbis *v = stb_vorbis_open_memory(mem, len, &error, NULL); if (v == NULL) return -1; limit = v->channels * 4096; *channels = v->channels; if (sample_rate) *sample_rate = v->sample_rate; offset = data_len = 0; total = limit; data = (short *) malloc(total * sizeof(*data)); if (data == NULL) { stb_vorbis_close(v); return -2; } for (;;) { int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset); if (n == 0) break; data_len += n; offset += n * v->channels; if (offset + limit > total) { short *data2; total *= 2; data2 = (short *) realloc(data, total * sizeof(*data)); if (data2 == NULL) { free(data); stb_vorbis_close(v); return -2; } data = data2; } } *output = data; stb_vorbis_close(v); return data_len; } #endif // STB_VORBIS_NO_INTEGER_CONVERSION int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats) { float **outputs; int len = num_floats / channels; int n=0; int z = f->channels; if (z > channels) z = channels; while (n < len) { int i,j; int k = f->channel_buffer_end - f->channel_buffer_start; if (n+k >= len) k = len - n; for (j=0; j < k; ++j) { for (i=0; i < z; ++i) *buffer++ = f->channel_buffers[i][f->channel_buffer_start+j]; for ( ; i < channels; ++i) *buffer++ = 0; } n += k; f->channel_buffer_start += k; if (n == len) break; if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; } return n; } int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples) { float **outputs; int n=0; int z = f->channels; if (z > channels) z = channels; while (n < num_samples) { int i; int k = f->channel_buffer_end - f->channel_buffer_start; if (n+k >= num_samples) k = num_samples - n; if (k) { for (i=0; i < z; ++i) memcpy(buffer[i]+n, f->channel_buffers[i]+f->channel_buffer_start, sizeof(float)*k); for ( ; i < channels; ++i) memset(buffer[i]+n, 0, sizeof(float) * k); } n += k; f->channel_buffer_start += k; if (n == num_samples) break; if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; } return n; } #endif // STB_VORBIS_NO_PULLDATA_API /* Version history 1.17 - 2019-07-08 - fix CVE-2019-13217, -13218, -13219, -13220, -13221, -13222, -13223 found with Mayhem by ForAllSecure 1.16 - 2019-03-04 - fix warnings 1.15 - 2019-02-07 - explicit failure if Ogg Skeleton data is found 1.14 - 2018-02-11 - delete bogus dealloca usage 1.13 - 2018-01-29 - fix truncation of last frame (hopefully) 1.12 - 2017-11-21 - limit residue begin/end to blocksize/2 to avoid large temp allocs in bad/corrupt files 1.11 - 2017-07-23 - fix MinGW compilation 1.10 - 2017-03-03 - more robust seeking; fix negative ilog(); clear error in open_memory 1.09 - 2016-04-04 - back out 'avoid discarding last frame' fix from previous version 1.08 - 2016-04-02 - fixed multiple warnings; fix setup memory leaks; avoid discarding last frame of audio data 1.07 - 2015-01-16 - fixed some warnings, fix mingw, const-correct API some more crash fixes when out of memory or with corrupt files 1.06 - 2015-08-31 - full, correct support for seeking API (Dougall Johnson) some crash fixes when out of memory or with corrupt files 1.05 - 2015-04-19 - don't define __forceinline if it's redundant 1.04 - 2014-08-27 - fix missing const-correct case in API 1.03 - 2014-08-07 - Warning fixes 1.02 - 2014-07-09 - Declare qsort compare function _cdecl on windows 1.01 - 2014-06-18 - fix stb_vorbis_get_samples_float 1.0 - 2014-05-26 - fix memory leaks; fix warnings; fix bugs in multichannel (API change) report sample rate for decode-full-file funcs 0.99996 - bracket #include <malloc.h> for macintosh compilation by Laurent Gomila 0.99995 - use union instead of pointer-cast for fast-float-to-int to avoid alias-optimization problem 0.99994 - change fast-float-to-int to work in single-precision FPU mode, remove endian-dependence 0.99993 - remove assert that fired on legal files with empty tables 0.99992 - rewind-to-start 0.99991 - bugfix to stb_vorbis_get_samples_short by Bernhard Wodo 0.9999 - (should have been 0.99990) fix no-CRT support, compiling as C++ 0.9998 - add a full-decode function with a memory source 0.9997 - fix a bug in the read-from-FILE case in 0.9996 addition 0.9996 - query length of vorbis stream in samples/seconds 0.9995 - bugfix to another optimization that only happened in certain files 0.9994 - bugfix to one of the optimizations that caused significant (but inaudible?) errors 0.9993 - performance improvements; runs in 99% to 104% of time of reference implementation 0.9992 - performance improvement of IMDCT; now performs close to reference implementation 0.9991 - performance improvement of IMDCT 0.999 - (should have been 0.9990) performance improvement of IMDCT 0.998 - no-CRT support from Casey Muratori 0.997 - bugfixes for bugs found by Terje Mathisen 0.996 - bugfix: fast-huffman decode initialized incorrectly for sparse codebooks; fixing gives 10% speedup - found by Terje Mathisen 0.995 - bugfix: fix to 'effective' overrun detection - found by Terje Mathisen 0.994 - bugfix: garbage decode on final VQ symbol of a non-multiple - found by Terje Mathisen 0.993 - bugfix: pushdata API required 1 extra byte for empty page (failed to consume final page if empty) - found by Terje Mathisen 0.992 - fixes for MinGW warning 0.991 - turn fast-float-conversion on by default 0.990 - fix push-mode seek recovery if you seek into the headers 0.98b - fix to bad release of 0.98 0.98 - fix push-mode seek recovery; robustify float-to-int and support non-fast mode 0.97 - builds under c++ (typecasting, don't use 'class' keyword) 0.96 - somehow MY 0.95 was right, but the web one was wrong, so here's my 0.95 rereleased as 0.96, fixes a typo in the clamping code 0.95 - clamping code for 16-bit functions 0.94 - not publically released 0.93 - fixed all-zero-floor case (was decoding garbage) 0.92 - fixed a memory leak 0.91 - conditional compiles to omit parts of the API and the infrastructure to support them: STB_VORBIS_NO_PULLDATA_API, STB_VORBIS_NO_PUSHDATA_API, STB_VORBIS_NO_STDIO, STB_VORBIS_NO_INTEGER_CONVERSION 0.90 - first public release */ #endif // STB_VORBIS_HEADER_ONLY /* ------------------------------------------------------------------------------ This software is available under 2 licenses -- choose whichever you prefer. ------------------------------------------------------------------------------ ALTERNATIVE A - MIT License Copyright (c) 2017 Sean Barrett Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ ALTERNATIVE B - Public Domain (www.unlicense.org) This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ */
the_stack_data/76701106.c
#include <string.h> #include <stdio.h> void *ft_memmove(void *dst, const void *src, size_t len); int main(void) { char dst1[] = "Hey marvin!!"; char dst2[] = "Hey marvin!!"; char dst3[] = "Hey marvin!!"; char dst4[] = "Hey marvin!!"; const char src[] = "Ola"; const char src2[] = "Ola MarVin Yeh!"; const char src3[] = "@@@"; memmove(dst1, src, 3); printf("dst1 >> %s \n", dst1); ft_memmove(dst2, src, 3); printf("dst2 >> %s \n", dst2); printf("================\n"); memmove(dst3, src2, 10); printf("dst3 >> %s \n", dst3); ft_memmove(dst4, src2, 10); printf("dst4 >> %s \n", dst4); printf("================\n"); memmove(dst1, src3, 0); printf("dst1 >> %s \n", dst1); ft_memmove(dst2, src3, 0); printf("dst2 >> %s \n", dst2); return (0); }
the_stack_data/883357.c
#include <stdio.h> int main(){ printf("강한친구 대한육군\n"); printf("강한친구 대한육군"); }
the_stack_data/243894286.c
#ifdef HAVE_ETH2 #include "shared_context.h" #include "ui_callbacks.h" void prepare_eth2_public_key() { snprintf(strings.tmp.tmp, 100, "0x%.*H", 48, tmpCtx.publicKeyContext.publicKey.W); } // clang-format off UX_STEP_NOCB( ux_display_public_eth2_flow_1_step, pnn, { &C_icon_eye, "Verify ETH2", "public key", }); UX_STEP_NOCB_INIT( ux_display_public_eth2_flow_2_step, bnnn_paging, prepare_eth2_public_key(), { .title = "Public Key", .text = strings.tmp.tmp, }); UX_STEP_CB( ux_display_public_eth2_flow_3_step, pb, io_seproxyhal_touch_eth2_address_ok(NULL), { &C_icon_validate_14, "Approve", }); UX_STEP_CB( ux_display_public_eth2_flow_4_step, pb, io_seproxyhal_touch_address_cancel(NULL), { &C_icon_crossmark, "Reject", }); // clang-format on UX_FLOW(ux_display_public_eth2_flow, &ux_display_public_eth2_flow_1_step, &ux_display_public_eth2_flow_2_step, &ux_display_public_eth2_flow_3_step, &ux_display_public_eth2_flow_4_step); #endif
the_stack_data/82949906.c
#include <stdio.h> int main() { int J = 60; int I = 1; for (int x = 0; x <= 12; x++) { printf("I=%d ", I); printf("J=%d\n", J); J-=5; I+=3; } return 0; }
the_stack_data/14526.c
/* Name: checking.c Purpose: Balances a checkbook. Author: K.N. King Date: 05.04.2022 */ #include <stdio.h> int main(void) { int cmd; float balance = 0.0f, credit, debit; printf("*** ACME checkbook-balancing program ***\n"); printf("Commands: 0=clear, 1=credit, 2=debit, "); printf("3=balance, 4=exit\n\n"); for (;;) { printf("Enter command: "); scanf("%d", &cmd); switch (cmd) { case 0: balance = 0.0f; break; case 1: printf("Enter amount of credit: "); scanf("%f", &credit); balance += credit; break; case 2: printf("Enter amount of debit: "); scanf("%f", &debit); balance -= debit; break; case 3: printf("Current balance: $%.2f\n", balance); break; case 4: return 0; default: printf("Commands: 0=clear, 1=credit, 2=debit, "); printf("3=balance, 4=exit\n\n"); break; } } return 0; }
the_stack_data/33260.c
#include <stdio.h> #include <stdlib.h> #include <math.h> /* gcc dbl_setup_f.c -lm -O2 -o dbl_setup_f && ./dbl_setup_f 61 */ void make_tables(int kmax){ // prepare tables and scale correction int k, n, Nmax, k_n[2*(kmax+1)]; double sec2a, K=1., f64_a[2*(kmax+1)]; for (k=0, n=0; k<=kmax; k++){ f64_a[k] = atan(1./(1LL<<k)); k_n[n++] = k; sec2a = 1 + 1./(1LL<<k)/(1LL<<k); if (sec2a>1) { K /= sec2a; k_n[n++] = k; } } Nmax = n; // print parameters and tables printf("#define Nmax %d\n", Nmax); printf("#define K %-21.13a\n", K); printf("\n"); printf("atan(a_k)\n"); for (k=0; k<=kmax; ++k) printf("%-21.13a,%s", f64_a[k], (k+1)%4?" ":"\n"); printf("\n\nshift values k_n\n"); for (n=0; n<Nmax; ++n) printf("%2d,%s", k_n[n], (n+1)%16?" ":"\n"); printf("\n"); } int main(int argc, char *argv[]) { int kmax, bp; kmax = atoi(argv[1]); // largest shift value make_tables(kmax); return 0; }
the_stack_data/293338.c
// RUN: %clang_cc1 -triple x86_64-unknown-linux -fsanitize=cfi-icall -fsanitize-trap=cfi-icall -emit-llvm -o - %s | FileCheck --check-prefix=ITANIUM %s // RUN: %clang_cc1 -triple x86_64-pc-windows-msvc -fsanitize=cfi-icall -fsanitize-trap=cfi-icall -emit-llvm -o - %s | FileCheck --check-prefix=MS %s // Tests that we assign appropriate identifiers to unprototyped functions. void f() { } void xf(); void g(int b) { void (*fp)() = b ? f : xf; // ITANIUM: call i1 @llvm.bitset.test(i8* {{.*}}, metadata !"_ZTSFvE") fp(); } // ITANIUM-DAG: !{!"_ZTSFvE", void ()* @f, i64 0} // ITANIUM-DAG: !{!"_ZTSFvE", void (...)* @xf, i64 0} // MS-DAG: !{!"?6AX@Z", void ()* @f, i64 0} // MS-DAG: !{!"?6AX@Z", void (...)* @xf, i64 0}
the_stack_data/192330579.c
/* Compile: Windows: mingw32-gcc.exe -o pick.exe pick.c -static linux: gcc -o pick tools/linux/src/pick.c -static macsox: gcc -o tools/macos/pick tools/macos/src/pick.c */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/types.h> #define PATTERN_1 0x96969999 #define PATTERN_2 0xFC66CC3F unsigned int image_header[8] = {0,0,0,0,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF}; int main(int argc, char* argv[]) { int arg_num = 5; unsigned int is_raw = 0; if ((argc > 5) && ((strcmp(argv[5], "boot") == 0) || (strcmp(argv[5], "raw") == 0))) { if (strcmp(argv[5], "raw") == 0) { printf("is_law = 1\n"); is_raw = 1; } arg_num++; } if (argc != arg_num) { printf("Usage: pick <start addr> <end addr> <input name> <output name> [options]\nOptions:\n\tboot To distinguish Image1 and Image2. Image1 should add this option\n\traw Remove bss section according to start addr and end addr\n"); return -1; } unsigned char *buf; unsigned int start; unsigned int end; unsigned int base; char *inf = argv[3]; char *outf = argv[4]; int size; FILE *ifp, *ofp; start = strtol(argv[1], NULL, 0); end = strtol(argv[2], NULL, 0); base = start&0xFFFF0000; printf("start = %x, end = %x, base = %x\n", start, end, base); ifp = fopen(inf, "rb"); if (!ifp) { printf("Input file open error."); return -2; } ofp = fopen(outf, "wb"); if (!ofp) { printf("Output file open error."); return -3; } //fseek(ifp, 0, SEEK_END); //size = ftell(ifp); size = end-start; printf("Input file size: %d\n", size); buf = malloc(size); if (!buf) { return -4; } if (end==0) { end = base+size; } if ((end - start + 1) > 0) { // fseek(ifp, start-base, SEEK_SET); fseek(ifp, 0, SEEK_SET); fread(buf, end-start, 1, ifp); if (is_raw == 0) { if ((argc > 5) && (strcmp(argv[5], "boot") == 0)) { image_header[0] = PATTERN_1; image_header[1] = PATTERN_2; } else { image_header[0] = 0x35393138; image_header[1] = 0x31313738; } image_header[2] = size; image_header[3] = start; fwrite(image_header, 8, sizeof(unsigned int), ofp); } fwrite(buf, end-start, 1, ofp); } printf("copy size %d\n", end-start); fclose(ifp); fclose(ofp); free(buf); return 0; }
the_stack_data/3925.c
#include<stdio.h> int main() { printf("hello world!"); }
the_stack_data/34513593.c
/* Capstone Disassembly Engine */ /* TMS320C64x Backend by Fotis Loukos <[email protected]> 2016 */ #ifdef CAPSTONE_HAS_TMS320C64X #include <string.h> #include "../../cs_priv.h" #include "../../utils.h" #include "../../MCInst.h" #include "../../MCInstrDesc.h" #include "../../MCFixedLenDisassembler.h" #include "../../MCRegisterInfo.h" #include "../../MCDisassembler.h" #include "../../MathExtras.h" static uint64_t getFeatureBits(int mode); static DecodeStatus DecodeGPRegsRegisterClass(MCInst *Inst, unsigned RegNo, uint64_t Address, void *Decoder); static DecodeStatus DecodeControlRegsRegisterClass(MCInst *Inst, unsigned RegNo, uint64_t Address, void *Decoder); static DecodeStatus DecodeScst5(MCInst *Inst, unsigned Val, uint64_t Address, void *Decoder); static DecodeStatus DecodeScst16(MCInst *Inst, unsigned Val, uint64_t Address, void *Decoder); static DecodeStatus DecodePCRelScst7(MCInst *Inst, unsigned Val, uint64_t Address, void *Decoder); static DecodeStatus DecodePCRelScst10(MCInst *Inst, unsigned Val, uint64_t Address, void *Decoder); static DecodeStatus DecodePCRelScst12(MCInst *Inst, unsigned Val, uint64_t Address, void *Decoder); static DecodeStatus DecodePCRelScst21(MCInst *Inst, unsigned Val, uint64_t Address, void *Decoder); static DecodeStatus DecodeMemOperand(MCInst *Inst, unsigned Val, uint64_t Address, void *Decoder); static DecodeStatus DecodeMemOperandSc(MCInst *Inst, unsigned Val, uint64_t Address, void *Decoder); static DecodeStatus DecodeMemOperand2(MCInst *Inst, unsigned Val, uint64_t Address, void *Decoder); static DecodeStatus DecodeRegPair5(MCInst *Inst, unsigned RegNo, uint64_t Address, void *Decoder); static DecodeStatus DecodeRegPair4(MCInst *Inst, unsigned RegNo, uint64_t Address, void *Decoder); static DecodeStatus DecodeCondRegister(MCInst *Inst, unsigned Val, uint64_t Address, void *Decoder); static DecodeStatus DecodeCondRegisterZero(MCInst *Inst, unsigned Val, uint64_t Address, void *Decoder); static DecodeStatus DecodeSide(MCInst *Inst, unsigned Val, uint64_t Address, void *Decoder); static DecodeStatus DecodeParallel(MCInst *Inst, unsigned Val, uint64_t Address, void *Decoder); static DecodeStatus DecodeCrosspathX1(MCInst *Inst, unsigned Val, uint64_t Address, void *Decoder); static DecodeStatus DecodeCrosspathX2(MCInst *Inst, unsigned Val, uint64_t Address, void *Decoder); static DecodeStatus DecodeCrosspathX3(MCInst *Inst, unsigned Val, uint64_t Address, void *Decoder); static DecodeStatus DecodeNop(MCInst *Inst, unsigned Val, uint64_t Address, void *Decoder); #include "TMS320C64xGenDisassemblerTables.inc" #define GET_REGINFO_ENUM #define GET_REGINFO_MC_DESC #include "TMS320C64xGenRegisterInfo.inc" static const unsigned GPRegsDecoderTable[] = { TMS320C64x_A0, TMS320C64x_A1, TMS320C64x_A2, TMS320C64x_A3, TMS320C64x_A4, TMS320C64x_A5, TMS320C64x_A6, TMS320C64x_A7, TMS320C64x_A8, TMS320C64x_A9, TMS320C64x_A10, TMS320C64x_A11, TMS320C64x_A12, TMS320C64x_A13, TMS320C64x_A14, TMS320C64x_A15, TMS320C64x_A16, TMS320C64x_A17, TMS320C64x_A18, TMS320C64x_A19, TMS320C64x_A20, TMS320C64x_A21, TMS320C64x_A22, TMS320C64x_A23, TMS320C64x_A24, TMS320C64x_A25, TMS320C64x_A26, TMS320C64x_A27, TMS320C64x_A28, TMS320C64x_A29, TMS320C64x_A30, TMS320C64x_A31 }; static const unsigned ControlRegsDecoderTable[] = { TMS320C64x_AMR, TMS320C64x_CSR, TMS320C64x_ISR, TMS320C64x_ICR, TMS320C64x_IER, TMS320C64x_ISTP, TMS320C64x_IRP, TMS320C64x_NRP, ~0U, ~0U, TMS320C64x_TSCL, TMS320C64x_TSCH, ~0U, TMS320C64x_ILC, TMS320C64x_RILC, TMS320C64x_REP, TMS320C64x_PCE1, TMS320C64x_DNUM, ~0U, ~0U, ~0U, TMS320C64x_SSR, TMS320C64x_GPLYA, TMS320C64x_GPLYB, TMS320C64x_GFPGFR, TMS320C64x_DIER, TMS320C64x_TSR, TMS320C64x_ITSR, TMS320C64x_NTSR, TMS320C64x_ECR, ~0U, TMS320C64x_IERR }; static uint64_t getFeatureBits(int mode) { // support everything return (uint64_t)-1; } static unsigned getReg(const unsigned *RegTable, unsigned RegNo) { if(RegNo > 31) return ~0U; return RegTable[RegNo]; } static DecodeStatus DecodeGPRegsRegisterClass(MCInst *Inst, unsigned RegNo, uint64_t Address, void *Decoder) { unsigned Reg; if(RegNo > 31) return MCDisassembler_Fail; Reg = getReg(GPRegsDecoderTable, RegNo); if(Reg == ~0U) return MCDisassembler_Fail; MCOperand_CreateReg0(Inst, Reg); return MCDisassembler_Success; } static DecodeStatus DecodeControlRegsRegisterClass(MCInst *Inst, unsigned RegNo, uint64_t Address, void *Decoder) { unsigned Reg; if(RegNo > 31) return MCDisassembler_Fail; Reg = getReg(ControlRegsDecoderTable, RegNo); if(Reg == ~0U) return MCDisassembler_Fail; MCOperand_CreateReg0(Inst, Reg); return MCDisassembler_Success; } static DecodeStatus DecodeScst5(MCInst *Inst, unsigned Val, uint64_t Address, void *Decoder) { int32_t imm; imm = Val; /* Sign extend 5 bit value */ if(imm & (1 << (5 - 1))) imm |= ~((1 << 5) - 1); MCOperand_CreateImm0(Inst, imm); return MCDisassembler_Success; } static DecodeStatus DecodeScst16(MCInst *Inst, unsigned Val, uint64_t Address, void *Decoder) { int32_t imm; imm = Val; /* Sign extend 16 bit value */ if(imm & (1 << (16 - 1))) imm |= ~((1 << 16) - 1); MCOperand_CreateImm0(Inst, imm); return MCDisassembler_Success; } static DecodeStatus DecodePCRelScst7(MCInst *Inst, unsigned Val, uint64_t Address, void *Decoder) { int32_t imm; imm = Val; /* Sign extend 7 bit value */ if(imm & (1 << (7 - 1))) imm |= ~((1 << 7) - 1); /* Address is relative to the address of the first instruction in the fetch packet */ MCOperand_CreateImm0(Inst, (Address & ~31) + (imm << 2)); return MCDisassembler_Success; } static DecodeStatus DecodePCRelScst10(MCInst *Inst, unsigned Val, uint64_t Address, void *Decoder) { int32_t imm; imm = Val; /* Sign extend 10 bit value */ if(imm & (1 << (10 - 1))) imm |= ~((1 << 10) - 1); /* Address is relative to the address of the first instruction in the fetch packet */ MCOperand_CreateImm0(Inst, (Address & ~31) + (imm << 2)); return MCDisassembler_Success; } static DecodeStatus DecodePCRelScst12(MCInst *Inst, unsigned Val, uint64_t Address, void *Decoder) { int32_t imm; imm = Val; /* Sign extend 12 bit value */ if(imm & (1 << (12 - 1))) imm |= ~((1 << 12) - 1); /* Address is relative to the address of the first instruction in the fetch packet */ MCOperand_CreateImm0(Inst, (Address & ~31) + (imm << 2)); return MCDisassembler_Success; } static DecodeStatus DecodePCRelScst21(MCInst *Inst, unsigned Val, uint64_t Address, void *Decoder) { int32_t imm; imm = Val; /* Sign extend 21 bit value */ if(imm & (1 << (21 - 1))) imm |= ~((1 << 21) - 1); /* Address is relative to the address of the first instruction in the fetch packet */ MCOperand_CreateImm0(Inst, (Address & ~31) + (imm << 2)); return MCDisassembler_Success; } static DecodeStatus DecodeMemOperand(MCInst *Inst, unsigned Val, uint64_t Address, void *Decoder) { return DecodeMemOperandSc(Inst, Val | (1 << 15), Address, Decoder); } static DecodeStatus DecodeMemOperandSc(MCInst *Inst, unsigned Val, uint64_t Address, void *Decoder) { uint8_t scaled, base, offset, mode, unit; unsigned basereg, offsetreg; scaled = (Val >> 15) & 1; base = (Val >> 10) & 0x1f; offset = (Val >> 5) & 0x1f; mode = (Val >> 1) & 0xf; unit = Val & 1; if((base >= TMS320C64X_REG_A0) && (base <= TMS320C64X_REG_A31)) base = (base - TMS320C64X_REG_A0 + TMS320C64X_REG_B0); else if((base >= TMS320C64X_REG_B0) && (base <= TMS320C64X_REG_B31)) base = (base - TMS320C64X_REG_B0 + TMS320C64X_REG_A0); basereg = getReg(GPRegsDecoderTable, base); switch(mode) { case 0: case 1: case 8: case 9: case 10: case 11: MCOperand_CreateImm0(Inst, (scaled << 19) | (basereg << 12) | (offset << 5) | (mode << 1) | unit); break; case 4: case 5: case 12: case 13: case 14: case 15: if((offset >= TMS320C64X_REG_A0) && (offset <= TMS320C64X_REG_A31)) offset = (offset - TMS320C64X_REG_A0 + TMS320C64X_REG_B0); else if((offset >= TMS320C64X_REG_B0) && (offset <= TMS320C64X_REG_B31)) offset = (offset - TMS320C64X_REG_B0 + TMS320C64X_REG_A0); offsetreg = getReg(GPRegsDecoderTable, offset); MCOperand_CreateImm0(Inst, (scaled << 19) | (basereg << 12) | (offsetreg << 5) | (mode << 1) | unit); break; default: return MCDisassembler_Fail; } return MCDisassembler_Success; } static DecodeStatus DecodeMemOperand2(MCInst *Inst, unsigned Val, uint64_t Address, void *Decoder) { uint16_t offset; unsigned basereg; if(Val & 1) basereg = TMS320C64X_REG_B15; else basereg = TMS320C64X_REG_B14; offset = (Val >> 1) & 0x7fff; MCOperand_CreateImm0(Inst, (offset << 7) | basereg); return MCDisassembler_Success; } static DecodeStatus DecodeRegPair5(MCInst *Inst, unsigned RegNo, uint64_t Address, void *Decoder) { unsigned Reg; if(RegNo > 31) return MCDisassembler_Fail; Reg = getReg(GPRegsDecoderTable, RegNo); MCOperand_CreateReg0(Inst, Reg); return MCDisassembler_Success; } static DecodeStatus DecodeRegPair4(MCInst *Inst, unsigned RegNo, uint64_t Address, void *Decoder) { unsigned Reg; if(RegNo > 15) return MCDisassembler_Fail; Reg = getReg(GPRegsDecoderTable, RegNo << 1); MCOperand_CreateReg0(Inst, Reg); return MCDisassembler_Success; } static DecodeStatus DecodeCondRegister(MCInst *Inst, unsigned Val, uint64_t Address, void *Decoder) { DecodeStatus ret = MCDisassembler_Success; if(!Inst->flat_insn->detail) return MCDisassembler_Success; switch(Val) { case 0: case 7: Inst->flat_insn->detail->tms320c64x.condition.reg = TMS320C64X_REG_INVALID; break; case 1: Inst->flat_insn->detail->tms320c64x.condition.reg = TMS320C64X_REG_B0; break; case 2: Inst->flat_insn->detail->tms320c64x.condition.reg = TMS320C64X_REG_B1; break; case 3: Inst->flat_insn->detail->tms320c64x.condition.reg = TMS320C64X_REG_B2; break; case 4: Inst->flat_insn->detail->tms320c64x.condition.reg = TMS320C64X_REG_A1; break; case 5: Inst->flat_insn->detail->tms320c64x.condition.reg = TMS320C64X_REG_A2; break; case 6: Inst->flat_insn->detail->tms320c64x.condition.reg = TMS320C64X_REG_A0; break; default: Inst->flat_insn->detail->tms320c64x.condition.reg = TMS320C64X_REG_INVALID; ret = MCDisassembler_Fail; break; } return ret; } static DecodeStatus DecodeCondRegisterZero(MCInst *Inst, unsigned Val, uint64_t Address, void *Decoder) { DecodeStatus ret = MCDisassembler_Success; if(!Inst->flat_insn->detail) return MCDisassembler_Success; switch(Val) { case 0: Inst->flat_insn->detail->tms320c64x.condition.zero = 0; break; case 1: Inst->flat_insn->detail->tms320c64x.condition.zero = 1; break; default: Inst->flat_insn->detail->tms320c64x.condition.zero = 0; ret = MCDisassembler_Fail; break; } return ret; } static DecodeStatus DecodeSide(MCInst *Inst, unsigned Val, uint64_t Address, void *Decoder) { DecodeStatus ret = MCDisassembler_Success; MCOperand *op; int i; /* This is pretty messy, probably we should find a better way */ if(Val == 1) { for(i = 0; i < Inst->size; i++) { op = &Inst->Operands[i]; if(op->Kind == kRegister) { if((op->RegVal >= TMS320C64X_REG_A0) && (op->RegVal <= TMS320C64X_REG_A31)) op->RegVal = (op->RegVal - TMS320C64X_REG_A0 + TMS320C64X_REG_B0); else if((op->RegVal >= TMS320C64X_REG_B0) && (op->RegVal <= TMS320C64X_REG_B31)) op->RegVal = (op->RegVal - TMS320C64X_REG_B0 + TMS320C64X_REG_A0); } } } if(!Inst->flat_insn->detail) return MCDisassembler_Success; switch(Val) { case 0: Inst->flat_insn->detail->tms320c64x.funit.side = 1; break; case 1: Inst->flat_insn->detail->tms320c64x.funit.side = 2; break; default: Inst->flat_insn->detail->tms320c64x.funit.side = 0; ret = MCDisassembler_Fail; break; } return ret; } static DecodeStatus DecodeParallel(MCInst *Inst, unsigned Val, uint64_t Address, void *Decoder) { DecodeStatus ret = MCDisassembler_Success; if(!Inst->flat_insn->detail) return MCDisassembler_Success; switch(Val) { case 0: Inst->flat_insn->detail->tms320c64x.parallel = 0; break; case 1: Inst->flat_insn->detail->tms320c64x.parallel = 1; break; default: Inst->flat_insn->detail->tms320c64x.parallel = -1; ret = MCDisassembler_Fail; break; } return ret; } static DecodeStatus DecodeCrosspathX1(MCInst *Inst, unsigned Val, uint64_t Address, void *Decoder) { DecodeStatus ret = MCDisassembler_Success; MCOperand *op; if(!Inst->flat_insn->detail) return MCDisassembler_Success; switch(Val) { case 0: Inst->flat_insn->detail->tms320c64x.funit.crosspath = 0; break; case 1: Inst->flat_insn->detail->tms320c64x.funit.crosspath = 1; op = &Inst->Operands[0]; if(op->Kind == kRegister) { if((op->RegVal >= TMS320C64X_REG_A0) && (op->RegVal <= TMS320C64X_REG_A31)) op->RegVal = (op->RegVal - TMS320C64X_REG_A0 + TMS320C64X_REG_B0); else if((op->RegVal >= TMS320C64X_REG_B0) && (op->RegVal <= TMS320C64X_REG_B31)) op->RegVal = (op->RegVal - TMS320C64X_REG_B0 + TMS320C64X_REG_A0); } break; default: Inst->flat_insn->detail->tms320c64x.funit.crosspath = -1; ret = MCDisassembler_Fail; break; } return ret; } static DecodeStatus DecodeCrosspathX2(MCInst *Inst, unsigned Val, uint64_t Address, void *Decoder) { DecodeStatus ret = MCDisassembler_Success; MCOperand *op; if(!Inst->flat_insn->detail) return MCDisassembler_Success; switch(Val) { case 0: Inst->flat_insn->detail->tms320c64x.funit.crosspath = 0; break; case 1: Inst->flat_insn->detail->tms320c64x.funit.crosspath = 1; op = &Inst->Operands[1]; if(op->Kind == kRegister) { if((op->RegVal >= TMS320C64X_REG_A0) && (op->RegVal <= TMS320C64X_REG_A31)) op->RegVal = (op->RegVal - TMS320C64X_REG_A0 + TMS320C64X_REG_B0); else if((op->RegVal >= TMS320C64X_REG_B0) && (op->RegVal <= TMS320C64X_REG_B31)) op->RegVal = (op->RegVal - TMS320C64X_REG_B0 + TMS320C64X_REG_A0); } break; default: Inst->flat_insn->detail->tms320c64x.funit.crosspath = -1; ret = MCDisassembler_Fail; break; } return ret; } static DecodeStatus DecodeCrosspathX3(MCInst *Inst, unsigned Val, uint64_t Address, void *Decoder) { DecodeStatus ret = MCDisassembler_Success; MCOperand *op; if(!Inst->flat_insn->detail) return MCDisassembler_Success; switch(Val) { case 0: Inst->flat_insn->detail->tms320c64x.funit.crosspath = 0; break; case 1: Inst->flat_insn->detail->tms320c64x.funit.crosspath = 2; op = &Inst->Operands[2]; if(op->Kind == kRegister) { if((op->RegVal >= TMS320C64X_REG_A0) && (op->RegVal <= TMS320C64X_REG_A31)) op->RegVal = (op->RegVal - TMS320C64X_REG_A0 + TMS320C64X_REG_B0); else if((op->RegVal >= TMS320C64X_REG_B0) && (op->RegVal <= TMS320C64X_REG_B31)) op->RegVal = (op->RegVal - TMS320C64X_REG_B0 + TMS320C64X_REG_A0); } break; default: Inst->flat_insn->detail->tms320c64x.funit.crosspath = -1; ret = MCDisassembler_Fail; break; } return ret; } static DecodeStatus DecodeNop(MCInst *Inst, unsigned Val, uint64_t Address, void *Decoder) { MCOperand_CreateImm0(Inst, Val + 1); return MCDisassembler_Success; } #define GET_INSTRINFO_ENUM #include "TMS320C64xGenInstrInfo.inc" bool TMS320C64x_getInstruction(csh ud, const uint8_t *code, size_t code_len, MCInst *MI, uint16_t *size, uint64_t address, void *info) { uint32_t insn; DecodeStatus result; if(code_len < 4) { *size = 0; return MCDisassembler_Fail; } if(MI->flat_insn->detail) memset(MI->flat_insn->detail, 0, offsetof(cs_detail, tms320c64x)+sizeof(cs_tms320c64x)); insn = (code[3] << 0) | (code[2] << 8) | (code[1] << 16) | (code[0] << 24); result = decodeInstruction_4(DecoderTable32, MI, insn, address, info, 0); if(result == MCDisassembler_Success) { *size = 4; return true; } MCInst_clear(MI); *size = 0; return false; } void TMS320C64x_init(MCRegisterInfo *MRI) { MCRegisterInfo_InitMCRegisterInfo(MRI, TMS320C64xRegDesc, 90, 0, 0, TMS320C64xMCRegisterClasses, 7, 0, 0, TMS320C64xRegDiffLists, 0, TMS320C64xSubRegIdxLists, 1, 0); } #endif
the_stack_data/92327577.c
// This is a test code for the new token support. // new test codes: // 1) Toky() macro to write code // 2) Token pasting operator ## // 3) Use equivalentce of generated binary as a test for generate source code // that is equivalent to the input file up to the use of new lines and other // white space. // 4) Use multiple variable names in the same variable declaration. void foobar() { int a,b,c; }
the_stack_data/51701229.c
#include <stdio.h> // The Body Mass Index (BMI) is defined as ratio of the weight of a // person (in kilograms) to the square of the height (in meters). // Write a program that recieves weight and height, calculates the BMI, // and reports the BMI category int main(void) { float weight, height, bmi; printf("Please enter your weight (in kg): "); scanf("%f", &weight); printf("Please enter your height (in meters): "); scanf("%f", &height); bmi = weight / (height * height); printf("BMI category: "); if (bmi < 15) printf("Starvation"); else if ( bmi > 15 && bmi <= 17.5 ) printf("Anorexic"); else if ( bmi > 17.5 && bmi <= 18.5 ) printf("Underweight"); else if ( bmi > 18.5 && bmi <= 24.9 ) printf("Ideal"); else if ( bmi > 24.9 && bmi <= 25.9 ) printf("Overweight"); else if ( bmi > 25.9 && bmi <= 39.9 ) printf("Obese"); else if ( bmi > 39.9 ) printf("Morbidly Obese"); else printf("Invalid"); }
the_stack_data/90763383.c
#include<stdio.h> #include<math.h> #include<stdlib.h> double biomass(double fpar, double solar_day, double evap_fr, double light_use_ef) { double result, apar, conversion_coefs; /*fPAR in Bastiaassen and Ali = a (= 1.257) * NDVI + b (= -0.161); */ /*light use efficiency is variable for each crop! */ /* Cotton light_use_ef in Uzbekistan is 1.9 */ /* apar = (b+a*ndvi); */ conversion_coefs = 0.0864 * 10; apar = fpar * (0.48 * solar_day); result = apar * light_use_ef * evap_fr * conversion_coefs; return result; }
the_stack_data/73574435.c
/* Reentrant random function from POSIX.1c. Copyright (C) 1996-2015 Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by Ulrich Drepper <[email protected]>, 1996. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #include <stdlib.h> /* This algorithm is mentioned in the ISO C standard, here extended for 32 bits. */ int rand_r (unsigned int *seed) { unsigned int next = *seed; int result; next *= 1103515245; next += 12345; result = (unsigned int) (next / 65536) % 2048; next *= 1103515245; next += 12345; result <<= 10; result ^= (unsigned int) (next / 65536) % 1024; next *= 1103515245; next += 12345; result <<= 10; result ^= (unsigned int) (next / 65536) % 1024; *seed = next; return result; }
the_stack_data/102253.c
#include <stdio.h> int main(int argc, char *argv[]) { printf("hello,world!\n"); return 0; }
the_stack_data/162643515.c
#include <limits.h> #include <string.h> /* * Compute an unsigned long integer hash from a byte array. * * If 'bytes' is a NULL pointer, or 'len' is less than 1, the hash is zero. * * If 'len' is 1, then the hash is just the integer value of the first byte. * Otherwise, we read 'len' bytes from 'bytes', and for each byte we save the * leftmost bit of the hash, bitshift the hash one bit left, then add the value * of the new byte, less the value of the bit that was shifted off, multiplied * by the value of the preceding byte (if not the first byte). */ unsigned long hash_shimmy2_len(const char *bytes, const size_t len) { unsigned long result = 0; unsigned char shift = 0; unsigned int ch = 0; const size_t bits = (sizeof result) * CHAR_BIT - 1; if (len == 0) { return 0; } else if (len == 1) { return bytes[0]; } for (size_t i = 0; i < len; i++) { shift = result >> bits; result <<= 1; ch = bytes[i] - shift; if (i > 0) ch *= bytes[i - 1]; result += ch; } return result; } /* * Compute an unsigned long integer hash from a NUL-terminated byte array. * * As for hash_shimmy2_len(), except we consume bytes from 'bytes' until we * encounter a zero byte. */ unsigned long hash_shimmy2(const char *bytes) { if (!bytes) { return 0; } return hash_shimmy2_len(bytes, strlen(bytes)); }
the_stack_data/125515.c
// Write a program that will print your mailing address in the following form #include <stdio.h> void main() { printf("Name\n"); printf("Door No, Street\n"); printf("City, Pin code\n"); }
the_stack_data/37638075.c
//Funções fgetc e getc #include <stdio.h> int main() { char x[100]; int i = 0; while ((x[i] = fgetc(stdin)) != '\n') //OBTERA DADOS DA ENTRADA PADRAO { ++i; } x[i] = '\0'; //x[++i] = '\0'; printf("%s", x); return 0; }
the_stack_data/221765.c
#include <stdio.h> int main(void) { int scores[3]; scores[0] = 72; scores[1] = 73; scores[2] = 33; printf("Average: %i\n", (scores[0] + scores[1] + scores[2]) /3); }
the_stack_data/126702350.c
/* Program to demonstrate 'extern' storage class: Highlight: Variable delcared with 'extern' keyword is defined at one location(globally/other file) and used in other location. a. storage area: Data segment b. default value: zero (0) c. scope: global/across files d. lifetime: till program ends */ #include <stdio.h> extern int var = 2; int main(void) { //extern int var=2; extern int var; printf("%d", var); //no error on usage of 'var' as extern variable 'var' has been assigned a value of 2 outisde. return 0; }
the_stack_data/187642292.c
/* * malloc/free/realloc memory management routines. * * This is a very simple, but fast storage allocator. It allocates blocks * of a small number of different sizes, and keeps free lists of each size. * Blocks that don't exactly fit are passed up to the next larger size. * In this implementation, the available sizes are (2^(i+4))-8 bytes long. * This is designed for use in a single-threaded virtual memory environment. * * This version is derived from: malloc.c (Caltech) 2/21/82, Chris Kingsley, * kingsley@cit-20, and a similar version of Larry Wall, used by perl. * * Rewritten by Eric Wassenaar, Nikhef-H, <[email protected]> * * Not only varies the vendor-supplied implementation of this package greatly * for different platforms, there are also many subtle semantic differences, * especially for anomalous conditions. This makes it risky to use a separate * package, in case other library routines depend on those special features. * Nevertheless, we assume that external routines under normal circumstances * just need the basic malloc/free/realloc functionality. * * To avoid possible conflicts, included in this package are some auxiliary * functions: memalign, calloc/cfree, valloc/vfree, because they are closely * related to and built upon the basic functions. * * Not supported are special functions: mallopt/mallinfo/mstats, and those * which are found on specific platforms only: mallocblksize/recalloc (sgi), * malloc_debug/malloc_verify (sun), malloc_size/malloc_error (next). * * The simplicity of this package imposes the following limitations: * - Memory once allocated is never returned to the system, but is put on * free lists for subsequent use. The process size grows monotonously. * - Allocating zero-size data blocks is not an error. * - In case realloc fails, the old block may no longer be allocated. * - The strictest alignment for memalign is the page size. */ #ifndef lint static char Version[] = "@(#)malloc.c [email protected] (Eric Wassenaar) 970519"; #endif #if defined(apollo) && defined(lint) #define __attribute(x) #endif #include <stdio.h> #include <errno.h> #include <sys/types.h> #include <sys/param.h> #ifdef lint #define EXTERN #else #define EXTERN extern #endif EXTERN int errno; /* * Portability definitions. These are probably too primitive, but the * semantics on various platforms are too chaotic to do it correctly. */ #if defined(SYSV) || defined(SVR4) #define SYSV_MALLOC #define SYSV_MEMSET #endif #ifdef SYSV_MALLOC typedef void ptr_t; typedef u_int siz_t; typedef void free_t; #define free_return(x) return #else typedef char ptr_t; typedef u_int siz_t; typedef int free_t; #define free_return(x) return(x) #endif #ifdef SYSV_MEMSET #define bzero(a,n) (void) memset(a,'\0',n) #define bcopy(a,b,n) (void) memcpy(b,a,n) #endif /* * The page size used to request blocks of system memory. */ #if defined(sgi) && !defined(_PAGESZ) #define _PAGESZ 16384 /* kludge for sgi && IRIX64 */ #endif #ifndef PAGESIZE #ifdef NBPG #ifdef CLSIZE #define PAGESIZE (NBPG*CLSIZE) /* sun && SunOS, ultrix */ #else #define PAGESIZE NBPG /* hpux */ #endif #else /*not NBPG*/ #ifdef NBPC #define PAGESIZE NBPC /* sgi */ #else #define PAGESIZE 4096 /* some reasonable default */ #endif #endif /*NBPG*/ #endif static int pagesize = 0; /* page size after initialization */ /* * The overhead on a block is 8 bytes on traditional 32-bit platforms. * When free, this space contains a pointer to the next free block, * and the lower 3 bits of this pointer must be zero. * When in use, the first field is set to OVMAGIC with the lower 3 bits * nonzero, and the second field is the hash bucket index. * The overhead information precedes the data area returned to the user. * When special alignment is required, a fragment is created within the * data block, preceded by a special fragment header containing a magic * number FRMAGIC and the align offset from the overlapping block. */ typedef union overhead { struct { union overhead *ovfree_next; /* next chunk on free list */ } ov_free; struct { int ovused_magic; /* magic number */ int ovused_index; /* bucket index */ } ov_used; struct { int ovfrag_fmagic; /* fragment magic number */ int ovfrag_offset; /* fragment align offset */ } ov_frag; /* align on double word boundary */ double ov_align; } OVHDR; #define ov_next ov_free.ovfree_next /* next on free list */ #define ov_magic ov_used.ovused_magic /* magic number */ #define ov_index ov_used.ovused_index /* bucket index */ #define ov_fmagic ov_frag.ovfrag_fmagic /* fragment magic number */ #define ov_offset ov_frag.ovfrag_offset /* fragment align offset */ #define OVMAGIC 0xef /* overhead magic number */ #define FRMAGIC 0x5555 /* fragment magic number */ #define OVHDRSZ sizeof(OVHDR) /* size of overhead data */ /* * freelist[i] is the pointer to the next free chunk of size 2^(i+4). * The smallest allocatable chunk is 16 bytes, containing a user data * block of 8 bytes (assuming 8 bytes overhead on 32-bit platforms). */ #define MINCHUNK 4 /* minimum chunk size 2^(0+4) */ #define MAXCHUNK 30 /* maximum chunk size 2^(26+4) */ #define NBUCKETS 27 /* MAXCHUNK - MINCHUNK + 1 */ static OVHDR *freelist[NBUCKETS]; /* hash list of free chunks */ static int malloced[NBUCKETS]; /* number of allocated chunks */ #define chunk_size(i) (1 << ((i) + MINCHUNK)) #define data_size(i) (chunk_size(i) - OVHDRSZ) #define MINDATA ((1 << MINCHUNK) - OVHDRSZ) #define MAXDATA ((1 << MAXCHUNK) - OVHDRSZ) #define get_offset(a,b) ((unsigned long)(a) & ((b) - 1)) #define word_offset(a) get_offset(a, OVHDRSZ) #define page_offset(a) get_offset(a, PAGESIZE) #define aligned(a,b) (get_offset(a,b) == 0) #define word_aligned(a) aligned(a, OVHDRSZ) #define page_aligned(a) aligned(a, PAGESIZE) #define auto_aligned(a) aligned(a, a) #define valid_index(i) ((i) >= 0 && (i) < NBUCKETS) #define valid_offset(i) ((i) > OVHDRSZ && auto_aligned(i) && (i) <= PAGESIZE) /* * Definition of modules. */ #define PROTO(TYPES) () ptr_t *malloc PROTO((siz_t)); ptr_t *memalign PROTO((siz_t, siz_t)); free_t free PROTO((ptr_t *)); ptr_t *realloc PROTO((ptr_t *, siz_t)); ptr_t *calloc PROTO((siz_t, siz_t)); free_t cfree PROTO((ptr_t *)); ptr_t *valloc PROTO((siz_t)); free_t vfree PROTO((ptr_t *)); extern ptr_t *sbrk PROTO((int)); /* ** MALLOC -- Allocate more memory ** ------------------------------ */ ptr_t * malloc(size) siz_t size; /* amount of memory to allocate */ { register OVHDR *op; /* chunk pointer */ register int bucket; /* hash bucket index */ register int bucketsize; /* size of hash bucket chunk */ register int memsize; /* amount of memory to expand */ /* * First time malloc is called, do some sanity checks, setup page size, * and align the break pointer so all chunk data will be page aligned. * Note. Cannot issue debugging print statements during initialization. */ if (pagesize == 0) { if (page_offset(PAGESIZE) || word_offset(OVHDRSZ)) { errno = EINVAL; return(NULL); } op = (OVHDR *)sbrk(0); if (op == NULL || (char *)op == (char *)-1) { errno = ENOMEM; return(NULL); } memsize = page_offset(op); if (memsize > 0) { memsize = PAGESIZE - memsize; op = (OVHDR *)sbrk(memsize); if (op == NULL || (char *)op == (char *)-1) { errno = ENOMEM; return(NULL); } } /* initialization complete */ pagesize = PAGESIZE; } /* * Convert amount of memory requested into closest chunk size * stored in hash buckets which satisfies request. */ bucket = 0; bucketsize = chunk_size(bucket); while (bucketsize < OVHDRSZ || size > (bucketsize - OVHDRSZ)) { bucket++; bucketsize <<= 1; if (bucket >= NBUCKETS) { errno = EINVAL; return(NULL); } } /* * If nothing in hash bucket right now, request more memory from the system. * Add new memory allocated to that on free list for this hash bucket. * System memory is expanded by increments of whole pages. For small chunk * sizes, the page is subdivided into a list of free chunks. */ if (freelist[bucket] == NULL) { memsize = (bucketsize < PAGESIZE) ? PAGESIZE : bucketsize; op = (OVHDR *)sbrk(memsize); if (op == NULL || (char *)op == (char *)-1) { errno = ENOMEM; return(NULL); } freelist[bucket] = op; while (memsize > bucketsize) { memsize -= bucketsize; op->ov_next = (OVHDR *)((char *)op + bucketsize); op = op->ov_next; } op->ov_next = NULL; } /* * Memory is available. */ /* remove from linked list */ op = freelist[bucket]; freelist[bucket] = op->ov_next; malloced[bucket]++; /* mark this chunk in use */ op->ov_magic = OVMAGIC; op->ov_index = bucket; /* return pointer to user data block */ return((ptr_t *)((char *)op + OVHDRSZ)); } /* ** MEMALIGN -- Allocate memory with alignment constraints ** ------------------------------------------------------ */ ptr_t * memalign(align, size) siz_t align; /* required memory alignment */ siz_t size; /* amount of memory to allocate */ { register OVHDR *op; /* chunk pointer */ register ptr_t *newbuf; /* new block of user data */ register int offset = 0; /* fragment offset for alignment */ /* * The alignment must be a power of two, and no bigger than the page size. */ if ((align == 0) || !auto_aligned(align) || (align > PAGESIZE)) { errno = EINVAL; return(NULL); } /* * For ordinary small alignment sizes, we can use the plain malloc. */ if (align > OVHDRSZ) offset = align - OVHDRSZ; newbuf = malloc(size + offset); if (newbuf == NULL) return(NULL); /* * Otherwise we have to create a more strictly aligned fragment. */ if (offset > 0) { /* locate the proper alignment boundary within the block */ newbuf = (ptr_t *)((char *)newbuf + offset); /* mark this block as a special fragment */ op = (OVHDR *)((char *)newbuf - OVHDRSZ); op->ov_fmagic = FRMAGIC; op->ov_offset = OVHDRSZ + offset; } return(newbuf); } /* ** DEALLOC -- Put unneeded memory on the free list ** ----------------------------------------------- */ static int dealloc(oldbuf) ptr_t *oldbuf; /* old block of user data */ { register OVHDR *op; /* chunk pointer */ register int bucket; /* hash bucket index */ register int offset; /* fragment offset for alignment */ /* if no old block, or if not yet initialized */ if (oldbuf == NULL || pagesize == 0) { errno = EINVAL; return(0); } /* avoid bogus block addresses */ if (!word_aligned(oldbuf)) { errno = EINVAL; return(0); } /* move to the header for this chunk */ op = (OVHDR *)((char *)oldbuf - OVHDRSZ); /* adjust in case this is an aligned fragment */ if ((op->ov_fmagic == FRMAGIC) && valid_offset(op->ov_offset)) { offset = op->ov_offset - OVHDRSZ; op = (OVHDR *)((char *)op - offset); } /* check whether this chunk was really allocated */ if ((op->ov_magic != OVMAGIC) || !valid_index(op->ov_index)) { errno = EINVAL; return(0); } /* put back on the free list for this bucket */ bucket = op->ov_index; op->ov_next = freelist[bucket]; freelist[bucket] = op; malloced[bucket]--; return(1); } /* ** FREE -- Put unneeded memory on the free list ** -------------------------------------------- ** ** In this implementation, unneeded memory is never returned to ** the system, but is put on a free memory hash list instead. ** Subsequent malloc requests will first examine the free lists ** to see whether a request can be satisfied. ** As a consequence of this strategy, the process size will grow ** monotonously, up to the largest amount needed at any moment. ** ** On some platforms, this routine does not return a status code. ** The status will be stored in a global variable ``free_status'' ** which can be examined if desired. */ int free_status = 0; /* return code of last free */ free_t free(oldbuf) ptr_t *oldbuf; /* old block of user data */ { free_status = dealloc(oldbuf); free_return(free_status); } /* ** FINDBUCKET -- Locate a chunk of memory on the free list ** ------------------------------------------------------- ** ** When a program attempts "storage compaction" as mentioned in the ** old malloc man page, it realloc's an already freed block. Usually ** this is the last block it freed; occasionally it might be farther ** back. We have to search all the free lists for the block in order ** to determine its bucket: first we make one pass thru the lists ** checking only the first block in each; if that fails we search ** the entire lists for a match. If still not found it is an error. */ static int findbucket(oldop) OVHDR *oldop; /* old chunk to search for */ { register OVHDR *op; /* chunk pointer */ register int bucket; /* hash bucket index */ for (bucket = 0; bucket < NBUCKETS; bucket++) { if (freelist[bucket] == oldop) return(bucket); } for (bucket = 0; bucket < NBUCKETS; bucket++) { for (op = freelist[bucket]; op != NULL; op = op->ov_next) { if (op == oldop) return(bucket); } } /* not found */ return(-1); } /* ** REALLOC -- Rellocate already allocated memory ** --------------------------------------------- */ ptr_t * realloc(oldbuf, size) ptr_t *oldbuf; /* old block of user data */ siz_t size; /* amount of memory to allocate */ { register OVHDR *op; /* chunk pointer */ register ptr_t *newbuf; /* new block of user data */ register int bucket; /* hash bucket index */ register int offset = 0; /* fragment offset for alignment */ siz_t minsize, maxsize; /* size limits for this bucket */ int allocated = 0; /* set if old chunk was allocated */ /* * Do plain malloc if no old block, or if not yet initialized. * Otherwise, get the header, and check for special conditions. */ if (oldbuf == NULL || pagesize == 0) { newbuf = malloc(size); return(newbuf); } /* avoid bogus block addresses */ if (!word_aligned(oldbuf)) { errno = EINVAL; return(NULL); } /* move to the header for this chunk */ op = (OVHDR *)((char *)oldbuf - OVHDRSZ); /* adjust in case this is an aligned fragment */ if ((op->ov_fmagic == FRMAGIC) && valid_offset(op->ov_offset)) { offset = op->ov_offset - OVHDRSZ; op = (OVHDR *)((char *)op - offset); } /* * Check whether this chunk is allocated at this moment. * If not, try to locate it on the free list hash buckets. */ if ((op->ov_magic == OVMAGIC) && valid_index(op->ov_index)) { allocated = 1; bucket = op->ov_index; } else { bucket = findbucket(op); if (bucket < 0) { errno = EINVAL; return(NULL); } } /* * If the new size block fits into the same already allocated chunk, * we can just use it again, avoiding a malloc and a bcopy. Otherwise, * we can safely put it on the free list (the contents are preserved). */ /* make sure the alignment offset is consistent with the bucket */ if ((offset > 0) && (bucket == 0 || offset > data_size(bucket-1))) { errno = EINVAL; return(NULL); } /* maximum data block size of this chunk */ maxsize = data_size(bucket) - offset; if (allocated) { /* maximum data block size in the preceding hash bucket */ minsize = (bucket > 0) ? data_size(bucket-1) - offset : 0; /* re-use same block if within bounds */ if (size <= maxsize && size > minsize) return(oldbuf); /* no longer useable */ (void) dealloc(oldbuf); } /* * A new chunk must be allocated, possibly with alignment restrictions. */ newbuf = malloc(size + offset); if (newbuf == NULL) return(NULL); if (offset > 0) { /* locate the proper alignment boundary within the block */ newbuf = (ptr_t *)((char *)newbuf + offset); /* mark this block as a special fragment */ op = (OVHDR *)((char *)newbuf - OVHDRSZ); op->ov_fmagic = FRMAGIC; op->ov_offset = OVHDRSZ + offset; } /* * Copy the contents of the old user data block into the new block. * In case we shrink, only copy the requested amount of user data. * If we expand, copy the maximum possible amount from the old block. * Note that the exact amount of valid old user data is not known. */ if (oldbuf != newbuf) bcopy(oldbuf, newbuf, (size < maxsize) ? size : maxsize); return(newbuf); } /* ** CALLOC -- Allocate memory for number of elements, and clear it ** -------------------------------------------------------------- ** ** This is a wrapper for malloc to request memory for a number ** of consecutive elements of certain length. ** As a side effect, the entire memory block obtained is cleared. */ ptr_t * calloc(count, length) siz_t count; /* number of elements */ siz_t length; /* size per element */ { register ptr_t *newbuf; /* new block of user data */ register siz_t size; /* amount of memory to allocate */ size = count * length; newbuf = malloc(size); if (newbuf == NULL) return(NULL); bzero(newbuf, size); return(newbuf); } /* ** CFREE -- Put unneeded memory on the free list ** --------------------------------------------- */ free_t cfree(oldbuf) ptr_t *oldbuf; /* old block of user data */ { free_status = dealloc(oldbuf); free_return(free_status); } /* ** VALLOC -- Allocate memory on a page boundary ** -------------------------------------------- ** ** This is a wrapper for memalign to request memory that is ** aligned on a page boundary. In this implementation, this ** is the strictest alignment possible. */ ptr_t * valloc(size) siz_t size; /* amount of memory to allocate */ { register ptr_t *newbuf; /* new block of user data */ siz_t align = PAGESIZE; /* alignment on page boundary */ newbuf = memalign(align, size); return(newbuf); } /* ** VFREE -- Put unneeded memory on the free list ** --------------------------------------------- */ free_t vfree(oldbuf) ptr_t *oldbuf; /* old block of user data */ { free_status = dealloc(oldbuf); free_return(free_status); }
the_stack_data/9514101.c
/* Arquivo: ex8.2.c Autor: Felipe de Andrade Nascimento */ #include <stdio.h> #include <stdlib.h> void trocar( int *, int * ); int main() { int n1; int n2; // entrada do n1 printf("n1: "); scanf("%d", &n1); // entrada do n2 printf("n2: "); scanf("%d", &n2); //saída printf("\n\nAntes:\n"); printf(" n1: %d\n", n1); printf(" n2: %d\n", n2); trocar( &n1, &n2 ); printf("Depois:\n"); printf(" n1: %d\n", n1); printf(" n2: %d", n2); return 0; } void trocar( int *n1, int *n2 ) { int t; t = *n2; *n2 = *n1; *n1 = t; }
the_stack_data/92325824.c
// C program to implement concurrent merge sort #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include<time.h> void insertionSort(int arr[], int n); void merge(int a[], int l1, int h1, int h2); void merge2(int arr[], int l, int m, int r) { int i, j, k; int n1 = m - l + 1; int n2 = r - m; /* create temp arrays */ int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) R[j] = arr[m + 1+ j]; /* Merge the temp arrays back into arr[l..r]*/ i = 0; // Initial index of first subarray j = 0; // Initial index of second subarray k = l; // Initial index of merged subarray while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } void mergeSort2(int arr[], int l, int r) { if (l < r) { // Same as (l+r)/2, but avoids overflow for // large l and h int m = l+(r-l)/2; // Sort first and second halves mergeSort2(arr, l, m); mergeSort2(arr, m+1, r); merge2(arr, l, m, r); } } void mergeSort(int a[], int l, int h) { int i, len=(h-l+1); // Using insertion sort for small sized array if (len<=5) { mergeSort2(a, l ,h); return; } pid_t lpid,rpid; lpid = fork(); if (lpid<0) { // Lchild proc not created perror("Left Child Proc. not created\n"); _exit(-1); } else if (lpid==0) { mergeSort(a,l,l+len/2-1); _exit(0); } else { rpid = fork(); if (rpid<0) { // Rchild proc not created perror("Right Child Proc. not created\n"); _exit(-1); } else if(rpid==0) { mergeSort(a,l+len/2,h); _exit(0); } } int status; // Wait for child processes to finish waitpid(lpid, &status, 0); waitpid(rpid, &status, 0); // Merge the sorted subarrays merge(a, l, l+len/2-1, h); } // Method to merge sorted subarrays void merge(int a[], int l1, int h1, int h2) { // We can directly copy the sorted elements // in the final array, no need for a temporary // sorted array. int count=h2-l1+1; int sorted[count]; int i=l1, k=h1+1, m=0; while (i<=h1 && k<=h2) { if (a[i]<a[k]) sorted[m++]=a[i++]; else if (a[k]<a[i]) sorted[m++]=a[k++]; else if (a[i]==a[k]) { sorted[m++]=a[i++]; sorted[m++]=a[k++]; } } while (i<=h1) sorted[m++]=a[i++]; while (k<=h2) sorted[m++]=a[k++]; int arr_count = l1; for (i=0; i<count; i++,l1++) a[l1] = sorted[i]; } // To check if array is actually sorted or not void isSorted(int arr[], int len) { if (len==1) { printf("Sorting Done Successfully\n"); return; } int i; for (i=1; i<len; i++) { if (arr[i]<arr[i-1]) { printf("Sorting Not Done\n"); return; } } printf("Sorting Done Successfully\n"); return; } // To fill randome values in array for testing // purpise void fillData(int a[], int len) { // Create random arrays int i; for (i=0; i<len; i++) a[i] = rand(); return; } // Driver code int main() { int shmid; key_t key = IPC_PRIVATE; int *shm_array; // Using fixed size array. We can uncomment // below lines to take size from user int length = 1000; /* printf("Enter No of elements of Array:"); scanf("%d",&length); */ // Calculate segment length size_t SHM_SIZE = sizeof(int)*length; // Create the segment. if ((shmid = shmget(key, SHM_SIZE, IPC_CREAT | 0666)) < 0) { perror("shmget"); _exit(1); } // Now we attach the segment to our data space. if ((shm_array = shmat(shmid, NULL, 0)) == (int *) -1) { perror("shmat"); _exit(1); } // Create a random array of given length double total_time; clock_t start, end; start = clock(); //time count starts srand(time(NULL)); fillData(shm_array, length); // Sort the created array mergeSort(shm_array, 0, length-1); // Check if array is sorted or not isSorted(shm_array, length); if (shmdt(shm_array) == -1) { perror("shmdt"); _exit(1); } /* Delete the shared memory segment. */ if (shmctl(shmid, IPC_RMID, NULL) == -1) { perror("shmctl"); _exit(1); } end = clock(); total_time = ((double) (end - start)) / _SC_CLK_TCK; printf("\nTime taken: %f", total_time); return 0; }
the_stack_data/995325.c
/** ****************************************************************************** * @file stm32l1xx_ll_rtc.c * @author MCD Application Team * @version 21-April-2017 * @date V1.3.0 * @brief RTC LL module driver. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2017 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ #if defined(USE_FULL_LL_DRIVER) /* Includes ------------------------------------------------------------------*/ #include "stm32l1xx_ll_rtc.h" #include "stm32l1xx_ll_cortex.h" #ifdef USE_FULL_ASSERT #include "stm32_assert.h" #else #define assert_param(expr) ((void)0U) #endif /** @addtogroup STM32L1xx_LL_Driver * @{ */ #if defined(RTC) /** @addtogroup RTC_LL * @{ */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /** @addtogroup RTC_LL_Private_Constants * @{ */ /* Default values used for prescaler */ #define RTC_ASYNCH_PRESC_DEFAULT 0x0000007FU #define RTC_SYNCH_PRESC_DEFAULT 0x000000FFU /* Values used for timeout */ #define RTC_INITMODE_TIMEOUT 1000U /* 1s when tick set to 1ms */ #define RTC_SYNCHRO_TIMEOUT 1000U /* 1s when tick set to 1ms */ /** * @} */ /* Private macros ------------------------------------------------------------*/ /** @addtogroup RTC_LL_Private_Macros * @{ */ #define IS_LL_RTC_HOURFORMAT(__VALUE__) (((__VALUE__) == LL_RTC_HOURFORMAT_24HOUR) \ || ((__VALUE__) == LL_RTC_HOURFORMAT_AMPM)) #define IS_LL_RTC_ASYNCH_PREDIV(__VALUE__) ((__VALUE__) <= 0x7FU) #define IS_LL_RTC_SYNCH_PREDIV(__VALUE__) ((__VALUE__) <= 0x7FFFU) #define IS_LL_RTC_FORMAT(__VALUE__) (((__VALUE__) == LL_RTC_FORMAT_BIN) \ || ((__VALUE__) == LL_RTC_FORMAT_BCD)) #define IS_LL_RTC_TIME_FORMAT(__VALUE__) (((__VALUE__) == LL_RTC_TIME_FORMAT_AM_OR_24) \ || ((__VALUE__) == LL_RTC_TIME_FORMAT_PM)) #define IS_LL_RTC_HOUR12(__HOUR__) (((__HOUR__) > 0U) && ((__HOUR__) <= 12U)) #define IS_LL_RTC_HOUR24(__HOUR__) ((__HOUR__) <= 23U) #define IS_LL_RTC_MINUTES(__MINUTES__) ((__MINUTES__) <= 59U) #define IS_LL_RTC_SECONDS(__SECONDS__) ((__SECONDS__) <= 59U) #define IS_LL_RTC_WEEKDAY(__VALUE__) (((__VALUE__) == LL_RTC_WEEKDAY_MONDAY) \ || ((__VALUE__) == LL_RTC_WEEKDAY_TUESDAY) \ || ((__VALUE__) == LL_RTC_WEEKDAY_WEDNESDAY) \ || ((__VALUE__) == LL_RTC_WEEKDAY_THURSDAY) \ || ((__VALUE__) == LL_RTC_WEEKDAY_FRIDAY) \ || ((__VALUE__) == LL_RTC_WEEKDAY_SATURDAY) \ || ((__VALUE__) == LL_RTC_WEEKDAY_SUNDAY)) #define IS_LL_RTC_DAY(__DAY__) (((__DAY__) >= 1U) && ((__DAY__) <= 31U)) #define IS_LL_RTC_MONTH(__VALUE__) (((__VALUE__) == LL_RTC_MONTH_JANUARY) \ || ((__VALUE__) == LL_RTC_MONTH_FEBRUARY) \ || ((__VALUE__) == LL_RTC_MONTH_MARCH) \ || ((__VALUE__) == LL_RTC_MONTH_APRIL) \ || ((__VALUE__) == LL_RTC_MONTH_MAY) \ || ((__VALUE__) == LL_RTC_MONTH_JUNE) \ || ((__VALUE__) == LL_RTC_MONTH_JULY) \ || ((__VALUE__) == LL_RTC_MONTH_AUGUST) \ || ((__VALUE__) == LL_RTC_MONTH_SEPTEMBER) \ || ((__VALUE__) == LL_RTC_MONTH_OCTOBER) \ || ((__VALUE__) == LL_RTC_MONTH_NOVEMBER) \ || ((__VALUE__) == LL_RTC_MONTH_DECEMBER)) #define IS_LL_RTC_YEAR(__YEAR__) ((__YEAR__) <= 99U) #define IS_LL_RTC_ALMA_MASK(__VALUE__) (((__VALUE__) == LL_RTC_ALMA_MASK_NONE) \ || ((__VALUE__) == LL_RTC_ALMA_MASK_DATEWEEKDAY) \ || ((__VALUE__) == LL_RTC_ALMA_MASK_HOURS) \ || ((__VALUE__) == LL_RTC_ALMA_MASK_MINUTES) \ || ((__VALUE__) == LL_RTC_ALMA_MASK_SECONDS) \ || ((__VALUE__) == LL_RTC_ALMA_MASK_ALL)) #define IS_LL_RTC_ALMB_MASK(__VALUE__) (((__VALUE__) == LL_RTC_ALMB_MASK_NONE) \ || ((__VALUE__) == LL_RTC_ALMB_MASK_DATEWEEKDAY) \ || ((__VALUE__) == LL_RTC_ALMB_MASK_HOURS) \ || ((__VALUE__) == LL_RTC_ALMB_MASK_MINUTES) \ || ((__VALUE__) == LL_RTC_ALMB_MASK_SECONDS) \ || ((__VALUE__) == LL_RTC_ALMB_MASK_ALL)) #define IS_LL_RTC_ALMA_DATE_WEEKDAY_SEL(__SEL__) (((__SEL__) == LL_RTC_ALMA_DATEWEEKDAYSEL_DATE) || \ ((__SEL__) == LL_RTC_ALMA_DATEWEEKDAYSEL_WEEKDAY)) #define IS_LL_RTC_ALMB_DATE_WEEKDAY_SEL(__SEL__) (((__SEL__) == LL_RTC_ALMB_DATEWEEKDAYSEL_DATE) || \ ((__SEL__) == LL_RTC_ALMB_DATEWEEKDAYSEL_WEEKDAY)) /** * @} */ /* Private function prototypes -----------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup RTC_LL_Exported_Functions * @{ */ /** @addtogroup RTC_LL_EF_Init * @{ */ /** * @brief De-Initializes the RTC registers to their default reset values. * @note This function doesn't reset the RTC Clock source and RTC Backup Data * registers. * @param RTCx RTC Instance * @retval An ErrorStatus enumeration value: * - SUCCESS: RTC registers are de-initialized * - ERROR: RTC registers are not de-initialized */ ErrorStatus LL_RTC_DeInit(RTC_TypeDef *RTCx) { ErrorStatus status = ERROR; /* Check the parameter */ assert_param(IS_RTC_ALL_INSTANCE(RTCx)); /* Disable the write protection for RTC registers */ LL_RTC_DisableWriteProtection(RTCx); /* Set Initialization mode */ if (LL_RTC_EnterInitMode(RTCx) != ERROR) { /* Reset TR, DR and CR registers */ LL_RTC_WriteReg(RTCx, TR, 0x00000000U); #if defined(RTC_WAKEUP_SUPPORT) LL_RTC_WriteReg(RTCx, WUTR, RTC_WUTR_WUT); #endif /* RTC_WAKEUP_SUPPORT */ LL_RTC_WriteReg(RTCx, DR , (RTC_DR_WDU_0 | RTC_DR_MU_0 | RTC_DR_DU_0)); /* Reset All CR bits except CR[2:0] */ #if defined(RTC_WAKEUP_SUPPORT) LL_RTC_WriteReg(RTCx, CR, (LL_RTC_ReadReg(RTCx, CR) & RTC_CR_WUCKSEL)); #else LL_RTC_WriteReg(RTCx, CR, 0x00000000U); #endif /* RTC_WAKEUP_SUPPORT */ LL_RTC_WriteReg(RTCx, PRER, (RTC_PRER_PREDIV_A | RTC_SYNCH_PRESC_DEFAULT)); LL_RTC_WriteReg(RTCx, ALRMAR, 0x00000000U); LL_RTC_WriteReg(RTCx, ALRMBR, 0x00000000U); #if defined(RTC_SHIFTR_ADD1S) LL_RTC_WriteReg(RTCx, SHIFTR, 0x00000000U); #endif /* RTC_SHIFTR_ADD1S */ #if defined(RTC_SMOOTHCALIB_SUPPORT) LL_RTC_WriteReg(RTCx, CALR, 0x00000000U); #endif /* RTC_SMOOTHCALIB_SUPPORT */ #if defined(RTC_SUBSECOND_SUPPORT) LL_RTC_WriteReg(RTCx, ALRMASSR, 0x00000000U); LL_RTC_WriteReg(RTCx, ALRMBSSR, 0x00000000U); #endif /* RTC_SUBSECOND_SUPPORT */ /* Reset ISR register and exit initialization mode */ LL_RTC_WriteReg(RTCx, ISR, 0x00000000U); /* Reset Tamper and alternate functions configuration register */ LL_RTC_WriteReg(RTCx, TAFCR, 0x00000000U); /* Wait till the RTC RSF flag is set */ status = LL_RTC_WaitForSynchro(RTCx); } /* Enable the write protection for RTC registers */ LL_RTC_EnableWriteProtection(RTCx); return status; } /** * @brief Initializes the RTC registers according to the specified parameters * in RTC_InitStruct. * @param RTCx RTC Instance * @param RTC_InitStruct pointer to a @ref LL_RTC_InitTypeDef structure that contains * the configuration information for the RTC peripheral. * @note The RTC Prescaler register is write protected and can be written in * initialization mode only. * @retval An ErrorStatus enumeration value: * - SUCCESS: RTC registers are initialized * - ERROR: RTC registers are not initialized */ ErrorStatus LL_RTC_Init(RTC_TypeDef *RTCx, LL_RTC_InitTypeDef *RTC_InitStruct) { ErrorStatus status = ERROR; /* Check the parameters */ assert_param(IS_RTC_ALL_INSTANCE(RTCx)); assert_param(IS_LL_RTC_HOURFORMAT(RTC_InitStruct->HourFormat)); assert_param(IS_LL_RTC_ASYNCH_PREDIV(RTC_InitStruct->AsynchPrescaler)); assert_param(IS_LL_RTC_SYNCH_PREDIV(RTC_InitStruct->SynchPrescaler)); /* Disable the write protection for RTC registers */ LL_RTC_DisableWriteProtection(RTCx); /* Set Initialization mode */ if (LL_RTC_EnterInitMode(RTCx) != ERROR) { /* Set Hour Format */ LL_RTC_SetHourFormat(RTCx, RTC_InitStruct->HourFormat); /* Configure Synchronous and Asynchronous prescaler factor */ LL_RTC_SetSynchPrescaler(RTCx, RTC_InitStruct->SynchPrescaler); LL_RTC_SetAsynchPrescaler(RTCx, RTC_InitStruct->AsynchPrescaler); /* Exit Initialization mode */ LL_RTC_DisableInitMode(RTCx); status = SUCCESS; } /* Enable the write protection for RTC registers */ LL_RTC_EnableWriteProtection(RTCx); return status; } /** * @brief Set each @ref LL_RTC_InitTypeDef field to default value. * @param RTC_InitStruct pointer to a @ref LL_RTC_InitTypeDef structure which will be initialized. * @retval None */ void LL_RTC_StructInit(LL_RTC_InitTypeDef *RTC_InitStruct) { /* Set RTC_InitStruct fields to default values */ RTC_InitStruct->HourFormat = LL_RTC_HOURFORMAT_24HOUR; RTC_InitStruct->AsynchPrescaler = RTC_ASYNCH_PRESC_DEFAULT; RTC_InitStruct->SynchPrescaler = RTC_SYNCH_PRESC_DEFAULT; } /** * @brief Set the RTC current time. * @param RTCx RTC Instance * @param RTC_Format This parameter can be one of the following values: * @arg @ref LL_RTC_FORMAT_BIN * @arg @ref LL_RTC_FORMAT_BCD * @param RTC_TimeStruct pointer to a RTC_TimeTypeDef structure that contains * the time configuration information for the RTC. * @retval An ErrorStatus enumeration value: * - SUCCESS: RTC Time register is configured * - ERROR: RTC Time register is not configured */ ErrorStatus LL_RTC_TIME_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, LL_RTC_TimeTypeDef *RTC_TimeStruct) { ErrorStatus status = ERROR; /* Check the parameters */ assert_param(IS_RTC_ALL_INSTANCE(RTCx)); assert_param(IS_LL_RTC_FORMAT(RTC_Format)); if (RTC_Format == LL_RTC_FORMAT_BIN) { if (LL_RTC_GetHourFormat(RTCx) != LL_RTC_HOURFORMAT_24HOUR) { assert_param(IS_LL_RTC_HOUR12(RTC_TimeStruct->Hours)); assert_param(IS_LL_RTC_TIME_FORMAT(RTC_TimeStruct->TimeFormat)); } else { RTC_TimeStruct->TimeFormat = 0x00U; assert_param(IS_LL_RTC_HOUR24(RTC_TimeStruct->Hours)); } assert_param(IS_LL_RTC_MINUTES(RTC_TimeStruct->Minutes)); assert_param(IS_LL_RTC_SECONDS(RTC_TimeStruct->Seconds)); } else { if (LL_RTC_GetHourFormat(RTCx) != LL_RTC_HOURFORMAT_24HOUR) { assert_param(IS_LL_RTC_HOUR12(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Hours))); assert_param(IS_LL_RTC_TIME_FORMAT(RTC_TimeStruct->TimeFormat)); } else { RTC_TimeStruct->TimeFormat = 0x00U; assert_param(IS_LL_RTC_HOUR24(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Hours))); } assert_param(IS_LL_RTC_MINUTES(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Minutes))); assert_param(IS_LL_RTC_SECONDS(__LL_RTC_CONVERT_BCD2BIN(RTC_TimeStruct->Seconds))); } /* Disable the write protection for RTC registers */ LL_RTC_DisableWriteProtection(RTCx); /* Set Initialization mode */ if (LL_RTC_EnterInitMode(RTCx) != ERROR) { /* Check the input parameters format */ if (RTC_Format != LL_RTC_FORMAT_BIN) { LL_RTC_TIME_Config(RTCx, RTC_TimeStruct->TimeFormat, RTC_TimeStruct->Hours, RTC_TimeStruct->Minutes, RTC_TimeStruct->Seconds); } else { LL_RTC_TIME_Config(RTCx, RTC_TimeStruct->TimeFormat, __LL_RTC_CONVERT_BIN2BCD(RTC_TimeStruct->Hours), __LL_RTC_CONVERT_BIN2BCD(RTC_TimeStruct->Minutes), __LL_RTC_CONVERT_BIN2BCD(RTC_TimeStruct->Seconds)); } /* Exit Initialization mode */ LL_RTC_DisableInitMode(RTC); #if defined(RTC_CR_BYPSHAD) /* If RTC_CR_BYPSHAD bit = 0, wait for synchro else this check is not needed */ if (LL_RTC_IsShadowRegBypassEnabled(RTCx) == 0U) { status = LL_RTC_WaitForSynchro(RTCx); } else { status = SUCCESS; } #else status = SUCCESS; #endif /* RTC_CR_BYPSHAD */ } /* Enable the write protection for RTC registers */ LL_RTC_EnableWriteProtection(RTCx); return status; } /** * @brief Set each @ref LL_RTC_TimeTypeDef field to default value (Time = 00h:00min:00sec). * @param RTC_TimeStruct pointer to a @ref LL_RTC_TimeTypeDef structure which will be initialized. * @retval None */ void LL_RTC_TIME_StructInit(LL_RTC_TimeTypeDef *RTC_TimeStruct) { /* Time = 00h:00min:00sec */ RTC_TimeStruct->TimeFormat = LL_RTC_TIME_FORMAT_AM_OR_24; RTC_TimeStruct->Hours = 0U; RTC_TimeStruct->Minutes = 0U; RTC_TimeStruct->Seconds = 0U; } /** * @brief Set the RTC current date. * @param RTCx RTC Instance * @param RTC_Format This parameter can be one of the following values: * @arg @ref LL_RTC_FORMAT_BIN * @arg @ref LL_RTC_FORMAT_BCD * @param RTC_DateStruct: pointer to a RTC_DateTypeDef structure that contains * the date configuration information for the RTC. * @retval An ErrorStatus enumeration value: * - SUCCESS: RTC Day register is configured * - ERROR: RTC Day register is not configured */ ErrorStatus LL_RTC_DATE_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, LL_RTC_DateTypeDef *RTC_DateStruct) { ErrorStatus status = ERROR; /* Check the parameters */ assert_param(IS_RTC_ALL_INSTANCE(RTCx)); assert_param(IS_LL_RTC_FORMAT(RTC_Format)); if ((RTC_Format == LL_RTC_FORMAT_BIN) && ((RTC_DateStruct->Month & 0x10U) == 0x10U)) { RTC_DateStruct->Month = (RTC_DateStruct->Month & (uint32_t)~(0x10U)) + 0x0AU; } if (RTC_Format == LL_RTC_FORMAT_BIN) { assert_param(IS_LL_RTC_YEAR(RTC_DateStruct->Year)); assert_param(IS_LL_RTC_MONTH(RTC_DateStruct->Month)); assert_param(IS_LL_RTC_DAY(RTC_DateStruct->Day)); } else { assert_param(IS_LL_RTC_YEAR(__LL_RTC_CONVERT_BCD2BIN(RTC_DateStruct->Year))); assert_param(IS_LL_RTC_MONTH(__LL_RTC_CONVERT_BCD2BIN(RTC_DateStruct->Month))); assert_param(IS_LL_RTC_DAY(__LL_RTC_CONVERT_BCD2BIN(RTC_DateStruct->Day))); } assert_param(IS_LL_RTC_WEEKDAY(RTC_DateStruct->WeekDay)); /* Disable the write protection for RTC registers */ LL_RTC_DisableWriteProtection(RTCx); /* Set Initialization mode */ if (LL_RTC_EnterInitMode(RTCx) != ERROR) { /* Check the input parameters format */ if (RTC_Format != LL_RTC_FORMAT_BIN) { LL_RTC_DATE_Config(RTCx, RTC_DateStruct->WeekDay, RTC_DateStruct->Day, RTC_DateStruct->Month, RTC_DateStruct->Year); } else { LL_RTC_DATE_Config(RTCx, RTC_DateStruct->WeekDay, __LL_RTC_CONVERT_BIN2BCD(RTC_DateStruct->Day), __LL_RTC_CONVERT_BIN2BCD(RTC_DateStruct->Month), __LL_RTC_CONVERT_BIN2BCD(RTC_DateStruct->Year)); } /* Exit Initialization mode */ LL_RTC_DisableInitMode(RTC); #if defined(RTC_CR_BYPSHAD) /* If RTC_CR_BYPSHAD bit = 0, wait for synchro else this check is not needed */ if (LL_RTC_IsShadowRegBypassEnabled(RTCx) == 0U) { status = LL_RTC_WaitForSynchro(RTCx); } else { status = SUCCESS; } #else status = SUCCESS; #endif /* RTC_CR_BYPSHAD */ } /* Enable the write protection for RTC registers */ LL_RTC_EnableWriteProtection(RTCx); return status; } /** * @brief Set each @ref LL_RTC_DateTypeDef field to default value (date = Monday, January 01 xx00) * @param RTC_DateStruct pointer to a @ref LL_RTC_DateTypeDef structure which will be initialized. * @retval None */ void LL_RTC_DATE_StructInit(LL_RTC_DateTypeDef *RTC_DateStruct) { /* Monday, January 01 xx00 */ RTC_DateStruct->WeekDay = LL_RTC_WEEKDAY_MONDAY; RTC_DateStruct->Day = 1U; RTC_DateStruct->Month = LL_RTC_MONTH_JANUARY; RTC_DateStruct->Year = 0U; } /** * @brief Set the RTC Alarm A. * @note The Alarm register can only be written when the corresponding Alarm * is disabled (Use @ref LL_RTC_ALMA_Disable function). * @param RTCx RTC Instance * @param RTC_Format This parameter can be one of the following values: * @arg @ref LL_RTC_FORMAT_BIN * @arg @ref LL_RTC_FORMAT_BCD * @param RTC_AlarmStruct pointer to a @ref LL_RTC_AlarmTypeDef structure that * contains the alarm configuration parameters. * @retval An ErrorStatus enumeration value: * - SUCCESS: ALARMA registers are configured * - ERROR: ALARMA registers are not configured */ ErrorStatus LL_RTC_ALMA_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, LL_RTC_AlarmTypeDef *RTC_AlarmStruct) { /* Check the parameters */ assert_param(IS_RTC_ALL_INSTANCE(RTCx)); assert_param(IS_LL_RTC_FORMAT(RTC_Format)); assert_param(IS_LL_RTC_ALMA_MASK(RTC_AlarmStruct->AlarmMask)); assert_param(IS_LL_RTC_ALMA_DATE_WEEKDAY_SEL(RTC_AlarmStruct->AlarmDateWeekDaySel)); if (RTC_Format == LL_RTC_FORMAT_BIN) { if (LL_RTC_GetHourFormat(RTCx) != LL_RTC_HOURFORMAT_24HOUR) { assert_param(IS_LL_RTC_HOUR12(RTC_AlarmStruct->AlarmTime.Hours)); assert_param(IS_LL_RTC_TIME_FORMAT(RTC_AlarmStruct->AlarmTime.TimeFormat)); } else { RTC_AlarmStruct->AlarmTime.TimeFormat = 0x00U; assert_param(IS_LL_RTC_HOUR24(RTC_AlarmStruct->AlarmTime.Hours)); } assert_param(IS_LL_RTC_MINUTES(RTC_AlarmStruct->AlarmTime.Minutes)); assert_param(IS_LL_RTC_SECONDS(RTC_AlarmStruct->AlarmTime.Seconds)); if (RTC_AlarmStruct->AlarmDateWeekDaySel == LL_RTC_ALMA_DATEWEEKDAYSEL_DATE) { assert_param(IS_LL_RTC_DAY(RTC_AlarmStruct->AlarmDateWeekDay)); } else { assert_param(IS_LL_RTC_WEEKDAY(RTC_AlarmStruct->AlarmDateWeekDay)); } } else { if (LL_RTC_GetHourFormat(RTCx) != LL_RTC_HOURFORMAT_24HOUR) { assert_param(IS_LL_RTC_HOUR12(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Hours))); assert_param(IS_LL_RTC_TIME_FORMAT(RTC_AlarmStruct->AlarmTime.TimeFormat)); } else { RTC_AlarmStruct->AlarmTime.TimeFormat = 0x00U; assert_param(IS_LL_RTC_HOUR24(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Hours))); } assert_param(IS_LL_RTC_MINUTES(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Minutes))); assert_param(IS_LL_RTC_SECONDS(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Seconds))); if (RTC_AlarmStruct->AlarmDateWeekDaySel == LL_RTC_ALMA_DATEWEEKDAYSEL_DATE) { assert_param(IS_LL_RTC_DAY(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmDateWeekDay))); } else { assert_param(IS_LL_RTC_WEEKDAY(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmDateWeekDay))); } } /* Disable the write protection for RTC registers */ LL_RTC_DisableWriteProtection(RTCx); /* Select weekday selection */ if (RTC_AlarmStruct->AlarmDateWeekDaySel == LL_RTC_ALMA_DATEWEEKDAYSEL_DATE) { /* Set the date for ALARM */ LL_RTC_ALMA_DisableWeekday(RTCx); if (RTC_Format != LL_RTC_FORMAT_BIN) { LL_RTC_ALMA_SetDay(RTCx, RTC_AlarmStruct->AlarmDateWeekDay); } else { LL_RTC_ALMA_SetDay(RTCx, __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmDateWeekDay)); } } else { /* Set the week day for ALARM */ LL_RTC_ALMA_EnableWeekday(RTCx); LL_RTC_ALMA_SetWeekDay(RTCx, RTC_AlarmStruct->AlarmDateWeekDay); } /* Configure the Alarm register */ if (RTC_Format != LL_RTC_FORMAT_BIN) { LL_RTC_ALMA_ConfigTime(RTCx, RTC_AlarmStruct->AlarmTime.TimeFormat, RTC_AlarmStruct->AlarmTime.Hours, RTC_AlarmStruct->AlarmTime.Minutes, RTC_AlarmStruct->AlarmTime.Seconds); } else { LL_RTC_ALMA_ConfigTime(RTCx, RTC_AlarmStruct->AlarmTime.TimeFormat, __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Hours), __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Minutes), __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Seconds)); } /* Set ALARM mask */ LL_RTC_ALMA_SetMask(RTCx, RTC_AlarmStruct->AlarmMask); /* Enable the write protection for RTC registers */ LL_RTC_EnableWriteProtection(RTCx); return SUCCESS; } /** * @brief Set the RTC Alarm B. * @note The Alarm register can only be written when the corresponding Alarm * is disabled (@ref LL_RTC_ALMB_Disable function). * @param RTCx RTC Instance * @param RTC_Format This parameter can be one of the following values: * @arg @ref LL_RTC_FORMAT_BIN * @arg @ref LL_RTC_FORMAT_BCD * @param RTC_AlarmStruct pointer to a @ref LL_RTC_AlarmTypeDef structure that * contains the alarm configuration parameters. * @retval An ErrorStatus enumeration value: * - SUCCESS: ALARMB registers are configured * - ERROR: ALARMB registers are not configured */ ErrorStatus LL_RTC_ALMB_Init(RTC_TypeDef *RTCx, uint32_t RTC_Format, LL_RTC_AlarmTypeDef *RTC_AlarmStruct) { /* Check the parameters */ assert_param(IS_RTC_ALL_INSTANCE(RTCx)); assert_param(IS_LL_RTC_FORMAT(RTC_Format)); assert_param(IS_LL_RTC_ALMB_MASK(RTC_AlarmStruct->AlarmMask)); assert_param(IS_LL_RTC_ALMB_DATE_WEEKDAY_SEL(RTC_AlarmStruct->AlarmDateWeekDaySel)); if (RTC_Format == LL_RTC_FORMAT_BIN) { if (LL_RTC_GetHourFormat(RTCx) != LL_RTC_HOURFORMAT_24HOUR) { assert_param(IS_LL_RTC_HOUR12(RTC_AlarmStruct->AlarmTime.Hours)); assert_param(IS_LL_RTC_TIME_FORMAT(RTC_AlarmStruct->AlarmTime.TimeFormat)); } else { RTC_AlarmStruct->AlarmTime.TimeFormat = 0x00U; assert_param(IS_LL_RTC_HOUR24(RTC_AlarmStruct->AlarmTime.Hours)); } assert_param(IS_LL_RTC_MINUTES(RTC_AlarmStruct->AlarmTime.Minutes)); assert_param(IS_LL_RTC_SECONDS(RTC_AlarmStruct->AlarmTime.Seconds)); if (RTC_AlarmStruct->AlarmDateWeekDaySel == LL_RTC_ALMB_DATEWEEKDAYSEL_DATE) { assert_param(IS_LL_RTC_DAY(RTC_AlarmStruct->AlarmDateWeekDay)); } else { assert_param(IS_LL_RTC_WEEKDAY(RTC_AlarmStruct->AlarmDateWeekDay)); } } else { if (LL_RTC_GetHourFormat(RTCx) != LL_RTC_HOURFORMAT_24HOUR) { assert_param(IS_LL_RTC_HOUR12(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Hours))); assert_param(IS_LL_RTC_TIME_FORMAT(RTC_AlarmStruct->AlarmTime.TimeFormat)); } else { RTC_AlarmStruct->AlarmTime.TimeFormat = 0x00U; assert_param(IS_LL_RTC_HOUR24(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Hours))); } assert_param(IS_LL_RTC_MINUTES(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Minutes))); assert_param(IS_LL_RTC_SECONDS(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmTime.Seconds))); if (RTC_AlarmStruct->AlarmDateWeekDaySel == LL_RTC_ALMB_DATEWEEKDAYSEL_DATE) { assert_param(IS_LL_RTC_DAY(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmDateWeekDay))); } else { assert_param(IS_LL_RTC_WEEKDAY(__LL_RTC_CONVERT_BCD2BIN(RTC_AlarmStruct->AlarmDateWeekDay))); } } /* Disable the write protection for RTC registers */ LL_RTC_DisableWriteProtection(RTCx); /* Select weekday selection */ if (RTC_AlarmStruct->AlarmDateWeekDaySel == LL_RTC_ALMB_DATEWEEKDAYSEL_DATE) { /* Set the date for ALARM */ LL_RTC_ALMB_DisableWeekday(RTCx); if (RTC_Format != LL_RTC_FORMAT_BIN) { LL_RTC_ALMB_SetDay(RTCx, RTC_AlarmStruct->AlarmDateWeekDay); } else { LL_RTC_ALMB_SetDay(RTCx, __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmDateWeekDay)); } } else { /* Set the week day for ALARM */ LL_RTC_ALMB_EnableWeekday(RTCx); LL_RTC_ALMB_SetWeekDay(RTCx, RTC_AlarmStruct->AlarmDateWeekDay); } /* Configure the Alarm register */ if (RTC_Format != LL_RTC_FORMAT_BIN) { LL_RTC_ALMB_ConfigTime(RTCx, RTC_AlarmStruct->AlarmTime.TimeFormat, RTC_AlarmStruct->AlarmTime.Hours, RTC_AlarmStruct->AlarmTime.Minutes, RTC_AlarmStruct->AlarmTime.Seconds); } else { LL_RTC_ALMB_ConfigTime(RTCx, RTC_AlarmStruct->AlarmTime.TimeFormat, __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Hours), __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Minutes), __LL_RTC_CONVERT_BIN2BCD(RTC_AlarmStruct->AlarmTime.Seconds)); } /* Set ALARM mask */ LL_RTC_ALMB_SetMask(RTCx, RTC_AlarmStruct->AlarmMask); /* Enable the write protection for RTC registers */ LL_RTC_EnableWriteProtection(RTCx); return SUCCESS; } /** * @brief Set each @ref LL_RTC_AlarmTypeDef of ALARMA field to default value (Time = 00h:00mn:00sec / * Day = 1st day of the month/Mask = all fields are masked). * @param RTC_AlarmStruct pointer to a @ref LL_RTC_AlarmTypeDef structure which will be initialized. * @retval None */ void LL_RTC_ALMA_StructInit(LL_RTC_AlarmTypeDef *RTC_AlarmStruct) { /* Alarm Time Settings : Time = 00h:00mn:00sec */ RTC_AlarmStruct->AlarmTime.TimeFormat = LL_RTC_ALMA_TIME_FORMAT_AM; RTC_AlarmStruct->AlarmTime.Hours = 0U; RTC_AlarmStruct->AlarmTime.Minutes = 0U; RTC_AlarmStruct->AlarmTime.Seconds = 0U; /* Alarm Day Settings : Day = 1st day of the month */ RTC_AlarmStruct->AlarmDateWeekDaySel = LL_RTC_ALMA_DATEWEEKDAYSEL_DATE; RTC_AlarmStruct->AlarmDateWeekDay = 1U; /* Alarm Masks Settings : Mask = all fields are not masked */ RTC_AlarmStruct->AlarmMask = LL_RTC_ALMA_MASK_NONE; } /** * @brief Set each @ref LL_RTC_AlarmTypeDef of ALARMA field to default value (Time = 00h:00mn:00sec / * Day = 1st day of the month/Mask = all fields are masked). * @param RTC_AlarmStruct pointer to a @ref LL_RTC_AlarmTypeDef structure which will be initialized. * @retval None */ void LL_RTC_ALMB_StructInit(LL_RTC_AlarmTypeDef *RTC_AlarmStruct) { /* Alarm Time Settings : Time = 00h:00mn:00sec */ RTC_AlarmStruct->AlarmTime.TimeFormat = LL_RTC_ALMB_TIME_FORMAT_AM; RTC_AlarmStruct->AlarmTime.Hours = 0U; RTC_AlarmStruct->AlarmTime.Minutes = 0U; RTC_AlarmStruct->AlarmTime.Seconds = 0U; /* Alarm Day Settings : Day = 1st day of the month */ RTC_AlarmStruct->AlarmDateWeekDaySel = LL_RTC_ALMB_DATEWEEKDAYSEL_DATE; RTC_AlarmStruct->AlarmDateWeekDay = 1U; /* Alarm Masks Settings : Mask = all fields are not masked */ RTC_AlarmStruct->AlarmMask = LL_RTC_ALMB_MASK_NONE; } /** * @brief Enters the RTC Initialization mode. * @note The RTC Initialization mode is write protected, use the * @ref LL_RTC_DisableWriteProtection before calling this function. * @param RTCx RTC Instance * @retval An ErrorStatus enumeration value: * - SUCCESS: RTC is in Init mode * - ERROR: RTC is not in Init mode */ ErrorStatus LL_RTC_EnterInitMode(RTC_TypeDef *RTCx) { __IO uint32_t timeout = RTC_INITMODE_TIMEOUT; ErrorStatus status = SUCCESS; uint32_t tmp = 0U; /* Check the parameter */ assert_param(IS_RTC_ALL_INSTANCE(RTCx)); /* Check if the Initialization mode is set */ if (LL_RTC_IsActiveFlag_INIT(RTCx) == 0U) { /* Set the Initialization mode */ LL_RTC_EnableInitMode(RTCx); /* Wait till RTC is in INIT state and if Time out is reached exit */ tmp = LL_RTC_IsActiveFlag_INIT(RTCx); while ((timeout != 0U) && (tmp != 1U)) { if (LL_SYSTICK_IsActiveCounterFlag() == 1U) { timeout --; } tmp = LL_RTC_IsActiveFlag_INIT(RTCx); if (timeout == 0U) { status = ERROR; } } } return status; } /** * @brief Exit the RTC Initialization mode. * @note When the initialization sequence is complete, the calendar restarts * counting after 4 RTCCLK cycles. * @note The RTC Initialization mode is write protected, use the * @ref LL_RTC_DisableWriteProtection before calling this function. * @param RTCx RTC Instance * @retval An ErrorStatus enumeration value: * - SUCCESS: RTC exited from in Init mode * - ERROR: Not applicable */ ErrorStatus LL_RTC_ExitInitMode(RTC_TypeDef *RTCx) { /* Check the parameter */ assert_param(IS_RTC_ALL_INSTANCE(RTCx)); /* Disable initialization mode */ LL_RTC_DisableInitMode(RTCx); return SUCCESS; } /** * @brief Waits until the RTC Time and Day registers (RTC_TR and RTC_DR) are * synchronized with RTC APB clock. * @note The RTC Resynchronization mode is write protected, use the * @ref LL_RTC_DisableWriteProtection before calling this function. * @note To read the calendar through the shadow registers after Calendar * initialization, calendar update or after wakeup from low power modes * the software must first clear the RSF flag. * The software must then wait until it is set again before reading * the calendar, which means that the calendar registers have been * correctly copied into the RTC_TR and RTC_DR shadow registers. * @param RTCx RTC Instance * @retval An ErrorStatus enumeration value: * - SUCCESS: RTC registers are synchronised * - ERROR: RTC registers are not synchronised */ ErrorStatus LL_RTC_WaitForSynchro(RTC_TypeDef *RTCx) { __IO uint32_t timeout = RTC_SYNCHRO_TIMEOUT; ErrorStatus status = SUCCESS; uint32_t tmp = 0U; /* Check the parameter */ assert_param(IS_RTC_ALL_INSTANCE(RTCx)); /* Clear RSF flag */ LL_RTC_ClearFlag_RS(RTCx); /* Wait the registers to be synchronised */ tmp = LL_RTC_IsActiveFlag_RS(RTCx); while ((timeout != 0U) && (tmp != 0U)) { if (LL_SYSTICK_IsActiveCounterFlag() == 1U) { timeout--; } tmp = LL_RTC_IsActiveFlag_RS(RTCx); if (timeout == 0U) { status = ERROR; } } if (status != ERROR) { timeout = RTC_SYNCHRO_TIMEOUT; tmp = LL_RTC_IsActiveFlag_RS(RTCx); while ((timeout != 0U) && (tmp != 1U)) { if (LL_SYSTICK_IsActiveCounterFlag() == 1U) { timeout--; } tmp = LL_RTC_IsActiveFlag_RS(RTCx); if (timeout == 0U) { status = ERROR; } } } return (status); } /** * @} */ /** * @} */ /** * @} */ #endif /* defined(RTC) */ /** * @} */ #endif /* USE_FULL_LL_DRIVER */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
the_stack_data/154831027.c
#include <stdio.h> #include <stdlib.h> #include <omp.h> int main() { int n, i, token, t = 2, result, *a; printf("Inserire la dimensione del vettore: "); scanf("%d", &n); a = (int *)malloc(n*sizeof(int)); for(i = 0; i < n; i++) { a[i] = 2 * i; printf("[%d]\t", a[i]); } printf("\nInserire il numero da cercare: "); scanf("%d", &token); result = binarySearch(0, n - 1, t, token, a); if (result < 0) printf("\nThe number not is in the vector."); else printf("\nThe number is in the position: %d\n", result+1); return 0; } int binarySearch(int left, int right, int t, int token, int *a) { int result = -1, i; int size = (right - left + 1)/2; //Sottoporzione del vettore. if (size == 0) //Se il vettore è composto da un solo elemento. { if(a[left] != token) //Se l'unico elemento presente nel vettore è diverso dalla chiave, ritorna -1. { return -1; } else { return left; //Se l'unico elemento presente nel vettore è uguale alla chiave, ritorna la posizione in cui si trova l'elemento. } } omp_set_num_threads(t); //t = 2, quindi 2 thread. omp_set_nested(1); #pragma omp parallel shared(a, token, left, right, size, result) { int id = omp_get_thread_num(); int leftThread = left + id * size; int rightThread = leftThread + size - 1; printf("\nLeftThread: %d", leftThread); printf("\nRightThread: %d", rightThread); if(id == t-1) rightThread = right; if(a[leftThread] <= token && a[rightThread] >= token) { result = binarySearch(leftThread, rightThread, t, token, a); } } }
the_stack_data/162641846.c
#include <stdio.h> void call_me() { printf("I was called"); } int main() { call_me(); return 0; }
the_stack_data/127846.c
/* Qn : Write a program to find the maximum and minimum value of a 2D array using function. The program of printing output have to be shown in the main function. Sample Input Sample Output 1 -2 3 4 0 4 max: 20 min: -2 3 20 7 */ /* Author : Arnob Mahmud mail : [email protected] */ #include <stdio.h> #include <math.h> int main(int argc, char const *argv[]) { int A[3][3], max, min; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { scanf("%d", &A[i][j]); } } max = min = A[0][0]; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (A[i][j] > max) { max = A[i][j]; } else if (A[i][j] < min) { min = A[i][j]; } } } printf("Max : %d, Min : %d", max, min); return 0; }
the_stack_data/54826029.c
// // Sample Code: // #include <stdio.h> #include <stdlib.h> #include <string.h> //#define DEBUG_CORRECTNESS void pre_Initializing_Input_Tensors(); void post_Correctness(); // //# abcdef-dfga-gebc //t3 [a,16,b,16,c,16,d,16,e,16,f,16] += sum(g,16) * t2 [d,f,g,a] * v2 [g,e,b,c]; // int main(int argc, char** argv) { // for sd2 double *host_C, *host_C_chk; double *host_A; double *host_B; int size_idx_a, size_idx_b, size_idx_c, size_idx_d, size_idx_e, size_idx_f, size_idx_g; // Problem Size size_idx_a = 16; size_idx_b = 16; size_idx_c = 16; size_idx_d = 16; size_idx_e = 16; size_idx_f = 16; size_idx_g = 16; // if (argc == 8) { size_idx_a = atoi(argv[1]); size_idx_b = atoi(argv[2]); size_idx_c = atoi(argv[3]); size_idx_d = atoi(argv[4]); size_idx_e = atoi(argv[5]); size_idx_f = atoi(argv[6]); size_idx_g = atoi(argv[7]); } int size_C; int size_A; int size_B; int size_internal; long long int tmp_num = (long long int)((long long int)(size_idx_a * size_idx_b * size_idx_c * size_idx_d * size_idx_e * size_idx_f * size_idx_g) * 2); //# abcdef-dfga-gebc //t3 [a,16,b,16,c,16,d,16,e,16,f,16] += sum(g,16) * t2 [d,f,g,a] * v2 [g,e,b,c]; size_internal = size_idx_g; size_C = size_idx_a * size_idx_b * size_idx_c * size_idx_d * size_idx_e * size_idx_f; size_A = size_idx_d * size_idx_f * size_idx_g * size_idx_a; size_B = size_idx_g * size_idx_e * size_idx_b * size_idx_c; // host_C = (double*)malloc(sizeof(double) * size_C); host_C_chk = (double*)malloc(sizeof(double) * size_C); host_A = (double*)malloc(sizeof(double) * size_A); host_B = (double*)malloc(sizeof(double) * size_B); printf ("==========================================================================================================\n"); printf (">>> Problem Size (a,b,c,d,e,f) and (g): (%2d,%2d,%2d,%2d,%2d,%2d) and (%2d)\n", size_idx_a, size_idx_b, size_idx_c, size_idx_d, size_idx_e, size_idx_f, size_idx_g); printf (">>> # of Operations: %lld\n", tmp_num); printf ("==========================================================================================================\n"); // // Initialze "1" Output and "2 x 9" Inputs pre_Initializing_Input_Tensors(host_C, host_C_chk, size_C, host_A, size_A, host_B, size_B); // Run the Kernels initmemmodule_(); tccg_34_cuda(size_idx_a, size_idx_b, size_idx_c, size_idx_d, size_idx_e, size_idx_f, size_idx_g, host_C, host_A, host_B); #ifdef DEBUG_CORRECTNESS // Correctness-Check post_Correctness(host_C, host_C_chk, host_A, host_B, size_idx_a, size_idx_b, size_idx_c, size_idx_d, size_idx_e, size_idx_f, size_idx_g); #endif // Free free(host_C); free(host_C_chk); free(host_A); free(host_B); return 0; } // Initialize t3 (t3_temp), 9 t2 and 9 v2. void pre_Initializing_Input_Tensors(double* h_C, double* h_C_chk, int size_C, double* h_A, int size_A, double* h_B, int size_B) { // t3 int i, j; for (i = 0; i < size_C; i++) { h_C[i] = 0.0; h_C_chk[i] = 0.0; } for (j = 0; j < size_A; j++) { h_A[j] = ((double)rand() / RAND_MAX); } for (j = 0; j < size_B; j++) { h_B[j] = ((double)rand() / RAND_MAX); } printf ("==========================================================================================================\n"); printf (" >>> %s <<<\n", __func__); printf (" C: %'12d\n", size_C); printf (" A: %'12d, B: %'12d\n", size_A, size_B); printf ("==========================================================================================================\n"); } // void post_Correctness(double* h_C, double* h_C_chk, double* h_A, double* h_B, int size_idx_a, int size_idx_b, int size_idx_c, int size_idx_d, int size_idx_e, int size_idx_f, int size_idx_g) { //# abcdef-dfga-gebc //t3 [a,16,b,16,c,16,d,16,e,16,f,16] += sum(g,16) * t2 [d,f,g,a] * v2 [g,e,b,c]; int size_C = size_idx_a * size_idx_b * size_idx_c * size_idx_d * size_idx_e * size_idx_f; long long int tmp_ops = 0; int ops = 0; int idx_a, idx_b, idx_c, idx_d, idx_e, idx_f, idx_g; for (idx_a = 0; idx_a < size_idx_a; idx_a++) for (idx_b = 0; idx_b < size_idx_b; idx_b++) for (idx_c = 0; idx_c < size_idx_c; idx_c++) for (idx_d = 0; idx_d < size_idx_d; idx_d++) for (idx_e = 0; idx_e < size_idx_e; idx_e++) for (idx_f = 0; idx_f < size_idx_f; idx_f++) { ops = 0; for (idx_g = 0; idx_g < size_idx_g; idx_g++) { int tmp_r_idx = idx_a + (idx_b + (idx_c + (idx_d + (idx_e + (idx_f) * size_idx_e) * size_idx_d) * size_idx_c) * size_idx_b) * size_idx_a; h_C_chk[tmp_r_idx] += h_A[idx_d + (idx_f + (idx_g + (idx_a) * size_idx_g) * size_idx_f) * size_idx_d] * h_B[idx_g + (idx_e + (idx_b + (idx_c) * size_idx_b) * size_idx_e) * size_idx_g]; ops++; } tmp_ops = tmp_ops + ops; } printf ("======================================= Correctness Check ==========================================\n"); double epsilon = 0.00000001; int diff = 0; int same = 0; int i; for (i = 0; i < size_C; i++) { double check = h_C_chk[i] - h_C[i]; if (check < 0) check *= -1; if (check > epsilon) { diff++; if (diff < 8) printf ("Index: %5d, (Host) %8.4f, (Dev.) %8.4f >> (Diff.) %8.4f\n", i, h_C_chk[i], h_C[i], check); } else { same++; } } printf (" >>> PASSED: %'10d among %'10d in t3\n", same, size_C); printf (" >>> ERROR : %'10d among %'10d in t3\n", diff, size_C); printf (" >>> Total Operations: %'lld\n", tmp_ops * 2); printf ("====================================================================================================\n"); }
the_stack_data/771370.c
#include <stdlib.h> #include <stdio.h> #include <errno.h> enum { buf_max = 32, }; int main(int argc, char* argv[argc+1]) { int ret = EXIT_FAILURE; char buffer[buf_max] = { 0 }; for (int i = 1; i < argc; ++i) { // Processes args FILE* instream = fopen(argv[i], "r"); // as filenames if (instream) { while (fgets(buffer, buf_max, instream)) { fputs(buffer, stdout); } fclose(instream); ret = EXIT_SUCCESS; } else { /* Provides some error diagnostic. */ fprintf(stderr, "Could not open %s: ", argv[i]); perror(0); errno = 0; // Resets the error code } } return ret; }
the_stack_data/150348.c
// 下面的表格给出了一个城市到另一个城市的每日航班信息。 // 编写一个程序,要求用户输入一个时间(用24小时制的时分表示)。 // 程序选择起飞时间与用户输入最接近的航班,显示出相应的起飞时间和抵达时间。 // 提示:把输入用从午夜开始的分钟数表示。 // 将这个时间与表格里也用从午夜开始的分钟数表示的起飞时间相比。 // 例如,13:15从午夜开始是13×60+15 = // 795分钟,与下午12:47(从午夜开始是767分钟)最接近。 #include <stdio.h> #define DEPARTURE_TIME_0 480 // 8:00 AM #define DEPARTURE_TIME_1 583 // 9:43 AM #define DEPARTURE_TIME_2 679 // 11:19 AM #define DEPARTURE_TIME_3 767 // 12:47 AM #define DEPARTURE_TIME_4 840 // 2:00 PM #define DEPARTURE_TIME_5 945 // 3:45 PM #define DEPARTURE_TIME_6 1140 // 7:00 PM #define DEPARTURE_TIME_7 1305 // 9:45 PM #define ARRIVE_TIME_0 616 // 10:16 AM #define ARRIVE_TIME_1 712 // 11:52 AM #define ARRIVE_TIME_2 811 // 1:31 PM #define ARRIVE_TIME_3 900 // 3:00 PM #define ARRIVE_TIME_4 968 // 4:08 PM #define ARRIVE_TIME_5 1075 // 5:55 PM #define ARRIVE_TIME_6 1280 // 9:20 PM #define ARRIVE_TIME_7 1438 // 11:58 PM int main() { int hour, min; printf("Enter a 24-hour time: "); scanf("%d:%d", &hour, &min); int input_time = hour * 60 + min; int min_minus = 1440; int arrive_hour, arrive_min; if (DEPARTURE_TIME_0 - input_time >= 0 && min_minus > DEPARTURE_TIME_0 - input_time) min_minus = DEPARTURE_TIME_0 - input_time; if (DEPARTURE_TIME_1 - input_time >= 0 && min_minus > DEPARTURE_TIME_1 - input_time) min_minus = DEPARTURE_TIME_1 - input_time; if (DEPARTURE_TIME_2 - input_time >= 0 && min_minus > DEPARTURE_TIME_2 - input_time) min_minus = DEPARTURE_TIME_2 - input_time; if (DEPARTURE_TIME_3 - input_time >= 0 && min_minus > DEPARTURE_TIME_3 - input_time) min_minus = DEPARTURE_TIME_3 - input_time; if (DEPARTURE_TIME_4 - input_time >= 0 && min_minus > DEPARTURE_TIME_4 - input_time) min_minus = DEPARTURE_TIME_4 - input_time; if (DEPARTURE_TIME_5 - input_time >= 0 && min_minus > DEPARTURE_TIME_5 - input_time) min_minus = DEPARTURE_TIME_5 - input_time; if (DEPARTURE_TIME_6 - input_time >= 0 && min_minus > DEPARTURE_TIME_6 - input_time) min_minus = DEPARTURE_TIME_6 - input_time; if (DEPARTURE_TIME_7 - input_time >= 0 && min_minus > DEPARTURE_TIME_7 - input_time) min_minus = DEPARTURE_TIME_7 - input_time; if (min_minus + input_time == DEPARTURE_TIME_0) { arrive_hour = ARRIVE_TIME_0 / 60; arrive_min = ARRIVE_TIME_0 - arrive_hour * 60; } if (min_minus + input_time == DEPARTURE_TIME_1) { arrive_hour = ARRIVE_TIME_1 / 60; arrive_min = ARRIVE_TIME_1 - arrive_hour * 60; } if (min_minus + input_time == DEPARTURE_TIME_2) { arrive_hour = ARRIVE_TIME_2 / 60; arrive_min = ARRIVE_TIME_2 - arrive_hour * 60; } if (min_minus + input_time == DEPARTURE_TIME_3) { arrive_hour = ARRIVE_TIME_3 / 60; arrive_min = ARRIVE_TIME_3 - arrive_hour * 60; } if (min_minus + input_time == DEPARTURE_TIME_4) { arrive_hour = ARRIVE_TIME_4 / 60; arrive_min = ARRIVE_TIME_4 - arrive_hour * 60; } if (min_minus + input_time == DEPARTURE_TIME_5) { arrive_hour = ARRIVE_TIME_5 / 60; arrive_min = ARRIVE_TIME_5 - arrive_hour * 60; } if (min_minus + input_time == DEPARTURE_TIME_6) { arrive_hour = ARRIVE_TIME_6 / 60; arrive_min = ARRIVE_TIME_6 - arrive_hour * 60; } if (min_minus + input_time == DEPARTURE_TIME_7) { arrive_hour = ARRIVE_TIME_7 / 60; arrive_min = ARRIVE_TIME_7 - arrive_hour * 60; } int depature_hour = (input_time + min_minus) / 60; int depature_min = (input_time + min_minus) % 60; if (depature_hour > 12 && arrive_hour > 12) printf( "Close departure time is %1d%1d:%1d%1d p.m., arriving at " "%1d%1d:%1d%1d " "p.m.\n", (depature_hour - 12) / 10, (depature_hour - 12) % 10, depature_min / 10, depature_min % 10, (arrive_hour - 12) / 10, (arrive_hour - 12) % 10, arrive_min / 10, arrive_min % 10); if (depature_hour <= 12 && arrive_hour > 12) printf( "Close departure time is %1d%1d:%1d%1d a.m., arriving at " "%1d%1d:%1d%1d p.m.\n", depature_hour / 10, depature_hour % 10, depature_min / 10, depature_min % 10, (arrive_hour - 12) / 10, (arrive_hour - 12) % 10, arrive_min / 10, arrive_min % 10); if (depature_hour <= 12 && arrive_hour <= 12) printf( "Close departure time is %1d%1d:%1d%1d a.m., arriving at " "%1d%1d:%1d%1d a.m.\n", depature_hour / 10, depature_hour % 10, depature_min / 10, depature_min % 10, arrive_hour / 10, arrive_hour % 10, arrive_min / 10, arrive_min % 10); return 0; }
the_stack_data/16875.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_putstr.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jde-oliv <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/03/19 08:48:07 by jde-oliv #+# #+# */ /* Updated: 2018/03/19 08:48:09 by jde-oliv ### ########.fr */ /* */ /* ************************************************************************** */ void ft_putchar(char c); void ft_putstr(char *str) { int i; i = 0; while (str[i] != '\0') { ft_putchar(str[i]); i++; } }
the_stack_data/215769386.c
/* Test that the GP gets properly restored, either by the nonlocal receiver or the nested function. */ #ifndef NO_TRAMPOLINES typedef __SIZE_TYPE__ size_t; extern void abort (void); extern void exit (int); extern void qsort(void *, size_t, size_t, int (*)(const void *, const void *)); int main () { __label__ nonlocal; int compare (const void *a, const void *b) { goto nonlocal; } char array[3]; qsort (array, 3, 1, compare); abort (); nonlocal: exit (0); } #else int main() { return 0; } #endif
the_stack_data/438157.c
#define _POSIX_C_SOURCE 200809L #include <unistd.h> #include <errno.h> #include <stdbool.h> #include <stdlib.h> #include <stdio.h> #include <string.h> static struct { const char *argv0; bool unique : 1; bool reverse : 1; } opt; static struct { char **array; size_t len; size_t cap; } lines; static void lines_init(void) { lines.len = 0; lines.cap = 64; lines.array = malloc(lines.cap * sizeof(char *)); if (!lines.array) { fprintf(stderr, "%s: unable to allocate array: %s\n", opt.argv0, strerror(errno)); exit(1); } } static void lines_resize(void) { void *ptr; size_t new_cap; new_cap = lines.cap * 2; ptr = realloc(lines.array, new_cap * sizeof(char *)); if (!ptr) { fprintf(stderr, "%s: unable to resize array: %s\n", opt.argv0, strerror(errno)); exit(1); } lines.array = ptr; } static void lines_append(char *line) { if (lines.len >= lines.cap) lines_resize(); lines.array[lines.len] = line; lines.len++; } static int compare_normal(const void *_x, const void *_y) { const char *const *const x = _x; const char *const *const y = _y; return strcmp(*x, *y); } static int compare_reverse(const void *_x, const void *_y) { const char *const *const x = _x; const char *const *const y = _y; return -strcmp(*x, *y); } static void read_lines(FILE *fh) { char *line; size_t n; do { line = NULL; n = 0; if (getline(&line, &n, fh) < 0) { free(line); return; } lines_append(line); } while (line); } static void print_all(void) { size_t i; for (i = 0; i < lines.len; i++) { fputs(lines.array[i], stdout); free(lines.array[i]); } } static void print_unique(void) { size_t i; fputs(lines.array[0], stdout); for (i = 1; i < lines.len; i++) { if (strcmp(lines.array[i], lines.array[i - 1])) fputs(lines.array[i], stdout); free(lines.array[i - 1]); } free(lines.array[lines.len - 1]); } int main(int argc, char *argv[]) { size_t i; int ch; struct { FILE **array; size_t len; bool allocd : 1; } files; opt.argv0 = argv[0]; /* Parse command line options */ while ((ch = getopt(argc, argv, "ur")) != -1) { switch (ch) { case 'u': opt.unique = 1; break; case 'r': opt.reverse = 1; break; case '?': return 1; default: abort(); } } /* Open files */ if (optind == argc) { files.allocd = 0; files.array = &stdin; files.len = 1; } else { files.allocd = 1; files.len = argc - optind; files.array = malloc(files.len * sizeof(FILE *)); if (!files.array) { fprintf(stderr, "%s: unable to allocate file array: %s\n", argv[0], strerror(errno)); return 1; } for (i = 0; i < files.len; i++) { if (strcmp(argv[i], "-")) { files.array[i] = fopen(argv[i + optind], "r"); if (!files.array[i]) { fprintf(stderr, "%s: %s: unable to open\n", argv[0], argv[i]); return 1; } } else { files.array[i] = stdin; } } } /* Ingest lines from files */ lines_init(); for (i = 0; i < files.len; i++) { read_lines(files.array[i]); fclose(files.array[i]); } if (files.allocd) free(files.array); /* Sort and print lines */ qsort(lines.array, lines.len, sizeof(char *), (opt.reverse) ? compare_reverse : compare_normal); if (opt.unique) print_unique(); else print_all(); free(lines.array); return 0; }
the_stack_data/1108457.c
/** ****************************************************************************** * @file stm32g0xx_ll_lptim.c * @author MCD Application Team * @brief LPTIM LL module driver. ****************************************************************************** * @attention * * Copyright (c) 2018 STMicroelectronics. * All rights reserved. * * This software is licensed under terms that can be found in the LICENSE file * in the root directory of this software component. * If no LICENSE file comes with this software, it is provided AS-IS. * ****************************************************************************** */ #if defined(USE_FULL_LL_DRIVER) /* Includes ------------------------------------------------------------------*/ #include "stm32g0xx_ll_lptim.h" #include "stm32g0xx_ll_bus.h" #include "stm32g0xx_ll_rcc.h" #ifdef USE_FULL_ASSERT #include "stm32_assert.h" #else #define assert_param(expr) ((void)0U) #endif /* USE_FULL_ASSERT */ /** @addtogroup STM32G0xx_LL_Driver * @{ */ #if defined (LPTIM1) || defined (LPTIM2) /** @addtogroup LPTIM_LL * @{ */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /** @addtogroup LPTIM_LL_Private_Macros * @{ */ #define IS_LL_LPTIM_CLOCK_SOURCE(__VALUE__) (((__VALUE__) == LL_LPTIM_CLK_SOURCE_INTERNAL) \ || ((__VALUE__) == LL_LPTIM_CLK_SOURCE_EXTERNAL)) #define IS_LL_LPTIM_CLOCK_PRESCALER(__VALUE__) (((__VALUE__) == LL_LPTIM_PRESCALER_DIV1) \ || ((__VALUE__) == LL_LPTIM_PRESCALER_DIV2) \ || ((__VALUE__) == LL_LPTIM_PRESCALER_DIV4) \ || ((__VALUE__) == LL_LPTIM_PRESCALER_DIV8) \ || ((__VALUE__) == LL_LPTIM_PRESCALER_DIV16) \ || ((__VALUE__) == LL_LPTIM_PRESCALER_DIV32) \ || ((__VALUE__) == LL_LPTIM_PRESCALER_DIV64) \ || ((__VALUE__) == LL_LPTIM_PRESCALER_DIV128)) #define IS_LL_LPTIM_WAVEFORM(__VALUE__) (((__VALUE__) == LL_LPTIM_OUTPUT_WAVEFORM_PWM) \ || ((__VALUE__) == LL_LPTIM_OUTPUT_WAVEFORM_SETONCE)) #define IS_LL_LPTIM_OUTPUT_POLARITY(__VALUE__) (((__VALUE__) == LL_LPTIM_OUTPUT_POLARITY_REGULAR) \ || ((__VALUE__) == LL_LPTIM_OUTPUT_POLARITY_INVERSE)) /** * @} */ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /** @defgroup LPTIM_Private_Functions LPTIM Private Functions * @{ */ /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup LPTIM_LL_Exported_Functions * @{ */ /** @addtogroup LPTIM_LL_EF_Init * @{ */ /** * @brief Set LPTIMx registers to their reset values. * @param LPTIMx LP Timer instance * @retval An ErrorStatus enumeration value: * - SUCCESS: LPTIMx registers are de-initialized * - ERROR: invalid LPTIMx instance */ ErrorStatus LL_LPTIM_DeInit(LPTIM_TypeDef *LPTIMx) { ErrorStatus result = SUCCESS; /* Check the parameters */ assert_param(IS_LPTIM_INSTANCE(LPTIMx)); if (LPTIMx == LPTIM1) { LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_LPTIM1); LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_LPTIM1); } #if defined(LPTIM2) else if (LPTIMx == LPTIM2) { LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_LPTIM2); LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_LPTIM2); } #endif /* LPTIM2 */ else { result = ERROR; } return result; } /** * @brief Set each fields of the LPTIM_InitStruct structure to its default * value. * @param LPTIM_InitStruct pointer to a @ref LL_LPTIM_InitTypeDef structure * @retval None */ void LL_LPTIM_StructInit(LL_LPTIM_InitTypeDef *LPTIM_InitStruct) { /* Set the default configuration */ LPTIM_InitStruct->ClockSource = LL_LPTIM_CLK_SOURCE_INTERNAL; LPTIM_InitStruct->Prescaler = LL_LPTIM_PRESCALER_DIV1; LPTIM_InitStruct->Waveform = LL_LPTIM_OUTPUT_WAVEFORM_PWM; LPTIM_InitStruct->Polarity = LL_LPTIM_OUTPUT_POLARITY_REGULAR; } /** * @brief Configure the LPTIMx peripheral according to the specified parameters. * @note LL_LPTIM_Init can only be called when the LPTIM instance is disabled. * @note LPTIMx can be disabled using unitary function @ref LL_LPTIM_Disable(). * @param LPTIMx LP Timer Instance * @param LPTIM_InitStruct pointer to a @ref LL_LPTIM_InitTypeDef structure * @retval An ErrorStatus enumeration value: * - SUCCESS: LPTIMx instance has been initialized * - ERROR: LPTIMx instance hasn't been initialized */ ErrorStatus LL_LPTIM_Init(LPTIM_TypeDef *LPTIMx, const LL_LPTIM_InitTypeDef *LPTIM_InitStruct) { ErrorStatus result = SUCCESS; /* Check the parameters */ assert_param(IS_LPTIM_INSTANCE(LPTIMx)); assert_param(IS_LL_LPTIM_CLOCK_SOURCE(LPTIM_InitStruct->ClockSource)); assert_param(IS_LL_LPTIM_CLOCK_PRESCALER(LPTIM_InitStruct->Prescaler)); assert_param(IS_LL_LPTIM_WAVEFORM(LPTIM_InitStruct->Waveform)); assert_param(IS_LL_LPTIM_OUTPUT_POLARITY(LPTIM_InitStruct->Polarity)); /* The LPTIMx_CFGR register must only be modified when the LPTIM is disabled (ENABLE bit is reset to 0). */ if (LL_LPTIM_IsEnabled(LPTIMx) == 1UL) { result = ERROR; } else { /* Set CKSEL bitfield according to ClockSource value */ /* Set PRESC bitfield according to Prescaler value */ /* Set WAVE bitfield according to Waveform value */ /* Set WAVEPOL bitfield according to Polarity value */ MODIFY_REG(LPTIMx->CFGR, (LPTIM_CFGR_CKSEL | LPTIM_CFGR_PRESC | LPTIM_CFGR_WAVE | LPTIM_CFGR_WAVPOL), LPTIM_InitStruct->ClockSource | \ LPTIM_InitStruct->Prescaler | \ LPTIM_InitStruct->Waveform | \ LPTIM_InitStruct->Polarity); } return result; } /** * @brief Disable the LPTIM instance * @rmtoll CR ENABLE LL_LPTIM_Disable * @param LPTIMx Low-Power Timer instance * @note The following sequence is required to solve LPTIM disable HW limitation. * Please check Errata Sheet ES0335 for more details under "MCU may remain * stuck in LPTIM interrupt when entering Stop mode" section. * @retval None */ void LL_LPTIM_Disable(LPTIM_TypeDef *LPTIMx) { LL_RCC_ClocksTypeDef rcc_clock; uint32_t tmpclksource = 0; uint32_t tmpIER; uint32_t tmpCFGR; uint32_t tmpCMP; uint32_t tmpARR; uint32_t primask_bit; uint32_t tmpCFGR2; /* Check the parameters */ assert_param(IS_LPTIM_INSTANCE(LPTIMx)); /* Enter critical section */ primask_bit = __get_PRIMASK(); __set_PRIMASK(1) ; /********** Save LPTIM Config *********/ /* Save LPTIM source clock */ switch ((uint32_t)LPTIMx) { case LPTIM1_BASE: tmpclksource = LL_RCC_GetLPTIMClockSource(LL_RCC_LPTIM1_CLKSOURCE); break; #if defined(LPTIM2) case LPTIM2_BASE: tmpclksource = LL_RCC_GetLPTIMClockSource(LL_RCC_LPTIM2_CLKSOURCE); break; #endif /* LPTIM2 */ default: break; } /* Save LPTIM configuration registers */ tmpIER = LPTIMx->IER; tmpCFGR = LPTIMx->CFGR; tmpCMP = LPTIMx->CMP; tmpARR = LPTIMx->ARR; tmpCFGR2 = LPTIMx->CFGR2; /************* Reset LPTIM ************/ (void)LL_LPTIM_DeInit(LPTIMx); /********* Restore LPTIM Config *******/ LL_RCC_GetSystemClocksFreq(&rcc_clock); if ((tmpCMP != 0UL) || (tmpARR != 0UL)) { /* Force LPTIM source kernel clock from APB */ switch ((uint32_t)LPTIMx) { case LPTIM1_BASE: LL_RCC_SetLPTIMClockSource(LL_RCC_LPTIM1_CLKSOURCE_PCLK1); break; #if defined(LPTIM2) case LPTIM2_BASE: LL_RCC_SetLPTIMClockSource(LL_RCC_LPTIM2_CLKSOURCE_PCLK1); break; #endif /* LPTIM2 */ default: break; } if (tmpCMP != 0UL) { /* Restore CMP and ARR registers (LPTIM should be enabled first) */ LPTIMx->CR |= LPTIM_CR_ENABLE; LPTIMx->CMP = tmpCMP; /* Polling on CMP write ok status after above restore operation */ do { rcc_clock.SYSCLK_Frequency--; /* Used for timeout */ } while (((LL_LPTIM_IsActiveFlag_CMPOK(LPTIMx) != 1UL)) && ((rcc_clock.SYSCLK_Frequency) > 0UL)); LL_LPTIM_ClearFlag_CMPOK(LPTIMx); } if (tmpARR != 0UL) { LPTIMx->CR |= LPTIM_CR_ENABLE; LPTIMx->ARR = tmpARR; LL_RCC_GetSystemClocksFreq(&rcc_clock); /* Polling on ARR write ok status after above restore operation */ do { rcc_clock.SYSCLK_Frequency--; /* Used for timeout */ } while (((LL_LPTIM_IsActiveFlag_ARROK(LPTIMx) != 1UL)) && ((rcc_clock.SYSCLK_Frequency) > 0UL)); LL_LPTIM_ClearFlag_ARROK(LPTIMx); } /* Restore LPTIM source kernel clock */ LL_RCC_SetLPTIMClockSource(tmpclksource); } /* Restore configuration registers (LPTIM should be disabled first) */ LPTIMx->CR &= ~(LPTIM_CR_ENABLE); LPTIMx->IER = tmpIER; LPTIMx->CFGR = tmpCFGR; LPTIMx->CFGR2 = tmpCFGR2; /* Exit critical section: restore previous priority mask */ __set_PRIMASK(primask_bit); } /** * @} */ /** * @} */ /** * @} */ #endif /* LPTIM1 || LPTIM2 */ /** * @} */ #endif /* USE_FULL_LL_DRIVER */
the_stack_data/29826123.c
int fib(int n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2); } int main() { return fib(6); // 8 }
the_stack_data/1476.c
/* { dg-options { -nostartfiles below100.o -Tbelow100.ld -O2 } } */ /* { dg-final { scan-assembler "set1 B100,#0" } } */ typedef struct { unsigned short b0:1; unsigned short b1:1; unsigned short b2:1; unsigned short b3:1; unsigned short b4:1; unsigned short b5:1; unsigned short b6:1; unsigned short b7:1; unsigned short b8:1; unsigned short b9:1; unsigned short b10:1; unsigned short b11:1; unsigned short b12:1; unsigned short b13:1; unsigned short b14:1; unsigned short b15:1; } BitField; char acDummy[0xf0] __attribute__ ((__BELOW100__)); BitField B100 __attribute__ ((__BELOW100__)); unsigned short *p = (unsigned short *) &B100; void Do (void) { B100.b0 = 1; } int main (void) { *p = 0x1234; Do (); return (*p == 0x1235) ? 0 : 1; }
the_stack_data/125140721.c
#include <stdio.h> #include <stdlib.h> typedef struct node_t { int ID; int Num; struct node_t *Left, *Right; } node; node *MakeTree(node *Node, int ID, int Num) { if (!Node) { Node = (node *) malloc(sizeof(node)); Node->ID = ID; Node->Num = Num; Node->Left = Node->Right = NULL; } else { if (Node->Num > Num) Node->Left = MakeTree(Node->Left, ID, Num); else Node->Right = MakeTree(Node->Right, ID, Num); } return Node; } void PrintTreeMid(node *Node) { if (!Node) return; PrintTreeMid(Node->Left); printf("%d %d\n", Node->ID, Node->Num); PrintTreeMid(Node->Right); } int main() { int ID = 0, Num = 0, Length = 0, i = 0; while (scanf("%d", &Length) != EOF) { node *Node = NULL; for (i = 0; i < Length; i++) { scanf("%d%d", &ID, &Num); Node = MakeTree(Node, ID, Num); } PrintTreeMid(Node); } return 0; }
the_stack_data/59571.c
/* chksum64 V1.2, a program to calculate the ROM checksum of Nintendo64 ROMs. Copyright (C) 1997 Andreas Sterbenz ([email protected]) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define max2(a, b) ( (a)>(b) ? (a) : (b) ) #define min2(a, b) ( (a)<(b) ? (a) : (b) ) #define BUFSIZE 32768 #define CHECKSUM_START 0x1000 #define CHECKSUM_LENGTH 0x100000L #define CHECKSUM_HEADERPOS 0x10 #define CHECKSUM_END (CHECKSUM_START + CHECKSUM_LENGTH) #define CHECKSUM_STARTVALUE 0xf8ca4ddc #define ROL(i, b) (((i)<<(b)) | ((i)>>(32-(b)))) #define BYTES2LONG(b, s) ( (((b)[0^(s)] & 0xffL) << 24) | \ (((b)[1^(s)] & 0xffL) << 16) | \ (((b)[2^(s)] & 0xffL) << 8) | \ (((b)[3^(s)] & 0xffL)) ) #define LONG2BYTES(l, b, s) (b)[0^(s)] = ((l)>>24)&0xff; \ (b)[1^(s)] = ((l)>>16)&0xff; \ (b)[2^(s)] = ((l)>> 8)&0xff; \ (b)[3^(s)] = ((l) )&0xff; #define HEADER_MAGIC 0x80371240 void usage(char *progname) { fprintf(stderr, "Usage: %s [-r] [-o|-s] <File>\n\n", progname); fprintf(stderr, "This program calculates the ROM checksum for Nintendo64 ROM images.\n"); fprintf(stderr, "Checksum code reverse engineered from Nagra's program.\n"); exit(2); } int main(int argc, char *argv[]) { FILE *file1; char *fname1=NULL, *progname=argv[0]; unsigned char buffer1[BUFSIZE]; unsigned int flen1; unsigned int sum1, sum2; int swapped=-1; int readonly = 0; printf("CHKSUM64 V1.2 Copyright (C) 1997 Andreas Sterbenz ([email protected])\n"); printf("This program is released under the terms of the GNU public license. NO WARRANTY\n\n"); { int i; for( i=1; i<argc; i++ ) { if( argv[i][0] == '-' ) { char *c = argv[i]+1; if( *(c+1) != '\0' ) usage(progname); switch( *c ) { case 'r': readonly = 1; break; case 'o': swapped = 0; break; case 's': swapped = 1; break; default: usage(progname); } } else { if( fname1 == NULL ) { fname1 = argv[i]; } else { usage(progname); } } } } if( fname1 == NULL ) usage(progname); if( (readonly == 1) || (file1 = fopen(fname1, "r+b")) == NULL ) { if( (file1 = fopen(fname1, "rb")) == NULL ) { fprintf(stderr, "%s: Could not open file '%s' for reading.\n", progname, fname1); exit(1); } else { readonly = 1; } } if( fread(buffer1, 1, 12, file1) != 12 ) { fprintf(stderr, "%s: File is too short to be a N64 ROM Image, cannot checksum it.\n", progname); exit(1); } if( swapped == -1 ) { if( BYTES2LONG(buffer1, 0) == HEADER_MAGIC ) { swapped = 0; } else if( BYTES2LONG(buffer1, 1) == HEADER_MAGIC ) { swapped = 1; } } if( swapped != -1 ) { printf("The image '%s' is in %s format.\n", fname1, (swapped==0) ? "original (not swapped)" : "V64 (byte-swapped)"); } else { if( (buffer1[8] == 0x80) && (buffer1[9] != 0x80) ) { swapped = 0; } else { if( (buffer1[8] != 0x80) && (buffer1[9] == 0x80) ) { swapped = 1; } } if( swapped != -1 ) { printf("WARNING: I am not 100%% certain, but the image '%s' appears to be in %s format.\n", fname1, (swapped==0) ? "original (not swapped)" : "V64 (byte-swapped)"); } else { fprintf(stderr, "%s: Could not detect type of image '%s', use commandline to override.\n", progname, fname1); exit(1); } } fseek(file1, 0L, SEEK_END); flen1 = ftell(file1); if( flen1 < CHECKSUM_END ) { if( flen1 < CHECKSUM_START ) { fprintf(stderr, "%s: File is too short to be a N64 ROM Image, cannot checksum it.\n", progname); exit(1); } if( (flen1 & 3) != 0 ) { fprintf(stderr, "%s: File length is not a multiple of four, cannot calculate checksum.\n", progname); exit(1); } printf("File is only %ld bytes long, remaining %ld to be checksummed will be assumed 0.\n", flen1, CHECKSUM_END - flen1); } fseek(file1, CHECKSUM_START, SEEK_SET); { unsigned int i; unsigned int c1, k1, k2; unsigned int t1, t2, t3, t4; unsigned int t5, t6; unsigned int n; unsigned clen = CHECKSUM_LENGTH; unsigned rlen = flen1 - CHECKSUM_START; /* Below is the actual checksum calculation algorithm, which was reverse engineered out of Nagra's program. As you can see, the algorithm is total crap. Obviously it was designed to be difficult to guess and reverse engineer, and not to give a good checksum. A simple XOR and ROL 13 would give a just as good checksum. The ifs and the data dependent ROL are really extreme nonsense. */ t1 = CHECKSUM_STARTVALUE; t2 = CHECKSUM_STARTVALUE; t3 = CHECKSUM_STARTVALUE; t4 = CHECKSUM_STARTVALUE; t5 = CHECKSUM_STARTVALUE; t6 = CHECKSUM_STARTVALUE; for( ;; ) { if( rlen > 0 ) { n = fread(buffer1, 1, min2(BUFSIZE, clen), file1); if( (n & 0x03) != 0 ) { n += fread(buffer1+n, 1, 4-(n&3), file1); } } else { n = min2(BUFSIZE, clen); } if( (n == 0) || ((n&3) != 0) ) { if( (clen != 0) || (n != 0) ) { fprintf(stderr, "WARNING: Short read, checksum may be incorrect.\n"); } break; } for( i=0; i<n; i+=4 ) { c1 = BYTES2LONG(&buffer1[i], swapped); k1 = t6 + c1; if( k1 < t6 ) t4++; t6 = k1; t3 ^= c1; k2 = c1 & 0x1f; k1 = ROL(c1, k2); t5 += k1; if( c1 < t2 ) { t2 ^= k1; } else { t2 ^= t6 ^ c1; } t1 += c1 ^ t5; } if( rlen > 0 ) { rlen -= n; if( rlen <= 0 ) memset(buffer1, 0, BUFSIZE); } clen -= n; } sum1 = t6 ^ t4 ^ t3; sum2 = t5 ^ t2 ^ t1; } LONG2BYTES(sum1, &buffer1[0], 0); LONG2BYTES(sum2, &buffer1[4], 0); fseek(file1, CHECKSUM_HEADERPOS, SEEK_SET); fread(buffer1+8, 1, 8, file1); printf("Old Checksum: "); printf("%02X %02X %02X %02X ", buffer1[ 8^swapped], buffer1[ 9^swapped], buffer1[10^swapped], buffer1[11^swapped]); printf("%02X %02X %02X %02X\n", buffer1[12^swapped], buffer1[13^swapped], buffer1[14^swapped], buffer1[15^swapped]); printf("Calculated Checksum: "); printf("%02X %02X %02X %02X ", buffer1[0], buffer1[1], buffer1[2], buffer1[3]); printf("%02X %02X %02X %02X\n", buffer1[4], buffer1[5], buffer1[6], buffer1[7]); if( readonly == 0 ) { fseek(file1, CHECKSUM_HEADERPOS, SEEK_SET); LONG2BYTES(sum1, &buffer1[16], swapped); LONG2BYTES(sum2, &buffer1[20], swapped); if( fwrite(buffer1+16, 1, 8, file1) != 8 ) { fprintf(stderr, "%s: Could not write new checksum to file '%s'!\n", progname, fname1); exit(1); } else { printf("New checksum successfully written.\n"); } } else { printf("File opened in read-only mode, new checksum not written.\n"); } fclose(file1); return 0; }
the_stack_data/176706119.c
#include <stdio.h> #include <string.h> int main(int argc, char* argv[]) { int n,i; char a[2001], b[1001]; freopen("input.txt", "r", stdin); memset(a,' ',2000); memset(b,'*',1000); a[2000]=b[1000]='\0'; while(~scanf("%d", &n)) { for (i=0;i<n;i++){ printf("%s",&a[2*(1000-n+i+1)]); printf("%s\n",&b[1000-n-2*i]); } } return 0; } /* #include <stdio.h> int main(int argc, char* argv[]) { int n, i, j; freopen("input.txt", "r", stdin); while(~scanf("%d", &n)){ for (i=0;i<n;i++) { for (j=0;j<2*(n-i-1);j++){ putchar(' '); } for (j=0;j<n+2*i;j++){ putchar('*'); } putchar('\n'); } } return 0; } */
the_stack_data/36074911.c
/* * File: at_tools.c * Brief: * ----- * File Created: Monday, 11th February 2019 5:50:37 pm * Author: ldj * ----- * Last Modified: Tuesday, 12th February 2019 9:43:27 am * Modified By: ldj * ----- * Copyright (c) 2019 */ #include "stdint.h" #include "string.h" #include "ctype.h" void ATCharUpper(uint8_t *at_string) { uint32_t i; uint8_t *p = at_string; uint8_t str_len = strlen((const char*)at_string); for (i = 0; i < str_len; i++) { if ((*p >= 'a') && (*p <= 'z')) { *p -= 'a' - 'A'; } p++; } } const char char_buf[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; char hex2char(uint8_t data) { return char_buf[data]; } /* * Conver int to string based on radix (usually 2, 8, 10, and 16) */ /* http://baike.baidu.com/link?url=OEBXFGh29JKAcmOLcN-7BliwpzIP2wi8fIKJSSWpQNJsqkCVh9TfCWpFF_ptB43KNyD71iRa-a7Du-MtfQv9Mq */ char *itoa(int num, char *str, int radix) { char index[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; unsigned unum; int i = 0, j, k; char temp; if (radix == 10 && num < 0) { unum = (unsigned)-num; str[i++] = '-'; } else { unum = (unsigned)num; } do { str[i++] = index[unum % (unsigned)radix]; unum /= radix; } while (unum); str[i] = '\0'; if (str[0] == '-') k = 1; else k = 0; for (j = k; j <= (i - 1) / 2; j++) { temp = str[j]; str[j] = str[i - 1 + k - j]; str[i - 1 + k - j] = temp; } return str; } /* // C prototype : void StrToHex(BYTE *pbDest, BYTE *pbSrc, int nLen) // parameter(s): [OUT] pbDest - 输出缓冲区 // [IN] pbSrc - 字符串 // [IN] nLen - 16进制数的字节数(字符串的长度/2) // return value: // remarks : 将字符串转化为16进制数 */ void StrToHex(uint8_t *pbDest, uint8_t *pbSrc, uint8_t nLen) { char h1, h2; uint8_t s1, s2; int i; for (i = 0; i < nLen; i++) { h1 = pbSrc[2 * i]; h2 = pbSrc[2 * i + 1]; s1 = toupper(h1) - 0x30; if (s1 > 9) s1 -= 7; s2 = toupper(h2) - 0x30; if (s2 > 9) s2 -= 7; pbDest[i] = s1 * 16 + s2; } }
the_stack_data/965739.c
/* Test program that triggers mutex reinitialization. */ #define _GNU_SOURCE #include <assert.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> int main(int argc, char** argv) { pthread_mutex_t m; pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL); pthread_mutex_init(&m, &attr); pthread_mutexattr_destroy(&attr); pthread_mutex_lock(&m); pthread_mutex_unlock(&m); pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&m, &attr); pthread_mutexattr_destroy(&attr); pthread_mutex_lock(&m); pthread_mutex_unlock(&m); pthread_mutex_destroy(&m); fprintf(stderr, "Done.\n"); return 0; }
the_stack_data/71221.c
/** * Note: The returned array must be malloced, assume caller calls free(). */ #include <stdlib.h> #include <stdio.h> int *sortedSquares(int *A, int ASize, int *returnSize) { int i, j, t, *returnArr, flag = 0; *returnSize = ASize; returnArr = (int *)malloc(ASize * sizeof(int)); returnArr[0] = A[0] * A[0]; for (i = 1; i < ASize; i++) { t = A[i] * A[i]; for (j =i-1; j >=0; j--) { if (t < returnArr[j]) { returnArr[j+1] = returnArr[j]; } else break; } returnArr[j+1] = t; } return returnArr; } int main() { int arr[] = {1,2,4,2,1}; int size = sizeof(arr) / sizeof(int); int i, *arr2; arr2 = sortedSquares(arr, size, &size); for (i = 0; i < size; i++) { printf("%d ", arr2[i]); } }
the_stack_data/56567.c
/* PR middle-end/11151 */ /* Originator: Andrew Church <[email protected]> */ /* { dg-do run } */ /* This used to fail on SPARC because the (undefined) return value of 'bar' was overwriting that of 'foo'. */ extern void abort(void); int foo(int n) { return n+1; } int bar(int n) { __builtin_return(__builtin_apply((void (*)(void))foo, __builtin_apply_args(), 64)); } int main(void) { if (bar(1) != 2) abort(); return 0; }
the_stack_data/179790.c
/*BEGIN_LEGAL Intel Open Source License Copyright (c) 2002-2017 Intel Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. END_LEGAL */ #include <stdio.h> void foo() { printf("inside foo\n"); } void mark1() { printf("inside mark1\n"); } void mark2() { printf("inside mark2\n"); } void bar() { printf("inside bar \n"); } int main() { printf("inside main calling foo\n"); mark1(); foo(); printf("inside main calling bar\n"); mark2(); bar(); return 0; }
the_stack_data/215767018.c
//Classification: #default/p/DAM/NP/sS/D(v)/lc/cd //Written by: Sergey Pomelov //Reviewed by: Igor Eremeev //Comment: #include <stdio.h> int main(void) { int q = 2; int *p = &q; static int a = 1; int c; scanf("%d",&c); if (c==1) a = *p; printf("%d %d %d",a,c,q); return 0; }
the_stack_data/206393521.c
#include <stdio.h> int foo(int n){ n = 3*n; return n; } int main(){ int a,b; scanf("%d",&a); a = foo(a); if(a == 45){ b = 1; } else{ b=-1; } return 0; }
the_stack_data/91767.c
/* * Copyright (c) 2018, Olivier DEBON * All rights reserved. * Please checkout LICENSE file. */ #include <X11/Xlib.h> #include <X11/Xutil.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <unistd.h> static Display *dpy; static Window win; static int screen; static GC gc; static Font font; static XFontStruct *font_info; static pthread_t thread; static Atom wm_delete_window, wm_protocols, cm_hide_window; static char *message = ""; void hideWindow() { XEvent event; event.type = ClientMessage; event.xclient.window = win; event.xclient.message_type = cm_hide_window; event.xclient.format = 8; XSendEvent(dpy, win, False, 0, &event); XFlush(dpy); } void showMessage(char *msg) { message = msg; XEvent event; event.type = Expose; event.xexpose.count = 0; event.xexpose.window = win; XSendEvent(dpy, win, False, ExposureMask, &event); XFlush(dpy); } static void * mainLoop(void *arg) { int *go = arg; while(1) { XEvent event; XNextEvent(dpy, &event); if (event.type == Expose && event.xexpose.count == 0) { int width; XClearWindow(dpy, win); width = XTextWidth(font_info, message, strlen(message)); XDrawString(dpy, win, gc, (350-width)/2, 40, message, strlen(message)); XFlush(dpy); } if (event.type == ClientMessage) { if (event.xclient.message_type == wm_protocols) { if (event.xclient.data.l[0] == wm_delete_window) { break; } } if (event.xclient.message_type == cm_hide_window) { XIconifyWindow(dpy, win, screen); } } } XCloseDisplay(dpy); *go = 0; exit(0); } int gui_init(int *go) { *go = 1; XInitThreads(); dpy = XOpenDisplay(NULL); if (dpy == NULL) { return -1; } screen = DefaultScreen(dpy); win = XCreateSimpleWindow(dpy, RootWindow(dpy, screen), 10, 10, 350, 80, 1, BlackPixel(dpy, screen), WhitePixel(dpy, screen)); gc = XCreateGC(dpy, win, 0, 0); XSelectInput(dpy, win, ExposureMask); font_info = XLoadQueryFont(dpy, "-*-fixed-*-*-*-*-18-*-*-*-*-*-*-*"); if (font_info == NULL) { font_info = XLoadQueryFont(dpy, "fixed"); } font = font_info->fid; XSetFont(dpy, gc, font); XMapRaised(dpy, win); // WM stuff char *name = "Promys"; XStoreName(dpy, win, name); XClassHint *classHint = XAllocClassHint(); if (classHint) { classHint->res_name = name; classHint->res_class = name; } XSetClassHint(dpy, win, classHint); XFree(classHint); // Some WM client message atoms wm_protocols = XInternAtom(dpy, "WM_PROTOCOLS", False); wm_delete_window = XInternAtom(dpy, "WM_DELETE_WINDOW", False); XSetWMProtocols(dpy, win, &wm_delete_window, 1); // Create our client message cm_hide_window = XInternAtom(dpy, "PROMYS_HIDE_WINDOW", False); pthread_create(&thread, NULL, mainLoop, go); return 0; }
the_stack_data/498903.c
int printf ( const char * format ); void exit (int status); #define NULL 0 typedef unsigned int size_t; void* malloc (size_t size); struct addr { char name[40]; char street[40]; char zip[10]; }; int main() { struct addr *p; p = malloc(sizeof(struct addr)); if(p==NULL) { printf("Allocation Error\n"); exit(1); } return p; }
the_stack_data/19863.c
#include<assert.h> int main() { int a = 0; int *p = &a; int i; for (i=0; i<10; i++) { } *p = 10; assert(a == 10); }
the_stack_data/182951855.c
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ /** * Benchmark `cos`. */ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <sys/time.h> #define NAME "cos" #define ITERATIONS 1000000 #define REPEATS 3 /** * Prints the TAP version. */ void print_version() { printf( "TAP version 13\n" ); } /** * Prints the TAP summary. * * @param total total number of tests * @param passing total number of passing tests */ void print_summary( int total, int passing ) { printf( "#\n" ); printf( "1..%d\n", total ); // TAP plan printf( "# total %d\n", total ); printf( "# pass %d\n", passing ); printf( "#\n" ); printf( "# ok\n" ); } /** * Prints benchmarks results. * * @param elapsed elapsed time in seconds */ void print_results( double elapsed ) { double rate = (double)ITERATIONS / elapsed; printf( " ---\n" ); printf( " iterations: %d\n", ITERATIONS ); printf( " elapsed: %0.9f\n", elapsed ); printf( " rate: %0.9f\n", rate ); printf( " ...\n" ); } /** * Returns a clock time. * * @return clock time */ double tic() { struct timeval now; gettimeofday( &now, NULL ); return (double)now.tv_sec + (double)now.tv_usec/1.0e6; } /** * Generates a random double on the interval [0,1]. * * @return random double */ double rand_double() { int r = rand(); return (double)r / ( (double)RAND_MAX + 1.0 ); } /** * Runs a benchmark. * * @return elapsed time in seconds */ double benchmark() { double elapsed; double x; double y; double t; int i; t = tic(); for ( i = 0; i < ITERATIONS; i++ ) { x = ( 20.0*rand_double() ) - 10.0; y = cos( x ); if ( y != y ) { printf( "should not return NaN\n" ); break; } } elapsed = tic() - t; if ( y != y ) { printf( "should not return NaN\n" ); } return elapsed; } /** * Main execution sequence. */ int main( void ) { double elapsed; int i; // Use the current time to seed the random number generator: srand( time( NULL ) ); print_version(); for ( i = 0; i < REPEATS; i++ ) { printf( "# c::%s\n", NAME ); elapsed = benchmark(); print_results( elapsed ); printf( "ok %d benchmark finished\n", i+1 ); } print_summary( REPEATS, REPEATS ); }
the_stack_data/11076626.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 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) { { } } void RandomFunc(unsigned long input[1] , unsigned long output[1] ) { unsigned long state[1] ; char copy11 ; unsigned short copy12 ; { state[0UL] = (input[0UL] - 51238316UL) - 339126204UL; if ((state[0UL] >> 3UL) & 1UL) { if (state[0UL] & 1UL) { if (state[0UL] & 1UL) { copy11 = *((char *)(& state[0UL]) + 6); *((char *)(& state[0UL]) + 6) = *((char *)(& state[0UL]) + 5); *((char *)(& state[0UL]) + 5) = copy11; copy11 = *((char *)(& state[0UL]) + 5); *((char *)(& state[0UL]) + 5) = *((char *)(& state[0UL]) + 2); *((char *)(& state[0UL]) + 2) = copy11; state[0UL] |= (state[0UL] & 31UL) << 4UL; } else { state[0UL] += state[0UL]; state[0UL] += state[0UL]; } } else { state[0UL] |= (state[0UL] & 31UL) << 4UL; copy12 = *((unsigned short *)(& state[0UL]) + 1); *((unsigned short *)(& state[0UL]) + 1) = *((unsigned short *)(& state[0UL]) + 2); *((unsigned short *)(& state[0UL]) + 2) = copy12; } } else { state[0UL] *= state[0UL]; } output[0UL] = (state[0UL] + 309316150UL) + 8026621712UL; } } 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 ++; } } }
the_stack_data/128850.c
// WARNING: bad unlock balance in ucma_destroy_id // https://syzkaller.appspot.com/bug?id=62904d6fe6bc658ae12a6446d5f28140920d8d96 // 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 <net/if_arp.h> #include <netinet/in.h> #include <pthread.h> #include <sched.h> #include <setjmp.h> #include <signal.h> #include <stdarg.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/ioctl.h> #include <sys/mount.h> #include <sys/prctl.h> #include <sys/resource.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/time.h> #include <sys/types.h> #include <sys/uio.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> #include <linux/futex.h> #include <linux/if_addr.h> #include <linux/if_ether.h> #include <linux/if_link.h> #include <linux/if_tun.h> #include <linux/in6.h> #include <linux/ip.h> #include <linux/neighbour.h> #include <linux/net.h> #include <linux/netlink.h> #include <linux/rtnetlink.h> #include <linux/tcp.h> #include <linux/veth.h> unsigned long long procid; static __thread int skip_segv; static __thread jmp_buf segv_env; static void segv_handler(int sig, siginfo_t* info, void* ctx) { uintptr_t addr = (uintptr_t)info->si_addr; const uintptr_t prog_start = 1 << 20; const uintptr_t prog_end = 100 << 20; if (__atomic_load_n(&skip_segv, __ATOMIC_RELAXED) && (addr < prog_start || addr > prog_end)) { _longjmp(segv_env, 1); } exit(sig); } static void install_segv_handler(void) { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = SIG_IGN; syscall(SYS_rt_sigaction, 0x20, &sa, NULL, 8); syscall(SYS_rt_sigaction, 0x21, &sa, NULL, 8); memset(&sa, 0, sizeof(sa)); sa.sa_sigaction = segv_handler; sa.sa_flags = SA_NODEFER | SA_SIGINFO; sigaction(SIGSEGV, &sa, NULL); sigaction(SIGBUS, &sa, NULL); } #define NONFAILING(...) \ { \ __atomic_fetch_add(&skip_segv, 1, __ATOMIC_SEQ_CST); \ if (_setjmp(segv_env) == 0) { \ __VA_ARGS__; \ } \ __atomic_fetch_sub(&skip_segv, 1, __ATOMIC_SEQ_CST); \ } static void sleep_ms(uint64_t ms) { usleep(ms * 1000); } static uint64_t current_time_ms(void) { struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts)) exit(1); return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000; } static void use_temporary_dir(void) { char tmpdir_template[] = "./syzkaller.XXXXXX"; char* tmpdir = mkdtemp(tmpdir_template); if (!tmpdir) exit(1); if (chmod(tmpdir, 0777)) exit(1); if (chdir(tmpdir)) exit(1); } static void thread_start(void* (*fn)(void*), void* arg) { pthread_t th; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setstacksize(&attr, 128 << 10); int i; for (i = 0; i < 100; i++) { if (pthread_create(&th, &attr, fn, arg) == 0) { pthread_attr_destroy(&attr); return; } if (errno == EAGAIN) { usleep(50); continue; } break; } exit(1); } typedef struct { int state; } event_t; static void event_init(event_t* ev) { ev->state = 0; } static void event_reset(event_t* ev) { ev->state = 0; } static void event_set(event_t* ev) { if (ev->state) exit(1); __atomic_store_n(&ev->state, 1, __ATOMIC_RELEASE); syscall(SYS_futex, &ev->state, FUTEX_WAKE | FUTEX_PRIVATE_FLAG); } static void event_wait(event_t* ev) { while (!__atomic_load_n(&ev->state, __ATOMIC_ACQUIRE)) syscall(SYS_futex, &ev->state, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0, 0); } static int event_isset(event_t* ev) { return __atomic_load_n(&ev->state, __ATOMIC_ACQUIRE); } static int event_timedwait(event_t* ev, uint64_t timeout) { uint64_t start = current_time_ms(); uint64_t now = start; for (;;) { uint64_t remain = timeout - (now - start); struct timespec ts; ts.tv_sec = remain / 1000; ts.tv_nsec = (remain % 1000) * 1000 * 1000; syscall(SYS_futex, &ev->state, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0, &ts); if (__atomic_load_n(&ev->state, __ATOMIC_RELAXED)) return 1; now = current_time_ms(); if (now - start > timeout) return 0; } } static bool write_file(const char* file, const char* what, ...) { char buf[1024]; va_list args; va_start(args, what); vsnprintf(buf, sizeof(buf), what, args); va_end(args); buf[sizeof(buf) - 1] = 0; int len = strlen(buf); int fd = open(file, O_WRONLY | O_CLOEXEC); if (fd == -1) return false; if (write(fd, buf, len) != len) { int err = errno; close(fd); errno = err; return false; } close(fd); return true; } static struct { char* pos; int nesting; struct nlattr* nested[8]; char buf[1024]; } nlmsg; static void netlink_init(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(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 void netlink_nest(int typ) { struct nlattr* attr = (struct nlattr*)nlmsg.pos; attr->nla_type = typ; nlmsg.pos += sizeof(*attr); nlmsg.nested[nlmsg.nesting++] = attr; } static void netlink_done(void) { struct nlattr* attr = nlmsg.nested[--nlmsg.nesting]; attr->nla_len = nlmsg.pos - (char*)attr; } static int netlink_send(int sock) { 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 (n < sizeof(struct nlmsghdr) + sizeof(struct nlmsgerr)) exit(1); if (hdr->nlmsg_type != NLMSG_ERROR) exit(1); return -((struct nlmsgerr*)(hdr + 1))->error; } static void netlink_add_device_impl(const char* type, const char* name) { struct ifinfomsg hdr; memset(&hdr, 0, sizeof(hdr)); netlink_init(RTM_NEWLINK, NLM_F_EXCL | NLM_F_CREATE, &hdr, sizeof(hdr)); if (name) netlink_attr(IFLA_IFNAME, name, strlen(name)); netlink_nest(IFLA_LINKINFO); netlink_attr(IFLA_INFO_KIND, type, strlen(type)); } static void netlink_add_device(int sock, const char* type, const char* name) { netlink_add_device_impl(type, name); netlink_done(); int err = netlink_send(sock); (void)err; } static void netlink_add_veth(int sock, const char* name, const char* peer) { netlink_add_device_impl("veth", name); netlink_nest(IFLA_INFO_DATA); netlink_nest(VETH_INFO_PEER); nlmsg.pos += sizeof(struct ifinfomsg); netlink_attr(IFLA_IFNAME, peer, strlen(peer)); netlink_done(); netlink_done(); netlink_done(); int err = netlink_send(sock); (void)err; } static void netlink_add_hsr(int sock, const char* name, const char* slave1, const char* slave2) { netlink_add_device_impl("hsr", name); netlink_nest(IFLA_INFO_DATA); int ifindex1 = if_nametoindex(slave1); netlink_attr(IFLA_HSR_SLAVE1, &ifindex1, sizeof(ifindex1)); int ifindex2 = if_nametoindex(slave2); netlink_attr(IFLA_HSR_SLAVE2, &ifindex2, sizeof(ifindex2)); netlink_done(); netlink_done(); int err = netlink_send(sock); (void)err; } static void netlink_device_change(int sock, const char* name, bool up, const char* master, const void* mac, int macsize) { struct ifinfomsg hdr; memset(&hdr, 0, sizeof(hdr)); if (up) hdr.ifi_flags = hdr.ifi_change = IFF_UP; netlink_init(RTM_NEWLINK, 0, &hdr, sizeof(hdr)); netlink_attr(IFLA_IFNAME, name, strlen(name)); if (master) { int ifindex = if_nametoindex(master); netlink_attr(IFLA_MASTER, &ifindex, sizeof(ifindex)); } if (macsize) netlink_attr(IFLA_ADDRESS, mac, macsize); int err = netlink_send(sock); (void)err; } static int netlink_add_addr(int sock, const char* dev, const void* addr, int addrsize) { struct ifaddrmsg hdr; memset(&hdr, 0, sizeof(hdr)); hdr.ifa_family = addrsize == 4 ? AF_INET : AF_INET6; hdr.ifa_prefixlen = addrsize == 4 ? 24 : 120; hdr.ifa_scope = RT_SCOPE_UNIVERSE; hdr.ifa_index = if_nametoindex(dev); netlink_init(RTM_NEWADDR, NLM_F_CREATE | NLM_F_REPLACE, &hdr, sizeof(hdr)); netlink_attr(IFA_LOCAL, addr, addrsize); netlink_attr(IFA_ADDRESS, addr, addrsize); return netlink_send(sock); } static void netlink_add_addr4(int sock, const char* dev, const char* addr) { struct in_addr in_addr; inet_pton(AF_INET, addr, &in_addr); int err = netlink_add_addr(sock, dev, &in_addr, sizeof(in_addr)); (void)err; } static void netlink_add_addr6(int sock, const char* dev, const char* addr) { struct in6_addr in6_addr; inet_pton(AF_INET6, addr, &in6_addr); int err = netlink_add_addr(sock, dev, &in6_addr, sizeof(in6_addr)); (void)err; } static void netlink_add_neigh(int sock, const char* name, const void* addr, int addrsize, const void* mac, int macsize) { struct ndmsg hdr; memset(&hdr, 0, sizeof(hdr)); hdr.ndm_family = addrsize == 4 ? AF_INET : AF_INET6; hdr.ndm_ifindex = if_nametoindex(name); hdr.ndm_state = NUD_PERMANENT; netlink_init(RTM_NEWNEIGH, NLM_F_EXCL | NLM_F_CREATE, &hdr, sizeof(hdr)); netlink_attr(NDA_DST, addr, addrsize); netlink_attr(NDA_LLADDR, mac, macsize); int err = netlink_send(sock); (void)err; } static int tunfd = -1; static int tun_frags_enabled; #define SYZ_TUN_MAX_PACKET_SIZE 1000 #define TUN_IFACE "syz_tun" #define LOCAL_MAC 0xaaaaaaaaaaaa #define REMOTE_MAC 0xaaaaaaaaaabb #define LOCAL_IPV4 "172.20.20.170" #define REMOTE_IPV4 "172.20.20.187" #define LOCAL_IPV6 "fe80::aa" #define REMOTE_IPV6 "fe80::bb" #define IFF_NAPI 0x0010 #define IFF_NAPI_FRAGS 0x0020 static void initialize_tun(void) { tunfd = open("/dev/net/tun", O_RDWR | O_NONBLOCK); if (tunfd == -1) { printf("tun: can't open /dev/net/tun: please enable CONFIG_TUN=y\n"); printf("otherwise fuzzing or reproducing might not work as intended\n"); return; } const int kTunFd = 240; if (dup2(tunfd, kTunFd) < 0) exit(1); close(tunfd); tunfd = kTunFd; struct ifreq ifr; memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, TUN_IFACE, IFNAMSIZ); ifr.ifr_flags = IFF_TAP | IFF_NO_PI | IFF_NAPI | IFF_NAPI_FRAGS; if (ioctl(tunfd, TUNSETIFF, (void*)&ifr) < 0) { ifr.ifr_flags = IFF_TAP | IFF_NO_PI; if (ioctl(tunfd, TUNSETIFF, (void*)&ifr) < 0) exit(1); } if (ioctl(tunfd, TUNGETIFF, (void*)&ifr) < 0) exit(1); tun_frags_enabled = (ifr.ifr_flags & IFF_NAPI_FRAGS) != 0; char sysctl[64]; sprintf(sysctl, "/proc/sys/net/ipv6/conf/%s/accept_dad", TUN_IFACE); write_file(sysctl, "0"); sprintf(sysctl, "/proc/sys/net/ipv6/conf/%s/router_solicitations", TUN_IFACE); write_file(sysctl, "0"); int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (sock == -1) exit(1); netlink_add_addr4(sock, TUN_IFACE, LOCAL_IPV4); netlink_add_addr6(sock, TUN_IFACE, LOCAL_IPV6); uint64_t macaddr = REMOTE_MAC; struct in_addr in_addr; inet_pton(AF_INET, REMOTE_IPV4, &in_addr); netlink_add_neigh(sock, TUN_IFACE, &in_addr, sizeof(in_addr), &macaddr, ETH_ALEN); struct in6_addr in6_addr; inet_pton(AF_INET6, REMOTE_IPV6, &in6_addr); netlink_add_neigh(sock, TUN_IFACE, &in6_addr, sizeof(in6_addr), &macaddr, ETH_ALEN); macaddr = LOCAL_MAC; netlink_device_change(sock, TUN_IFACE, true, 0, &macaddr, ETH_ALEN); close(sock); } #define DEV_IPV4 "172.20.20.%d" #define DEV_IPV6 "fe80::%02x" #define DEV_MAC 0x00aaaaaaaaaa static void initialize_netdevices(void) { char netdevsim[16]; sprintf(netdevsim, "netdevsim%d", (int)procid); struct { const char* type; const char* dev; } devtypes[] = { {"ip6gretap", "ip6gretap0"}, {"bridge", "bridge0"}, {"vcan", "vcan0"}, {"bond", "bond0"}, {"team", "team0"}, {"dummy", "dummy0"}, {"nlmon", "nlmon0"}, {"caif", "caif0"}, {"batadv", "batadv0"}, {"vxcan", "vxcan1"}, {"netdevsim", netdevsim}, {"veth", 0}, }; const char* devmasters[] = {"bridge", "bond", "team"}; struct { const char* name; int macsize; bool noipv6; } devices[] = { {"lo", ETH_ALEN}, {"sit0", 0}, {"bridge0", ETH_ALEN}, {"vcan0", 0, true}, {"tunl0", 0}, {"gre0", 0}, {"gretap0", ETH_ALEN}, {"ip_vti0", 0}, {"ip6_vti0", 0}, {"ip6tnl0", 0}, {"ip6gre0", 0}, {"ip6gretap0", ETH_ALEN}, {"erspan0", ETH_ALEN}, {"bond0", ETH_ALEN}, {"veth0", ETH_ALEN}, {"veth1", ETH_ALEN}, {"team0", ETH_ALEN}, {"veth0_to_bridge", ETH_ALEN}, {"veth1_to_bridge", ETH_ALEN}, {"veth0_to_bond", ETH_ALEN}, {"veth1_to_bond", ETH_ALEN}, {"veth0_to_team", ETH_ALEN}, {"veth1_to_team", ETH_ALEN}, {"veth0_to_hsr", ETH_ALEN}, {"veth1_to_hsr", ETH_ALEN}, {"hsr0", 0}, {"dummy0", ETH_ALEN}, {"nlmon0", 0}, {"vxcan1", 0, true}, {"caif0", ETH_ALEN}, {"batadv0", ETH_ALEN}, {netdevsim, ETH_ALEN}, }; int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (sock == -1) exit(1); unsigned i; for (i = 0; i < sizeof(devtypes) / sizeof(devtypes[0]); i++) netlink_add_device(sock, devtypes[i].type, devtypes[i].dev); for (i = 0; i < sizeof(devmasters) / (sizeof(devmasters[0])); i++) { char master[32], slave0[32], veth0[32], slave1[32], veth1[32]; sprintf(slave0, "%s_slave_0", devmasters[i]); sprintf(veth0, "veth0_to_%s", devmasters[i]); netlink_add_veth(sock, slave0, veth0); sprintf(slave1, "%s_slave_1", devmasters[i]); sprintf(veth1, "veth1_to_%s", devmasters[i]); netlink_add_veth(sock, slave1, veth1); sprintf(master, "%s0", devmasters[i]); netlink_device_change(sock, slave0, false, master, 0, 0); netlink_device_change(sock, slave1, false, master, 0, 0); } netlink_device_change(sock, "bridge_slave_0", true, 0, 0, 0); netlink_device_change(sock, "bridge_slave_1", true, 0, 0, 0); netlink_add_veth(sock, "hsr_slave_0", "veth0_to_hsr"); netlink_add_veth(sock, "hsr_slave_1", "veth1_to_hsr"); netlink_add_hsr(sock, "hsr0", "hsr_slave_0", "hsr_slave_1"); netlink_device_change(sock, "hsr_slave_0", true, 0, 0, 0); netlink_device_change(sock, "hsr_slave_1", true, 0, 0, 0); for (i = 0; i < sizeof(devices) / (sizeof(devices[0])); i++) { char addr[32]; sprintf(addr, DEV_IPV4, i + 10); netlink_add_addr4(sock, devices[i].name, addr); if (!devices[i].noipv6) { sprintf(addr, DEV_IPV6, i + 10); netlink_add_addr6(sock, devices[i].name, addr); } uint64_t macaddr = DEV_MAC + ((i + 10ull) << 40); netlink_device_change(sock, devices[i].name, true, 0, &macaddr, devices[i].macsize); } close(sock); } static void initialize_netdevices_init(void) { int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (sock == -1) exit(1); struct { const char* type; int macsize; bool noipv6; bool noup; } devtypes[] = { {"nr", 7, true}, {"rose", 5, true, true}, }; unsigned i; for (i = 0; i < sizeof(devtypes) / sizeof(devtypes[0]); i++) { char dev[32], addr[32]; sprintf(dev, "%s%d", devtypes[i].type, (int)procid); sprintf(addr, "172.30.%d.%d", i, (int)procid + 1); netlink_add_addr4(sock, dev, addr); if (!devtypes[i].noipv6) { sprintf(addr, "fe88::%02x:%02x", i, (int)procid + 1); netlink_add_addr6(sock, dev, addr); } int macsize = devtypes[i].macsize; uint64_t macaddr = 0xbbbbbb + ((unsigned long long)i << (8 * (macsize - 2))) + (procid << (8 * (macsize - 1))); netlink_device_change(sock, dev, !devtypes[i].noup, 0, &macaddr, macsize); } close(sock); } static int read_tun(char* data, int size) { if (tunfd < 0) return -1; int rv = read(tunfd, data, size); if (rv < 0) { if (errno == EAGAIN) return -1; if (errno == EBADFD) return -1; exit(1); } return rv; } static void flush_tun() { char data[SYZ_TUN_MAX_PACKET_SIZE]; while (read_tun(&data[0], sizeof(data)) != -1) { } } #define XT_TABLE_SIZE 1536 #define XT_MAX_ENTRIES 10 struct xt_counters { uint64_t pcnt, bcnt; }; struct ipt_getinfo { char name[32]; unsigned int valid_hooks; unsigned int hook_entry[5]; unsigned int underflow[5]; unsigned int num_entries; unsigned int size; }; struct ipt_get_entries { char name[32]; unsigned int size; void* entrytable[XT_TABLE_SIZE / sizeof(void*)]; }; struct ipt_replace { char name[32]; unsigned int valid_hooks; unsigned int num_entries; unsigned int size; unsigned int hook_entry[5]; unsigned int underflow[5]; unsigned int num_counters; struct xt_counters* counters; char entrytable[XT_TABLE_SIZE]; }; struct ipt_table_desc { const char* name; struct ipt_getinfo info; struct ipt_replace replace; }; static struct ipt_table_desc ipv4_tables[] = { {.name = "filter"}, {.name = "nat"}, {.name = "mangle"}, {.name = "raw"}, {.name = "security"}, }; static struct ipt_table_desc ipv6_tables[] = { {.name = "filter"}, {.name = "nat"}, {.name = "mangle"}, {.name = "raw"}, {.name = "security"}, }; #define IPT_BASE_CTL 64 #define IPT_SO_SET_REPLACE (IPT_BASE_CTL) #define IPT_SO_GET_INFO (IPT_BASE_CTL) #define IPT_SO_GET_ENTRIES (IPT_BASE_CTL + 1) struct arpt_getinfo { char name[32]; unsigned int valid_hooks; unsigned int hook_entry[3]; unsigned int underflow[3]; unsigned int num_entries; unsigned int size; }; struct arpt_get_entries { char name[32]; unsigned int size; void* entrytable[XT_TABLE_SIZE / sizeof(void*)]; }; struct arpt_replace { char name[32]; unsigned int valid_hooks; unsigned int num_entries; unsigned int size; unsigned int hook_entry[3]; unsigned int underflow[3]; unsigned int num_counters; struct xt_counters* counters; char entrytable[XT_TABLE_SIZE]; }; struct arpt_table_desc { const char* name; struct arpt_getinfo info; struct arpt_replace replace; }; static struct arpt_table_desc arpt_tables[] = { {.name = "filter"}, }; #define ARPT_BASE_CTL 96 #define ARPT_SO_SET_REPLACE (ARPT_BASE_CTL) #define ARPT_SO_GET_INFO (ARPT_BASE_CTL) #define ARPT_SO_GET_ENTRIES (ARPT_BASE_CTL + 1) static void checkpoint_iptables(struct ipt_table_desc* tables, int num_tables, int family, int level) { struct ipt_get_entries entries; socklen_t optlen; int fd, i; fd = socket(family, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (i = 0; i < num_tables; i++) { struct ipt_table_desc* table = &tables[i]; strcpy(table->info.name, table->name); strcpy(table->replace.name, table->name); optlen = sizeof(table->info); if (getsockopt(fd, level, IPT_SO_GET_INFO, &table->info, &optlen)) { switch (errno) { case EPERM: case ENOENT: case ENOPROTOOPT: continue; } exit(1); } if (table->info.size > sizeof(table->replace.entrytable)) exit(1); if (table->info.num_entries > XT_MAX_ENTRIES) exit(1); memset(&entries, 0, sizeof(entries)); strcpy(entries.name, table->name); entries.size = table->info.size; optlen = sizeof(entries) - sizeof(entries.entrytable) + table->info.size; if (getsockopt(fd, level, IPT_SO_GET_ENTRIES, &entries, &optlen)) exit(1); table->replace.valid_hooks = table->info.valid_hooks; table->replace.num_entries = table->info.num_entries; table->replace.size = table->info.size; memcpy(table->replace.hook_entry, table->info.hook_entry, sizeof(table->replace.hook_entry)); memcpy(table->replace.underflow, table->info.underflow, sizeof(table->replace.underflow)); memcpy(table->replace.entrytable, entries.entrytable, table->info.size); } close(fd); } static void reset_iptables(struct ipt_table_desc* tables, int num_tables, int family, int level) { struct xt_counters counters[XT_MAX_ENTRIES]; struct ipt_get_entries entries; struct ipt_getinfo info; socklen_t optlen; int fd, i; fd = socket(family, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (i = 0; i < num_tables; i++) { struct ipt_table_desc* table = &tables[i]; if (table->info.valid_hooks == 0) continue; memset(&info, 0, sizeof(info)); strcpy(info.name, table->name); optlen = sizeof(info); if (getsockopt(fd, level, IPT_SO_GET_INFO, &info, &optlen)) exit(1); if (memcmp(&table->info, &info, sizeof(table->info)) == 0) { memset(&entries, 0, sizeof(entries)); strcpy(entries.name, table->name); entries.size = table->info.size; optlen = sizeof(entries) - sizeof(entries.entrytable) + entries.size; if (getsockopt(fd, level, IPT_SO_GET_ENTRIES, &entries, &optlen)) exit(1); if (memcmp(table->replace.entrytable, entries.entrytable, table->info.size) == 0) continue; } table->replace.num_counters = info.num_entries; table->replace.counters = counters; optlen = sizeof(table->replace) - sizeof(table->replace.entrytable) + table->replace.size; if (setsockopt(fd, level, IPT_SO_SET_REPLACE, &table->replace, optlen)) exit(1); } close(fd); } static void checkpoint_arptables(void) { struct arpt_get_entries entries; socklen_t optlen; unsigned i; int fd; fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (i = 0; i < sizeof(arpt_tables) / sizeof(arpt_tables[0]); i++) { struct arpt_table_desc* table = &arpt_tables[i]; strcpy(table->info.name, table->name); strcpy(table->replace.name, table->name); optlen = sizeof(table->info); if (getsockopt(fd, SOL_IP, ARPT_SO_GET_INFO, &table->info, &optlen)) { switch (errno) { case EPERM: case ENOENT: case ENOPROTOOPT: continue; } exit(1); } if (table->info.size > sizeof(table->replace.entrytable)) exit(1); if (table->info.num_entries > XT_MAX_ENTRIES) exit(1); memset(&entries, 0, sizeof(entries)); strcpy(entries.name, table->name); entries.size = table->info.size; optlen = sizeof(entries) - sizeof(entries.entrytable) + table->info.size; if (getsockopt(fd, SOL_IP, ARPT_SO_GET_ENTRIES, &entries, &optlen)) exit(1); table->replace.valid_hooks = table->info.valid_hooks; table->replace.num_entries = table->info.num_entries; table->replace.size = table->info.size; memcpy(table->replace.hook_entry, table->info.hook_entry, sizeof(table->replace.hook_entry)); memcpy(table->replace.underflow, table->info.underflow, sizeof(table->replace.underflow)); memcpy(table->replace.entrytable, entries.entrytable, table->info.size); } close(fd); } static void reset_arptables() { struct xt_counters counters[XT_MAX_ENTRIES]; struct arpt_get_entries entries; struct arpt_getinfo info; socklen_t optlen; unsigned i; int fd; fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (i = 0; i < sizeof(arpt_tables) / sizeof(arpt_tables[0]); i++) { struct arpt_table_desc* table = &arpt_tables[i]; if (table->info.valid_hooks == 0) continue; memset(&info, 0, sizeof(info)); strcpy(info.name, table->name); optlen = sizeof(info); if (getsockopt(fd, SOL_IP, ARPT_SO_GET_INFO, &info, &optlen)) exit(1); if (memcmp(&table->info, &info, sizeof(table->info)) == 0) { memset(&entries, 0, sizeof(entries)); strcpy(entries.name, table->name); entries.size = table->info.size; optlen = sizeof(entries) - sizeof(entries.entrytable) + entries.size; if (getsockopt(fd, SOL_IP, ARPT_SO_GET_ENTRIES, &entries, &optlen)) exit(1); if (memcmp(table->replace.entrytable, entries.entrytable, table->info.size) == 0) continue; } else { } table->replace.num_counters = info.num_entries; table->replace.counters = counters; optlen = sizeof(table->replace) - sizeof(table->replace.entrytable) + table->replace.size; if (setsockopt(fd, SOL_IP, ARPT_SO_SET_REPLACE, &table->replace, optlen)) exit(1); } close(fd); } #define NF_BR_NUMHOOKS 6 #define EBT_TABLE_MAXNAMELEN 32 #define EBT_CHAIN_MAXNAMELEN 32 #define EBT_BASE_CTL 128 #define EBT_SO_SET_ENTRIES (EBT_BASE_CTL) #define EBT_SO_GET_INFO (EBT_BASE_CTL) #define EBT_SO_GET_ENTRIES (EBT_SO_GET_INFO + 1) #define EBT_SO_GET_INIT_INFO (EBT_SO_GET_ENTRIES + 1) #define EBT_SO_GET_INIT_ENTRIES (EBT_SO_GET_INIT_INFO + 1) struct ebt_replace { char name[EBT_TABLE_MAXNAMELEN]; unsigned int valid_hooks; unsigned int nentries; unsigned int entries_size; struct ebt_entries* hook_entry[NF_BR_NUMHOOKS]; unsigned int num_counters; struct ebt_counter* counters; char* entries; }; struct ebt_entries { unsigned int distinguisher; char name[EBT_CHAIN_MAXNAMELEN]; unsigned int counter_offset; int policy; unsigned int nentries; char data[0] __attribute__((aligned(__alignof__(struct ebt_replace)))); }; struct ebt_table_desc { const char* name; struct ebt_replace replace; char entrytable[XT_TABLE_SIZE]; }; static struct ebt_table_desc ebt_tables[] = { {.name = "filter"}, {.name = "nat"}, {.name = "broute"}, }; static void checkpoint_ebtables(void) { socklen_t optlen; unsigned i; int fd; fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (i = 0; i < sizeof(ebt_tables) / sizeof(ebt_tables[0]); i++) { struct ebt_table_desc* table = &ebt_tables[i]; strcpy(table->replace.name, table->name); optlen = sizeof(table->replace); if (getsockopt(fd, SOL_IP, EBT_SO_GET_INIT_INFO, &table->replace, &optlen)) { switch (errno) { case EPERM: case ENOENT: case ENOPROTOOPT: continue; } exit(1); } if (table->replace.entries_size > sizeof(table->entrytable)) exit(1); table->replace.num_counters = 0; table->replace.entries = table->entrytable; optlen = sizeof(table->replace) + table->replace.entries_size; if (getsockopt(fd, SOL_IP, EBT_SO_GET_INIT_ENTRIES, &table->replace, &optlen)) exit(1); } close(fd); } static void reset_ebtables() { struct ebt_replace replace; char entrytable[XT_TABLE_SIZE]; socklen_t optlen; unsigned i, j, h; int fd; fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } exit(1); } for (i = 0; i < sizeof(ebt_tables) / sizeof(ebt_tables[0]); i++) { struct ebt_table_desc* table = &ebt_tables[i]; if (table->replace.valid_hooks == 0) continue; memset(&replace, 0, sizeof(replace)); strcpy(replace.name, table->name); optlen = sizeof(replace); if (getsockopt(fd, SOL_IP, EBT_SO_GET_INFO, &replace, &optlen)) exit(1); replace.num_counters = 0; table->replace.entries = 0; for (h = 0; h < NF_BR_NUMHOOKS; h++) table->replace.hook_entry[h] = 0; if (memcmp(&table->replace, &replace, sizeof(table->replace)) == 0) { memset(&entrytable, 0, sizeof(entrytable)); replace.entries = entrytable; optlen = sizeof(replace) + replace.entries_size; if (getsockopt(fd, SOL_IP, EBT_SO_GET_ENTRIES, &replace, &optlen)) exit(1); if (memcmp(table->entrytable, entrytable, replace.entries_size) == 0) continue; } for (j = 0, h = 0; h < NF_BR_NUMHOOKS; h++) { if (table->replace.valid_hooks & (1 << h)) { table->replace.hook_entry[h] = (struct ebt_entries*)table->entrytable + j; j++; } } table->replace.entries = table->entrytable; optlen = sizeof(table->replace) + table->replace.entries_size; if (setsockopt(fd, SOL_IP, EBT_SO_SET_ENTRIES, &table->replace, optlen)) exit(1); } close(fd); } static void checkpoint_net_namespace(void) { checkpoint_ebtables(); checkpoint_arptables(); checkpoint_iptables(ipv4_tables, sizeof(ipv4_tables) / sizeof(ipv4_tables[0]), AF_INET, SOL_IP); checkpoint_iptables(ipv6_tables, sizeof(ipv6_tables) / sizeof(ipv6_tables[0]), AF_INET6, SOL_IPV6); } static void reset_net_namespace(void) { reset_ebtables(); reset_arptables(); reset_iptables(ipv4_tables, sizeof(ipv4_tables) / sizeof(ipv4_tables[0]), AF_INET, SOL_IP); reset_iptables(ipv6_tables, sizeof(ipv6_tables) / sizeof(ipv6_tables[0]), AF_INET6, SOL_IPV6); } static void setup_cgroups() { if (mkdir("/syzcgroup", 0777)) { } if (mkdir("/syzcgroup/unified", 0777)) { } if (mount("none", "/syzcgroup/unified", "cgroup2", 0, NULL)) { } if (chmod("/syzcgroup/unified", 0777)) { } write_file("/syzcgroup/unified/cgroup.subtree_control", "+cpu +memory +io +pids +rdma"); if (mkdir("/syzcgroup/cpu", 0777)) { } if (mount("none", "/syzcgroup/cpu", "cgroup", 0, "cpuset,cpuacct,perf_event,hugetlb")) { } write_file("/syzcgroup/cpu/cgroup.clone_children", "1"); if (chmod("/syzcgroup/cpu", 0777)) { } if (mkdir("/syzcgroup/net", 0777)) { } if (mount("none", "/syzcgroup/net", "cgroup", 0, "net_cls,net_prio,devices,freezer")) { } if (chmod("/syzcgroup/net", 0777)) { } } static void setup_cgroups_loop() { int pid = getpid(); char file[128]; char cgroupdir[64]; snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/unified/syz%llu", procid); if (mkdir(cgroupdir, 0777)) { } snprintf(file, sizeof(file), "%s/pids.max", cgroupdir); write_file(file, "32"); snprintf(file, sizeof(file), "%s/memory.low", cgroupdir); write_file(file, "%d", 298 << 20); snprintf(file, sizeof(file), "%s/memory.high", cgroupdir); write_file(file, "%d", 299 << 20); snprintf(file, sizeof(file), "%s/memory.max", cgroupdir); write_file(file, "%d", 300 << 20); snprintf(file, sizeof(file), "%s/cgroup.procs", cgroupdir); write_file(file, "%d", pid); snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/cpu/syz%llu", procid); if (mkdir(cgroupdir, 0777)) { } snprintf(file, sizeof(file), "%s/cgroup.procs", cgroupdir); write_file(file, "%d", pid); snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/net/syz%llu", procid); if (mkdir(cgroupdir, 0777)) { } snprintf(file, sizeof(file), "%s/cgroup.procs", cgroupdir); write_file(file, "%d", pid); } static void setup_cgroups_test() { char cgroupdir[64]; snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/unified/syz%llu", procid); if (symlink(cgroupdir, "./cgroup")) { } snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/cpu/syz%llu", procid); if (symlink(cgroupdir, "./cgroup.cpu")) { } snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/net/syz%llu", procid); if (symlink(cgroupdir, "./cgroup.net")) { } } static void setup_common() { if (mount(0, "/sys/fs/fuse/connections", "fusectl", 0, 0)) { } setup_cgroups(); } static void loop(); static void sandbox_common() { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); setpgrp(); setsid(); struct rlimit rlim; rlim.rlim_cur = rlim.rlim_max = (200 << 20); setrlimit(RLIMIT_AS, &rlim); rlim.rlim_cur = rlim.rlim_max = 32 << 20; setrlimit(RLIMIT_MEMLOCK, &rlim); rlim.rlim_cur = rlim.rlim_max = 136 << 20; setrlimit(RLIMIT_FSIZE, &rlim); rlim.rlim_cur = rlim.rlim_max = 1 << 20; setrlimit(RLIMIT_STACK, &rlim); rlim.rlim_cur = rlim.rlim_max = 0; setrlimit(RLIMIT_CORE, &rlim); rlim.rlim_cur = rlim.rlim_max = 256; setrlimit(RLIMIT_NOFILE, &rlim); if (unshare(CLONE_NEWNS)) { } if (unshare(CLONE_NEWIPC)) { } if (unshare(0x02000000)) { } if (unshare(CLONE_NEWUTS)) { } if (unshare(CLONE_SYSVSEM)) { } typedef struct { const char* name; const char* value; } sysctl_t; static const sysctl_t sysctls[] = { {"/proc/sys/kernel/shmmax", "16777216"}, {"/proc/sys/kernel/shmall", "536870912"}, {"/proc/sys/kernel/shmmni", "1024"}, {"/proc/sys/kernel/msgmax", "8192"}, {"/proc/sys/kernel/msgmni", "1024"}, {"/proc/sys/kernel/msgmnb", "1024"}, {"/proc/sys/kernel/sem", "1024 1048576 500 1024"}, }; unsigned i; for (i = 0; i < sizeof(sysctls) / sizeof(sysctls[0]); i++) write_file(sysctls[i].name, sysctls[i].value); } int wait_for_loop(int pid) { if (pid < 0) exit(1); int status = 0; while (waitpid(-1, &status, __WALL) != pid) { } return WEXITSTATUS(status); } static int do_sandbox_none(void) { if (unshare(CLONE_NEWPID)) { } int pid = fork(); if (pid != 0) return wait_for_loop(pid); setup_common(); sandbox_common(); initialize_netdevices_init(); if (unshare(CLONE_NEWNET)) { } initialize_tun(); initialize_netdevices(); loop(); exit(1); } #define FS_IOC_SETFLAGS _IOW('f', 2, long) static void remove_dir(const char* dir) { DIR* dp; struct dirent* ep; int iter = 0; retry: while (umount2(dir, MNT_DETACH) == 0) { } dp = opendir(dir); if (dp == NULL) { if (errno == EMFILE) { exit(1); } exit(1); } while ((ep = readdir(dp))) { if (strcmp(ep->d_name, ".") == 0 || strcmp(ep->d_name, "..") == 0) continue; char filename[FILENAME_MAX]; snprintf(filename, sizeof(filename), "%s/%s", dir, ep->d_name); while (umount2(filename, MNT_DETACH) == 0) { } struct stat st; if (lstat(filename, &st)) exit(1); if (S_ISDIR(st.st_mode)) { remove_dir(filename); continue; } int i; for (i = 0;; i++) { if (unlink(filename) == 0) break; if (errno == EPERM) { int fd = open(filename, O_RDONLY); if (fd != -1) { long flags = 0; if (ioctl(fd, FS_IOC_SETFLAGS, &flags) == 0) close(fd); continue; } } if (errno == EROFS) { break; } if (errno != EBUSY || i > 100) exit(1); if (umount2(filename, MNT_DETACH)) exit(1); } } closedir(dp); int i; for (i = 0;; i++) { if (rmdir(dir) == 0) break; if (i < 100) { if (errno == EPERM) { int fd = open(dir, O_RDONLY); if (fd != -1) { long flags = 0; if (ioctl(fd, FS_IOC_SETFLAGS, &flags) == 0) close(fd); continue; } } if (errno == EROFS) { break; } if (errno == EBUSY) { if (umount2(dir, MNT_DETACH)) exit(1); continue; } if (errno == ENOTEMPTY) { if (iter < 100) { iter++; goto retry; } } } exit(1); } } 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_loop() { setup_cgroups_loop(); checkpoint_net_namespace(); } static void reset_loop() { reset_net_namespace(); } static void setup_test() { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); setpgrp(); setup_cgroups_test(); write_file("/proc/self/oom_score_adj", "1000"); flush_tun(); } static void close_fds() { int fd; for (fd = 3; fd < 30; fd++) close(fd); } static void setup_binfmt_misc() { if (mount(0, "/proc/sys/fs/binfmt_misc", "binfmt_misc", 0, 0)) { } write_file("/proc/sys/fs/binfmt_misc/register", ":syz0:M:0:\x01::./file0:"); write_file("/proc/sys/fs/binfmt_misc/register", ":syz1:M:1:\x02::./file0:POC"); } struct thread_t { int created, call; event_t ready, done; }; static struct thread_t threads[16]; static void execute_call(int call); static int running; static void* thr(void* arg) { struct thread_t* th = (struct thread_t*)arg; for (;;) { event_wait(&th->ready); event_reset(&th->ready); execute_call(th->call); __atomic_fetch_sub(&running, 1, __ATOMIC_RELAXED); event_set(&th->done); } return 0; } static void execute_one(void) { int i, call, thread; int collide = 0; again: for (call = 0; call < 5; call++) { for (thread = 0; thread < (int)(sizeof(threads) / sizeof(threads[0])); thread++) { struct thread_t* th = &threads[thread]; if (!th->created) { th->created = 1; event_init(&th->ready); event_init(&th->done); event_set(&th->done); thread_start(thr, th); } if (!event_isset(&th->done)) continue; event_reset(&th->done); th->call = call; __atomic_fetch_add(&running, 1, __ATOMIC_RELAXED); event_set(&th->ready); if (collide && (call % 2) == 0) break; event_timedwait(&th->done, 45); break; } } for (i = 0; i < 100 && __atomic_load_n(&running, __ATOMIC_RELAXED); i++) sleep_ms(1); close_fds(); if (!collide) { collide = 1; goto again; } } static void execute_one(void); #define WAIT_FLAGS __WALL static void loop(void) { setup_loop(); int iter; for (iter = 0;; iter++) { char cwdbuf[32]; sprintf(cwdbuf, "./%d", iter); if (mkdir(cwdbuf, 0777)) exit(1); reset_loop(); int pid = fork(); if (pid < 0) exit(1); if (pid == 0) { if (chdir(cwdbuf)) exit(1); 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; } remove_dir(cwdbuf); } } uint64_t r[3] = {0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff}; void execute_call(int call) { intptr_t res; switch (call) { case 0: NONFAILING(memcpy((void*)0x20000380, "/dev/infiniband/rdma_cm\000", 24)); res = syscall(__NR_openat, 0xffffffffffffff9c, 0x20000380, 2, 0); if (res != -1) r[0] = res; break; case 1: NONFAILING(*(uint32_t*)0x20000200 = 0); NONFAILING(*(uint16_t*)0x20000204 = 0x18); NONFAILING(*(uint16_t*)0x20000206 = 0xfa00); NONFAILING(*(uint64_t*)0x20000208 = 0); NONFAILING(*(uint64_t*)0x20000210 = 0x20000040); NONFAILING(*(uint16_t*)0x20000218 = 0x106); NONFAILING(*(uint8_t*)0x2000021a = 0); NONFAILING(*(uint8_t*)0x2000021b = 0); NONFAILING(*(uint8_t*)0x2000021c = 0); NONFAILING(*(uint8_t*)0x2000021d = 0); NONFAILING(*(uint8_t*)0x2000021e = 0); NONFAILING(*(uint8_t*)0x2000021f = 0); res = syscall(__NR_write, r[0], 0x20000200, 0x20); if (res != -1) NONFAILING(r[1] = *(uint32_t*)0x20000040); break; case 2: NONFAILING(memcpy((void*)0x200001c0, "/dev/infiniband/rdma_cm\000", 24)); res = syscall(__NR_openat, 0xffffffffffffff9c, 0x200001c0, 2, 0); if (res != -1) r[2] = res; break; case 3: NONFAILING(*(uint32_t*)0x20000080 = 0x12); NONFAILING(*(uint16_t*)0x20000084 = 0x10); NONFAILING(*(uint16_t*)0x20000086 = 0xfa00); NONFAILING(*(uint64_t*)0x20000088 = 0); NONFAILING(*(uint32_t*)0x20000090 = r[1]); NONFAILING(*(uint32_t*)0x20000094 = r[0]); syscall(__NR_write, r[2], 0x20000080, 0x18); break; case 4: NONFAILING(*(uint32_t*)0x20000100 = 1); NONFAILING(*(uint16_t*)0x20000104 = 0x10); NONFAILING(*(uint16_t*)0x20000106 = 0xfa00); NONFAILING(*(uint64_t*)0x20000108 = 0); NONFAILING(*(uint32_t*)0x20000110 = r[1]); NONFAILING(*(uint32_t*)0x20000114 = 0); syscall(__NR_write, r[0], 0x20000100, 0x20000118); break; } } int main(void) { syscall(__NR_mmap, 0x20000000, 0x1000000, 3, 0x32, -1, 0); setup_binfmt_misc(); install_segv_handler(); use_temporary_dir(); do_sandbox_none(); return 0; }
the_stack_data/140212.c
/* ============================================================================ Name : ArbitraryPrecision.c Author : Version : Copyright : Your copyright notice Description : In computer science, arbitrary-precision arithmetic, also called bignum arithmetic, multiple precision arithmetic, or sometimes infinite-precision arithmetic, indicates that calculations are performed on numbers whose digits of precision are limited only by the available memory of the host system. This contrasts with the faster fixed-precision arithmetic found in most arithmetic logic unit (ALU) hardware, which typically offers between 8 and 64 bits of precision. ============================================================================ */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define DATA_SIZE 1205 void printArray(unsigned char data[], int n, int maxPos) { int i; printf(", %4d: ", maxPos); for (i = n - 1; i >= 0; i--) { if (i <= maxPos) { printf("%d", data[i]); } else { printf(" "); } } printf("\n"); } void ArbitraryPrecision_n(int base, int n) { unsigned char data[DATA_SIZE]; int i, j, maxPos; memset(data, 0, sizeof(data)); data[0] = 1; maxPos = 0; for (i = 0; i < n; i++) { printf("%4d", i); int increase = 0; for (j = 0; j <= maxPos; j++) { int temp = 0; if (data[j] > 0) { temp = data[j] * base; } temp += increase; increase = (temp >= 10) ? 1 : 0; data[j] = temp % 10; } if (increase == 1) { data[++maxPos] = 1; } printArray(data, sizeof(data), maxPos); if ((maxPos + 1) == DATA_SIZE) { break; } } } int main(void) { ArbitraryPrecision_n(2, 4000); return EXIT_SUCCESS; }
the_stack_data/37637063.c
#include <stdio.h> int main() { long long int n, p, q, a, b, c, doudou, i; while (scanf("%lld %lld %lld", &n, &p, &q) != EOF) { if (n <= p) printf("LOSE\n"); doudou = 0; for (i = p; i <= q; i++) { if ((n - i) % (p + q) <= p) { printf("WIN\n"); doudou = 1; break; } } if (doudou == 0) printf("LOSE\n"); } return 0; }
the_stack_data/182953506.c
/* f2c.h -- Standard Fortran to C header file */ /** barf [ba:rf] 2. "He suggested using FORTRAN, and everybody barfed." - From The Shogakukan DICTIONARY OF NEW ENGLISH (Second edition) */ #ifndef F2C_INCLUDE #define F2C_INCLUDE #include <math.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <complex.h> #ifdef complex #undef complex #endif #ifdef I #undef I #endif #if defined(_WIN64) typedef long long BLASLONG; typedef unsigned long long BLASULONG; #else typedef long BLASLONG; typedef unsigned long BLASULONG; #endif #ifdef LAPACK_ILP64 typedef BLASLONG blasint; #if defined(_WIN64) #define blasabs(x) llabs(x) #else #define blasabs(x) labs(x) #endif #else typedef int blasint; #define blasabs(x) abs(x) #endif typedef blasint integer; typedef unsigned int uinteger; typedef char *address; typedef short int shortint; typedef float real; typedef double doublereal; typedef struct { real r, i; } complex; typedef struct { doublereal r, i; } doublecomplex; static inline _Complex float Cf(complex *z) {return z->r + z->i*_Complex_I;} static inline _Complex double Cd(doublecomplex *z) {return z->r + z->i*_Complex_I;} static inline _Complex float * _pCf(complex *z) {return (_Complex float*)z;} static inline _Complex double * _pCd(doublecomplex *z) {return (_Complex double*)z;} #define pCf(z) (*_pCf(z)) #define pCd(z) (*_pCd(z)) typedef int logical; typedef short int shortlogical; typedef char logical1; typedef char integer1; #define TRUE_ (1) #define FALSE_ (0) /* Extern is for use with -E */ #ifndef Extern #define Extern extern #endif /* I/O stuff */ typedef int flag; typedef int ftnlen; typedef int ftnint; /*external read, write*/ typedef struct { flag cierr; ftnint ciunit; flag ciend; char *cifmt; ftnint cirec; } cilist; /*internal read, write*/ typedef struct { flag icierr; char *iciunit; flag iciend; char *icifmt; ftnint icirlen; ftnint icirnum; } icilist; /*open*/ typedef struct { flag oerr; ftnint ounit; char *ofnm; ftnlen ofnmlen; char *osta; char *oacc; char *ofm; ftnint orl; char *oblnk; } olist; /*close*/ typedef struct { flag cerr; ftnint cunit; char *csta; } cllist; /*rewind, backspace, endfile*/ typedef struct { flag aerr; ftnint aunit; } alist; /* inquire */ typedef struct { flag inerr; ftnint inunit; char *infile; ftnlen infilen; ftnint *inex; /*parameters in standard's order*/ ftnint *inopen; ftnint *innum; ftnint *innamed; char *inname; ftnlen innamlen; char *inacc; ftnlen inacclen; char *inseq; ftnlen inseqlen; char *indir; ftnlen indirlen; char *infmt; ftnlen infmtlen; char *inform; ftnint informlen; char *inunf; ftnlen inunflen; ftnint *inrecl; ftnint *innrec; char *inblank; ftnlen inblanklen; } inlist; #define VOID void union Multitype { /* for multiple entry points */ integer1 g; shortint h; integer i; /* longint j; */ real r; doublereal d; complex c; doublecomplex z; }; typedef union Multitype Multitype; struct Vardesc { /* for Namelist */ char *name; char *addr; ftnlen *dims; int type; }; typedef struct Vardesc Vardesc; struct Namelist { char *name; Vardesc **vars; int nvars; }; typedef struct Namelist Namelist; #define abs(x) ((x) >= 0 ? (x) : -(x)) #define dabs(x) (fabs(x)) #define f2cmin(a,b) ((a) <= (b) ? (a) : (b)) #define f2cmax(a,b) ((a) >= (b) ? (a) : (b)) #define dmin(a,b) (f2cmin(a,b)) #define dmax(a,b) (f2cmax(a,b)) #define bit_test(a,b) ((a) >> (b) & 1) #define bit_clear(a,b) ((a) & ~((uinteger)1 << (b))) #define bit_set(a,b) ((a) | ((uinteger)1 << (b))) #define abort_() { sig_die("Fortran abort routine called", 1); } #define c_abs(z) (cabsf(Cf(z))) #define c_cos(R,Z) { pCf(R)=ccos(Cf(Z)); } #define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);} #define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);} #define c_exp(R, Z) {pCf(R) = cexpf(Cf(Z));} #define c_log(R, Z) {pCf(R) = clogf(Cf(Z));} #define c_sin(R, Z) {pCf(R) = csinf(Cf(Z));} //#define c_sqrt(R, Z) {*(R) = csqrtf(Cf(Z));} #define c_sqrt(R, Z) {pCf(R) = csqrtf(Cf(Z));} #define d_abs(x) (fabs(*(x))) #define d_acos(x) (acos(*(x))) #define d_asin(x) (asin(*(x))) #define d_atan(x) (atan(*(x))) #define d_atn2(x, y) (atan2(*(x),*(y))) #define d_cnjg(R, Z) { pCd(R) = conj(Cd(Z)); } #define r_cnjg(R, Z) { pCf(R) = conj(Cf(Z)); } #define d_cos(x) (cos(*(x))) #define d_cosh(x) (cosh(*(x))) #define d_dim(__a, __b) ( *(__a) > *(__b) ? *(__a) - *(__b) : 0.0 ) #define d_exp(x) (exp(*(x))) #define d_imag(z) (cimag(Cd(z))) #define r_imag(z) (cimag(Cf(z))) #define d_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define r_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define d_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define r_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define d_log(x) (log(*(x))) #define d_mod(x, y) (fmod(*(x), *(y))) #define u_nint(__x) ((__x)>=0 ? floor((__x) + .5) : -floor(.5 - (__x))) #define d_nint(x) u_nint(*(x)) #define u_sign(__a,__b) ((__b) >= 0 ? ((__a) >= 0 ? (__a) : -(__a)) : -((__a) >= 0 ? (__a) : -(__a))) #define d_sign(a,b) u_sign(*(a),*(b)) #define r_sign(a,b) u_sign(*(a),*(b)) #define d_sin(x) (sin(*(x))) #define d_sinh(x) (sinh(*(x))) #define d_sqrt(x) (sqrt(*(x))) #define d_tan(x) (tan(*(x))) #define d_tanh(x) (tanh(*(x))) #define i_abs(x) abs(*(x)) #define i_dnnt(x) ((integer)u_nint(*(x))) #define i_len(s, n) (n) #define i_nint(x) ((integer)u_nint(*(x))) #define i_sign(a,b) ((integer)u_sign((integer)*(a),(integer)*(b))) #define pow_dd(ap, bp) ( pow(*(ap), *(bp))) #define pow_si(B,E) spow_ui(*(B),*(E)) #define pow_ri(B,E) spow_ui(*(B),*(E)) #define pow_di(B,E) dpow_ui(*(B),*(E)) #define pow_zi(p, a, b) {pCd(p) = zpow_ui(Cd(a), *(b));} #define pow_ci(p, a, b) {pCf(p) = cpow_ui(Cf(a), *(b));} #define pow_zz(R,A,B) {pCd(R) = cpow(Cd(A),*(B));} #define s_cat(lpp, rpp, rnp, np, llp) { ftnlen i, nc, ll; char *f__rp, *lp; ll = (llp); lp = (lpp); for(i=0; i < (int)*(np); ++i) { nc = ll; if((rnp)[i] < nc) nc = (rnp)[i]; ll -= nc; f__rp = (rpp)[i]; while(--nc >= 0) *lp++ = *(f__rp)++; } while(--ll >= 0) *lp++ = ' '; } #define s_cmp(a,b,c,d) ((integer)strncmp((a),(b),f2cmin((c),(d)))) #define s_copy(A,B,C,D) { int __i,__m; for (__i=0, __m=f2cmin((C),(D)); __i<__m && (B)[__i] != 0; ++__i) (A)[__i] = (B)[__i]; } #define sig_die(s, kill) { exit(1); } #define s_stop(s, n) {exit(0);} static char junk[] = "\n@(#)LIBF77 VERSION 19990503\n"; #define z_abs(z) (cabs(Cd(z))) #define z_exp(R, Z) {pCd(R) = cexp(Cd(Z));} #define z_sqrt(R, Z) {pCd(R) = csqrt(Cd(Z));} #define myexit_() break; #define mycycle() continue; #define myceiling(w) {ceil(w)} #define myhuge(w) {HUGE_VAL} //#define mymaxloc_(w,s,e,n) {if (sizeof(*(w)) == sizeof(double)) dmaxloc_((w),*(s),*(e),n); else dmaxloc_((w),*(s),*(e),n);} #define mymaxloc(w,s,e,n) {dmaxloc_(w,*(s),*(e),n)} /* procedure parameter types for -A and -C++ */ #define F2C_proc_par_types 1 #ifdef __cplusplus typedef logical (*L_fp)(...); #else typedef logical (*L_fp)(); #endif static float spow_ui(float x, integer n) { float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static double dpow_ui(double x, integer n) { double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static _Complex float cpow_ui(_Complex float x, integer n) { _Complex float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static _Complex double zpow_ui(_Complex double x, integer n) { _Complex double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static integer pow_ii(integer x, integer n) { integer pow; unsigned long int u; if (n <= 0) { if (n == 0 || x == 1) pow = 1; else if (x != -1) pow = x == 0 ? 1/x : 0; else n = -n; } if ((n > 0) || !(n == 0 || x == 1 || x != -1)) { u = n; for(pow = 1; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static integer dmaxloc_(double *w, integer s, integer e, integer *n) { double m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static integer smaxloc_(float *w, integer s, integer e, integer *n) { float m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static inline void cdotc_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i])) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i*incx])) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i])) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i*incx])) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i]) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i*incx]) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i]) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i*incx]) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } #endif /* -- translated by f2c (version 20000121). You must link the resulting object file with the libraries: -lf2c -lm (in that order) */ /* > \brief \b ZSYCONVF */ /* =========== DOCUMENTATION =========== */ /* Online html documentation available at */ /* http://www.netlib.org/lapack/explore-html/ */ /* > \htmlonly */ /* > Download ZSYCONVF + dependencies */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/zsyconv f.f"> */ /* > [TGZ]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/zsyconv f.f"> */ /* > [ZIP]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/zsyconv f.f"> */ /* > [TXT]</a> */ /* > \endhtmlonly */ /* Definition: */ /* =========== */ /* SUBROUTINE ZSYCONVF( UPLO, WAY, N, A, LDA, E, IPIV, INFO ) */ /* CHARACTER UPLO, WAY */ /* INTEGER INFO, LDA, N */ /* INTEGER IPIV( * ) */ /* COMPLEX*16 A( LDA, * ), E( * ) */ /* > \par Purpose: */ /* ============= */ /* > */ /* > \verbatim */ /* > If parameter WAY = 'C': */ /* > ZSYCONVF converts the factorization output format used in */ /* > ZSYTRF provided on entry in parameter A into the factorization */ /* > output format used in ZSYTRF_RK (or ZSYTRF_BK) that is stored */ /* > on exit in parameters A and E. It also coverts in place details of */ /* > the intechanges stored in IPIV from the format used in ZSYTRF into */ /* > the format used in ZSYTRF_RK (or ZSYTRF_BK). */ /* > */ /* > If parameter WAY = 'R': */ /* > ZSYCONVF performs the conversion in reverse direction, i.e. */ /* > converts the factorization output format used in ZSYTRF_RK */ /* > (or ZSYTRF_BK) provided on entry in parameters A and E into */ /* > the factorization output format used in ZSYTRF that is stored */ /* > on exit in parameter A. It also coverts in place details of */ /* > the intechanges stored in IPIV from the format used in ZSYTRF_RK */ /* > (or ZSYTRF_BK) into the format used in ZSYTRF. */ /* > */ /* > ZSYCONVF can also convert in Hermitian matrix case, i.e. between */ /* > formats used in ZHETRF and ZHETRF_RK (or ZHETRF_BK). */ /* > \endverbatim */ /* Arguments: */ /* ========== */ /* > \param[in] UPLO */ /* > \verbatim */ /* > UPLO is CHARACTER*1 */ /* > Specifies whether the details of the factorization are */ /* > stored as an upper or lower triangular matrix A. */ /* > = 'U': Upper triangular */ /* > = 'L': Lower triangular */ /* > \endverbatim */ /* > */ /* > \param[in] WAY */ /* > \verbatim */ /* > WAY is CHARACTER*1 */ /* > = 'C': Convert */ /* > = 'R': Revert */ /* > \endverbatim */ /* > */ /* > \param[in] N */ /* > \verbatim */ /* > N is INTEGER */ /* > The order of the matrix A. N >= 0. */ /* > \endverbatim */ /* > */ /* > \param[in,out] A */ /* > \verbatim */ /* > A is COMPLEX*16 array, dimension (LDA,N) */ /* > */ /* > 1) If WAY ='C': */ /* > */ /* > On entry, contains factorization details in format used in */ /* > ZSYTRF: */ /* > a) all elements of the symmetric block diagonal */ /* > matrix D on the diagonal of A and on superdiagonal */ /* > (or subdiagonal) of A, and */ /* > b) If UPLO = 'U': multipliers used to obtain factor U */ /* > in the superdiagonal part of A. */ /* > If UPLO = 'L': multipliers used to obtain factor L */ /* > in the superdiagonal part of A. */ /* > */ /* > On exit, contains factorization details in format used in */ /* > ZSYTRF_RK or ZSYTRF_BK: */ /* > a) ONLY diagonal elements of the symmetric block diagonal */ /* > matrix D on the diagonal of A, i.e. D(k,k) = A(k,k); */ /* > (superdiagonal (or subdiagonal) elements of D */ /* > are stored on exit in array E), and */ /* > b) If UPLO = 'U': factor U in the superdiagonal part of A. */ /* > If UPLO = 'L': factor L in the subdiagonal part of A. */ /* > */ /* > 2) If WAY = 'R': */ /* > */ /* > On entry, contains factorization details in format used in */ /* > ZSYTRF_RK or ZSYTRF_BK: */ /* > a) ONLY diagonal elements of the symmetric block diagonal */ /* > matrix D on the diagonal of A, i.e. D(k,k) = A(k,k); */ /* > (superdiagonal (or subdiagonal) elements of D */ /* > are stored on exit in array E), and */ /* > b) If UPLO = 'U': factor U in the superdiagonal part of A. */ /* > If UPLO = 'L': factor L in the subdiagonal part of A. */ /* > */ /* > On exit, contains factorization details in format used in */ /* > ZSYTRF: */ /* > a) all elements of the symmetric block diagonal */ /* > matrix D on the diagonal of A and on superdiagonal */ /* > (or subdiagonal) of A, and */ /* > b) If UPLO = 'U': multipliers used to obtain factor U */ /* > in the superdiagonal part of A. */ /* > If UPLO = 'L': multipliers used to obtain factor L */ /* > in the superdiagonal part of A. */ /* > \endverbatim */ /* > */ /* > \param[in] LDA */ /* > \verbatim */ /* > LDA is INTEGER */ /* > The leading dimension of the array A. LDA >= f2cmax(1,N). */ /* > \endverbatim */ /* > */ /* > \param[in,out] E */ /* > \verbatim */ /* > E is COMPLEX*16 array, dimension (N) */ /* > */ /* > 1) If WAY ='C': */ /* > */ /* > On entry, just a workspace. */ /* > */ /* > On exit, contains the superdiagonal (or subdiagonal) */ /* > elements of the symmetric block diagonal matrix D */ /* > with 1-by-1 or 2-by-2 diagonal blocks, where */ /* > If UPLO = 'U': E(i) = D(i-1,i), i=2:N, E(1) is set to 0; */ /* > If UPLO = 'L': E(i) = D(i+1,i), i=1:N-1, E(N) is set to 0. */ /* > */ /* > 2) If WAY = 'R': */ /* > */ /* > On entry, contains the superdiagonal (or subdiagonal) */ /* > elements of the symmetric block diagonal matrix D */ /* > with 1-by-1 or 2-by-2 diagonal blocks, where */ /* > If UPLO = 'U': E(i) = D(i-1,i),i=2:N, E(1) not referenced; */ /* > If UPLO = 'L': E(i) = D(i+1,i),i=1:N-1, E(N) not referenced. */ /* > */ /* > On exit, is not changed */ /* > \endverbatim */ /* . */ /* > \param[in,out] IPIV */ /* > \verbatim */ /* > IPIV is INTEGER array, dimension (N) */ /* > */ /* > 1) If WAY ='C': */ /* > On entry, details of the interchanges and the block */ /* > structure of D in the format used in ZSYTRF. */ /* > On exit, details of the interchanges and the block */ /* > structure of D in the format used in ZSYTRF_RK */ /* > ( or ZSYTRF_BK). */ /* > */ /* > 1) If WAY ='R': */ /* > On entry, details of the interchanges and the block */ /* > structure of D in the format used in ZSYTRF_RK */ /* > ( or ZSYTRF_BK). */ /* > On exit, details of the interchanges and the block */ /* > structure of D in the format used in ZSYTRF. */ /* > \endverbatim */ /* > */ /* > \param[out] INFO */ /* > \verbatim */ /* > INFO is INTEGER */ /* > = 0: successful exit */ /* > < 0: if INFO = -i, the i-th argument had an illegal value */ /* > \endverbatim */ /* Authors: */ /* ======== */ /* > \author Univ. of Tennessee */ /* > \author Univ. of California Berkeley */ /* > \author Univ. of Colorado Denver */ /* > \author NAG Ltd. */ /* > \date November 2017 */ /* > \ingroup complex16SYcomputational */ /* > \par Contributors: */ /* ================== */ /* > */ /* > \verbatim */ /* > */ /* > November 2017, Igor Kozachenko, */ /* > Computer Science Division, */ /* > University of California, Berkeley */ /* > */ /* > \endverbatim */ /* ===================================================================== */ /* Subroutine */ int zsyconvf_(char *uplo, char *way, integer *n, doublecomplex *a, integer *lda, doublecomplex *e, integer *ipiv, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2; /* Local variables */ integer i__; extern logical lsame_(char *, char *); logical upper; extern /* Subroutine */ int zswap_(integer *, doublecomplex *, integer *, doublecomplex *, integer *); integer ip; extern /* Subroutine */ int xerbla_(char *, integer *, ftnlen); logical convert; /* -- LAPACK computational routine (version 3.8.0) -- */ /* -- LAPACK is a software package provided by Univ. of Tennessee, -- */ /* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */ /* November 2017 */ /* ===================================================================== */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1 * 1; a -= a_offset; --e; --ipiv; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); convert = lsame_(way, "C"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (! convert && ! lsame_(way, "R")) { *info = -2; } else if (*n < 0) { *info = -3; } else if (*lda < f2cmax(1,*n)) { *info = -5; } if (*info != 0) { i__1 = -(*info); xerbla_("ZSYCONVF", &i__1, (ftnlen)8); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } if (upper) { /* Begin A is UPPER */ if (convert) { /* Convert A (A is upper) */ /* Convert VALUE */ /* Assign superdiagonal entries of D to array E and zero out */ /* corresponding entries in input storage A */ i__ = *n; e[1].r = 0., e[1].i = 0.; while(i__ > 1) { if (ipiv[i__] < 0) { i__1 = i__; i__2 = i__ - 1 + i__ * a_dim1; e[i__1].r = a[i__2].r, e[i__1].i = a[i__2].i; i__1 = i__ - 1; e[i__1].r = 0., e[i__1].i = 0.; i__1 = i__ - 1 + i__ * a_dim1; a[i__1].r = 0., a[i__1].i = 0.; --i__; } else { i__1 = i__; e[i__1].r = 0., e[i__1].i = 0.; } --i__; } /* Convert PERMUTATIONS and IPIV */ /* Apply permutations to submatrices of upper part of A */ /* in factorization order where i decreases from N to 1 */ i__ = *n; while(i__ >= 1) { if (ipiv[i__] > 0) { /* 1-by-1 pivot interchange */ /* Swap rows i and IPIV(i) in A(1:i,N-i:N) */ ip = ipiv[i__]; if (i__ < *n) { if (ip != i__) { i__1 = *n - i__; zswap_(&i__1, &a[i__ + (i__ + 1) * a_dim1], lda, & a[ip + (i__ + 1) * a_dim1], lda); } } } else { /* 2-by-2 pivot interchange */ /* Swap rows i-1 and IPIV(i) in A(1:i,N-i:N) */ ip = -ipiv[i__]; if (i__ < *n) { if (ip != i__ - 1) { i__1 = *n - i__; zswap_(&i__1, &a[i__ - 1 + (i__ + 1) * a_dim1], lda, &a[ip + (i__ + 1) * a_dim1], lda); } } /* Convert IPIV */ /* There is no interchnge of rows i and and IPIV(i), */ /* so this should be reflected in IPIV format for */ /* *SYTRF_RK ( or *SYTRF_BK) */ ipiv[i__] = i__; --i__; } --i__; } } else { /* Revert A (A is upper) */ /* Revert PERMUTATIONS and IPIV */ /* Apply permutations to submatrices of upper part of A */ /* in reverse factorization order where i increases from 1 to N */ i__ = 1; while(i__ <= *n) { if (ipiv[i__] > 0) { /* 1-by-1 pivot interchange */ /* Swap rows i and IPIV(i) in A(1:i,N-i:N) */ ip = ipiv[i__]; if (i__ < *n) { if (ip != i__) { i__1 = *n - i__; zswap_(&i__1, &a[ip + (i__ + 1) * a_dim1], lda, & a[i__ + (i__ + 1) * a_dim1], lda); } } } else { /* 2-by-2 pivot interchange */ /* Swap rows i-1 and IPIV(i) in A(1:i,N-i:N) */ ++i__; ip = -ipiv[i__]; if (i__ < *n) { if (ip != i__ - 1) { i__1 = *n - i__; zswap_(&i__1, &a[ip + (i__ + 1) * a_dim1], lda, & a[i__ - 1 + (i__ + 1) * a_dim1], lda); } } /* Convert IPIV */ /* There is one interchange of rows i-1 and IPIV(i-1), */ /* so this should be recorded in two consecutive entries */ /* in IPIV format for *SYTRF */ ipiv[i__] = ipiv[i__ - 1]; } ++i__; } /* Revert VALUE */ /* Assign superdiagonal entries of D from array E to */ /* superdiagonal entries of A. */ i__ = *n; while(i__ > 1) { if (ipiv[i__] < 0) { i__1 = i__ - 1 + i__ * a_dim1; i__2 = i__; a[i__1].r = e[i__2].r, a[i__1].i = e[i__2].i; --i__; } --i__; } /* End A is UPPER */ } } else { /* Begin A is LOWER */ if (convert) { /* Convert A (A is lower) */ /* Convert VALUE */ /* Assign subdiagonal entries of D to array E and zero out */ /* corresponding entries in input storage A */ i__ = 1; i__1 = *n; e[i__1].r = 0., e[i__1].i = 0.; while(i__ <= *n) { if (i__ < *n && ipiv[i__] < 0) { i__1 = i__; i__2 = i__ + 1 + i__ * a_dim1; e[i__1].r = a[i__2].r, e[i__1].i = a[i__2].i; i__1 = i__ + 1; e[i__1].r = 0., e[i__1].i = 0.; i__1 = i__ + 1 + i__ * a_dim1; a[i__1].r = 0., a[i__1].i = 0.; ++i__; } else { i__1 = i__; e[i__1].r = 0., e[i__1].i = 0.; } ++i__; } /* Convert PERMUTATIONS and IPIV */ /* Apply permutations to submatrices of lower part of A */ /* in factorization order where k increases from 1 to N */ i__ = 1; while(i__ <= *n) { if (ipiv[i__] > 0) { /* 1-by-1 pivot interchange */ /* Swap rows i and IPIV(i) in A(i:N,1:i-1) */ ip = ipiv[i__]; if (i__ > 1) { if (ip != i__) { i__1 = i__ - 1; zswap_(&i__1, &a[i__ + a_dim1], lda, &a[ip + a_dim1], lda); } } } else { /* 2-by-2 pivot interchange */ /* Swap rows i+1 and IPIV(i) in A(i:N,1:i-1) */ ip = -ipiv[i__]; if (i__ > 1) { if (ip != i__ + 1) { i__1 = i__ - 1; zswap_(&i__1, &a[i__ + 1 + a_dim1], lda, &a[ip + a_dim1], lda); } } /* Convert IPIV */ /* There is no interchnge of rows i and and IPIV(i), */ /* so this should be reflected in IPIV format for */ /* *SYTRF_RK ( or *SYTRF_BK) */ ipiv[i__] = i__; ++i__; } ++i__; } } else { /* Revert A (A is lower) */ /* Revert PERMUTATIONS and IPIV */ /* Apply permutations to submatrices of lower part of A */ /* in reverse factorization order where i decreases from N to 1 */ i__ = *n; while(i__ >= 1) { if (ipiv[i__] > 0) { /* 1-by-1 pivot interchange */ /* Swap rows i and IPIV(i) in A(i:N,1:i-1) */ ip = ipiv[i__]; if (i__ > 1) { if (ip != i__) { i__1 = i__ - 1; zswap_(&i__1, &a[ip + a_dim1], lda, &a[i__ + a_dim1], lda); } } } else { /* 2-by-2 pivot interchange */ /* Swap rows i+1 and IPIV(i) in A(i:N,1:i-1) */ --i__; ip = -ipiv[i__]; if (i__ > 1) { if (ip != i__ + 1) { i__1 = i__ - 1; zswap_(&i__1, &a[ip + a_dim1], lda, &a[i__ + 1 + a_dim1], lda); } } /* Convert IPIV */ /* There is one interchange of rows i+1 and IPIV(i+1), */ /* so this should be recorded in consecutive entries */ /* in IPIV format for *SYTRF */ ipiv[i__] = ipiv[i__ + 1]; } --i__; } /* Revert VALUE */ /* Assign subdiagonal entries of D from array E to */ /* subgiagonal entries of A. */ i__ = 1; while(i__ <= *n - 1) { if (ipiv[i__] < 0) { i__1 = i__ + 1 + i__ * a_dim1; i__2 = i__; a[i__1].r = e[i__2].r, a[i__1].i = e[i__2].i; ++i__; } ++i__; } } /* End A is LOWER */ } return 0; /* End of ZSYCONVF */ } /* zsyconvf_ */
the_stack_data/181392436.c
#include <stdio.h> #include <stdlib.h> int main(void) { int *vetor=NULL; int num_elementos = 0; int num; do { printf ("\nEntre com o numero inteiro que deseja inserir no vetor: "); scanf("%d",&num); if(num) { num_elementos++; vetor = (int *)realloc(vetor,num_elementos * sizeof(int)); if (!vetor) { printf ("\n** ERRO! Memoria insuficiente **\n"); exit(1); } vetor[num_elementos-1]=num; } } while(num); printf("\nOs elementos do vetor sao:"); for (num = 0; num < num_elementos; num++) printf("\nO elemento %d do vetor e %d", num+1, *(vetor+num)); free(vetor); return 0; }
the_stack_data/92328561.c
// RUN: clang %s -O0 -S -emit-llvm -o %t.ll // RUN: sed -i s/optnone//g %t.ll // RUN: llvm-link %t.ll -S -o %t.ll // RUN: opt -load=%bindir/passes/BasicBlockTagger/BasicBlockTaggerPass.so --basic_block_tagger %t.ll -S -o %t.meta.ll // RUN: opt -load=%bindir/passes/BasicBlockInstr/BasicBlockInstrPass.so --basic_block_instr %t.meta.ll -S -o %t.tracer.ll // RUN: clang++ -O0 %t.tracer.ll -o %t.tracer.bin %bindir/runtime/libfuzzilly.a // RUN: export FZL_TRACE_FILE=%t.trace; %t.tracer.bin arg > %t.tracer.stdout // RUN: %bindir/tools/Retrace/fuzzilly-retrace -S -i %t.meta.ll -t %t.trace -o %t.retraced.ll // RUN: clang -o %t.retraced.bin %t.retraced.ll // RUN: %t.retraced.bin > %t.retraced.stdout; diff %t.retraced.stdout %t.tracer.stdout #include <stdio.h> int child(int arg) { return arg - 1; } int main(int argc, char *argv[]) { argc = child(argc); if (argc == 1) { puts("ONE"); } else { puts("NOT ONE"); } return 0; }
the_stack_data/283262.c
#include <stdio.h> int main(void){ int n, a[1010]; int dp[1010] = {0}; scanf("%d", &n); for(int i=1;i<=n;i++) scanf("%d", &a[i]); for(int i=1;i<=n;i++){ int bef = 0; for(int j=1;j<i;j++){ if(a[i] > a[j] && bef < dp[j]){ bef = dp[j]; } } dp[i] = bef + a[i]; } int max = 0; for(int i=1;i<=n;i++){ if(max < dp[i]) max = dp[i]; } printf("%d", max); return 0; }
the_stack_data/819111.c
int func4() { return 4; }
the_stack_data/225143877.c
/** * SmartCard-HSM PKCS#11 Module * * Copyright (c) 2013, CardContact Systems GmbH, Minden, Germany * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of CardContact Systems GmbH nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL CardContact Systems GmbH 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. * * @file slot-ctapi.c * @author Andreas Schwier * @brief Slot implementation for CT-API reader */ #ifdef CTAPI #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <common/memset_s.h> #include <pkcs11/slot.h> #include <pkcs11/token.h> #include <pkcs11/slotpool.h> #include <pkcs11/slot-ctapi.h> #include <pkcs11/strbpcpy.h> #ifdef DEBUG #include <common/debug.h> #endif #include <ctccid/ctapi.h> extern struct p11Context_t *context; #define MAX_READERS 16 static unsigned short numberOfReaders = 0; /* * Process an ISO 7816 APDU with the underlying terminal hardware. * * CLA : Class byte of instruction * INS : Instruction byte * P1 : Parameter P1 * P2 : Parameter P2 * OutLen : Length of outgoing data (Lc) * OutData : Outgoing data or NULL if none * InLen : Length of incoming data (Le) * InData : Input buffer for incoming data * InSize : buffer size * SW1SW2 : Address of short integer to receive SW1SW2 * * Returns : < 0 Error > 0 Bytes read */ int transmitAPDUwithCTAPI(struct p11Slot_t *slot, int todad, unsigned char CLA, unsigned char INS, unsigned char P1, unsigned char P2, int OutLen, unsigned char *OutData, int InLen, unsigned char *InData, int InSize, unsigned short *SW1SW2) { int rc; unsigned char apdu[MAX_APDULEN]; FUNC_CALLED(); rc = encodeCommandAPDU(CLA, INS, P1, P2, OutLen, OutData, InData ? InLen : -1, apdu, sizeof(apdu)); if (rc < 0) { memset_s(apdu, sizeof(apdu), 0, sizeof(apdu)); FUNC_FAILS(rc, "Encoding APDU failed"); } rc = transmitAPDUviaCTAPI(slot, todad, apdu, rc, apdu, sizeof(apdu)); if (rc >= 2) { *SW1SW2 = (apdu[rc - 2] << 8) | apdu[rc - 1]; rc -= 2; if (InData && InSize) { if (rc > InSize) { // Never return more than caller allocated a buffer for rc = InSize; } memcpy(InData, apdu, rc); } } else { rc = -1; } memset_s(apdu, sizeof(apdu), 0, sizeof(apdu)); FUNC_RETURNS(rc); } /** * Transmit APDU using CT-API * * @param slot the slot to use for communication * @param capdu the command APDU * @param capdu_len the length of the command APDU * @param rapdu the response APDU * @param rapdu_len the length of the response APDU * @return -1 for error or length of received response APDU */ int transmitAPDUviaCTAPI(struct p11Slot_t *slot, int todad, unsigned char *capdu, size_t capdu_len, unsigned char *rapdu, size_t rapdu_len) { int rc; unsigned short lenr; unsigned char dad, sad; FUNC_CALLED(); sad = HOST; dad = todad; lenr = rapdu_len; rc = CT_data(slot->ctn, &dad, &sad, capdu_len, capdu, &lenr, rapdu); if (rc < 0) FUNC_FAILS(rc, "CT_data failed"); FUNC_RETURNS(lenr); } /** * checkForNewCTAPIToken looks into a specific slot for a token. * * @param slot Pointer to slot structure. * * @return * <P><TABLE> * <TR><TD>Code</TD><TD>Meaning</TD></TR> * <TR> * <TD>CKR_OK </TD> * <TD>Success </TD> * </TR> * <TR> * <TD>CKR_HOST_MEMORY </TD> * <TD>Error getting memory (malloc) </TD> * </TR> * <TR> * <TD>CKR_GENERAL_ERROR </TD> * <TD>Error opening slot directory </TD> * </TR> * </TABLE></P> */ static int checkForNewCTAPIToken(struct p11Slot_t *slot) { struct p11Token_t *ptoken; unsigned char rsp[260]; int rc; unsigned short SW1SW2; FUNC_CALLED(); if (slot->closed) { FUNC_RETURNS(CKR_TOKEN_NOT_PRESENT); } // GET STATUS rc = transmitAPDUwithCTAPI(slot, 1, 0x20, 0x13, 0x01, 0x80, 0, NULL, 0, rsp, sizeof(rsp), &SW1SW2); if (rc == ERR_CT) { closeSlot(slot); } if (rc < 0) { FUNC_FAILS(CKR_DEVICE_ERROR, "GET_STATUS failed"); } if ((SW1SW2 != 0x9000) || (rc < 3) || (rsp[0] != 0x80) || (rsp[1] == 0) || (rsp[1] > rc - 2)) { FUNC_FAILS(CKR_DEVICE_ERROR, "GET_STATUS returned invalid response"); } if (!(rsp[2] & 0x01)) { // No Card in reader FUNC_RETURNS(CKR_TOKEN_NOT_PRESENT); } rc = transmitAPDUwithCTAPI(slot, 1, 0x20, 0x12, 0x01, 0x01, 0, NULL, 0, rsp, sizeof(rsp), &SW1SW2); if (rc < 0) { FUNC_FAILS(CKR_TOKEN_NOT_RECOGNIZED, "REQUEST ICC failed"); } if (SW1SW2 != 0x9001) { FUNC_FAILS(CKR_TOKEN_NOT_RECOGNIZED, "Reset failed"); } rc = newToken(slot, rsp, rc, &ptoken); if (rc != CKR_OK) { FUNC_FAILS(rc, "newToken failed()"); } FUNC_RETURNS(CKR_OK); } /** * checkForRemovedCTAPIToken looks into a specific slot for a removed token. * * @param slot Pointer to slot structure. * * @return * <P><TABLE> * <TR><TD>Code</TD><TD>Meaning</TD></TR> * <TR> * <TD>CKR_OK </TD> * <TD>Success </TD> * </TR> * <TR> * <TD>CKR_HOST_MEMORY </TD> * <TD>Error getting memory (malloc) </TD> * </TR> * <TR> * <TD>CKR_GENERAL_ERROR </TD> * <TD>Error opening slot directory </TD> * </TR> * </TABLE></P> */ static int checkForRemovedCTAPIToken(struct p11Slot_t *slot) { unsigned char rsp[260]; int rc; unsigned short SW1SW2; FUNC_CALLED(); rc = transmitAPDUwithCTAPI(slot, 1, 0x20, 0x13, 0x01, 0x80, 0, NULL, 0, rsp, sizeof(rsp), &SW1SW2); if (rc == ERR_CT) { // Reader or USB-Device removed removeToken(slot); closeSlot(slot); } if (rc < 0) { FUNC_FAILS(CKR_GENERAL_ERROR, "GET_STATUS failed"); } if ((SW1SW2 != 0x9000) || (rc < 3) || (rsp[0] != 0x80) || (rsp[1] == 0) || (rsp[1] > rc - 2)) { FUNC_FAILS(CKR_GENERAL_ERROR, "GET_STATUS returned invalid response"); } if (rsp[2] & 0x01) { // Token still in reader FUNC_RETURNS(CKR_OK); } rc = removeToken(slot); if (rc != CKR_OK) { FUNC_RETURNS(rc); } // Check if a new token was inserted in the meantime rc = checkForNewCTAPIToken(slot); if (rc == CKR_TOKEN_NOT_PRESENT) { FUNC_RETURNS(CKR_DEVICE_REMOVED); } FUNC_RETURNS(rc); } int getCTAPIToken(struct p11Slot_t *slot, struct p11Token_t **token) { int rc; FUNC_CALLED(); if (slot->token) { rc = checkForRemovedCTAPIToken(slot); } else { rc = checkForNewCTAPIToken(slot); } *token = slot->token; return rc; } int updateCTAPISlots(struct p11SlotPool_t *pool) { struct p11Slot_t *slot; unsigned short ctn; char scr[20]; int rc; FUNC_CALLED(); slot = pool->list; while (slot) { if (slot->closed) { ctn = slot->ctn; rc = CT_init(ctn, ctn); if (rc != OK) { #ifdef DEBUG debug("CT_init returns %d\n", rc); #endif } else { slot->closed = FALSE; } } slot = slot->next; } while (numberOfReaders < MAX_READERS) { ctn = numberOfReaders; rc = CT_init(ctn, ctn); if (rc != OK) { #ifdef DEBUG debug("CT_init returns %d\n", rc); #endif break; } slot = (struct p11Slot_t *) calloc(1, sizeof(struct p11Slot_t)); if (slot == NULL) { FUNC_FAILS(CKR_HOST_MEMORY, "Out of memory"); } sprintf(scr, "CT-API Port %d", ctn); slot->ctn = ctn; strbpcpy(slot->info.slotDescription, scr, sizeof(slot->info.slotDescription)); strbpcpy(slot->info.manufacturerID, "CardContact", sizeof(slot->info.manufacturerID)); slot->info.hardwareVersion.minor = 0; slot->info.hardwareVersion.major = 0; slot->info.firmwareVersion.minor = VERSION_MAJOR; slot->info.firmwareVersion.major = VERSION_MINOR; slot->maxRAPDU = MAX_RAPDU; slot->maxCAPDU = MAX_CAPDU; slot->info.flags = CKF_REMOVABLE_DEVICE | CKF_HW_SLOT; addSlot(&context->slotPool, slot); numberOfReaders++; checkForNewCTAPIToken(slot); } FUNC_RETURNS(CKR_OK); } int closeCTAPISlot(struct p11Slot_t *slot) { int rc; FUNC_CALLED(); rc = CT_close(slot->ctn); if (rc != OK) { #ifdef DEBUG debug("CT_close returns %d\n", rc); #endif } slot->closed = TRUE; FUNC_RETURNS(CKR_OK); } #endif
the_stack_data/112309.c
#include <stdio.h> #include <string.h> #define F(X, Y) X *Y #define MA(x) x *(x - 1) #define MIN(x, y) (x) < (y) ? (x) : (y) int main() { // int a = 3, b = 4; // printf("%d\n", F(3 + 5, 3 - 5)); // int m[][3] = {1, 4, 7, 2, 5, 8, 3, 6, 9}; // int i, j, k = 2; // for (i = 0; i < 3; i++) // printf("%d", m[k][i]); // int x = 023; // printf("%d\n", --x); // int x, y, z; // x = 1, y = 10; // z = x++, y++, ++y; //z的值是z = x++ ,如果右边右括号的话,z = ++y // printf("%d,%d,%d\n", x, y, z); // int x, y, t; // x = y = 3; // t = ++x || ++y; //短路, ||运算符左边为真,右边不计算 // printf("%d", y); // int a = 1, b = 5; // printf("%d\n", MA(1 + a + b)); //#define 宏就是简单替换,用 1+a+b 去替换x // int i = 10, j = 15, k; // k = 10 * MIN(i, j); //宏展开 k=10*(10)<(15)?(10):(15) // printf("%d\n", k); // int y = 10; // while (y--) // ; // printf("y=%d\n", y); // char str[] = "aeiou", *p = str; // printf("%c\n", *p + 4); //先求*p值为a,再+4为c // float x = 123.4567; // printf("%f\n", (int)(x * 100 + 0.5) / 100.0); //6位有效数字 // int a = 3, b = 2; // b = a < 0 && a++ > 3; //短路 左边为假值,右边不计算 // printf("%d,%d\n", a, b); // int k = 11; // printf("k=%d,k=%o,k=%x\n", k, k, k); //k=11,k=13,k=b // int a = 3, b = 4, c = 5, t = 99; // if (b < a && a < c) // t = a; // a = c; // c = t; // if (a < c && b < c) // t = b; // b = a; // a = t; // printf("%d%d%d\n", a, b, c); // int a[] = {10, 20, 30, 40, 50, 60}, *p; // p = a + 3; // printf("%d\n", *p++); // char s[] = "ABCD", *p = s; // printf("%d\n", *(p + 4)); // char str[] = "\tab\n\012\\\""; // printf("%d\n", strlen(str)); // char st[80]; // int i = 0, j = 0; // scanf("%s", st); // while (st[i]) // { // if (st[i] >= '0' && st[i] <= '9') // st[j++] = st[i]; // i++; // } // st[j] = '\0'; // printf("%s\n", st); // int a = 3, b = 4, c = 5, d = 2; // if (a < b) // if (b < c) // printf("%d", d++ + 1); //输出d+1=3,此时d值仍然等于2,然后d++,d值为3 // else // printf("%d", ++d + 1); // printf("%d\n", d); //输出d的值为3 // char s[] = "1234567890", *p = s + 3; // int i = 5; // printf("%d,%s\n", --i, p++); // printf("%s\n", p - i); // char s[] = "123456789", *p=s, i = 0; // while (*p) // { // if (i % 2 == 0) // *p = '*'; // p++; // i++; // } // printf("%s\n", s); // int a = 0, b = 4, c = 5; // switch (a == 0) // { // case 1: // switch (b < 0) // { // case 1: // printf("@"); // break; // case 0: // printf("!"); // break; // } // case 2: // switch (c == 5) // { // case 0: // printf("*"); // break; // case 1: // printf("#"); // break; // } // default: // printf("&"); // } // int a = 10, *p = &a, *p1; // p1 = *&p; // printf("%d", *p1); // return 0; int a[5] = {1, 20, 3, 4, 5}; int *p = a; int num = 6, num1 = 6; printf("%d,", *p++); printf("%d", *++p); }
the_stack_data/54834.c
#include<stdio.h> #include<stdint.h> #include<stdlib.h> void parse_swid(); void parse_mri(); void parse_ipv4(); void parse_ipv4_option(); void accept(); void ipv4_lpm_141857(); void tbl_add_mri_option_150190(); void swid_1_141825(); void tbl_act_150375(); void reject(); int action_run; int added_switch_id = 0; int extract_id[9] = {0}; int push_fronts = 0; typedef struct { uint32_t ingress_port : 9; uint32_t egress_spec : 9; uint32_t egress_port : 9; uint32_t clone_spec : 32; uint32_t instance_type : 32; uint8_t drop : 1; uint32_t recirculate_port : 16; uint32_t packet_length : 32; uint32_t enq_timestamp : 32; uint32_t enq_qdepth : 19; uint32_t deq_timedelta : 32; uint32_t deq_qdepth : 19; uint64_t ingress_global_timestamp : 48; uint32_t lf_field_list : 32; uint32_t mcast_grp : 16; uint8_t resubmit_flag : 1; uint32_t egress_rid : 16; } standard_metadata_t; void mark_to_drop() { exit(0); } typedef uint32_t egressSpec_t; typedef uint64_t macAddr_t; typedef uint32_t ip4Addr_t; typedef uint32_t switchID_t; switchID_t id_const; typedef struct { uint8_t isValid : 1; macAddr_t dstAddr: 48; macAddr_t srcAddr: 48; uint32_t etherType : 16; } ethernet_t; typedef struct { uint8_t isValid : 1; uint8_t version : 4; uint8_t ihl : 4; uint8_t diffserv : 8; uint32_t totalLen : 16; uint32_t identification : 16; uint8_t flags : 3; uint32_t fragOffset : 13; uint8_t ttl : 8; uint8_t protocol : 8; uint32_t hdrChecksum : 16; ip4Addr_t srcAddr: 32; ip4Addr_t dstAddr: 32; } ipv4_t; typedef struct { uint8_t isValid : 1; uint8_t copyFlag : 1; uint8_t optClass : 2; uint8_t option : 5; uint8_t optionLength : 8; } ipv4_option_t; typedef struct { uint8_t isValid : 1; uint32_t count : 16; } mri_t; typedef struct { uint8_t isValid : 1; switchID_t swid: 32; } switch_t; typedef struct { uint32_t count : 16; } ingress_metadata_t; typedef struct { uint32_t remaining : 16; } parser_metadata_t; typedef struct { ingress_metadata_t ingress_metadata; parser_metadata_t parser_metadata; } metadata; typedef struct { ethernet_t ethernet; ipv4_t ipv4; ipv4_option_t ipv4_option; mri_t mri; int swids_index; switch_t swids[9]; } headers; headers hdr; metadata meta; standard_metadata_t standard_metadata; uint8_t tmp_7; uint32_t tmp_8; void start() { hdr.ethernet.isValid = 1; switch(hdr.ethernet.etherType){ case 2048: parse_ipv4(); break; default: accept(); break; } } void parse_ipv4() { tmp_7 = hdr.ipv4.ihl >= 5; klee_assume(tmp_7); switch(hdr.ipv4.ihl){ case 5: accept(); break; default: parse_ipv4_option(); break; } } void parse_ipv4_option() { hdr.ipv4_option.isValid = 1; switch(hdr.ipv4_option.option){ case 31: parse_mri(); break; default: accept(); break; } } void parse_mri() { hdr.mri.isValid = 1; meta.parser_metadata.remaining = hdr.mri.count; switch(meta.parser_metadata.remaining){ case 0: accept(); break; default: parse_swid(); break; } } void reject() { exit(0); } void parse_swid() { if (hdr.swids_index >= 9){ reject(); } hdr.swids[hdr.swids_index].isValid = 1; extract_id[hdr.swids_index] = 1; hdr.swids_index++; tmp_8 = meta.parser_metadata.remaining + 65535; meta.parser_metadata.remaining = tmp_8; switch(meta.parser_metadata.remaining){ case 0: accept(); break; default: parse_swid(); break; } } void accept() { } void ParserImpl() { klee_make_symbolic(&hdr, sizeof(hdr), "hdr"); klee_make_symbolic(&meta, sizeof(meta), "meta"); klee_make_symbolic(&standard_metadata, sizeof(standard_metadata), "standard_metadata"); hdr.swids_index = 0; start(); } //Control void verifyChecksum() { } //Control uint8_t tmp_9; uint32_t tmp_10; uint8_t tmp_11; uint8_t tmp_12; uint8_t tmp_13; void ingress() { if(hdr.ipv4.isValid) { ipv4_lpm_141857(); if(!hdr.mri.isValid) { tbl_add_mri_option_150190(); } swid_1_141825(); } } // Action void NoAction_0_141591() { action_run = 141591; } // Action void NoAction_3_141601() { action_run = 141601; } // Action void drop_0_141602() { action_run = 141602; mark_to_drop(); } // Action void add_mri_option_0_143531() { action_run = 143531; hdr.ipv4_option.isValid = 1; hdr.ipv4_option.copyFlag = 1; hdr.ipv4_option.optClass = 2; hdr.ipv4_option.option = 31; hdr.ipv4_option.optionLength = 4; hdr.mri.isValid = 1; hdr.mri.count = 0; tmp_9 = hdr.ipv4.ihl + 1; hdr.ipv4.ihl = hdr.ipv4.ihl + 1; } void push_front(int count) { int i; for (i = 8; i >= 0; i -= 1) { if (i >= count) { hdr.swids[i] = hdr.swids[i-count]; } else { hdr.swids[i].isValid = 0; } } hdr.swids_index = hdr.swids_index + count; push_fronts += count; if (hdr.swids_index > 8) hdr.swids_index = 8; // Note: this.last, this.next, and this.lastIndex adjust with this.nextIndex } // Action void add_swid_0_143681() { action_run = 143681; switchID_t id; klee_make_symbolic(&id, sizeof(id), "id"); tmp_10 = hdr.mri.count + 1; hdr.mri.count = hdr.mri.count + 1; push_front(1); hdr.swids[0].swid = id; id_const = id; added_switch_id = 1; tmp_11 = hdr.ipv4.ihl + 1; hdr.ipv4.ihl = hdr.ipv4.ihl + 1; tmp_12 = hdr.ipv4_option.optionLength + 4; hdr.ipv4_option.optionLength = hdr.ipv4_option.optionLength + 4; } // Action void ipv4_forward_0_143838() { action_run = 143838; macAddr_t dstAddr; klee_make_symbolic(&dstAddr, sizeof(dstAddr), "dstAddr"); egressSpec_t port; klee_make_symbolic(&port, sizeof(port), "port"); standard_metadata.egress_spec = port; hdr.ethernet.srcAddr = hdr.ethernet.dstAddr; hdr.ethernet.dstAddr = dstAddr; tmp_13 = hdr.ipv4.ttl + 255; hdr.ipv4.ttl = hdr.ipv4.ttl + 255; } //Table void swid_1_141825() { int symbol; klee_make_symbolic(&symbol, sizeof(symbol), "symbol"); switch(symbol) { case 0: add_swid_0_143681(); break; default: NoAction_0_141591(); break; } // default_action NoAction_0(); } //Table void ipv4_lpm_141857() { int symbol; klee_make_symbolic(&symbol, sizeof(symbol), "symbol"); switch(symbol) { case 0: ipv4_forward_0_143838(); break; case 1: drop_0_141602(); break; default: NoAction_3_141601(); break; } // size 1024 // default_action NoAction_3(); } //Table void tbl_add_mri_option_150190() { int symbol; klee_make_symbolic(&symbol, sizeof(symbol), "symbol"); switch(symbol) { default: add_mri_option_0_143531(); break; } // default_action add_mri_option_0(); } //Control void egress() { } typedef struct { uint8_t field : 4; uint8_t field_0 : 4; uint8_t field_1 : 8; uint32_t field_2 : 16; uint32_t field_3 : 16; uint8_t field_4 : 3; uint32_t field_5 : 13; uint8_t field_6 : 8; uint8_t field_7 : 8; uint32_t field_8 : 32; uint32_t field_9 : 32; } tuple_0; //Control uint32_t tmp_14; void computeChecksum() { if(hdr.ipv4.isValid) { klee_make_symbolic(&tmp_14, sizeof(tmp_14), "tmp_14"); tbl_act_150375(); } } // Action void act_148943() { action_run = 148943; hdr.ipv4.hdrChecksum = tmp_14; } //Table void tbl_act_150375() { int symbol; klee_make_symbolic(&symbol, sizeof(symbol), "symbol"); switch(symbol) { default: act_148943(); break; } // default_action act(); } //Control void DeparserImpl() { //Emit hdr.ethernet //Emit hdr.ipv4 //Emit hdr.ipv4_option //Emit hdr.mri //Emit hdr.swids if(added_switch_id && id_const != hdr.swids[0].swid){ klee_print_once(0, "Assert error: const(switchid)"); } int i; for(i = 0; i < 9; i++){ if(extract_id[i] == 1 && !(hdr.swids[i+push_fronts].isValid == 1)){ klee_print_once(1, "switch id removed"); } } } int main() { ParserImpl(); ingress(); egress(); DeparserImpl(); return 0; }
the_stack_data/554625.c
#include <stdio.h> int main() { int n; printf("Enter the number of process\n"); scanf("%d",&n); int a[n][4],c=0; for(int i=0;i<n;i++){ printf("Enter the arival time and burst time of process %d\n",(i+1)); scanf("%d%d",&a[i][0],&a[i][1]); a[i][2]=c+a[i][1]-a[i][0]; //a[i][2] is storing turn around time of each process a[i][3]=a[i][2]-a[i][1]; //a[i][3] is storing waiting time of each process c=c+a[i][1]; } printf("No\tTAT\tWT\n"); int a1,a2=0; for(int i=0;i<n;i++){ printf("P%d\t%d\t%d\n",(i+1),a[i][2],a[i][3]); a1+=a[i][2]; a2=a2+a[i][3]; } printf("Average TAT=%d\n",(a1/n)); printf("Average WT=%d\n",(a2/n)); }
the_stack_data/200142710.c
#include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <errno.h> #include <signal.h> void term_status(int status) { wait(&status); if(WIFEXITED(status)){ printf("(exit) status:%x\n",WEXITSTATUS(status)); }else if(WTERMSIG(status)){ printf("(signal)status: 0x%x\n",status&0x7f); } } void my_sig(int signo){ int status; printf("signo=%d\n",signo); while(waitpid(-1,&status,WNOHANG)>0){ term_status(status); } } int main(void) { int i; pid_t pid; signal(SIGCHLD,my_sig); if((pid=fork())>0){ for(i=0;i<10000;i++){ usleep(50000); printf("%d\n",i+1); } }else if(!pid){ sleep(5); }else{ perror("fork"); exit(-1); } return 0; }
the_stack_data/36076442.c
/* Fibonacci and Prime using pipe - fibprime.c */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> main() { pid_t pid; int pfd[2]; int i,j,flg,f1,f2,f3; static unsigned int ar[25],br[25]; if(pipe(pfd) == -1) { printf("Error in pipe"); exit(-1); } pid=fork(); if (pid == 0) { printf("Child process generates Fibonacci series\n" ); f1 = -1; f2 = 1; for(i = 0;i < 25; i++) { f3 = f1 + f2; printf("%d\t",f3); f1 = f2; f2 = f3; ar[i] = f3; } write(pfd[1],ar,25*sizeof(int)); } else if (pid > 0) { wait(NULL); read(pfd[0], br, 25*sizeof(int)); printf("\nParent prints Fibonacci that are Prime\n"); for(i = 0;i < 25; i++) { flg = 0; if (br[i] <= 1) flg = 1; for(j=2; j<=br[i]/2; j++) { if (br[i]%j == 0) { flg=1; break; } } if (flg == 0) printf("%d\t", br[i]); } printf("\n"); } else { printf("Process creation failed"); exit(-1); } }
the_stack_data/45449420.c
#include <stdio.h> #include <string.h> #include <stdlib.h> // rep関数(文字列置換関数)※マルチバイト文字ではエラー生じる場合あり int rep(char *buf, const char *str, const char *repbef, const char *repaft) { char *pos; //strstr関数で使用するポインタ char *poss = (char *)str; //検索開始のポインタの位置(possとは[pos + start]の意) int len; //検索開始ポインタ(poss)から検索結果ポインタ(pos)までの長さ int beflen = strlen(repbef); //検索語句の長さ strcpy(buf, "\0"); //strcpyは第2引数のNULL終端を含めコピーする(バッファオーバーランには注意) while(1) { pos = (char *)strstr(poss, repbef); if (pos == NULL) { strcat(buf, poss); //strcatもNULL終端する(バッファオーバーランには注意) break; } else { strncat(buf, poss, pos - poss); //strncatもNULL終端する(バッファオーバーランには注意) strcat(buf, repaft); //strcatもNULL終端する(バッファオーバーランには注意) poss = pos + beflen; } } return 0; }
the_stack_data/113081.c
/** * @file oauth2-helper.c * * @copyright 2018 Bill Zissimopoulos */ /* * general definitions */ #if defined(_WIN64) || defined(_WIN32) #include <windows.h> #undef RtlFillMemory NTSYSAPI VOID NTAPI RtlFillMemory(VOID *Destination, DWORD Length, BYTE Fill); #define memset(d, v, s) (RtlFillMemory(d, v, s), (d)) #define strcpy(d, s) lstrcpyA(d, s) #define strlen(s) lstrlenA(s) #define malloc(s) HeapAlloc(GetProcessHeap(), 0, s) #define realloc(p, s) HeapReAlloc(GetProcessHeap(), 0, p, s) #define free(p) ((p) ? (void)HeapFree(GetProcessHeap(), 0, p) : (void)0) #define exit(n) ExitProcess(n) #define STDOUT_FILENO (intptr_t)GetStdHandle(STD_OUTPUT_HANDLE) #define STDERR_FILENO (intptr_t)GetStdHandle(STD_ERROR_HANDLE) #elif defined(__CYGWIN__) #include <errno.h> #include <fcntl.h> #include <netinet/in.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <unistd.h> void *__stdcall ShellExecuteA( void *hwnd, const char *lpOperation, const char *lpFile, const char *lpParameters, const char *lpDirectory, int nShowCmd); unsigned long __stdcall GetLastError(void); #define SW_SHOWNORMAL 1 #elif defined(__APPLE__) #include <CoreFoundation/CoreFoundation.h> #include <CoreServices/CoreServices.h> #include <netinet/in.h> #include <sys/socket.h> #elif defined(__linux__) #include <errno.h> #include <fcntl.h> #include <netinet/in.h> #include <spawn.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/wait.h> #include <unistd.h> extern char **environ; #else #error Unknown platform #endif /* * file I/O */ #if defined(_WIN64) || defined(_WIN32) #define O_RDONLY 0x0000 #define O_WRONLY 0x0001 #define O_RDWR 0x0002 #define O_APPEND 0x0008 #define O_CREAT 0x0100 #define O_TRUNC 0x0200 #define O_EXCL 0x0400 static inline intptr_t open(const char *path, int oflag) { static DWORD da[] = { GENERIC_READ, GENERIC_WRITE, GENERIC_READ | GENERIC_WRITE, 0 }; static DWORD cd[] = { OPEN_EXISTING, OPEN_ALWAYS, TRUNCATE_EXISTING, CREATE_ALWAYS }; DWORD DesiredAccess = 0 == (oflag & O_APPEND) ? da[oflag & (O_RDONLY | O_WRONLY | O_RDWR)] : (da[oflag & (O_RDONLY | O_WRONLY | O_RDWR)] & ~FILE_WRITE_DATA) | FILE_APPEND_DATA; DWORD CreationDisposition = (O_CREAT | O_EXCL) == (oflag & (O_CREAT | O_EXCL)) ? CREATE_NEW : cd[(oflag & (O_CREAT | O_TRUNC)) >> 8]; HANDLE h = CreateFileA(path, DesiredAccess, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 0, CreationDisposition, FILE_ATTRIBUTE_NORMAL, 0); return INVALID_HANDLE_VALUE != h ? (intptr_t)h : -1; } static inline int close(intptr_t fd) { return CloseHandle((HANDLE)fd) ? 0 : -1; } static inline int read(intptr_t fd, void *buf, size_t len) { DWORD BytesTransferred; return ReadFile((HANDLE)fd, buf, len, &BytesTransferred, 0) ? BytesTransferred : -1; } static inline int write(intptr_t fd, const void *buf, size_t len) { DWORD BytesTransferred; return WriteFile((HANDLE)fd, buf, len, &BytesTransferred, 0) ? BytesTransferred : -1; } static inline int file_errno() { return GetLastError(); } #else /* POSIX */ static inline int file_errno() { return errno; } #endif /* * sockets */ #if defined(_WIN64) || defined(_WIN32) typedef int socklen_t; static int socket_init(void) { static int initdone = 0; WSADATA wsadata; int status; if (initdone) return 0; status = WSAStartup(MAKEWORD(2, 0), &wsadata); if (0 != status) return status; initdone = 1; return 0; } static inline int socket_close(SOCKET s) { return closesocket(s); } static inline int socket_errno() { return WSAGetLastError(); } #else typedef int SOCKET; #define INVALID_SOCKET (-1) #define SOCKET_ERROR (-1) static int socket_init(void) { return 0; } static inline int socket_close(SOCKET s) { return close(s); } static inline int socket_errno() { return errno; } #endif enum { E_FILE = 'F', E_BROWSER = 'B', E_SERVER = 'S', E_NETWORK = 'N', E_TIMEOUT = 'T', }; #define RSP200\ "HTTP/1.1 200 OK\r\n"\ "Content-type: text/html\r\n"\ "\r\n"\ "<html>"\ "<body>"\ "<h1>You are authorized</h1>"\ "</body>"\ "</html>" #define RSP404\ "HTTP/1.1 404 Not Found\r\n"\ "Content-type: text/html\r\n"\ "\r\n"\ "<html>"\ "<body>"\ "<h1>404 Not Found</h1>"\ "</body>"\ "</html>" void err(int result, const char *fmt, ...) { va_list ap; char buf[64+1024]; size_t len; switch (result) { case E_FILE: strcpy(buf, "E_FILE: "); break; case E_BROWSER: strcpy(buf, "E_BROWSER: "); break; case E_SERVER: strcpy(buf, "E_SERVER: "); break; case E_NETWORK: strcpy(buf, "E_NETWORK: "); break; case E_TIMEOUT: strcpy(buf, "E_TIMEOUT: "); break; default: strcpy(buf, "E_UNKNOWN: "); break; } len = strlen(buf); va_start(ap, fmt); #if defined(_WIN64) || defined(_WIN32) wvsprintfA(buf + len, fmt, ap); #else vsnprintf(buf + len, sizeof buf - len, fmt, ap); #endif va_end(ap); write(STDERR_FILENO, buf, strlen(buf)); } int load_file(const char *path, char **pp) { int result = E_FILE; char *p = 0, *q; size_t n = 64 * 1024; int fd = -1; *pp = 0; p = malloc(n); if (0 == p) { err(result, "malloc\n"); goto exit; } fd = open(path, O_RDONLY); if (-1 == fd) { err(result, "open: %d\n", file_errno()); goto exit; } n = read(fd, p, n - 1); if (-1 == n) { err(result, "read: %d\n", file_errno()); goto exit; } p[n++] = '\0'; q = realloc(p, n); if (0 == q) { err(result, "realloc\n"); goto exit; } *pp = q; result = 0; exit: if (-1 != fd) close(fd); if (0 != result) free(p); return result; } int browser(const char *url) { int result = E_BROWSER; #if defined(_WIN64) || defined(_WIN32) || defined(__CYGWIN__) if (!ShellExecuteA(0, "open", url, 0, 0, SW_SHOWNORMAL)) { err(result, "ShellExecuteA: %d\n", GetLastError()); goto exit; } result = 0; exit: #elif defined(__APPLE__) CFStringRef urlstr = 0; CFURLRef urlref = 0; OSStatus status; urlstr = CFStringCreateWithCString(0, url, kCFStringEncodingUTF8); if (0 == urlstr) { err(result, "CFStringCreateWithCString\n"); goto exit; } urlref = CFURLCreateWithString(0, urlstr, 0); if (0 == urlstr) { err(result, "CFURLCreateWithString\n"); goto exit; } status = LSOpenCFURLRef(urlref, 0); if (noErr != status) { err(result, "LSOpenCFURLRef: %d\n", status); goto exit; } result = 0; exit: if (0 != urlref) CFRelease(urlref); if (0 != urlstr) CFRelease(urlstr); #elif defined(__linux__) char *argv[] = { "xdg-open", (char *)url, 0, }; posix_spawn_file_actions_t file_actions_stg, *file_actions = 0; pid_t pid; int status; status = posix_spawn_file_actions_init(&file_actions_stg); if (0 != status) { err(result, "posix_spawn_file_actions_init: %d\n", status); goto exit; } file_actions = &file_actions_stg; status = posix_spawn_file_actions_addopen( file_actions, STDOUT_FILENO, "/dev/null", O_WRONLY, 0); if (0 != status) { err(result, "posix_spawn_file_actions_addopen: %d\n", status); goto exit; } status = posix_spawnp(&pid, argv[0], file_actions, 0, argv, environ); if (0 != status) { err(result, "posix_spawnp: %d\n", status); goto exit; } if (pid != waitpid(pid, &status, 0)) { err(result, "waitpid: %d\n", errno); goto exit; } if (!WIFEXITED(status) || 0 != WEXITSTATUS(status)) { err(result, "xdg-open: %d\n", status); goto exit; } result = 0; exit: if (0 != file_actions) posix_spawn_file_actions_destroy(file_actions); #endif return result; } int server_socket(unsigned port, unsigned *pport, SOCKET *psocket) { int result = E_SERVER; SOCKET s = INVALID_SOCKET; struct sockaddr_in addr; socklen_t len; int status; status = socket_init(); if (0 != status) { err(result, "socket_init: %d\n", status); goto fail; } s = socket(AF_INET, SOCK_STREAM, 0); if (INVALID_SOCKET == s) { err(result, "socket: %d\n", socket_errno()); goto fail; } memset(&addr, 0, sizeof addr); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); addr.sin_port = htons(port); status = bind(s, (struct sockaddr *)&addr, sizeof addr); if (SOCKET_ERROR == status) { err(result, "bind: %d\n", socket_errno()); goto fail; } status = listen(s, 1); if (SOCKET_ERROR == status) { err(result, "listen: %d\n", socket_errno()); goto fail; } len = sizeof addr; status = getsockname(s, (struct sockaddr *)&addr, &len); if (SOCKET_ERROR == status) { err(result, "getsockname: %d\n", socket_errno()); goto fail; } result = 0; *pport = ntohs(addr.sin_port); *psocket = s; return result; fail: if (INVALID_SOCKET != s) socket_close(s); *pport = 0; *psocket = INVALID_SOCKET; return result; } int server(SOCKET s, unsigned timeout, char *rsp200) { int result; SOCKET a = INVALID_SOCKET; struct timeval tv; fd_set fds; int status, n; char req[2048 + 1], *rsp; char *resource = 0, *p; tv.tv_sec = timeout ? timeout : 120; tv.tv_usec = 0; FD_ZERO(&fds); FD_SET(s, &fds); status = select(s + 1, &fds, 0, 0, &tv); if (SOCKET_ERROR == status) { err(result = E_SERVER, "select: %d\n", socket_errno()); goto exit; } else if (0 == status) { err(result = E_TIMEOUT, "select\n"); goto exit; } a = accept(s, 0, 0); if (INVALID_SOCKET == a) { err(result = E_NETWORK, "accept: %d\n", socket_errno()); goto exit; } n = recv(a, req, sizeof req - 1, 0); if (SOCKET_ERROR == n) { err(result = E_NETWORK, "recv: %d\n", socket_errno()); goto exit; } req[n] = '\0'; if ('G' == req[0] && 'E' == req[1] && 'T' == req[2] && req[3] == ' ') { resource = req + 3; *resource = '+'; for (p = resource + 1; *p && ' ' != *p && '\r' != *p && '\n' != *p; p++) ; *p++ = '\n'; } rsp = resource ? (rsp200 ? rsp200 : RSP200) : RSP404; send(a, rsp, strlen(rsp), 0); if (0 == resource) { err(result = E_NETWORK, "HTTP: no resource\n"); goto exit; } write(STDOUT_FILENO, resource, p - resource); result = 0; exit: if (INVALID_SOCKET != a) socket_close(a); return result; } static unsigned strtouint(const char *p) { unsigned v; for (v = 0; *p; p++) { int c = *p; if ('0' <= c && c <= '9') v = 10 * v + (c - '0'); else break; } return v; } void usage(void) { char usage[] = "usage: oauth2-helper [-pPORT][-tTIMEOUT][-FPATH] URL\n"; write(STDERR_FILENO, usage, strlen(usage)); exit(2); } int main(int argc, char *argv[]) { char *urlarg, url[1024]; unsigned port = 0, timeout = 0; const char *rsp200file = 0; int argi; char *rsp200 = 0; SOCKET s; int result; for (argi = 1; argc > argi; argi++) { if ('-' != argv[argi][0]) break; switch (argv[argi][1]) { case 'p': port = strtouint(argv[argi] + 2); break; case 't': timeout = strtouint(argv[argi] + 2); break; case 'F': rsp200file = argv[argi] + 2; break; default: usage(); break; } } if (1 != argc - argi) usage(); urlarg = argv[argi]; if (!('h' == urlarg[0] && 't' == urlarg[1] && 't' == urlarg[2] && 'p' == urlarg[3] && (':' == urlarg[4] || ('s' == urlarg[4] && ':' == urlarg[5])))) usage(); if (0 != rsp200file) { result = load_file(rsp200file, &rsp200); if (0 != result) goto fail; } result = server_socket(port, &port, &s); if (0 != result) goto fail; for (char *p = urlarg; *p; p++) if ('%' == *p) *p = '\x01'; else if ('[' == p[0] && ']' == p[1]) { p[0] = '%'; p[1] = 'd'; } #if defined(_WIN64) || defined(_WIN32) wsprintfA(url, urlarg, port); #else snprintf(url, sizeof url, urlarg, port); #endif for (char *p = url; *p; p++) if ('\x01' == *p) *p = '%'; result = browser(url); if (0 != result) goto fail; result = server(s, timeout, rsp200); if (0 != result) goto fail; socket_close(s); free(rsp200); return 0; fail: { char resbuf[3]; resbuf[0] = '-'; resbuf[1] = result; resbuf[2] = '\n'; write(STDOUT_FILENO, resbuf, 3); } return 1; } #if defined(_WIN64) || defined(_WIN32) void mainCRTStartup(void) { DWORD Argc; PWSTR *Argv; int Length; char **argv, *argp, *argendp; Argv = CommandLineToArgvW(GetCommandLineW(), &Argc); if (0 == Argv) ExitProcess(GetLastError()); Length = 0; for (DWORD I = 0; Argc > I; I++) Length += WideCharToMultiByte(CP_UTF8, 0, Argv[I], -1, 0, 0, 0, 0); argv = malloc((Argc + 1) * sizeof(char *) + Length); argp = (char *)argv + (Argc + 1) * sizeof(char *); argendp = argp + Length; for (DWORD I = 0; Argc > I; I++) { argv[I] = argp; argp += WideCharToMultiByte(CP_UTF8, 0, Argv[I], -1, argp, argendp - argp, 0, 0); } argv[Argc] = 0; LocalFree(Argv); ExitProcess(main(Argc, argv)); } #endif
the_stack_data/200143498.c
#include<stdio.h> #include<stdlib.h> struct Node { int data; struct Node *next; } *firstNode; void createNodes(int array[], int numberOfNodes) { struct Node *tempNode, *lastNode; firstNode = (struct Node *) malloc(sizeof(struct Node)); firstNode->data = array[0]; firstNode->next = NULL; lastNode = firstNode; for(int i = 1; i < numberOfNodes; i++) { tempNode = (struct Node *) malloc(sizeof(struct Node)); tempNode->data = array[i]; tempNode->next = NULL; lastNode->next = tempNode; lastNode = tempNode; } } void displayNodes(struct Node *pointNode) { printf("\nDisplaying Nodes:\n\n"); while(pointNode != NULL) { printf("%d ", pointNode->data); pointNode = pointNode->next; } printf("\n"); } int countNodes(struct Node *pointNode) { int count = 0; while(pointNode != NULL) { count++; pointNode = pointNode->next; } return count; } int main() { int array [] = {1, 3, 7, 11, 13, 17, 19, 23, 31}; createNodes(array, 9); displayNodes(firstNode); printf("\nTotal Number of Nodes in Linked List: %d\n", countNodes(firstNode)); return 0; }
the_stack_data/59514017.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <CL/cl.h> unsigned char *read_buffer(char *file_name, size_t *size_ptr) { FILE *f; unsigned char *buf; size_t size; /* Open file */ f = fopen(file_name, "rb"); if (!f) return NULL; /* Obtain file size */ fseek(f, 0, SEEK_END); size = ftell(f); fseek(f, 0, SEEK_SET); /* Allocate and read buffer */ buf = malloc(size + 1); fread(buf, 1, size, f); buf[size] = '\0'; /* Return size of buffer */ if (size_ptr) *size_ptr = size; /* Return buffer */ return buf; } void write_buffer(char *file_name, const char *buffer, size_t buffer_size) { FILE *f; /* Open file */ f = fopen(file_name, "w+"); /* Write buffer */ if(buffer) fwrite(buffer, 1, buffer_size, f); /* Close file */ fclose(f); } int main(int argc, char const *argv[]) { /* Get platform */ cl_platform_id platform; cl_uint num_platforms; cl_int ret = clGetPlatformIDs(1, &platform, &num_platforms); if (ret != CL_SUCCESS) { printf("error: call to 'clGetPlatformIDs' failed\n"); exit(1); } printf("Number of platforms: %d\n", num_platforms); printf("platform=%p\n", platform); /* Get platform name */ char platform_name[100]; ret = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(platform_name), platform_name, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clGetPlatformInfo' failed\n"); exit(1); } printf("platform.name='%s'\n\n", platform_name); /* Get device */ cl_device_id device; cl_uint num_devices; ret = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, &num_devices); if (ret != CL_SUCCESS) { printf("error: call to 'clGetDeviceIDs' failed\n"); exit(1); } printf("Number of devices: %d\n", num_devices); printf("device=%p\n", device); /* Get device name */ char device_name[100]; ret = clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(device_name), device_name, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clGetDeviceInfo' failed\n"); exit(1); } printf("device.name='%s'\n", device_name); printf("\n"); /* Create a Context Object */ cl_context context; context = clCreateContext(NULL, 1, &device, NULL, NULL, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateContext' failed\n"); exit(1); } printf("context=%p\n", context); /* Create a Command Queue Object*/ cl_command_queue command_queue; command_queue = clCreateCommandQueue(context, device, 0, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateCommandQueue' failed\n"); exit(1); } printf("command_queue=%p\n", command_queue); printf("\n"); /* Program source */ unsigned char *source_code; size_t source_length; /* Read program from 'exp10_float8.cl' */ source_code = read_buffer("exp10_float8.cl", &source_length); /* Create a program */ cl_program program; program = clCreateProgramWithSource(context, 1, (const char **)&source_code, &source_length, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateProgramWithSource' failed\n"); exit(1); } printf("program=%p\n", program); /* Build program */ ret = clBuildProgram(program, 1, &device, NULL, NULL, NULL); if (ret != CL_SUCCESS ) { size_t size; char *log; /* Get log size */ clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,0, NULL, &size); /* Allocate log and print */ log = malloc(size); clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,size, log, NULL); printf("error: call to 'clBuildProgram' failed:\n%s\n", log); /* Free log and exit */ free(log); exit(1); } printf("program built\n"); printf("\n"); /* Create a Kernel Object */ cl_kernel kernel; kernel = clCreateKernel(program, "exp10_float8", &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateKernel' failed\n"); exit(1); } /* Create and allocate host buffers */ size_t num_elem = 10; /* Create and init host side src buffer 0 */ cl_float8 *src_0_host_buffer; src_0_host_buffer = malloc(num_elem * sizeof(cl_float8)); for (int i = 0; i < num_elem; i++) src_0_host_buffer[i] = (cl_float8){{2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0}}; /* Create and init device side src buffer 0 */ cl_mem src_0_device_buffer; src_0_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_float8), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create source buffer\n"); exit(1); } ret = clEnqueueWriteBuffer(command_queue, src_0_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_float8), src_0_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueWriteBuffer' failed\n"); exit(1); } /* Create host dst buffer */ cl_float8 *dst_host_buffer; dst_host_buffer = malloc(num_elem * sizeof(cl_float8)); memset((void *)dst_host_buffer, 1, num_elem * sizeof(cl_float8)); /* Create device dst buffer */ cl_mem dst_device_buffer; dst_device_buffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY, num_elem *sizeof(cl_float8), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create dst buffer\n"); exit(1); } /* Set kernel arguments */ ret = CL_SUCCESS; ret |= clSetKernelArg(kernel, 0, sizeof(cl_mem), &src_0_device_buffer); ret |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &dst_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clSetKernelArg' failed\n"); exit(1); } /* Launch the kernel */ size_t global_work_size = num_elem; size_t local_work_size = num_elem; ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueNDRangeKernel' failed\n"); exit(1); } /* Wait for it to finish */ clFinish(command_queue); /* Read results from GPU */ ret = clEnqueueReadBuffer(command_queue, dst_device_buffer, CL_TRUE,0, num_elem * sizeof(cl_float8), dst_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueReadBuffer' failed\n"); exit(1); } /* Dump dst buffer to file */ char dump_file[100]; sprintf((char *)&dump_file, "%s.result", argv[0]); write_buffer(dump_file, (const char *)dst_host_buffer, num_elem * sizeof(cl_float8)); printf("Result dumped to %s\n", dump_file); /* Free host dst buffer */ free(dst_host_buffer); /* Free device dst buffer */ ret = clReleaseMemObject(dst_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Free host side src buffer 0 */ free(src_0_host_buffer); /* Free device side src buffer 0 */ ret = clReleaseMemObject(src_0_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Release kernel */ ret = clReleaseKernel(kernel); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseKernel' failed\n"); exit(1); } /* Release program */ ret = clReleaseProgram(program); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseProgram' failed\n"); exit(1); } /* Release command queue */ ret = clReleaseCommandQueue(command_queue); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseCommandQueue' failed\n"); exit(1); } /* Release context */ ret = clReleaseContext(context); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseContext' failed\n"); exit(1); } return 0; }
the_stack_data/206391872.c
/*@ begin PerfTuning ( def build { arg build_command = 'gcc -O3 -fopenmp '; arg libs = '-lm -lrt'; } def performance_counter { arg repetitions = 35; } def performance_params { param T1_I[] = [1,16,32,64,128,256,512]; param T1_J[] = [1,16,32,64,128,256,512]; param T1_Ia[] = [1,64,128,256,512,1024,2048]; param T1_Ja[] = [1,64,128,256,512,1024,2048]; param T2_I[] = [1,16,32,64,128,256,512]; param T2_J[] = [1,16,32,64,128,256,512]; param T2_K[] = [1,16,32,64,128,256,512]; param T2_Ia[] = [1,64,128,256,512,1024,2048]; param T2_Ja[] = [1,64,128,256,512,1024,2048]; param T2_Ka[] = [1,64,128,256,512,1024,2048]; param U1_I[] = range(1,31); param U1_J[] = range(1,31); param U2_I[] = range(1,31); param U2_J[] = range(1,31); param U2_K[] = range(1,31); param RT1_I[] = [1,8,32]; param RT1_J[] = [1,8,32]; param RT2_I[] = [1,8,32]; param RT2_J[] = [1,8,32]; param RT2_K[] = [1,8,32]; param SCREP[] = [False,True]; param VEC1[] = [False,True]; param OMP1[] = [False,True]; param VEC2[] = [False,True]; param OMP2[] = [False,True]; constraint tileI1 = ((T1_Ia == 1) or (T1_Ia % T1_I == 0)); constraint tileJ1 = ((T1_Ja == 1) or (T1_Ja % T1_J == 0)); constraint tileI2 = ((T2_Ia == 1) or (T2_Ia % T2_I == 0)); constraint tileJ2 = ((T2_Ja == 1) or (T2_Ja % T2_J == 0)); constraint tileK2 = ((T2_Ka == 1) or (T2_Ka % T2_K == 0)); constraint reg_capacity_1 = (U1_I*U1_J <= 150); constraint unroll_limit_1 = ((U1_I == 1) or (U1_J == 1) ); constraint reg_capacity_2 = (U2_I*U2_J + U2_I*U2_K + U2_J*U2_K <= 150); constraint unroll_limit_2 = ((U2_I == 1) or (U2_J == 1) or (U2_K == 1)); } def search { arg algorithm = 'Randomsearch'; arg total_runs = 10000; } def input_params { param N[] = [750]; param alpha = 1; } def input_vars { decl static double A[N][N+20] = random; decl static double B[N][N+20] = random; } ) @*/ int i, j, k; int ii, jj, kk; int it, jt, kt; int iii, jjj, kkk; #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /*@ begin Loop( transform Composite( tile = [('i',T1_I,'ii'),('j',T1_J,'jj'), (('ii','i'),T1_Ia,'iii'),(('jj','j'),T1_Ja,'jjj')], unrolljam = (['i','j'],[U1_I,U1_J]), scalarreplace = (SCREP, 'double', 'scv_'), regtile = (['i','j'],[RT1_I,RT1_J]), vector = (VEC1, ['ivdep','vector always']), openmp = (OMP1, 'omp parallel for private(i,j,ii,jj,iii,jjj)') ) for (i=0; i<=N-1; i++) for (j=0; j<=N-1; j++) { B[i][j] = alpha*A[i][i]*B[i][j]; for (k=i+1; k<=N-1; k++) B[i][j] = B[i][j] + alpha*A[i][k]*B[k][j]; } transform Composite( tile = [('i',T2_I,'ii'),('j',T2_J,'jj'),('k',T2_K,'kk'), (('ii','i'),T2_Ia,'iii'),(('jj','j'),T2_Ja,'jjj'),(('kk','k'),T2_Ka,'kkk')], unrolljam = (['i','j','k'],[U2_I,U2_J,U2_K]), scalarreplace = (SCREP, 'double', 'scv_'), regtile = (['i','j','k'],[RT2_I,RT2_J,RT2_K]), vector = (VEC2, ['ivdep','vector always']), openmp = (OMP2, 'omp parallel for private(iii,jjj,kkk,ii,jj,kk,i,j,k)') ) for (i=0; i<=N-1; i++) for (j=0; j<=N-1; j++) for (k=i+1; k<=N-1; k++) B[i][j] = B[i][j] + alpha*A[i][k]*B[k][j]; ) @*/ /*@ end @*/ /*@ end @*/
the_stack_data/72622.c
// WARNING in hsr_forward_skb // https://syzkaller.appspot.com/bug?id=13de4605e86ebcf39093017dc255aa0fd6c2f12d // status:open // autogenerated by syzkaller (https://github.com/google/syzkaller) #define _GNU_SOURCE #include <arpa/inet.h> #include <endian.h> #include <errno.h> #include <fcntl.h> #include <net/if.h> #include <net/if_arp.h> #include <netinet/in.h> #include <sched.h> #include <stdarg.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/ioctl.h> #include <sys/mount.h> #include <sys/prctl.h> #include <sys/resource.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/time.h> #include <sys/types.h> #include <sys/uio.h> #include <sys/wait.h> #include <unistd.h> #include <linux/if_addr.h> #include <linux/if_ether.h> #include <linux/if_link.h> #include <linux/if_tun.h> #include <linux/in6.h> #include <linux/ip.h> #include <linux/neighbour.h> #include <linux/net.h> #include <linux/netlink.h> #include <linux/rtnetlink.h> #include <linux/tcp.h> #include <linux/veth.h> unsigned long long procid; static bool write_file(const char* file, const char* what, ...) { char buf[1024]; va_list args; va_start(args, what); vsnprintf(buf, sizeof(buf), what, args); va_end(args); buf[sizeof(buf) - 1] = 0; int len = strlen(buf); int fd = open(file, O_WRONLY | O_CLOEXEC); if (fd == -1) return false; if (write(fd, buf, len) != len) { int err = errno; close(fd); errno = err; return false; } close(fd); return true; } static struct { char* pos; int nesting; struct nlattr* nested[8]; char buf[1024]; } nlmsg; static void netlink_init(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(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 void netlink_nest(int typ) { struct nlattr* attr = (struct nlattr*)nlmsg.pos; attr->nla_type = typ; nlmsg.pos += sizeof(*attr); nlmsg.nested[nlmsg.nesting++] = attr; } static void netlink_done(void) { struct nlattr* attr = nlmsg.nested[--nlmsg.nesting]; attr->nla_len = nlmsg.pos - (char*)attr; } static int netlink_send(int sock) { 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 (n < sizeof(struct nlmsghdr) + sizeof(struct nlmsgerr)) exit(1); if (hdr->nlmsg_type != NLMSG_ERROR) exit(1); return -((struct nlmsgerr*)(hdr + 1))->error; } static void netlink_add_device_impl(const char* type, const char* name) { struct ifinfomsg hdr; memset(&hdr, 0, sizeof(hdr)); netlink_init(RTM_NEWLINK, NLM_F_EXCL | NLM_F_CREATE, &hdr, sizeof(hdr)); if (name) netlink_attr(IFLA_IFNAME, name, strlen(name)); netlink_nest(IFLA_LINKINFO); netlink_attr(IFLA_INFO_KIND, type, strlen(type)); } static void netlink_add_device(int sock, const char* type, const char* name) { netlink_add_device_impl(type, name); netlink_done(); int err = netlink_send(sock); (void)err; } static void netlink_add_veth(int sock, const char* name, const char* peer) { netlink_add_device_impl("veth", name); netlink_nest(IFLA_INFO_DATA); netlink_nest(VETH_INFO_PEER); nlmsg.pos += sizeof(struct ifinfomsg); netlink_attr(IFLA_IFNAME, peer, strlen(peer)); netlink_done(); netlink_done(); netlink_done(); int err = netlink_send(sock); (void)err; } static void netlink_add_hsr(int sock, const char* name, const char* slave1, const char* slave2) { netlink_add_device_impl("hsr", name); netlink_nest(IFLA_INFO_DATA); int ifindex1 = if_nametoindex(slave1); netlink_attr(IFLA_HSR_SLAVE1, &ifindex1, sizeof(ifindex1)); int ifindex2 = if_nametoindex(slave2); netlink_attr(IFLA_HSR_SLAVE2, &ifindex2, sizeof(ifindex2)); netlink_done(); netlink_done(); int err = netlink_send(sock); (void)err; } static void netlink_device_change(int sock, const char* name, bool up, const char* master, const void* mac, int macsize) { struct ifinfomsg hdr; memset(&hdr, 0, sizeof(hdr)); if (up) hdr.ifi_flags = hdr.ifi_change = IFF_UP; netlink_init(RTM_NEWLINK, 0, &hdr, sizeof(hdr)); netlink_attr(IFLA_IFNAME, name, strlen(name)); if (master) { int ifindex = if_nametoindex(master); netlink_attr(IFLA_MASTER, &ifindex, sizeof(ifindex)); } if (macsize) netlink_attr(IFLA_ADDRESS, mac, macsize); int err = netlink_send(sock); (void)err; } static int netlink_add_addr(int sock, const char* dev, const void* addr, int addrsize) { struct ifaddrmsg hdr; memset(&hdr, 0, sizeof(hdr)); hdr.ifa_family = addrsize == 4 ? AF_INET : AF_INET6; hdr.ifa_prefixlen = addrsize == 4 ? 24 : 120; hdr.ifa_scope = RT_SCOPE_UNIVERSE; hdr.ifa_index = if_nametoindex(dev); netlink_init(RTM_NEWADDR, NLM_F_CREATE | NLM_F_REPLACE, &hdr, sizeof(hdr)); netlink_attr(IFA_LOCAL, addr, addrsize); netlink_attr(IFA_ADDRESS, addr, addrsize); return netlink_send(sock); } static void netlink_add_addr4(int sock, const char* dev, const char* addr) { struct in_addr in_addr; inet_pton(AF_INET, addr, &in_addr); int err = netlink_add_addr(sock, dev, &in_addr, sizeof(in_addr)); (void)err; } static void netlink_add_addr6(int sock, const char* dev, const char* addr) { struct in6_addr in6_addr; inet_pton(AF_INET6, addr, &in6_addr); int err = netlink_add_addr(sock, dev, &in6_addr, sizeof(in6_addr)); (void)err; } #define DEV_IPV4 "172.20.20.%d" #define DEV_IPV6 "fe80::%02hx" #define DEV_MAC 0x00aaaaaaaaaa static void initialize_netdevices(void) { char netdevsim[16]; sprintf(netdevsim, "netdevsim%d", (int)procid); struct { const char* type; const char* dev; } devtypes[] = { {"ip6gretap", "ip6gretap0"}, {"bridge", "bridge0"}, {"vcan", "vcan0"}, {"bond", "bond0"}, {"team", "team0"}, {"dummy", "dummy0"}, {"nlmon", "nlmon0"}, {"caif", "caif0"}, {"batadv", "batadv0"}, {"vxcan", "vxcan1"}, {"netdevsim", netdevsim}, {"veth", 0}, }; const char* devmasters[] = {"bridge", "bond", "team"}; struct { const char* name; int macsize; bool noipv6; } devices[] = { {"lo", ETH_ALEN}, {"sit0", 0}, {"bridge0", ETH_ALEN}, {"vcan0", 0, true}, {"tunl0", 0}, {"gre0", 0}, {"gretap0", ETH_ALEN}, {"ip_vti0", 0}, {"ip6_vti0", 0}, {"ip6tnl0", 0}, {"ip6gre0", 0}, {"ip6gretap0", ETH_ALEN}, {"erspan0", ETH_ALEN}, {"bond0", ETH_ALEN}, {"veth0", ETH_ALEN}, {"veth1", ETH_ALEN}, {"team0", ETH_ALEN}, {"veth0_to_bridge", ETH_ALEN}, {"veth1_to_bridge", ETH_ALEN}, {"veth0_to_bond", ETH_ALEN}, {"veth1_to_bond", ETH_ALEN}, {"veth0_to_team", ETH_ALEN}, {"veth1_to_team", ETH_ALEN}, {"veth0_to_hsr", ETH_ALEN}, {"veth1_to_hsr", ETH_ALEN}, {"hsr0", 0}, {"dummy0", ETH_ALEN}, {"nlmon0", 0}, {"vxcan1", 0, true}, {"caif0", ETH_ALEN}, {"batadv0", ETH_ALEN}, {netdevsim, ETH_ALEN}, }; int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (sock == -1) exit(1); unsigned i; for (i = 0; i < sizeof(devtypes) / sizeof(devtypes[0]); i++) netlink_add_device(sock, devtypes[i].type, devtypes[i].dev); for (i = 0; i < sizeof(devmasters) / (sizeof(devmasters[0])); i++) { char master[32], slave0[32], veth0[32], slave1[32], veth1[32]; sprintf(slave0, "%s_slave_0", devmasters[i]); sprintf(veth0, "veth0_to_%s", devmasters[i]); netlink_add_veth(sock, slave0, veth0); sprintf(slave1, "%s_slave_1", devmasters[i]); sprintf(veth1, "veth1_to_%s", devmasters[i]); netlink_add_veth(sock, slave1, veth1); sprintf(master, "%s0", devmasters[i]); netlink_device_change(sock, slave0, false, master, 0, 0); netlink_device_change(sock, slave1, false, master, 0, 0); } netlink_device_change(sock, "bridge_slave_0", true, 0, 0, 0); netlink_device_change(sock, "bridge_slave_1", true, 0, 0, 0); netlink_add_veth(sock, "hsr_slave_0", "veth0_to_hsr"); netlink_add_veth(sock, "hsr_slave_1", "veth1_to_hsr"); netlink_add_hsr(sock, "hsr0", "hsr_slave_0", "hsr_slave_1"); netlink_device_change(sock, "hsr_slave_0", true, 0, 0, 0); netlink_device_change(sock, "hsr_slave_1", true, 0, 0, 0); for (i = 0; i < sizeof(devices) / (sizeof(devices[0])); i++) { char addr[32]; sprintf(addr, DEV_IPV4, i + 10); netlink_add_addr4(sock, devices[i].name, addr); if (!devices[i].noipv6) { sprintf(addr, DEV_IPV6, i + 10); netlink_add_addr6(sock, devices[i].name, addr); } uint64_t macaddr = DEV_MAC + ((i + 10ull) << 40); netlink_device_change(sock, devices[i].name, true, 0, &macaddr, devices[i].macsize); } close(sock); } static void initialize_netdevices_init(void) { int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (sock == -1) exit(1); struct { const char* type; int macsize; bool noipv6; bool noup; } devtypes[] = { {"nr", 7, true}, {"rose", 5, true, true}, }; unsigned i; for (i = 0; i < sizeof(devtypes) / sizeof(devtypes[0]); i++) { char dev[32], addr[32]; sprintf(dev, "%s%d", devtypes[i].type, (int)procid); sprintf(addr, "172.30.%d.%d", i, (int)procid + 1); netlink_add_addr4(sock, dev, addr); if (!devtypes[i].noipv6) { sprintf(addr, "fe88::%02hx:%02hx", i, (int)procid + 1); netlink_add_addr6(sock, dev, addr); } int macsize = devtypes[i].macsize; uint64_t macaddr = 0xbbbbbb + ((unsigned long long)i << (8 * (macsize - 2))) + (procid << (8 * (macsize - 1))); netlink_device_change(sock, dev, !devtypes[i].noup, 0, &macaddr, macsize); } close(sock); } static void setup_common() { if (mount(0, "/sys/fs/fuse/connections", "fusectl", 0, 0)) { } } static void loop(); static void sandbox_common() { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); setpgrp(); setsid(); struct rlimit rlim; rlim.rlim_cur = rlim.rlim_max = 200 << 20; setrlimit(RLIMIT_AS, &rlim); rlim.rlim_cur = rlim.rlim_max = 32 << 20; setrlimit(RLIMIT_MEMLOCK, &rlim); rlim.rlim_cur = rlim.rlim_max = 136 << 20; setrlimit(RLIMIT_FSIZE, &rlim); rlim.rlim_cur = rlim.rlim_max = 1 << 20; setrlimit(RLIMIT_STACK, &rlim); rlim.rlim_cur = rlim.rlim_max = 0; setrlimit(RLIMIT_CORE, &rlim); rlim.rlim_cur = rlim.rlim_max = 256; setrlimit(RLIMIT_NOFILE, &rlim); if (unshare(CLONE_NEWNS)) { } if (unshare(CLONE_NEWIPC)) { } if (unshare(0x02000000)) { } if (unshare(CLONE_NEWUTS)) { } if (unshare(CLONE_SYSVSEM)) { } typedef struct { const char* name; const char* value; } sysctl_t; static const sysctl_t sysctls[] = { {"/proc/sys/kernel/shmmax", "16777216"}, {"/proc/sys/kernel/shmall", "536870912"}, {"/proc/sys/kernel/shmmni", "1024"}, {"/proc/sys/kernel/msgmax", "8192"}, {"/proc/sys/kernel/msgmni", "1024"}, {"/proc/sys/kernel/msgmnb", "1024"}, {"/proc/sys/kernel/sem", "1024 1048576 500 1024"}, }; unsigned i; for (i = 0; i < sizeof(sysctls) / sizeof(sysctls[0]); i++) write_file(sysctls[i].name, sysctls[i].value); } int wait_for_loop(int pid) { if (pid < 0) exit(1); int status = 0; while (waitpid(-1, &status, __WALL) != pid) { } return WEXITSTATUS(status); } static int do_sandbox_none(void) { if (unshare(CLONE_NEWPID)) { } int pid = fork(); if (pid != 0) return wait_for_loop(pid); setup_common(); sandbox_common(); initialize_netdevices_init(); if (unshare(CLONE_NEWNET)) { } initialize_netdevices(); loop(); exit(1); } uint64_t r[2] = {0xffffffffffffffff, 0x0}; void loop(void) { long res = 0; res = syscall(__NR_socket, 0x11, 2, 0x300); if (res != -1) r[0] = res; memcpy((void*)0x20000c40, "hsr0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 16); *(uint32_t*)0x20000c50 = 0; res = syscall(__NR_ioctl, r[0], 0x8933, 0x20000c40); if (res != -1) r[1] = *(uint32_t*)0x20000c50; *(uint64_t*)0x20008a80 = 0x20000180; *(uint16_t*)0x20000180 = 0x11; *(uint16_t*)0x20000182 = htobe16(0x8100); *(uint32_t*)0x20000184 = r[1]; *(uint16_t*)0x20000188 = 1; *(uint8_t*)0x2000018a = 0; *(uint8_t*)0x2000018b = 6; *(uint8_t*)0x2000018c = 1; *(uint8_t*)0x2000018d = 0x80; *(uint8_t*)0x2000018e = 0xc2; *(uint8_t*)0x2000018f = 0; *(uint8_t*)0x20000190 = 0; *(uint8_t*)0x20000191 = 0; *(uint8_t*)0x20000192 = 0; *(uint8_t*)0x20000193 = 0; *(uint32_t*)0x20008a88 = 0x80; *(uint64_t*)0x20008a90 = 0; *(uint64_t*)0x20008a98 = 0; *(uint64_t*)0x20008aa0 = 0; *(uint64_t*)0x20008aa8 = 0; *(uint32_t*)0x20008ab0 = 0; *(uint32_t*)0x20008ab8 = 0; syscall(__NR_sendmmsg, r[0], 0x20008a80, 0x300, 0); } int main(void) { syscall(__NR_mmap, 0x20000000, 0x1000000, 3, 0x32, -1, 0); do_sandbox_none(); return 0; }
the_stack_data/218893436.c
// exemple pour point fixe while #include <stdlib.h> #include <stdio.h> struct rec_st; typedef struct rec_st * recursive; struct rec_st { int i; recursive n; }; int main(void) { // srand(1); int data = 0; recursive l; l = NULL; while (rand()%19) { recursive q; q = (recursive) malloc(sizeof(struct rec_st)); q->i = data++; q->n = l; l = q; } // affiche la longueur de la liste créée fprintf(stdout, "data=%d\n", data); return 0; }
the_stack_data/55164.c
#include <stdio.h> #include <ctype.h> #include <string.h> int sedol_weights[] = {1, 3, 1, 7, 3, 9}; const char *reject = "AEIOUaeiou"; int sedol_checksum(const char *sedol6) { int len = strlen(sedol6); int sum = 0, i; if ( len == 7 ) { fprintf(stderr, "SEDOL code already checksummed? (%s)\n", sedol6); return sedol6[6] & 0x7f; } if ( (len > 7) || (len < 6) || ( strcspn(sedol6, reject) != 6 )) { fprintf(stderr, "not a SEDOL code? (%s)\n", sedol6); return -1; } for(i=0; i < 6; i++) { if ( isdigit(sedol6[i]) ) { sum += (sedol6[i]-'0')*sedol_weights[i]; } else if ( isalpha(sedol6[i]) ) { sum += ((toupper(sedol6[i])-'A') + 10)*sedol_weights[i]; } else { fprintf(stderr, "SEDOL with not alphanumeric digit\n"); return -1; } } return (10 - (sum%10))%10 + '0'; } #define MAXLINELEN 10 int main() { char line[MAXLINELEN]; int sr, len; while( fgets(line, MAXLINELEN, stdin) != NULL ) { len = strlen(line); if ( line[len-1] == '\n' ) line[len-1]='\0'; sr = sedol_checksum(line); if ( sr > 0 ) printf("%s%c\n", line, sr); } return 0; }
the_stack_data/176704692.c
/*numPass=4, numTotal=5 Verdict:ACCEPTED, Visibility:1, Input:"3 23", ExpOutput:"3 5 7 11 13 17 19 23 ", Output:"3 5 7 11 13 17 19 23 " Verdict:ACCEPTED, Visibility:1, Input:"5 31", ExpOutput:"5 7 11 13 17 19 23 29 31 ", Output:"5 7 11 13 17 19 23 29 31 " Verdict:WRONG_ANSWER, Visibility:1, Input:"1 20", ExpOutput:"2 3 5 7 11 13 17 19 ", Output:"1 2 3 5 7 11 13 17 19 " Verdict:ACCEPTED, Visibility:0, Input:"23 57", ExpOutput:"23 29 31 37 41 43 47 53 ", Output:"23 29 31 37 41 43 47 53 " Verdict:ACCEPTED, Visibility:0, Input:"31 47", ExpOutput:"31 37 41 43 47 ", Output:"31 37 41 43 47 " */ #include<stdio.h> int check_prime(int num); void print_prime(int n1, int n2); int check_prime(int num){ /* The function returns 1 if num is prime otherwise it return 0 */ int i; // i: for the iteration in for loop for(i=2;i<num;i++) { if(num%i==0) { return 0; /* if the number would be divisible it won't be prime */ } } return 1; } void print_prime(int n1, int n2){ /* The function calls function check_prime() and prints prime numbers */ int i; //for the iteration in for loop for(i=n1;i<=n2;i++) { if(check_prime(i)) printf("%d ",i); } } int main(){ int n1,n2; //To store the input limits scanf("%d%d",&n1,&n2);//to receive input from user print_prime(n1,n2); return 0; }
the_stack_data/12637654.c
#include <stdio.h> #include <stdlib.h> typedef struct character{ char name[15]; int level; float peso; } personagem; int main() { int i; personagem character[10]; for(i = 0; i < 4; i++) { printf("Digite o nome do personagem %d: \n", i+1); scanf("%s", character[i].name); printf("Digite o nível do personagem %s: \n", character[i].name); scanf("%d", &character[i].level); printf("Digite o peso do personagem %s: \n", character[i].name); scanf("%f", &character[i].peso); } for(i = 0; i < 4; i++) { printf("O personagem %s tem nível %d e pesa %.2fKg!\n", character[i].name, character[i].level, character[i].peso); } return 0; }
the_stack_data/92364.c
#include <stdio.h> #include <math.h> int euclides(int f1, int f2) { int r1=1; while(r1 != 0) { r1 = f1 % f2; f1 = f2; f2 = r1; } return f1; } int main() { int f1,f2,n,i, divisor, j; scanf("%d", &n); for(i=0; i < n; i++) { scanf("%d%d",&f1,&f2); if(f1 > f2) { int temp = f2; f2 = f1; f1 = temp; } divisor = euclides(f2,f1%f2); printf("%d\n", divisor); } return 0; }
the_stack_data/870203.c
/* https://www.hackerrank.com/contests/mockcodestorm/challenges/vowels-counter */ #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int main() { int count=0; char ch; while((ch=getchar())!=EOF) { if(ch=='A'||ch=='a') count++; else if(ch=='E'||ch=='e') count++; else if(ch=='I'||ch=='i') count++; else if(ch=='O'||ch=='o') count++; else if(ch=='U'||ch=='u') count++; } printf("%d\n",count); return 0; }