file
stringlengths 18
26
| data
stringlengths 3
1.04M
|
---|---|
the_stack_data/1093893.c | #include <stdlib.h>
#include <string.h>
void str_replace(char *target, const char *needle, const char *replacement)
{
char buffer[1024] = {0};
char *insert_point = &buffer[0];
const char *tmp = target;
size_t needle_len = strlen(needle), repl_len = strlen(replacement);
while (1)
{
const char *p = strstr(tmp, needle);
if (p == NULL)
{
strcpy(insert_point, tmp);
break;
}
memcpy(insert_point, tmp, p - tmp);
insert_point += p - tmp;
memcpy(insert_point, replacement, repl_len);
insert_point += repl_len;
tmp = p + needle_len;
}
strcpy(target, buffer);
}
char **parse_string(char *string)
{
char **array = malloc(strlen(string) * sizeof(char *));
int i = 0;
array[i] = strtok(string, " \t\r\n\a");
while (array[i])
{
array[++i] = strtok(NULL, " \t\r\n\a");
}
return array;
} |
the_stack_data/64182.c | int _HUGE;
int __argc;
int __argv;
int __initenv;
int __mb_cur_max;
int __wargv;
int __winitenv;
int _acmdln;
int _aexit_rtn;
int _ctype;
int _daylight;
int _dstbias;
int _environ;
int _fileinfo;
int _iob;
int _mbctype;
int _osver;
int _pctype;
int _pgmptr;
int _pwctype;
int _sys_errlist;
int _sys_nerr;
int _timezone;
int _tzname;
int _wcmdln;
int _wenviron;
int _winmajor;
int _winminor;
int _winver;
int _wpgmptr;;
|
the_stack_data/991254.c | /*
* --- Revised 3-Clause BSD License ---
* Copyright (C) 2016-2019, SEMTECH (International) AG.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL SEMTECH BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#if defined(CFG_lgw2)
#include <stdio.h>
#include "uj.h"
#include "kwcrc.h"
#include "sys.h"
#include "sx1301v2conf.h"
#include "lgw2/sx1301ar_err.h"
// Describes radio config for HW spec sx1301/n as sent by LNS
struct lns_sx1301_conf {
u4_t chanFreqs[SX1301AR_CHIP_CHAN_NB];
u2_t chanEnabled;
struct chanLSA {
u1_t spreadfactor;
u1_t bandwidth;
} lsaChan;
u4_t fskDatarate;
};
static void parse_tx_lut (ujdec_t* D, sx1301ar_tx_gain_lut_t* txlut) {
int slot;
uj_enterArray(D);
while( (slot = uj_nextSlot(D)) >= 0 ) {
if( slot >= SX1301AR_BOARD_MAX_LUT_NB )
uj_error(D, "Too many 'tx_lut' entries (no more than %d allowed)", SX1301AR_BOARD_MAX_LUT_NB);
ujcrc_t field;
uj_enterObject(D);
while( (field = uj_nextField(D)) ) {
switch(field) {
case J_rf_power : { txlut->lut[slot].rf_power = uj_intRange(D, -128, 127); break; }
case J_fpga_dig_gain : { txlut->lut[slot].fpga_dig_gain = uj_intRange(D, 0, 255); break; }
case J_ad9361_atten : { txlut->lut[slot].ad9361_gain.atten = uj_intRange(D, 0,65535); break; }
case J_ad9361_auxdac_vref : { txlut->lut[slot].ad9361_gain.auxdac_vref = uj_intRange(D, 0, 255); break; }
case J_ad9361_auxdac_word : { txlut->lut[slot].ad9361_gain.auxdac_word = uj_intRange(D, 0,65535); break; }
case J_ad9361_tcomp_coeff_a: { txlut->lut[slot].ad9361_tcomp.coeff_a = uj_intRange(D,-32768,32767); break; }
case J_ad9361_tcomp_coeff_b: { txlut->lut[slot].ad9361_tcomp.coeff_b = uj_intRange(D,-32768,32767); break; }
default: {
uj_error(D, "Illegal 'txlut' field: %s", D->field.name);
}
}
}
uj_exitObject(D);
txlut->size = slot+1;
}
uj_exitArray(D);
}
static u1_t parse_antenna_type (str_t s) {
if( strcasecmp(s,"omni") == 0 )
return SX1301_ANT_OMNI;
if( strcasecmp(s,"sector") == 0 )
return SX1301_ANT_SECTOR;
LOG(MOD_RAL|ERROR,"Unknown antenna info: %s (treating as undefined)", s);
return SX1301_ANT_UNDEF;
}
static void parse_rf_chain_conf (ujdec_t* D, sx1301ar_board_cfg_t* board, float* txpow_adjusts, u1_t* antenna_types) {
int slot;
uj_enterArray(D);
while( (slot = uj_nextSlot(D)) >= 0 ) {
if( slot >= SX1301AR_BOARD_RFCHAIN_NB )
uj_error(D, "Too many 'rf_chain_conf' entries (no more than %d allowed)", SX1301AR_BOARD_RFCHAIN_NB);
sx1301ar_rfchain_t* rfchain = &board->rf_chain[slot];
ujcrc_t field;
uj_enterObject(D);
while( (field = uj_nextField(D)) ) {
switch(field) {
case J_tx_enable: { rfchain->tx_enable = uj_bool(D); break; }
case J_rx_enable: { rfchain->rx_enable = uj_bool(D); break; }
case J_rssi_offset: { rfchain->rssi_offset = uj_num(D); break; }
case J_rssi_offset_coeff_a: { rfchain->rssi_offset_coeff_a = uj_intRange(D,-32768,32767); break; }
case J_rssi_offset_coeff_b: { rfchain->rssi_offset_coeff_a = uj_intRange(D,-32768,32767); break; }
case J_tx_freq_min:
case J_tx_freq_max: { uj_uint(D); break; } // we're not using this - checked via LNS channel plan
case J_tx_lut: { parse_tx_lut(D, &rfchain->tx_lut); break; }
// -------------------- station specific
case J_txpow_adjust: { txpow_adjusts[slot] = uj_num(D); break; }
case J_antenna_type: { antenna_types[slot] = parse_antenna_type(uj_str(D)); break; }
default: {
uj_error(D, "Illegal field (ignored): %s", D->field.name);
}
}
}
uj_exitObject(D);
}
uj_exitArray(D);
}
static void parse_lbt_conf (ujdec_t* D, sx1301ar_lbt_cfg_t* lbtconf) {
ujcrc_t field;
uj_enterObject(D);
while( (field = uj_nextField(D)) ) {
switch(field) {
case J_enable: { lbtconf->enable = uj_bool(D); break; }
case J_rssi_target: { lbtconf->rssi_target = uj_intRange(D,-128,127); break; }
case J_rssi_shift: { lbtconf->rssi_shift = uj_intRange(D, 0,255); break; }
case J_chan_cfg: { uj_skipValue(D); break; } // we auto populate from channel plan
default: {
uj_error(D, "Illegal field: %s", D->field.name);
}
}
}
uj_exitObject(D);
}
static int parse_bandwidth (ujdec_t* D) {
sL_t bw = uj_int(D);
switch(bw) {
case 500000: return BW_500K; break;
case 250000: return BW_250K; break;
case 125000: return BW_125K; break;
default:
uj_error(D, "Illegal bandwidth value: %ld (must be 125000, 250000, or 500000)");
return BW_UNDEFINED; // NOT REACHED
}
}
static int parse_spread_factor_range (ujdec_t* D) {
if( uj_nextValue(D) == UJ_STRING ) {
str_t s = uj_str(D);
int sfmin = rt_readDec(&s);
int sfmax = sfmin;
if( s[0] == '-' ) {
s += 1;
sfmax = rt_readDec(&s);
}
if( sfmin < 7 || sfmin > 12 || sfmin > sfmax || s[0] )
uj_error(D, "Failed to parse spread factor range (expecting \"num-num\" or \"num\")");
return ((MR_SF7 << (sfmax-7+1)) - 1) & ~((MR_SF7 << (sfmin-7)) - 1);
} else {
return MR_SF7 << (uj_intRange(D, 7,12) - 7);
}
}
static int parse_spread_factor (ujdec_t* D) {
sL_t sf = uj_int(D);
if( sf < 7 || sf > 12 )
uj_error(D, "Illegal spread_factor value: %ld (must be 7,..,12)", sf);
return MR_SF7 << (sf-7);
}
static void parse_SX1301_conf (ujdec_t* D, sx1301ar_chip_cfg_t* chipconf, sx1301ar_chan_cfg_t* chanconfs) {
ujcrc_t field;
int chan = 0;
uj_enterObject(D);
while( (field = uj_nextField(D)) ) {
switch(field) {
case J_chip_enable : { chipconf->enable = uj_bool(D); break; }
case J_chip_center_freq: { chipconf->freq_hz = uj_int(D); break; }
case J_chip_rf_chain : { chipconf->rf_chain = uj_intRange(D, 0, SX1301AR_BOARD_RFCHAIN_NB-1); break; }
case J_chan_multiSF_7 : { chan = 7; goto multiSFx; }
case J_chan_multiSF_6 : { chan = 6; goto multiSFx; }
case J_chan_multiSF_5 : { chan = 5; goto multiSFx; }
case J_chan_multiSF_4 : { chan = 4; goto multiSFx; }
case J_chan_multiSF_3 : { chan = 3; goto multiSFx; }
case J_chan_multiSF_2 : { chan = 2; goto multiSFx; }
case J_chan_multiSF_1 : { chan = 1; goto multiSFx; }
case J_chan_multiSF_0 : { chan = 0;
multiSFx:
uj_enterObject(D);
while( (field = uj_nextField(D)) ) {
switch(field) {
case J_chan_rx_freq : { chanconfs[chan].freq_hz = uj_uint(D); break; }
case J_bandwidth : { chanconfs[chan].bandwidth = parse_bandwidth(D); break; }
case J_spread_factor: { chanconfs[chan].modrate = parse_spread_factor_range(D); break; }
default: { uj_error(D, "Illegal field: %s", D->field.name); }
}
}
uj_exitObject(D);
break;
}
case J_chan_LoRa_std: {
uj_enterObject(D);
while( (field = uj_nextField(D)) ) {
switch(field) {
case J_chan_rx_freq : { chanconfs[SX1301AR_CHIP_LSA_IDX].freq_hz = uj_uint(D); break; }
case J_bandwidth : { chanconfs[SX1301AR_CHIP_LSA_IDX].bandwidth = parse_bandwidth(D); break; }
case J_spread_factor: { chanconfs[SX1301AR_CHIP_LSA_IDX].modrate = parse_spread_factor(D); break; }
default: { uj_error(D, "Illegal field: %s", D->field.name); }
}
}
uj_exitObject(D);
break;
}
case J_chan_FSK: {
uj_enterObject(D);
while( (field = uj_nextField(D)) ) {
switch(field) {
case J_chan_rx_freq : { chanconfs[SX1301AR_CHIP_FSK_IDX].freq_hz = uj_uint(D); break; }
case J_bandwidth : { chanconfs[SX1301AR_CHIP_FSK_IDX].bandwidth = parse_bandwidth(D); break; }
case J_bit_rate : { chanconfs[SX1301AR_CHIP_FSK_IDX].modrate = uj_uint(D); break; }
default: { uj_error(D, "Illegal field: %s", D->field.name); }
}
}
uj_exitObject(D);
break;
}
default: {
uj_error(D, "Illegal field: %s", D->field.name);
}
}
}
uj_exitObject(D);
}
static void setDevice (struct board_conf* boardconf, str_t device) {
str_t dev = sys_radioDevice(device);
int sz = sizeof(boardconf->device);
int n = snprintf(boardconf->device, sz, "%s", dev);
if( n > sz-1 )
LOG(ERROR, "Device string too long (max %d chars): %s", sz-1, dev);
rt_free((void*)dev);
}
static void parse_radio_conf (ujdec_t* D, struct sx1301v2conf* sx1301v2conf) {
int boardidx;
uj_enterArray(D);
while( (boardidx = uj_nextSlot(D)) >= 0 ) {
if( boardidx >= SX1301AR_MAX_BOARD_NB )
uj_error(D, "Too many radio boards - max %d supported", SX1301AR_MAX_BOARD_NB);
sx1301ar_board_cfg_t* boardconf = &sx1301v2conf->boards[boardidx].boardConf;
ujcrc_t field;
uj_enterObject(D);
while( (field = uj_nextField(D)) ) {
switch(field) {
case J_loramac_public: { boardconf->loramac_public = uj_bool(D); break; }
case J_device : { setDevice(&sx1301v2conf->boards[boardidx], uj_str(D)); break; } // station specific
case J_pps : { sx1301v2conf->boards[boardidx].pps = uj_bool(D); break; } // ditto
case J_board_rx_freq : { boardconf->rx_freq_hz = uj_uint(D); break; }
case J_board_rx_bw : { boardconf->rx_bw_hz = uj_uint(D); break; }
case J_full_duplex : { boardconf->full_duplex = uj_bool(D); break; }
case J_board_type: {
str_t s = uj_str(D);
/**/ if( strcmp(s,"MASTER") == 0 ) boardconf->board_type = BRD_MASTER;
else if( strcmp(s,"SLAVE") == 0 ) boardconf->board_type = BRD_SLAVE;
else uj_error(D, "Wrong board type: %s (must be MASTER or SLAVE)", s);
break;
}
case J_FSK_sync: {
u1_t buf[8];
int n = uj_hexstr(D, buf, sizeof(buf));
uL_t fsk_sync = 0;
for( int i=0; i<n; i++ )
fsk_sync = (fsk_sync<<8) | buf[i];
boardconf->fsk_sync_word = fsk_sync;
boardconf->fsk_sync_size = n;
break;
}
case J_calibration_temperature_celsius_room: {
boardconf->room_temp_ref = uj_intRange(D,-128,127);
break;
}
case J_calibration_temperature_code_ad9361: {
boardconf->ad9361_temp_ref = uj_intRange(D,0,255);
break;
}
case J_nb_dsp: {
boardconf->nb_dsp = uj_intRange(D,0,SX1301AR_BOARD_NB_CHIP_PER_DSP);
break;
}
case J_dsp_stat_interval: {
boardconf->dsp_stat_interval = uj_intRange(D,0,255);
break;
}
case J_aes_key: {
int n = uj_hexstr(D, boardconf->aes_key, sizeof(boardconf->aes_key));
if( n != 16 )
uj_error(D, "AES key must be %d bytes long", sizeof(boardconf->aes_key));
break;
}
case J_rf_chain_conf: {
parse_rf_chain_conf(D, boardconf,
sx1301v2conf->boards[boardidx].txpowAdjusts,
sx1301v2conf->boards[boardidx].antennaTypes);
break;
}
case J_SX1301_conf: {
int sxidx, chipidx = 0;
for( int i=0; i < boardidx; i++ )
chipidx = sx1301v2conf->boards[i].boardConf.nb_chip;
uj_enterArray(D);
while( (sxidx = uj_nextSlot(D)) >= 0 ) {
if( chipidx+sxidx >= MAX_SX1301_NUM )
uj_error(D, "Too many SX1301 chips - max %d supported", MAX_SX1301_NUM);
struct chip_conf* p = &sx1301v2conf->sx1301[chipidx+sxidx];
parse_SX1301_conf(D, &p->chipConf, p->chanConfs);
sx1301v2conf->boards[boardidx].boardConf.nb_chip = sxidx+1;
}
uj_exitArray(D);
break;
}
case J_lbt_conf: {
parse_lbt_conf(D, &sx1301v2conf->boards[boardidx].lbtConf);
break;
}
default: {
LOG(MOD_RAL|WARNING, "Ignoring unsupported/unknown field: %s", D->field.name);
uj_skipValue(D);
break;
}
}
}
uj_exitObject(D);
}
uj_exitArray(D);
}
static int find_and_parse_radio_conf (str_t filename, struct sx1301v2conf* sx1301v2conf) {
dbuf_t jbuf = sys_readFile(filename);
if( jbuf.buf == NULL )
return 0;
ujdec_t D;
uj_iniDecoder(&D, jbuf.buf, jbuf.bufsize);
if( uj_decode(&D) ) {
LOG(MOD_RAL|ERROR, "Parsing of JSON failed - '%s' ignored", filename);
rt_free(jbuf.buf);
return 0;
}
ujcrc_t field;
uj_enterObject(&D);
while( (field = uj_nextField(&D)) ) {
switch(field) {
case J_radio_conf: {
parse_radio_conf(&D, sx1301v2conf);
break;
}
case J_station_conf: {
// Parsed elsewhere
uj_skipValue(&D);
break;
}
default: {
LOG(MOD_RAL|WARNING, "Ignoring unsupported/unknown field: %s", D.field.name);
uj_skipValue(&D);
break;
}
}
}
uj_exitObject(&D);
uj_assertEOF(&D);
rt_free(jbuf.buf);
return 1;
}
static int setup_LBT (struct sx1301v2conf* sx1301v2conf, u4_t cca_region) {
u2_t scantime_us = 0;
s1_t rssi_target = 0;
if( cca_region == J_AS923JP ) {
scantime_us = 5000;
rssi_target = -80;
}
else if( cca_region == J_KR920 ) {
scantime_us = 5000;
rssi_target = -67;
}
else {
LOG(MOD_RAL|ERROR, "Failed to setup CCA/LBT for region (crc=0x%08X)", cca_region);
return 0;
}
for( int i=0; i < MAX_SX1301_NUM; i++ ) {
sx1301v2conf->boards[SX1301AR_MAX_BOARD_NB].lbtConf.rssi_target = rssi_target;
}
// By default use 125KHz up link frequencies as LBT frequencies
// Otherwise we should have gotten a freq list from the server
int lbtchan = 0;
int boardidx = 0;
for( int i=0; i < MAX_SX1301_NUM; i++ ) {
for( int j=0; j < SX1301AR_CHIP_MULTI_NB; j++ ) {
u4_t f = sx1301v2conf->sx1301[i].chanConfs[j].freq_hz;
if( f==0 ) continue;
if( lbtchan == 0 )
sx1301v2conf->boards[boardidx].lbtConf.enable = 1;
sx1301v2conf->boards[boardidx].lbtConf.channels[lbtchan].freq_hz = f;
sx1301v2conf->boards[boardidx].lbtConf.channels[lbtchan].scan_time_us = scantime_us;
if( (lbtchan += 1) == SX1301AR_LBT_CHANNEL_NB_MAX ) {
lbtchan = 0;
if( (boardidx += 1) == SX1301AR_MAX_BOARD_NB )
goto stop;
}
}
}
stop:
for( int i=0; i < SX1301AR_MAX_BOARD_NB; i++ ) {
if( sx1301v2conf->boards[i].lbtConf.enable ) {
if( sx1301ar_conf_lbt(i, &sx1301v2conf->boards[i].lbtConf) ) {
LOG(MOD_RAL|ERROR, "sx1301ar_conf_lbt(%d,..) failed: %s", i, sx1301ar_err_message(sx1301ar_errno));
return 0;
}
}
}
return 1;
}
static int parse_sx1301_lns_conf (ujdec_t* D, struct lns_sx1301_conf* confs) {
int sx1301idx, sx1301num;
uj_enterArray(D);
while( (sx1301idx = uj_nextSlot(D)) >= 0 ) {
sx1301num = sx1301idx+1;
if( sx1301idx >= MAX_SX1301_NUM )
uj_error(D, "Too many SX1301 - max %d supported", MAX_SX1301_NUM);
struct lns_sx1301_conf* conf = &confs[sx1301idx];
u4_t rfconf_freq[2] = {0,0};
u4_t chanRadio = 0;
ujcrc_t field;
uj_enterObject(D);
while( (field = uj_nextField(D)) ) {
switch(field) {
case J_radio_0:
case J_radio_1: {
int idx = uj_indexedField(D,"radio_");
uj_enterObject(D);
while( (field = uj_nextField(D)) ) {
switch(field) {
case J_enable: { uj_bool(D); break; }
case J_freq : { rfconf_freq[idx] = uj_intRangeOr(D, 1000000, 1000000000, 0); break; }
default: goto err;
}
}
uj_exitObject(D);
break;
}
case J_chan_multiSF_0:
case J_chan_multiSF_1:
case J_chan_multiSF_2:
case J_chan_multiSF_3:
case J_chan_multiSF_4:
case J_chan_multiSF_5:
case J_chan_multiSF_6:
case J_chan_multiSF_7: {
int idx = uj_indexedField(D,"chan_multiSF_");
uj_enterObject(D);
while( (field = uj_nextField(D)) ) {
switch(field) {
case J_enable :{ conf->chanEnabled |= uj_bool(D) << idx; break; }
case J_if :{ conf->chanFreqs[idx] = uj_int(D); break; }
case J_radio :{ chanRadio |= uj_intRange(D,0,1) << idx; break; }
default: goto err;
}
}
uj_exitObject(D);
break;
}
case J_chan_Lora_std:
case J_chan_LoRa_std: {
int idx = SX1301AR_CHIP_LSA_IDX;
uj_enterObject(D);
while( (field = uj_nextField(D)) ) {
switch(field) {
case J_enable :{ conf->chanEnabled |= uj_bool(D) << idx; break; }
case J_if :{ conf->chanFreqs[idx] = uj_int(D); break; }
case J_radio :{ chanRadio |= uj_intRange(D,0,1) << idx; break; }
case J_bandwidth:{ conf->lsaChan.bandwidth = parse_bandwidth(D); break; }
case J_spread_factor:{ conf->lsaChan.spreadfactor = parse_spread_factor(D); break; }
default: goto err;
}
}
uj_exitObject(D);
break;
}
case J_chan_FSK: {
int idx = SX1301AR_CHIP_FSK_IDX;
uj_enterObject(D);
while( (field = uj_nextField(D)) ) {
switch(field) {
case J_enable :{ conf->chanEnabled |= uj_bool(D) << idx; break; }
case J_if :{ conf->chanFreqs[idx] = uj_int(D); break; }
case J_radio :{ chanRadio |= uj_intRange(D,0,1) << idx; break; }
case J_datarate :{ conf->fskDatarate = uj_uint(D); break; }
default: goto err;
}
}
uj_exitObject(D);
break;
}
default: goto err;
}
}
uj_exitObject(D);
// Fix freq offsets into absolute frequencies
for( int i=0; i<SX1301AR_CHIP_CHAN_NB; i++ ) {
if( (conf->chanEnabled >> i) & 1 ) {
conf->chanFreqs[i] += rfconf_freq[(chanRadio >> i) & 1];
}
}
}
uj_exitArray(D);
return sx1301num;
err:
uj_error(D, "Server side radio config - Illegal field: %s", D->field.name);
return 0;
}
int sx1301v2conf_parse_setup (struct sx1301v2conf* sx1301v2conf, int slaveIdx,
str_t hwspec, char* json, int jsonlen) {
if( strncmp(hwspec, "sx1301/", 7) != 0 ) {
LOG(MOD_RAL|ERROR, "Unsupported hwspec: %s", hwspec);
return 0;
}
// Zero and setup some defaults
memset(sx1301v2conf, 0, sizeof(*sx1301v2conf));
for( int i=0; i < SX1301AR_MAX_BOARD_NB; i++ ) {
sx1301v2conf->boards[i].boardConf = sx1301ar_init_board_cfg();
sx1301v2conf->boards[i].lbtConf = sx1301ar_init_lbt_cfg();
sx1301v2conf->boards[i].boardConf.loramac_public = 1;
setDevice(&sx1301v2conf->boards[i], NULL);
for( int j=0; j<SX1301AR_BOARD_RFCHAIN_NB; j++ ) {
sx1301v2conf->boards[i].boardConf.rf_chain[j].tx_lut = sx1301ar_init_tx_gain_lut();
for( int k=0; k < SX1301AR_BOARD_MAX_LUT_NB; k++ ) {
sx1301v2conf->boards[i].boardConf.rf_chain[j].tx_lut.lut[k] = sx1301ar_init_tx_gain();
}
}
}
for( int i=0; i<MAX_SX1301_NUM; i++ ) {
sx1301v2conf->sx1301[i].chipConf = sx1301ar_init_chip_cfg();
for( int j=0; j<SX1301AR_CHIP_CHAN_NB; j++ )
sx1301v2conf->sx1301[i].chanConfs[j] = sx1301ar_init_chan_cfg();
}
if( !find_and_parse_radio_conf("station.conf", sx1301v2conf) )
return 0;
ujdec_t D;
uj_iniDecoder(&D, json, jsonlen);
if( uj_decode(&D) ) {
LOG(MOD_RAL|ERROR, "Parsing of JSON failed - 'router_config.sx1301_conf' ignored");
return 0;
}
if( uj_null(&D) ) {
LOG(MOD_RAL|ERROR, "LNS sx1301_conf is null but a HW setup IS required - no fallbacks");
return 0;
}
struct lns_sx1301_conf lnsconfs[MAX_SX1301_NUM];
memset(lnsconfs, 0, sizeof(lnsconfs));
int lns_sx1301_num = parse_sx1301_lns_conf(&D, lnsconfs);
uj_assertEOF(&D);
int hw_sx1301_num = 0;
for( int i=0; i < SX1301AR_MAX_BOARD_NB; i++ ) {
hw_sx1301_num += sx1301v2conf->boards[i].boardConf.nb_chip;
}
// Merge LNS settings into local config
if( lns_sx1301_num > hw_sx1301_num ) {
LOG(MOD_RAL|ERROR, "Cannot map region plan onto available SX1301 chips - LNS/HW: %d/%d", lns_sx1301_num, hw_sx1301_num);
return 0;
}
// Assign SX1301 definitions from LNS to loaded HW layout
for( int i=0; i < lns_sx1301_num; i++ ) {
struct chip_conf* c = &sx1301v2conf->sx1301[i];
u4_t minFreq = -1, maxFreq = 0;
for( int j=0; j < SX1301AR_CHIP_CHAN_NB; j++ ) {
sx1301ar_chan_cfg_t* chanc = &c->chanConfs[j];
u4_t f = lnsconfs[i].chanFreqs[j];
if( f==0 )
continue;
minFreq = min(minFreq, f);
maxFreq = max(maxFreq, f);
chanc->enable = 1;
chanc->freq_hz = f;
if( j == SX1301AR_CHIP_FSK_IDX ) {
chanc->modrate = MR_56000;
}
else if( j == SX1301AR_CHIP_LSA_IDX ) {
chanc->modrate = lnsconfs[i].lsaChan.spreadfactor;
chanc->bandwidth = lnsconfs[i].lsaChan.bandwidth;
}
else {
chanc->modrate = MR_SF7_12;
chanc->bandwidth = BW_125K;
}
}
c->chipConf.enable = 1;
c->chipConf.rf_chain = 0;
c->chipConf.freq_hz = (maxFreq+minFreq)/2;
}
return 1;
}
static void dump_boardConf (int bid, sx1301ar_board_cfg_t* c) {
LOG(MOD_RAL|VERBOSE,
"BRD#%d: rx_freq_hz=%d rx_bw_hz=%d",
bid,
c->rx_freq_hz,
c->rx_bw_hz);
}
static void dump_chipConf (int chipid, sx1301ar_chip_cfg_t* c) {
LOG(MOD_RAL|VERBOSE,
"SX1301#%d: enable=%d rf_chain=%d freq=%d",
chipid,
c->enable,
c->rf_chain,
c->freq_hz);
}
static void dump_chanConf (int chipid, int chanid, sx1301ar_chan_cfg_t* c) {
LOG(MOD_RAL|VERBOSE,
"SX1301#%d chan %2d: enable=%d freq=%d bandwidth=%d modrate=%d",
chipid, chanid,
c->enable,
c->freq_hz,
c->bandwidth,
c->modrate);
}
int sx1301v2conf_start (struct sx1301v2conf* sx1301v2conf, u4_t cca_region) {
int nboards = 0;
for( int boardidx=0; boardidx < SX1301AR_MAX_BOARD_NB; boardidx++ ) {
sx1301ar_board_cfg_t* bc = &sx1301v2conf->boards[boardidx].boardConf;
if( !bc->nb_chip ) continue;
nboards = boardidx+1;
dump_boardConf(boardidx, bc);
if( sx1301ar_conf_board(boardidx, bc) != 0 ) {
LOG(MOD_RAL|ERROR, "sx1301ar_conf_board(%d,..) failed: %s", boardidx, sx1301ar_err_message(sx1301ar_errno));
return 0;
}
for( int chipidx=0; chipidx < bc->nb_chip; chipidx++ ) {
struct chip_conf* cc = &sx1301v2conf->sx1301[chipidx];
if( !cc->chipConf.enable )
continue;
dump_chipConf(chipidx, &cc->chipConf);
if( sx1301ar_conf_chip(boardidx, chipidx, &cc->chipConf) != 0 ) {
LOG(MOD_RAL|ERROR, "sx1301ar_conf_chip(%d,%d,..) failed: %s",
boardidx, chipidx, sx1301ar_err_message(sx1301ar_errno));
return 0;
}
for( int chanidx=0; chanidx < SX1301AR_CHIP_CHAN_NB; chanidx++ ) {
if( !cc->chanConfs[chanidx].enable )
continue;
dump_chanConf(chipidx, chanidx, &cc->chanConfs[chanidx]);
if( sx1301ar_conf_chan(boardidx, (chipidx << 4) | chanidx, &cc->chanConfs[chanidx]) != 0 ) {
LOG(MOD_RAL|ERROR, "sx1301ar_conf_chan(%d,%d,%d,..) failed: %s",
boardidx, chipidx, chanidx, sx1301ar_err_message(sx1301ar_errno));
return 0;
}
}
}
}
if( cca_region && !setup_LBT(sx1301v2conf, cca_region) ) {
goto fail;
}
if( sx1301ar_start(nboards) != 0 ) {
LOG(MOD_RAL|ERROR, "sx1301ar_start(%d) failed: %s", nboards, sx1301ar_err_message(sx1301ar_errno));
return 0;
}
return 1;
fail:
return 0;
}
#endif // defined(CFG_lgw2)
|
the_stack_data/5507.c | // RUN: rm -rf %t*
// RUN: 3c -base-dir=%S -alltypes -addcr %s -- | FileCheck -match-full-lines -check-prefixes="CHECK_ALL","CHECK" %s
// RUN: 3c -base-dir=%S -addcr %s -- | FileCheck -match-full-lines -check-prefixes="CHECK_NOALL","CHECK" %s
// RUN: 3c -base-dir=%S -addcr %s -- | %clang -c -fcheckedc-extension -x c -o /dev/null -
// RUN: 3c -base-dir=%S -alltypes -output-dir=%t.checked %s --
// RUN: 3c -base-dir=%t.checked -alltypes %t.checked/b26_castprotounsafe.c -- | diff %t.checked/b26_castprotounsafe.c -
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int *sus(int *, int *);
//CHECK_NOALL: _Ptr<int> sus(int *x : itype(_Ptr<int>), _Ptr<int> y);
//CHECK_ALL: _Ptr<int> sus(_Array_ptr<int> x, _Ptr<int> y);
int *foo() {
//CHECK: _Ptr<int> foo(void) {
int sx = 3, sy = 4;
int *x = &sx;
//CHECK_NOALL: _Ptr<int> x = &sx;
//CHECK_ALL: int *x = &sx;
int *y = &sy;
//CHECK: _Ptr<int> y = &sy;
int *z = (int *)sus(x, y);
//CHECK_NOALL: _Ptr<int> z = (_Ptr<int>)sus(x, y);
//CHECK_ALL: _Ptr<int> z = (_Ptr<int>)sus(_Assume_bounds_cast<_Array_ptr<int>>(x, bounds(unknown)), y);
*z = *z + 1;
return z;
}
char *bar() {
//CHECK: char *bar(void) : itype(_Ptr<char>) {
int sx = 3, sy = 4;
int *x = &sx;
//CHECK_NOALL: _Ptr<int> x = &sx;
//CHECK_ALL: int *x = &sx;
int *y = &sy;
//CHECK: _Ptr<int> y = &sy;
char *z = (char *)(sus(x, y));
//CHECK_NOALL: char *z = (char *)(((int *)sus(x, y)));
//CHECK_ALL: char *z = (char *)(((int *)sus(_Assume_bounds_cast<_Array_ptr<int>>(x, bounds(unknown)), y)));
return z;
}
int *sus(int *x, int *y) {
//CHECK_NOALL: _Ptr<int> sus(int *x : itype(_Ptr<int>), _Ptr<int> y) {
//CHECK_ALL: _Ptr<int> sus(_Array_ptr<int> x, _Ptr<int> y) {
int *z = malloc(sizeof(int));
//CHECK: _Ptr<int> z = malloc<int>(sizeof(int));
*z = 1;
x++;
*x = 2;
return z;
}
|
the_stack_data/6387857.c | /*
* (C) Copyright 2005- ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
* In applying this licence, ECMWF does not waive the privileges and immunities
* granted to it by virtue of its status as an intergovernmental organisation
* nor does it submit to any jurisdiction.
*/
/* ecmwf_transfer.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Used in module strhandler (stransfer) */
void
ecmwf_transfer_(void *out, const int *Len_out,
const void *in, const int *Len_in
/* Possible hidden argument (not referred) */
, int Sta_lin)
{
int len = *Len_out;
if (*Len_in < len) len = *Len_in;
if (len > 0) memcpy(out,in,len);
}
|
the_stack_data/43888329.c | /*
print-prime.c
By David Broman.
Last modified: 2015-09-15
This file is in the public domain.
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdbool.h>
#define COLUMNS 6
/**
* Returns 1 if n is prime else 0.
* @param n - the number to be checked for prime status
* @return - 1 or 0 (true or false) whether or not n is prime
*/
int is_prime(int n){
if(n<2){
return 0;
}
int sqrt_rounded_up_int = (int) sqrt(n) +1;
for(int i = 2;i<sqrt_rounded_up_int;i++){
if(n % i == 0){
return 0;
}
}
return 1;
}
void print_number(int number_to_print){
printf("%8d ", number_to_print);
}
///does not use more than n bytes of the array (n+12 bytes total)
///@param n - largest number to check for primality / all numbers 2 to n are checked for prime status
///@return an array
void print_sieve(int n){
// int *x
//mem[x] -> y
//int* pointer_to_array = (int *) malloc(sizeof(int)*(n-1));
//bool is 1 byte
bool* sieves_prime = (bool *) malloc(sizeof(bool)*(n+1)); //sieves_prime[i] == 1 om i är primtal annars == 0 - n+1 eftersom vi har med 0 också därmed blir det n+1 värden
//example n==5
//[0,1,2,3,4,5] i.e. sieves_prime[0] <=> is_prime(2)
//[0,0,0,0,0,0]
for (int i = 0; i <= 2; i++){//initialize number 0 and 1 to false
sieves_prime [i] = false; //syntactic sugar for *(sieves_prime+i) = 0;
}
for (int i = 2; i <= n; i++){
sieves_prime [i] = true; // *(sieves_prime+i) = 1;
}
int sqrt_rounded_up_int = (int) sqrt(n) +1;
for (int i = 2; i <= sqrt_rounded_up_int; i++){
if(sieves_prime[i] == 1){ // 1 indicates that its a prime *(sieves_prime+i) == 1;
for (int j = i*i; j <= n; j+=i){//i^2, i^2+i, i^2+2i...
sieves_prime[j] = 0; // *(sieves_prime+j) = 0;
}
}
}
int num_prints_since_last_newline = 0;
for (int i = 0; i <= n; i++){
if(sieves_prime[i] == 1){
print_number(i);
num_prints_since_last_newline +=1;
}
if(num_prints_since_last_newline >= COLUMNS){
printf("\n");
num_prints_since_last_newline = 0;
}
}
//printf("%8d",&sieves_prime);
free(sieves_prime);
}
/*
int num_prints_since_last_newline = 0;
for(int i = 2; i < n; i++){
if(is_prime(i)){
print_number(i);
num_prints_since_last_newline +=1;
}
if(num_prints_since_last_newline >= COLUMNS){
printf("\n");
num_prints_since_last_newline = 0;
}
}
*/
//printf("%d", *sieves_prime);
// 'argc' contains the number of program arguments, and
// 'argv' is an array of char pointers, where each
// char pointer points to a null-terminated string.
int main(int argc, char *argv[]){
if(argc == 1+1) //1+ num_arguments in the program
print_sieve(atoi(argv[1]));
else
printf("Please state an interger number.\n");
return 0;
}
//2e7 till 5e7 give or take sieves-heap
//sieve går snabbare (stacken snabbare än heapen)
|
the_stack_data/193894184.c | #include <stdint.h>
#include <math.h>
// Lookup table for counting set bits
// http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetTable
static const unsigned int BitsSetTable256[256] = {
#define B2(n) n, n+1, n+1, n+2
#define B4(n) B2(n), B2(n+1), B2(n+1), B2(n+2)
#define B6(n) B4(n), B4(n+1), B4(n+1), B4(n+2)
B6(0), B6(1), B6(1), B6(2)
};
int count_set_bits(uint8_t *bytes, int size) {
int c = 0;
for (int i = 0; i < size; i++) {
c += BitsSetTable256[bytes[i]];
}
return c;
}
double z_score(int setbits, int size) {
double mean = size * 4;
double std = sqrt(mean * .5);
return (setbits - mean) / std;
} |
the_stack_data/72012453.c | const char glsl_plain_idx16_lut_fsh_src[] =
"\n"
"#pragma optimize (on)\n"
"#pragma debug (off)\n"
"\n"
"uniform sampler2D color_texture;\n"
"uniform sampler2D colortable_texture;\n"
"uniform vec2 colortable_sz; // ct size\n"
"uniform vec2 colortable_pow2_sz; // pow2 ct size\n"
"\n"
"void main()\n"
"{\n"
" vec4 color_tex;\n"
" vec2 color_map_coord;\n"
"\n"
" // normalized texture coordinates ..\n"
" color_tex = texture2D(color_texture, gl_TexCoord[0].st);\n"
"\n"
" // GL_UNSIGNED_SHORT GL_ALPHA in ALPHA16 conversion:\n"
" // general: f = c / ((2*N)-1), c color bitfield, N number of bits\n"
" // ushort: c = ((2**16)-1)*f;\n"
" color_map_coord.x = floor( 65535.0 * color_tex.a + 0.5 );\n"
"\n"
" // map it to the 2D lut table\n"
" color_map_coord.y = floor(color_map_coord.x/colortable_sz.x);\n"
" color_map_coord.x = mod(color_map_coord.x,colortable_sz.x);\n"
"\n"
" gl_FragColor = texture2D(colortable_texture, color_map_coord / (colortable_pow2_sz-1.0));\n"
"}\n"
"\n"
"\n"
;
|
the_stack_data/154239.c | int g = 0xEB0647DCL;
int main(void) {
int i = (0xEB0647DCL < (g | 0x4B54C5F6B4AB19F8LL));
return i;
}
|
the_stack_data/12904.c | /* Exercise 3-4. In a two's complement number representation, our version of
* itoa does not handle the largest negative number, that is, the value of n
* equal to -(2^wordsize-1). Explain why not. Modify it to print that value
* correctly, regardless of the machine on which it runs.
*/
/* Explanation:
In a two's complement number representation, 2147483648 cannot be represented
in a signed 32-bit integer, so we have to display it either as an unsigned long
int, or a long long int.
My solution simply changes the data type from a 32-bit int to an unsigned long
*/
#include<stdio.h>
#include<string.h>
#include<limits.h>
void itoa(unsigned long n, char s[]);
void reverse(char s[]);
int main(void)
{
char s[1000];
itoa(INT_MIN,s);
printf("%s",s);
return 0;
}
/* itoa: convert n to characters in s */
void itoa(unsigned long n, char s[])
{
int i, sign;
if ((sign = n) < 0) /* record sign */
n = -n; /* make n positive */
i = 0;
do { /* generate digits in reverse order */
s[i++] = n % 10 + '0'; /* get next digit */
} while ((n /= 10) > 0); /* delete it */
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
}
/* reverse: reverse string s in place */
void reverse(char s[])
{
int c, i ,j;
for (i= 0, j = strlen(s)-1; i < j; i++, j--) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
|
the_stack_data/51699036.c | #include <assert.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* readline();
int main()
{
char* n_endptr;
char* n_str = readline();
int n = strtol(n_str, &n_endptr, 10);
if (n_endptr == n_str || *n_endptr != '\0') { exit(EXIT_FAILURE); }
if(n==1)printf("one\n");
else if(n==2)printf("two\n");
else if(n==3)printf("three\n");
else if(n==4)printf("four\n");
else if(n==5)printf("five\n");
else if(n==6)printf("six\n");
else if(n==7)printf("seven\n");
else if(n==8)printf("eight\n");
else if(n==9)printf("nine\n");
else printf("Greater than 9\n");
return 0;
}
/*
Task
Given a positive integer denoting n do the following:
If n<9 print the lowercase English word corresponding to the number (e.g. one for 1, two for 2 etc.).
If n>9 print Greater than 9.
Input Format
The first line contains a single integer n.
*/
char* readline() {
size_t alloc_length = 1024;
size_t data_length = 0;
char* data = malloc(alloc_length);
while (true) {
char* cursor = data + data_length;
char* line = fgets(cursor, alloc_length - data_length, stdin);
if (!line) { break; }
data_length += strlen(cursor);
if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; }
size_t new_length = alloc_length << 1;
data = realloc(data, new_length);
if (!data) { break; }
alloc_length = new_length;
}
if (data[data_length - 1] == '\n') {
data[data_length - 1] = '\0';
}
data = realloc(data, data_length);
return data;
}
|
the_stack_data/68887304.c | int main() {
float A = 0, B = 0;
float i, j;
int k;
float z[1760];
char b[1760];
printf("\x1b[2J");
for(;;) {
memset(b,32,1760);
memset(z,0,7040);
for(j=0; j < 6.28; j += 0.07) {
for(i=0; i < 6.28; i += 0.02) {
float c = sin(i);
float d = cos(j);
float e = sin(A);
float f = sin(j);
float g = cos(A);
float h = d + 2;
float D = 1 / (c * h * e + f * g + 5);
float l = cos(i);
float m = cos(B);
float n = sin(B);
float t = c * h * g - f * e;
int x = 40 + 30 * D * (l * h * m - t * n);
int y= 12 + 15 * D * (l * h * n + t * m);
int o = x + 80 * y;
int N = 8 * ((f * e - c * d * g) * m - c * d * e - f * g - l * d * n);
if(22 > y && y > 0 && x > 0 && 80 > x && D > z[o]) {
z[o] = D;
b[o] = ".,-~:;=!*#$@"[N > 0 ? N : 0];
}
}
}
printf("\x1b[H");
for(k = 0; k < 1761; k++) {
putchar(k % 80 ? b[k] : 10);
A += 0.00004;
B += 0.00002;
}
usleep(30000);
}
return 0;
}
|
the_stack_data/535053.c | #include<stdio.h>
#include<string.h>
main()
{
char s[100],s1[100];
int i,len=0;
scanf("%[^\n]",s);
/* for(i=0;s[i]!='\0';i++)
{
if(s[i]==' ' && s[i+1]==' ')
continue;
printf("%c",s[i]);
}*/
for(i=0;i<strlen(s);i++)
{
s1[i]=s[i];
}
// s1[100]=s[100];
printf("%s",s1);
}
|
the_stack_data/20879.c | /* { dg-do compile } */
/* { dg-options "-O3" } */
int a, b;
char c;
void fn1() {
b = 30;
for (; b <= 32; b++) {
c = -17;
for (; c <= 56; c++)
a -= 0 == (c || b);
}
}
|
the_stack_data/141402.c | #include<stdio.h>
int main ()
{
int i;
const char *s[] = { "%d\n", "Fizz\n", s[3] + 4, "FizzBuzz\n" };
for (i = 1; i <= 100; i++)
printf(s[!(i % 3) + 2 * !(i % 5)], i);
return 0;
}
|
the_stack_data/190767994.c | #include <stdio.h>
// #define __def__
int main() {
#ifdef __def__
printf("Hello\n");
#endif
printf("Hello World\n");
return 0;
}
|
the_stack_data/86073971.c | int i,j;
int a[100][100];
void foo()
{
for (i=0;i<100;i++)
for (j=0;j<100;j++)
a[i][j]=a[i][j]+1;
}
|
the_stack_data/93888575.c | #include <stdio.h>
#include <stdint.h>
extern void ffmpeg_log_backend(uintptr_t, int, const char*);
void ffmpeg_log_stub(void* ptr, int level,
const char* format, va_list arg) {
char buf[1024]; // if a message is longer than this... oh well
vsnprintf(buf, sizeof(buf), format, arg);
ffmpeg_log_backend((uintptr_t)ptr, level, buf);
}
|
the_stack_data/90177.c | /*
* %CopyrightBegin%
*
* Copyright Ericsson AB and Kjell Winblad 2019. All Rights Reserved.
*
* 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.
*
* %CopyrightEnd%
*/
/*
* Description:
*
* Author: Kjell Winblad
*
*/
#include <stdio.h>
#include <stdlib.h>
#define YCF_YIELD()
int fun2(int x){
YCF_YIELD();
return x;
}
int fun(char x){
int y = 10;
/*special_code_start:ON_SAVE_YIELD_STATE*/
if(0){
printf("y=%d\n", y);
y = 42;
}
/*special_code_end*/
/*special_code_start:ON_RETURN*/
if(0){
printf("I returned y=%d\n", y);
}
/*special_code_end*/
/*special_code_start:ON_DESTROY_STATE_OR_RETURN*/
if(0){
int hej = 123;
printf("I got destroyed or returned y=%d hej=%d\n", y, hej);
}
/*special_code_end*/
/*special_code_start:ON_DESTROY_STATE*/
if(0){
int hej = 321;
printf("I got destroyed y=%d call_in_special_code=%d hej=%d\n", y, fun2(42), hej);
}
/*special_code_end*/
/*special_code_start:ON_RESTORE_YIELD_STATE*/
if(0){
x = 9;
}
/*special_code_end*/
if(0){
/*special_code_start:ON_SAVE_YIELD_STATE*/
if(0){
int z = 10;
printf("y=%d z=%d\n", y, z);
}
/*special_code_end*/
}
if(y != 10 || x != 1){
/*special_code_start:ON_RESTORE_YIELD_STATE*/
if(0){
printf("y=%d x=%d\n", y, x);
x = x*2;
printf("y=%d x=%d\n", y, x);
}
/*special_code_end*/
/*special_code_start:ON_RESTORE_YIELD_STATE*/
if(0){
printf("y=%d x=%d\n", y, x);
x = x/2;
printf("y=%d x=%d\n", y, x);
}
/*special_code_end*/
printf("ERROR BEFORE YIELD\n");
exit(1);
}
YCF_YIELD();
if(y != 42 || x != 9){
printf("ERROR AFTER YIELD\n");
exit(1);
}
printf("SUCCESS\n");
return x;
}
void* allocator(size_t size, void* context){
(void)context;
return malloc(size);
}
void freer(void* data, void* context){
(void)context;
free(data);
}
int main( int argc, const char* argv[] )
{
#ifdef YCF_YIELD_CODE_GENERATED
void* wb = NULL;
#endif
int ret = 0;
long nr_of_reductions = 1;
#ifdef YCF_YIELD_CODE_GENERATED
ret = fun_ycf_gen_yielding(&nr_of_reductions,&wb,NULL,allocator,freer,NULL,0,NULL,1);
printf("CALLING DESTROY\n");
fun_ycf_gen_destroy(wb);
wb = NULL;
printf("DESTROY ENDED\n");
do{
ret = fun_ycf_gen_yielding(&nr_of_reductions,&wb,NULL,allocator,freer,NULL,0,NULL,1);
if(wb != NULL){
printf("TRAPPED\n");
}
}while(wb != NULL);
if(wb != NULL){
free(wb);
}
#else
ret = fun(1);
#endif
printf("RETURNED %d\n", ret);
if(ret != 9){
return 1;
}else{
return 0;
}
}
|
the_stack_data/436751.c | #include <stdio.h>
#include <pthread.h>
void *printInt(void *x) {
printf("%d\n", x);
pthread_exit(NULL);
}
int main( ) {
pthread_t threads[2];
long t1 = 15;
long t2 = 17;
pthread_create(&threads[0], NULL, printInt, (void*)t1);
pthread_create(&threads[1], NULL, printInt, (void*)t2);
pthread_exit(NULL);
return 0;
}
|
the_stack_data/215767580.c | /*
!==========================================================================
elemental function gsw_ct_maxdensity (sa, p)
!==========================================================================
!
! Calculates the Conservative Temperature of maximum density of seawater.
! This function returns the Conservative temperature at which the density
! of seawater is a maximum, at given Absolute Salinity, SA, and sea
! pressure, p (in dbar).
!
! SA = Absolute Salinity [ g/kg ]
! p = sea pressure [ dbar ]
! ( i.e. absolute pressure - 10.1325 dbar )
!
! CT_maxdensity = Conservative Temperature at which [ deg C ]
! the density of seawater is a maximum for
! given Absolute Salinity and pressure.
!--------------------------------------------------------------------------
*/
double
gsw_ct_maxdensity(double sa, double p)
{
int number_of_iterations;
double alpha, ct, ct_mean, ct_old, dalpha_dct,
dct = 0.001;
ct = 3.978 - 0.22072*sa; /*the initial guess of ct.*/
dalpha_dct = 1.1e-5; /*the initial guess for dalpha_dct.*/
for (number_of_iterations = 1; number_of_iterations <= 3;
number_of_iterations++) {
ct_old = ct;
alpha = gsw_alpha(sa,ct_old,p);
ct = ct_old - alpha/dalpha_dct;
ct_mean = 0.5*(ct + ct_old);
dalpha_dct = (gsw_alpha(sa,ct_mean+dct,p)
- gsw_alpha(sa,ct_mean-dct,p))/(dct + dct);
ct = ct_old - alpha/dalpha_dct;
}
/*
! After three iterations of this modified Newton-Raphson (McDougall and
! Wotherspoon, 2012) iteration, the error in CT_maxdensity is typically
! no larger than 1x10^-15 degress C.
*/
return (ct);
}
|
the_stack_data/248579884.c | #include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#define REQUIRED_ARG_COUNT 1
int main(int argc, const char *const *argv)
{
if (argc < REQUIRED_ARG_COUNT + 1)
exit(EXIT_FAILURE);
for(;;)
{
printf("%s\n", argv[1]);
}
return EXIT_FAILURE;
}
|
the_stack_data/206392331.c | /* PR tree-optimization/34371 */
/* Testcase by Martin Michlmayr <[email protected]> */
void centerln (int width, int ch, char *s)
{
unsigned int sidebar;
int i;
char linet1[1000];
char linet2[100];
sidebar = (width - __builtin_strlen (s)) / 2;
for (i = 0; i < sidebar; i++)
linet2[i] = ch;
__builtin_strcpy (linet1, linet2);
}
|
the_stack_data/176706481.c | // A simple Sieve of Eratosthenes
#include <stdint.h>
#include <stdbool.h>
#ifdef TESTBENCH
# include <stdio.h>
#endif
#define BITMAP_SIZE 64
#define OUTPORT 0x10000000
static uint32_t bitmap[BITMAP_SIZE/32];
static void bitmap_set(uint32_t idx)
{
bitmap[idx/32] |= 1 << (idx % 32);
}
static bool bitmap_get(uint32_t idx)
{
return (bitmap[idx/32] & (1 << (idx % 32))) != 0;
}
static void output(uint32_t val)
{
#ifdef TESTBENCH
printf("%d\n", (int)val);
#else
*((volatile uint32_t*)OUTPORT) = val;
#endif
}
int main()
{
uint32_t i, j, k;
output(2);
for (i = 0; i < BITMAP_SIZE; i++) {
if (bitmap_get(i))
continue;
output(3+2*i);
for (j = 2*(3+2*i);; j += 3+2*i) {
if (j%2 == 0)
continue;
k = (j-3)/2;
if (k >= BITMAP_SIZE)
break;
bitmap_set(k);
}
}
output(0);
return 0;
}
|
the_stack_data/70431.c | #include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int *stat(char *a) {
#define LEN 10
int i, *p = malloc(sizeof(int) * LEN);
for (i = 0; i != LEN; i++) {
p[i] = 0;
}
for (; *a != '\0'; a++) {
if (isdigit(*a)) {
p[*a - '0']++;
}
}
return p;
}
int modsum(char *a, char *b) {
int *p = stat(a);
int *q = stat(b);
int i, j, sum;
for (i = 1, sum = 0; i != LEN; i++) {
for (j = 1; j != LEN; j++) {
sum += p[i] * q[j] * (i % j);
}
}
free(p);
free(q);
return sum;
}
int main() {
#define RAWLEN (10000 + 20)
char *a = malloc(sizeof(char) * RAWLEN);
char *b = malloc(sizeof(char) * RAWLEN);
int casenum, i;
scanf("%d", &casenum);
for (i = 0; i != casenum; i++) {
scanf("%s%s", a, b); // to support whitespace or newline as delimeter.
printf("%d\n", modsum(a, b));
}
free(a);
free(b);
return 0;
}
|
the_stack_data/57377.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define A (segments[0])
#define B (segments[1])
#define C (segments[2])
#define D (segments[3])
#define E (segments[4])
#define F (segments[5])
#define G (segments[6])
int
main(void)
{
char buf[128], *tok1, *tok2, *tok3;
int result = 0, display, bitrep;
int bitmask[7] = {0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40};
int orders[4] = {1000, 100, 10, 1};
int bits[7], digits[128], segments[7];
size_t i, j, len;
while (!feof(stdin)) {
if (fgets(buf, sizeof(buf), stdin)) {
tok1 = strtok(buf, "|");
tok2 = strtok(NULL, "\n");
for (i = 0; i < 7; ++i)
bits[i] = 0x7F;
for (tok3 = strtok(tok1, " "); tok3; tok3 = strtok(NULL, " ")) {
bitrep = 0x00;
for (j = 0, len = 0; tok3[j]; ++j, ++len)
bitrep |= bitmask[tok3[j] - 'a'];
bits[len] &= bitrep;
}
A = 0x7F & ~bits[2] & bits[3];
B = 0x7F & ~bits[3] & bits[4] & bits[6];
C = 0x7F & bits[2] & ~bits[6];
D = 0x7F & bits[4] & bits[5];
E = 0x7F & ~bits[4] & ~bits[6];
F = 0x7F & bits[2] & bits[6];
G = 0x7F & ~bits[3] & bits[5] & bits[6];
digits[(A | B | C | E | F | G)] = 0;
digits[( C | F )] = 1;
digits[(A | C | D | E | G)] = 2;
digits[(A | C | D | F | G)] = 3;
digits[( B | C | D | F )] = 4;
digits[(A | B | D | F | G)] = 5;
digits[(A | B | D | E | F | G)] = 6;
digits[(A | C | F )] = 7;
digits[(A | B | C | D | E | F | G)] = 8;
digits[(A | B | C | D | F | G)] = 9;
display = 0;
for (i = 0, tok3 = strtok(tok2, " ");
i < 4 && tok3;
++i, tok3 = strtok(NULL, " ")) {
bitrep = 0x00;
for (j = 0; tok3[j]; ++j)
bitrep |= bitmask[tok3[j] - 'a'];
display += digits[bitrep] * orders[i];
}
result += display;
}
}
printf("%d\n", result);
return EXIT_SUCCESS;
}
|
the_stack_data/639807.c | #include <stdio.h>
#include <stdlib.h>
int add( int a , int b)
{
int sum = a + b;
return sum;
}
int multiply( int x , int y )
{
int prod = x * y;
return prod;
}
int main()
{
int num1 ,num2 , ans ;
printf(" Enter 2 numbers: ");
scanf("%d %d" , &num1 , &num2 );
/// In-Line function call
printf("\n Sum of %d and %d is %d", num1 , num2 , add(num1,num2) );
printf("\n Product of %d and %d is %d", num1 , num2 , multiply(num1,num2) );
return 0;
}
|
the_stack_data/547.c | #include <stdio.h>
#include <stdlib.h>
typedef struct _Object {
char *name;
char gender;
int age;
} Object;
typedef struct _List {
void *data;
struct _List *next;
} List;
void add(void*);
void del(List*, Object*);
void print_list(List*);
static List *head = 0;
static List *tail = 0;
static int size = 0;
void add(void *data)
{
List *current = (List *) malloc(sizeof (List));
current->data = data;
current->next = 0;
if (head == 0)
{
head = current;
}
else
{
tail->next = current;
}
tail = current;
size++;
}
void print_list(List *l)
{
while (l)
{
Object *data = (Object *)l->data;
printf("name=%s, gender=%c, age=%d\n", data->name, data->gender, data->age);
l = l->next;
}
}
void del(List *l, Object *o)
{
List *list = 0;
List *prev = l;
while(l) {
Object *data = (Object *)l->data;
if (data == o) {
list = l;
break;
}
prev = l;
l = l->next;
}
if (list)
{
Object *d = (Object *)l->data;
if (list == head)
{
head = head->next;
} else {
prev->next = list->next;
}
printf("+++++++++++++++++++\n");
printf("Deleted: name=%s, gender=%c, age=%d\n", d->name, d->gender, d->age);
printf("+++++++++++++++++++\n");
free(list);
}
}
int main(void)
{
int s = sizeof(Object);
Object o1 = {
"Jack",
'm',
30
};
Object o2 = {
"Amy",
'f',
20
};
Object o3 = {
"Mike",
'm',
24
};
Object o4 = {
"John",
'm',
35
};
Object o5 = {
"Lily",
'f',
25
};
add(&o1);
add(&o2);
add(&o3);
add(&o4);
add(&o5);
printf("List size: %d\n", size);
print_list(head);
del(head, &o1);
print_list(head);
return 0;
}
|
the_stack_data/28262941.c | #include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Board {
char value[5][16];
int matrix[5][5];
int col[5];
int row[5];
int found;
} Board;
void PrintBoardInfo(Board *board, char *calledNumber);
void FindBoardMatches(int numOfBoards, Board *bd, char *calledNumber);
int SetBoards(FILE *, Board *);
Board *CheckForCompletion(int numOfBoards, Board *bd);
int main(int argc, char **argv) {
FILE *fd = fopen("input.txt", "r");
char calledNumbersList[1000];
char *calledNumber;
char correctedNumber[5];
Board bd[100];
int numOfBoards;
Board *completeboard;
for (int i = 0; i < 100; ++i) {
memset(bd[i].matrix, 0, 25 * sizeof(int));
memset(bd[i].col, 0, 5 * sizeof(int));
memset(bd[i].row, 0, 5 * sizeof(int));
bd[i].found = 0;
}
fgets(calledNumbersList, 1000, fd);
calledNumber = strtok(calledNumbersList, ",");
numOfBoards = SetBoards(fd, bd); // Set the boards with the file data
do {
if (strlen(calledNumber) == 1) {
correctedNumber[0] = ' ';
correctedNumber[1] = *calledNumber;
correctedNumber[2] = ' ';
} else {
strcpy(correctedNumber, calledNumber);
}
FindBoardMatches(numOfBoards, bd, correctedNumber);
if ((completeboard = CheckForCompletion(numOfBoards, bd)) != NULL)
break;
} while ((calledNumber = strtok(NULL, ",\n")) != NULL);
PrintBoardInfo(completeboard, correctedNumber);
fclose(fd);
return 0;
}
int SetBoards(FILE *fd, Board *bd) {
char board[100];
int count = -1;
int row = 0;
while (fgets(board, 100, fd) != NULL) {
if (!strcmp(board, "\n")) {
count++;
row = 0;
continue;
}
strcpy(bd[count].value[row], board);
bd[count].value[row][15] = '\0';
row++;
}
return count + 1;
}
void FindBoardMatches(int numOfBoards, Board *bd, char *calledNumber) {
char *remainder;
for (int i = 0; i < numOfBoards; ++i) {
for (int j = 0; j < 5; ++j) {
if ((remainder = strstr(bd[i].value[j], calledNumber)) != NULL) {
bd[i].matrix[j][(15 - strlen(remainder)) / 3] = 1;
bd[i].row[j] += 1;
bd[i].col[(15 - strlen(remainder)) / 3] += 1;
}
}
}
}
Board *CheckForCompletion(int numOfBoards, Board *bd) {
static int found = 0;
for (int i = 0; i < numOfBoards; ++i) {
for (int j = 0; j < 5; ++j) {
for (int k = 0; k < 5; ++k) {
if (bd[i].matrix[j][k]) {
if (bd[i].row[j] == 5 || bd[i].col[k] == 5) {
if (bd[i].found == 0) {
bd[i].found = 1;
found += 1;
}
if (found == 99) {
return &bd[i];
}
}
}
}
}
}
return NULL;
};
void PrintBoardInfo(Board *board, char *calledNumber) {
char converter[2];
int sum = 0;
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 5; ++j) {
if (!board->matrix[i][j]) {
converter[0] = board->value[i][j * 3];
converter[1] = board->value[i][j * 3 + 1];
sum += atoi(converter);
}
}
}
printf("With Number: %s\n", calledNumber);
for (int i = 0; i < 5; ++i) {
printf("%s", board->value[i]);
}
printf("\n");
for (int i = 0; i < 5; ++i) {
printf("%d|", board->row[i]);
for (int j = 0; j < 5; ++j) {
printf("%d ", board->matrix[i][j]);
}
printf("\n");
}
printf(" ");
for (int i = 0; i < 5; ++i) {
printf("- ");
}
printf("\n ");
for (int i = 0; i < 5; ++i) {
printf("%d ", board->col[i]);
}
printf("\n");
printf("\n");
printf("Answer is %d\n", sum * atoi(calledNumber));
printf("\n");
};
|
the_stack_data/98574976.c | /*Pre-processor Debugging*/
#include <stdio.h>
#include <stdlib.h>
int multiply (int a, int b) {
#ifdef DEBUG
fprintf(stderr, "multiply(%i, %i)\n", a, b) ; //Debug code
#endif
int result = a*b ;
#ifdef DEBUG
fprintf(stderr, "return %i\n", result ) ;
#endif
return result ;
}
int main (int argc, char argv []) {
int arg1 = 0, arg2 = 0 ;
if (argc > 1)
arg1 = atoi(argv[1]) ;
if (argc == 3)
arg2 = atoi(argv[2]) ;
#ifdef DEBUG //Debug code
fprintf(stderr, "Processed arguments = %i", argc - 1) ;
fprintf(stderr, "Arg1 = %i, Arg2 = %i", argv[1], argv[2]) ;
#endif
int multiply (int a, int b) ;
printf("%i\n", multiply(arg1, arg2)) ;
return 0 ;
} |
the_stack_data/18888438.c | /**
* recover.c
*
* Computer Science 50
* Problem Set 4
*
* Recovers JPEGs from a forensic image.
*/
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>
int main(int argc, char* argv[])
{
if (argc > 1)
{
printf("Usage: no command-line arguments required.");
return 1;
}
FILE* inptr = fopen("card.raw", "r");
FILE* outptr = NULL;
if (inptr == NULL)
{
printf("Could not open card.raw for reading.\n");
return 1;
}
uint16_t signatureA = 0xff + 0xd8 + 0xff + 0xe0;
uint16_t signatureB = 0xff + 0xd8 + 0xff + 0xe1;
// delay writing until first valid signature
bool foundFirstSignature = false;
// keep track of which file we're writing to
int fnumber = 0;
while (true)
{
// read 512 bytes into the free store, as opposed
// to the stack due to it's considerable size.
uint8_t* buffer = (uint8_t*) malloc(512);
if (fread(buffer, 512, 1, inptr) != 1)
{
// not enough blocks to justify continuation of jpeg
fclose(outptr);
free(buffer);
break;
}
// determine signature
uint16_t signature = buffer[0] + buffer[1] + buffer[2] + buffer[3];
// is this the start of a new file?
if (signature == signatureA || signature == signatureB)
{
// indicate that the first jpeg has now been found
// and we can now start outputting files.
foundFirstSignature = true;
// close previous file
if (outptr != NULL)
{
fclose(outptr);
}
// open next file
char fname[8];
sprintf(fname, "%03d.jpg", fnumber);
outptr = fopen(fname, "w");
// error handling
if (outptr == NULL)
{
printf("Could not open %s for writing.\n", fname);
fclose(inptr);
free(buffer);
return 1;
}
fnumber += 1;
}
if (foundFirstSignature)
{
// write current block to current file
fwrite(buffer, 512, 1, outptr);
}
free(buffer);
}
fclose(inptr);
return 0;
}
|
the_stack_data/200142288.c | #include <stdio.h>
extern int a;
void f();
int main() {
printf("main(): a:%d\n",a);
a=1;
printf("main(): a:%d\n",a);
f();
printf("main(): a:%d\n",a);
return 0;
}
|
the_stack_data/75138467.c | #include <stdio.h>
main()
{
int c;
c = getchar();
if(c == EOF)
{
printf("When c is equal to EOF, the value (c==EOF) is :%d",(c == EOF));
}
else{
printf("When c is not equal to EOF,the value (c == EOF) is :%d",(c==EOF));
}
/*
* When c is not equal to EOF,the value (c == EOF) is :0
* When c is equal to EOF, the value (c==EOF) is :1
*/
}
|
the_stack_data/12637914.c | /*
* Copyright 2016 The Emscripten Authors. All rights reserved.
* Emscripten is available under two separate licenses, the MIT license and the
* University of Illinois/NCSA Open Source License. Both these licenses can be
* found in the LICENSE file.
*/
#include <stdio.h>
int main()
{
long long a = 0x2b00505c10;
long long b = a >> 29;
long long c = a >> 32;
long long d = a >> 34;
printf("*%lld,%lld,%lld,%lld*\n", a, b, c, d);
unsigned long long ua = 0x2b00505c10;
unsigned long long ub = ua >> 29;
unsigned long long uc = ua >> 32;
unsigned long long ud = ua >> 34;
printf("*%lld,%lld,%lld,%lld*\n", ua, ub, uc, ud);
long long x = 0x0000def123450789ULL; // any bigger than this, and we
long long y = 0x00020ef123456089ULL; // start to run into the double precision limit!
printf("*%lld,%lld,%lld,%lld,%lld*\n", x, y, x | y, x & y, x ^ y);
printf("*");
long long z = 13;
int n = 0;
while (z > 1) {
printf("%.2f,", (float)z); // these must be integers!
z = z >> 1;
n++;
}
printf("*%d*\n", n);
return 0;
}
|
the_stack_data/375385.c | /*
** server.c -- a stream socket server demo
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#include <pthread.h>
#define PORT "4444" // the port users will be connecting to
#define MAXDATASIZE 500 // max number of bytes we can get at once
#define NUM_THREADS 50 //max number of threads to contact with clients
#define BACKLOG 10 // how many pending connections queue will hold
struct mystructure
{
int socketfd;
int new_fd1;
};
int client_fd[50]; //new file descriptor for communication with client
int client_count=0; //no of clients at present connected to server
void *chat(void *info)
{
//thread for new connection
char recv_data[MAXDATASIZE],send_data[MAXDATASIZE];
int numbytes;
int fd,nfd;
int i;
struct mystructure *sockinfo;
sockinfo=(struct mystructure *) info;
fd=sockinfo->socketfd;
nfd=sockinfo->new_fd1;
while (1)
{
printf("\n SEND (q or Q to quit) : ");
gets(send_data);
if (strcmp(send_data , "q") == 0 || strcmp(send_data , "Q") == 0)
{
send(nfd, send_data,strlen(send_data), 0);
close(nfd);
break;
}
else
send(nfd, send_data,strlen(send_data), 0);
if((numbytes = recv(nfd,recv_data,MAXDATASIZE-1,0))==-1)
{
perror("recv");
exit(1);
}
recv_data[numbytes] = '\0';
if (strcmp(recv_data , "q") == 0 || strcmp(recv_data , "Q") == 0)
{
close(nfd);
break;
}
else
printf("\n RECIEVED DATA = %s \n" , recv_data);
for(i=1;i<=client_count;i++)
{
send(client_fd[i], recv_data,strlen(recv_data), 0);
}
fflush(stdout);
}
pthread_exit(NULL);
}
// get sockaddr, IPv4 or IPv6:
void *get_in_addr(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
int main(void)
{
int sockfd, new_fd; // listen on sock_fd, new connection on new_fd
struct addrinfo hints, *servinfo, *p;
struct sockaddr_storage their_addr; // connector's address information
struct mystructure ms;
socklen_t sin_size;
int yes=1;
char s[INET6_ADDRSTRLEN];
int rv;
pthread_t threads;
int rc;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE; // use my IP
if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through all the results and bind to the first we can
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("server: socket");
continue;
}
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes,
sizeof(int)) == -1) {
perror("setsockopt");
exit(1);
}
if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
perror("server: bind");
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, "server: failed to bind\n");
return 2;
}
freeaddrinfo(servinfo); // all done with this structure
if (listen(sockfd, BACKLOG) == -1) {
perror("listen");
exit(1);
}
printf("server: waiting for connections...\n");
//while
while(1) { // main accept() loop
sin_size = sizeof their_addr;
new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
if (new_fd == -1) {
perror("accept");
continue;
}
inet_ntop(their_addr.ss_family,
get_in_addr((struct sockaddr *)&their_addr),
s, sizeof s);
printf("server: got connection from %s\n", s);
client_count=client_count+1;
client_fd[client_count]=new_fd;
ms.socketfd=sockfd;
ms.new_fd1=new_fd;
rc = pthread_create(&threads, NULL, chat, (void *) &ms);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
} //while ended
close(sockfd);
pthread_exit(NULL);
return 0;
}
|
the_stack_data/112691.c | #include <stdio.h>
#include <stdlib.h>
int external_obj = 35;
int func_arg1(int a) {
return a * a;
}
int func_arg2(int a, int b) {
return a * a + b * b;
}
int func_arg3(int a, int b, int c) {
return a * a + b * b + c * c;
}
int func_arg4(int a, int b, int c, int d) {
return a * a + b * b + c * c + d * d;
}
int func_arg5(int a, int b, int c, int d, int e) {
return a * a + b * b + c * c + d * d + e * e;
}
int func_arg6(int a, int b, int c, int d, int e, int f) {
return a * a + b * b + c * c + d * d + e * e + f * f;
}
int* alloc() {
int *p = (int *) calloc(3, sizeof(int));
p[0] = 53;
p[1] = 29;
p[2] = 64;
return p;
}
struct test_struct {
char c;
int n;
int a[4];
struct {
int x, y, z;
} v;
};
int test_struct(struct test_struct *s) {
if (s->c != 'A') return 1;
if (s->n != 45) return 1;
if (s->a[0] != 5) return 1;
if (s->a[1] != 3) return 1;
if (s->a[2] != 8) return 1;
if (s->a[3] != 7) return 1;
if (s->v.x != 67) return 1;
if (s->v.y != 1) return 1;
if (s->v.z != -41) return 1;
s->c = 'Z';
s->n = 82;
s->a[0] = 4;
s->a[1] = 4;
s->a[2] = 1234;
s->a[3] = -571;
s->v.x = 98;
s->v.y = 12;
s->v.z = 1;
return 0;
}
_Bool bool_ret(int b) {
return b;
}
double test_double(double a) {
return a * 2;
}
|
the_stack_data/98576425.c | int addTwo(int a, int b) {
return a + b;
} |
the_stack_data/200143100.c | #include<stdio.h>
#include<string.h>
#define LEN 128
int htoi(char *s);
int main()
{
char s[LEN];
char *ps;
ps = s;
int number;
printf("请输入一个十六进制字符串:\n");
scanf("%s",ps);
//fputs(ps,stdout);
number = htoi(ps);
printf("十六进值:0x%s,的十进制是:%d\n",ps,number);
return 0;
}
//16进制转化为10进制
int htoi(char *s)
{
int i,j;
int n;
int len = strlen(s);
char *pt = s;
int number = 0;
printf("len=%d\n",len);
for(i = 0; i < len; i++)
{
//putchar(*pt);
//转化为10进制
if(*pt > '0' && *pt <= '9')
{
n = *pt - '0';
}
else if(*pt >= 'a' && *pt <= 'z')
{
n = 10 + *pt - 'a';
}
else if(*pt >= 'A' && *pt <= 'Z')
{
n = 10 + *pt - 'A';
}
printf("%d\t",n);
for(j = 0; j < len - i - 1; j++)
{
n = n * 16;
}
number += n;
pt++;
}
putchar('\n');
return number;
}
|
the_stack_data/113519.c | // write a program that takes a lowercase letter from user and convert it to uppercase letter
#include<stdio.h>
int main()
{
char lower;
printf("Please enter any lowercase number: ");
scanf("%c", &lower);
printf("The uppercase letter is %c", lower-32); /*difference between lowercase and uppercase
letter is -32*/
return 0;
}
|
the_stack_data/72962.c | #include <stdio.h>
#include <stdlib.h>
void fun(n)
{
if (n > 0)
{
printf("%d ", n);
fun(n - 1);
fun(n - 1);
}
}
int main()
{
fun(3); // The output will be 3 2 1 1 2 1 1
return 0;
}
|
the_stack_data/282472.c | /* insert_string_acle.c -- insert_string variant using ACLE's CRC instructions
*
* Copyright (C) 1995-2013 Jean-loup Gailly and Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*
*/
#if defined(__ARM_FEATURE_CRC32) && defined(ARM_ACLE_CRC_HASH)
#include <arm_acle.h>
#include "../../zbuild.h"
#include "../../deflate.h"
/* ===========================================================================
* Insert string str in the dictionary and set match_head to the previous head
* of the hash chain (the most recent string with same hash key). Return
* the previous length of the hash chain.
* IN assertion: all calls to to INSERT_STRING are made with consecutive
* input characters and the first MIN_MATCH bytes of str are valid
* (except for the last MIN_MATCH-1 bytes of the input file).
*/
Pos insert_string_acle(deflate_state *const s, const Pos str, unsigned int count) {
Pos p, lp, ret;
if (UNLIKELY(count == 0)) {
return s->prev[str & s->w_mask];
}
ret = 0;
lp = str + count - 1; /* last position */
for (p = str; p <= lp; p++) {
uint32_t val, h, hm;
memcpy(&val, &s->window[p], sizeof(val));
if (s->level >= TRIGGER_LEVEL)
val &= 0xFFFFFF;
h = __crc32w(0, val);
hm = h & s->hash_mask;
Pos head = s->head[hm];
if (head != p) {
s->prev[p & s->w_mask] = head;
s->head[hm] = p;
if (p == lp)
ret = head;
} else if (p == lp) {
ret = p;
}
}
return ret;
}
#endif
|
the_stack_data/50138888.c | #include<stdio.h>
int main()
{
int t;
scanf("%d",&t);
int a,b,x;
for (int i=0; i<t; i++)
{
scanf("%d%d",&a,&b);
x=a%b;
if(x==0)
{
printf("%d\n",x);
}
else
{
printf("%d\n",b-x);
}
}
return 0;
}
|
the_stack_data/143951.c | //@ #include "modulo.gh"
/*@
lemma void div_mod(int g, int k, int l)
requires g == (k % l) &*& l > 0;
ensures (-l <= g) &*& (g < l);
{
div_rem(k, l);
}
lemma void div_mod_gt_0(int mod, int div, int whole)
requires mod == (div % whole) &*& whole > 0 &*& div >= 0;
ensures (0 <= mod) &*& (mod < whole);
{
div_rem(div, whole);
}
lemma void loop_lims(int k, int capacity)
requires 0 < capacity;
ensures 0 <= loop_fp(k, capacity) &*& loop_fp(k, capacity) < capacity;
{
div_rem(k, capacity);
assert(-capacity <= k%capacity);
assert(0 <= k%capacity + capacity);
div_rem((k + capacity), capacity);
assert(capacity > 0);
div_rem(k%capacity + capacity, capacity);
assert(0 <= ((k%capacity + capacity)%capacity));
}
lemma void bar(int a, int b, int q, int r)
requires 0 <= a &*& a < b &*& 0 <= r &*& a == q * b + r &*& r < b;
ensures q == 0;
{
if (q == 0) {
} else if (0 <= q) {
mul_mono(1, q, b);
} else {
mul_mono(q, -1, b);
}
}
lemma void quotidient_zero_pos(int a, int b, int q, int r)
requires 0 <= a &*& a < b &*& 0 <= r &*& a == q * b + r &*& r < b;
ensures q == 0;
{
if (q == 0) {
} else if (0 <= q) {
mul_mono(1, q, b);
} else {
mul_mono(q, -1, b);
}
}
lemma void quotidient_zero_neg(int a, int b, int q, int r)
requires -b < a &*& a <= 0 &*& -b < r &*& a == q * b + r &*& r <= 0;
ensures q == 0;
{
if (q == 0) {
} else if (0 <= q) {
mul_mono(1, q, b);
} else {
mul_mono(q, -1, b);
}
}
lemma void division_round_to_zero(int a, int b)
requires -b < a &*& a < b;
ensures a/b == 0;
{
div_rem(a, b);
if (0 <= a)
quotidient_zero_pos(a, b, a / b, a % b);
else
quotidient_zero_neg(a, b, a / b, a % b);
}
lemma void div_incr(int a, int b)
requires 0 <= a &*& 0 < b;
ensures true == ( (a+b)/b == a/b + 1 );
{
div_rem(a+b, b);
if ((a+b)/b <= a/b) {
div_rem(a, b);
mul_mono((a+b)/b, a/b, b);
assert true == ((a+b)/b*b <= a/b*b);
assert false;
}
assert a/b + 1 <= (a+b)/b;
assert 0 <= a;
div_rem(a, b);
if (a/b <= -1) {
mul_mono(a/b, -1, b);
assert(false);
}
assert 0 <= (a/b);
if (a/b + 1 <= (a+b)/b - 1) {
mul_mono(a/b + 1, (a+b)/b - 1, b);
assert(false);
}
}
lemma void loop_bijection(int k, int capacity)
requires 0 <= k &*& k < capacity;
ensures loop_fp(k, capacity) == k;
{
division_round_to_zero(k, capacity);
div_rem(k, capacity);
div_incr(k, capacity);
div_rem((k + capacity), capacity);
}
lemma void mod_rotate(int a, int b)
requires 0 <= a &*& 0 < b;
ensures true == ((a+b)%b == a%b);
{
div_rem(a+b, b);
div_rem(a, b);
div_incr(a, b);
mul_subst((a+b)/b, (a/b + 1), b);
}
lemma void loop_injection(int k, int capacity)
requires 0 <= k &*& 0 < capacity;
ensures loop_fp(k + capacity, capacity) == loop_fp(k, capacity);
{
mod_rotate(k, capacity);
}
lemma void loop_injection_minus_n(int k, int capacity, int n)
requires 0 <= k &*& 0 < capacity &*& 0 <= k + n*capacity &*& n < 0;
ensures loop_fp(k + n*capacity, capacity) == loop_fp(k, capacity);
{
int i = n;
for (i = n; i < 0; ++i)
invariant loop_fp(k + i*capacity, capacity) == loop_fp(k + n*capacity, capacity) &*&
0 <= k + i*capacity &*&
i <= 0;
decreases -i;
{
mod_rotate(k + i*capacity, capacity);
assert loop_fp(k + i*capacity, capacity) == loop_fp(k + n*capacity, capacity);
}
assume(loop_fp(k + i*capacity, capacity) == loop_fp(k + n*capacity, capacity));//workaround
assert loop_fp(k + i*capacity, capacity) == loop_fp(k + n*capacity, capacity);
}
lemma void loop_injection_n(int k, int capacity, int n)
requires 0 <= k &*& 0 < capacity &*& 0 <= k + n*capacity;
ensures loop_fp(k + n*capacity, capacity) == loop_fp(k, capacity);
{
if (0 <= n) {
for (int i = 0; i < n; ++i)
invariant loop_fp(k + i*capacity, capacity) == loop_fp(k, capacity) &*&
0 <= k + i*capacity &*&
i <= n;
decreases n-i;
{
mod_rotate(k + i*capacity, capacity);
}
} else {
loop_injection_minus_n(k, capacity, n);
}
}
lemma void loop_fixp(int k, int capacity)
requires 0 <= k &*& 0 < capacity;
ensures loop_fp(k, capacity) == loop_fp(loop_fp(k, capacity), capacity);
{
loop_lims(k, capacity);
loop_bijection(loop_fp(k, capacity), capacity);
}
lemma void mod_bijection(int x, int y)
requires -y < x &*& x < y;
ensures x == x%y;
{
division_round_to_zero(x, y);
div_rem(x, y);
}
lemma int loop_shift_inv(int x, int y, int capacity)
requires 0 <= x &*& x < capacity &*& 0 <= y &*& y < capacity;
ensures 0 <= result &*& result < capacity &*&
loop_fp(result + y, capacity) == x;
{
int z = loop_fp(y - x, capacity);
loop_lims(y - x, capacity);
if (z == 0) {
assert true == (((y-x)%capacity + capacity)%capacity == 0);
div_rem(y-x, capacity);
if (1 <= (y-x)%capacity) {
mod_rotate((y-x)%capacity, capacity);
assert true == (0 == ((y-x)%capacity%capacity));
division_round_to_zero((y-x)%capacity, capacity);
div_rem((y-x)%capacity, capacity);
assert false;
}
if ((y-x)%capacity <= -1) {
assert (-capacity < (y-x)%capacity);
assert true == (0 <= (y-x)%capacity + capacity);
division_round_to_zero((y-x)%capacity + capacity, capacity);
mul_subst(((y-x)%capacity + capacity)/capacity, 0, capacity);
assert true == (((y-x)%capacity + capacity)/capacity*capacity == 0);
div_rem((y-x)%capacity + capacity, capacity);
}
assert true == ((y-x)%capacity == 0);//TADA!!!
int n1 = (y-x)/capacity;
div_rem(y-x, capacity);
assert true == (y-x == n1*capacity);
int n = -n1;
assert true == (x-y == n*capacity);
assert true == (x == n*capacity + y);
division_round_to_zero(x, capacity);
div_rem(x, capacity);
assert true == (x%capacity == x);
assert true == (x == (n*capacity + y)%capacity);
assert true == (x + capacity == (n*capacity + y)%capacity + capacity);
mod_rotate(x, capacity);
assert true == ((x+capacity)%capacity == x);
assert true == (x == ((n*capacity + y)%capacity + capacity)%capacity);
loop_injection_n(y, capacity, n);
assert true == ((y - x) == (y - x)/capacity*capacity);
assert true == (((y%capacity) + capacity)%capacity == x);
assert(loop_fp(y, capacity) == x);
return 0;
} else {
assert(z == ((y-x)%capacity + capacity)%capacity);
assert(0 < z);
assert(z < capacity);
assert(0 <= (capacity - z + y));
if (0 <= y-x) {
div_rem(y-x, capacity);
assert true == (0 <= (y-x)%capacity);
mod_rotate((y-x)%capacity, capacity);
mod_bijection((y-x)%capacity, capacity);
assert true == ((y-x)%capacity == ((y-x)%capacity + capacity)%capacity);
if (y-x < capacity) {
mod_bijection((y-x), capacity);
assert true == ((y-x)%capacity == y-x);
mod_rotate(x, capacity);
mod_bijection(x, capacity);
assert true == (x == (capacity + x)%capacity);
mod_rotate((capacity + x)%capacity, capacity);
mod_bijection((capacity + x)%capacity, capacity);
assert true == (x == (((capacity + x)%capacity + capacity)%capacity));
} else {
div_rem(y-x, capacity);
int n = (y-x)/capacity;
int r = (y-x)%capacity;
assert true == (y-x == n*capacity + r);
mod_rotate(x, capacity);
mod_bijection(x, capacity);
assert true == (x == (capacity + x)%capacity);
mod_rotate((capacity + x)%capacity, capacity);
mod_bijection((capacity + x)%capacity, capacity);
assert true == (x == (((capacity + x)%capacity + capacity)%capacity));
if (0 <= capacity + y - r) {
if (capacity + y - r < capacity) {
mod_rotate_n(capacity + y - r, -n, capacity);
} else {
assert false;
}
} else {
assert false;
}
}
} else {
assert true == (y-x < 0);
assert true == (-capacity < y-x);
mod_bijection(y-x, capacity);
assert true == ((y-x)%capacity == y-x);
mod_bijection((y-x) + capacity, capacity);
mod_bijection(x, capacity);
mod_rotate(x, capacity);
assert true == (x == ((x%capacity + capacity)%capacity));
}
assert true == (((capacity - z + y)%capacity + capacity)%capacity == x);
return capacity - z;
}
}
lemma void inc_modulo_loop_hlp(int a, int quotient, int capacity)
requires 0 <= a &*& 0 < capacity &*&
0 <= a - quotient * capacity &*&
a - quotient * capacity < capacity;
ensures loop_fp(loop_fp(a, capacity) + 1, capacity) ==
loop_fp(a + 1, capacity);
{
int b = a - quotient * capacity;
loop_injection_n(b, capacity, quotient);
loop_bijection(b, capacity);
if (b + 1 < capacity) {
loop_injection_n(b + 1, capacity, quotient);
} else {
assert capacity <= b + 1;
loop_injection_n(b + 1, capacity, quotient);
loop_injection(0, capacity);
loop_bijection(0, capacity);
}
}
lemma void inc_modulo_loop(int a, int capacity)
requires 0 <= a &*& 0 < capacity;
ensures loop_fp(loop_fp(a, capacity) + 1, capacity) ==
loop_fp(a + 1, capacity);
{
int quotient = a / capacity;
div_rem(a, capacity);
inc_modulo_loop_hlp(a, a/capacity, capacity);
}//took 30m
lemma void div_exact(int a, int b)
requires 0 <= a &*& 0 < b;
ensures a*b/b == a;
{
div_rem_nonneg(0, b);
div_incr(0, b);
if (a != 0) {
for (int i = 1; i < a; i++)
invariant 1 <= i &*& i <= a &*& i*b/b == i;
decreases a - i;
{
mul_nonzero(i, b);
div_incr(i * b, b);
}
}
}
lemma void div_lt(int a, int b, int c)
requires 0 <= a &*& 0 < b &*& 0 < c &*& a < b*c;
ensures a/c < b*c/c;
{
div_exact(b, c);
div_rem_nonneg(a, c);
if (a/c >= b) {
mul_mono(b, a/c, c);
}
}
lemma void div_ge(int a, int b, int c)
requires 0 <= a &*& 0 < c &*& a <= b;
ensures a/c <= b/c;
{
if (a < b) {
div_rem_nonneg(a, c);
div_rem_nonneg(b, c);
div_exact(a/c, c);
div_exact(b/c, c);
assert ((a/c)*c < (b/c)*c || a%c < b%c);
if ((a/c)*c > (b/c)*c) {
mul_nonnegative(b/c, c);
div_lt((b/c)*c, a/c, c);
mul_mono_l((b/c) + 1, a/c, c);
assert false;
}
if ((a/c)*c < (b/c)*c) {
mul_nonnegative(a/c, c);
div_lt((a/c)*c, b/c, c);
}
}
}
lemma void loop_fp_pop(int k, int capacity)
requires 0 <= k &*& 0 < capacity;
ensures loop_fp(k, capacity) == k % capacity;
{
div_mod_gt_0(k%capacity, k, capacity);
mod_rotate(k%capacity, capacity);
mod_bijection(k%capacity, capacity);
}
lemma void mod_reduce(int a, int b, int k)
requires 0 <= a &*& 0 < b &*& 0 <= k;
ensures (a + b*k) % b == a % b;
{
mul_nonnegative(b, k);
loop_injection_n(a, b, k);
loop_fp_pop(a + b*k, b);
loop_fp_pop(a, b);
}
lemma void div_minus_one(int a, int b)
requires 0 < a &*& 0 < b;
ensures (a*b - 1) / b == a - 1;
{
div_exact(a, b);
div_exact(a - 1, b);
mul_nonzero(a, b);
div_lt(a*b - 1, a, b);
mul_nonnegative(a-1, b);
div_ge((a-1)*b, a*b - 1, b);
}
lemma void div_plus_one(int a, int b)
requires 0 < a &*& 1 < b;
ensures (a*b + 1) / b == a;
{
div_exact(a, b);
div_exact(a + 1, b);
mul_nonnegative(a, b);
div_lt(a*b+1, a+1, b);
div_ge(a*b, a*b + 1, b);
}
lemma void mod_rotate_mul(int a, int b)
requires 0 <= a &*& 0 < b;
ensures ((a * b) % b) == 0;
{
div_exact(a, b);
mul_nonnegative(a, b);
div_rem_nonneg(a * b, b);
}
@*/
|
the_stack_data/181393226.c | #include <stdio.h>
#define MAX 50
void insert();
void delete();
void display();
int queue_array[MAX];
int rear = - 1;
int front = - 1;
int main()
{
int choice;
while (1)
{
printf("1.Insert element to queue \n");
printf("2.Delete element from queue \n");
printf("3.Display all elements of queue \n");
printf("4.Quit \n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch (choice)
{
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
break;
default:
printf("Wrong choice \n");
} /* End of switch */
} /* End of while */
} /* End of main() */
void insert()
{
int add_item;
if (rear == MAX - 1)
printf("Queue Overflow \n");
else
{
if (front == - 1)
/*If queue is initially empty */
front = 0;
printf("Inset the element in queue : ");
scanf("%d", &add_item);
rear = rear + 1;
queue_array[rear] = add_item;
}
} /* End of insert() */
void delete()
{
if (front == - 1 || front > rear)
{
printf("Queue Underflow \n");
return ;
}
else
{
printf("Element deleted from queue is : %d\n", queue_array[front]);
front = front + 1;
}
} /* End of delete() */
void display()
{
int i;
if (front == - 1)
printf("Queue is empty \n");
else
{
printf("Queue is : \n");
for (i = front; i <= rear; i++)
printf("%d ", queue_array[i]);
printf("\n");
}
} /* End of display() */ |
the_stack_data/182952316.c | // Copyright (c) 2003-2021 James Daniels
// Distributed under the MIT License
// license terms: see LICENSE file in root or http://opensource.org/licenses/MIT
// Notes:
// + Max number of MODs = 256
// + Max total size of all samples = 33,554,432 bytes
// + Max total size of all patterns = 33,554,432 bytes
// + All functions declared static to work around problem with GCC
#include <dirent.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#define BYTE int8_t
#define UBYTE uint8_t
#define BOOL int8_t
#define WORD int16_t
#define UWORD uint16_t
#define ULONG uint32_t
#define TRUE 1
#define FALSE 0
__inline static int Min(int a, int b) {
if (a < b)
return a;
else
return b;
}
__inline static UWORD SwapUWORD(UWORD a) {
return (a >> 8) + ((a & 0xff) << 8);
}
static char GetHex(int val) {
const char dat[] = "0123456789ABCDEF";
if ((val >= 0) && (val <= 15)) {
return dat[val];
} else {
return '?';
}
/*
switch (val) {
case 0: return '0';
case 1: return '1';
case 2: return '2';
case 3: return '3';
case 4: return '4';
case 5: return '5';
case 6: return '6';
case 7: return '7';
case 8: return '8';
case 9: return '9';
case 10: return 'A';
case 11: return 'B';
case 12: return 'C';
case 13: return 'D';
case 14: return 'E';
case 15: return 'F';
default: return '?';
}
*/
}
static int memcmp_new(UBYTE *a, UBYTE *b, int length) {
for (; length > 0; --length)
if (*a++ != *b++)
return 1;
return 0;
}
static void memcpy_new(UBYTE *dest, UBYTE *source, int length) {
for (; length > 0; --length)
*dest++ = *source++;
}
#define MAX_DATA_LENGTH 33554432
typedef struct data_pack {
const char *chunk_name;
int chunk_data_length;
int chunk_unique;
int chunk_actual;
unsigned char chunk_data[MAX_DATA_LENGTH];
} DATAPACK;
static DATAPACK *DATA_Create(const char *name) {
DATAPACK *new_data = (DATAPACK *)malloc(sizeof(DATAPACK));
if (new_data) {
// printf( "DATA_Create( %s ): addr:%p\n", name, new_data );
new_data->chunk_name = name;
new_data->chunk_data_length = 0;
new_data->chunk_unique = 0;
new_data->chunk_actual = 0;
} else {
printf("DATA_Create( %s ): Failed (address:%p length:%)...\n", name,
new_data, sizeof(DATAPACK));
}
return new_data;
}
static int DATA_AppendAligned(DATAPACK *curr_data, unsigned char *data,
int length, int block_length) {
++curr_data->chunk_actual;
if ((block_length * ((int)(length / block_length))) != length) {
printf("DATA_AppendAligned( %p, %p, %d, %d ): Warning length not exactly "
"divisible by block_length!\n",
curr_data, data, length, block_length);
return 0;
} else if (length == 0) {
return 0;
} else {
int offset = 0;
while ((offset + block_length) <= curr_data->chunk_data_length) {
if (memcmp(data, curr_data->chunk_data + offset, length) == 0) {
return offset / block_length;
}
offset += block_length;
};
if (curr_data->chunk_data_length <= (MAX_DATA_LENGTH - length)) {
memmove(curr_data->chunk_data + offset, data, length);
curr_data->chunk_data_length += length;
++curr_data->chunk_unique;
return offset / block_length;
} else {
--curr_data->chunk_actual;
printf("DATA_AppendAligned( %p, %p, %d, %d ): Data >%d bytes!\n",
curr_data, data, length, block_length, MAX_DATA_LENGTH);
return 0;
}
}
}
static int DATA_Append(DATAPACK *curr_data, unsigned char *data, int length) {
++curr_data->chunk_actual;
if (length == 0) {
return 0;
} else {
int offset = 0;
while ((offset + length) <= curr_data->chunk_data_length) {
if (memcmp_new(data, curr_data->chunk_data + offset, length) == 0)
return offset;
++offset;
};
if (curr_data->chunk_data_length <= (MAX_DATA_LENGTH - length)) {
offset = curr_data->chunk_data_length;
memmove(curr_data->chunk_data + offset, data, length);
curr_data->chunk_data_length += length;
++curr_data->chunk_unique;
return offset;
} else {
--curr_data->chunk_actual;
printf("DATA_Append( %p, %d ): Data >%d bytes!\n", data, length,
MAX_DATA_LENGTH);
return 0;
}
}
}
static void DATA_Write(DATAPACK *curr_data, FILE *out_file) {
int i, len;
UBYTE val;
len = curr_data->chunk_data_length;
if (len & 0x3) {
len &= ~0x3;
len += 0x4;
}
printf("Writing %s (Unique:%d Actual:%d Length:%d)...", curr_data->chunk_name,
curr_data->chunk_unique, curr_data->chunk_actual, len);
fprintf(out_file, "\n.ALIGN\n.GLOBAL %s\n%s:\n.byte", curr_data->chunk_name,
curr_data->chunk_name);
if (len > 0) {
for (i = 0; i < len; ++i) {
if (i >= curr_data->chunk_data_length)
val = 0;
else
val = *(curr_data->chunk_data + i);
if (i == 0)
fprintf(out_file, " %d", val);
else
fprintf(out_file, ", %d", val);
}
fprintf(out_file, "\n");
} else {
fprintf(out_file, " 0\n");
}
printf("Done!\n");
free(curr_data);
}
struct ModSampleTemp {
UWORD repeat; // in halfwords
UWORD length; // in halfwords
UWORD truelen; // in halfwords
UBYTE volume;
UBYTE finetune;
};
struct ModSample {
ULONG data; // offset in bytes
UWORD repeat; // in halfwords
UWORD length; // in halfwords
UBYTE finetune;
UBYTE volume;
};
static void MISC_ProcessSound(BYTE *data, int length) {
for (; length > 0; --length) {
int val = *data;
if (val == -128)
val = -127;
*data++ = val;
}
}
static void MISC_ConvSoundToSigned(UBYTE *data, int length) {
for (; length > 0; --length) {
BYTE val_s = *data;
BYTE val_u = val_s - 128;
*data++ = val_u;
}
}
static void MOD_LoadSound(struct ModSample *smp, FILE *in_file,
DATAPACK *samples, int length, int truelen,
int repeat) {
BYTE *samp = (BYTE *)malloc((length << 1) + 16);
int data;
fread(samp + 16, (length << 1), 1, in_file);
if (truelen > 0) {
memset(samp, 0, 16);
if ((repeat < 65535) && (truelen > repeat))
memmove(samp + (repeat << 1), samp + (truelen << 1),
16); // should really merge, also wasteful of memory
MISC_ProcessSound(samp, (truelen << 1) + 16);
data = DATA_Append(samples, samp, (truelen << 1) + 16);
smp->data = data + 16;
} else {
smp->data = 0;
}
smp->length = truelen;
free(samp);
}
#define MAX_MODS 256
static struct ModSample samps[MAX_MODS][31];
static WORD patts[MAX_MODS][128][16]; // [mod][pattern][channel]
static UBYTE mod_num_chans[MAX_MODS];
static UBYTE mod_song_restart_pos[MAX_MODS];
static int max_song_length = 0;
static const char *effect_name[32] = {"*0: Arpeggio",
"*1: Slide Up",
"*2: Slide Down",
"*3: Tone Portamento",
"*4: Vibrato",
"*5: Tone Portamento + Volume Slide",
"*6: Vibrato + Volume Slide",
"*7: Tremolo",
"8: Set Panning Position",
"*9: Set Sample Offset",
"*A: Volume Slide",
"*B: Position Jump",
"*C: Set Volume",
"*D: Pattern Break",
"*F: Set Speed (BPM)",
"*F: Set Speed (Ticks)",
"*E0: Set Filter",
"*E1: Fine Slide Up",
"*E2: Fine Slide Down",
"E3: Glissando Control",
"E4: Set Vibrato Waveform",
"E5: Set FineTune",
"*E6: Set/Jump to Loop",
"E7: Set Tremolo Waveform",
"E8: Illegal",
"*E9: Retrigger Note",
"*EA: Fine Volume Slide Up",
"*EB: Fine Volume Slide Down",
"*EC: Note Cut",
"*ED: Note Delay",
"*EE: Pattern Delay",
"EF: Invert Loop"};
static int MOD_FindNote(int period) {
const int period_table[61] = {
0, 1712, 1616, 1524, 1440, 1356, 1280, 1208, 1140, 1076, 1016, 960, 906,
856, 808, 762, 720, 678, 640, 604, 570, 538, 508, 480, 453, 428,
404, 381, 360, 339, 320, 302, 285, 269, 254, 240, 226, 214, 202,
190, 180, 170, 160, 151, 143, 135, 127, 120, 113, 107, 101, 95,
90, 85, 80, 75, 71, 67, 63, 60, 56};
int i, d, r;
int closest = 1000000000;
r = -1;
for (i = 0; i < 61; ++i) {
d = abs(period_table[i] - period);
if (d < closest) {
r = i;
closest = d;
}
}
if (r == -1) {
printf("Can't find note with period:%d...\n", period);
}
return r;
}
#define FOUR_CHAR_CODE(ch0, ch1, ch2, ch3) \
((long)(unsigned char)(ch0) | ((long)(unsigned char)(ch1) << 8) | \
((long)(unsigned char)(ch2) << 16) | ((long)(unsigned char)(ch3) << 24))
static int MOD_GetNumChans(ULONG file_format) {
switch (file_format) {
case FOUR_CHAR_CODE('T', 'D', 'Z', '1'):
return 1;
break;
case FOUR_CHAR_CODE('2', 'C', 'H', 'N'):
case FOUR_CHAR_CODE('T', 'D', 'Z', '2'):
return 2;
break;
case FOUR_CHAR_CODE('T', 'D', 'Z', '3'):
return 3;
break;
case FOUR_CHAR_CODE('M', '.', 'K', '.'):
case FOUR_CHAR_CODE('F', 'L', 'T', '4'):
case FOUR_CHAR_CODE('M', '!', 'K', '!'):
return 4;
break;
case FOUR_CHAR_CODE('5', 'C', 'H', 'N'):
return 5;
break;
case FOUR_CHAR_CODE('6', 'C', 'H', 'N'):
return 6;
break;
case FOUR_CHAR_CODE('7', 'C', 'H', 'N'):
return 7;
break;
case FOUR_CHAR_CODE('8', 'C', 'H', 'N'):
case FOUR_CHAR_CODE('O', 'C', 'T', 'A'):
case FOUR_CHAR_CODE('C', 'D', '8', '1'):
return 8;
break;
case FOUR_CHAR_CODE('F', 'L', 'T', '8'):
return -2; // Unsupported MOD type
break;
case FOUR_CHAR_CODE('9', 'C', 'H', 'N'):
return 9;
break;
case FOUR_CHAR_CODE('1', '0', 'C', 'H'):
return 10;
break;
case FOUR_CHAR_CODE('1', '1', 'C', 'H'):
return 11;
break;
case FOUR_CHAR_CODE('1', '2', 'C', 'H'):
return 12;
break;
case FOUR_CHAR_CODE('1', '3', 'C', 'H'):
return 13;
break;
case FOUR_CHAR_CODE('1', '4', 'C', 'H'):
return 14;
break;
case FOUR_CHAR_CODE('1', '5', 'C', 'H'):
return 15;
break;
case FOUR_CHAR_CODE('1', '6', 'C', 'H'):
return 16;
break;
case FOUR_CHAR_CODE('1', '7', 'C', 'H'):
case FOUR_CHAR_CODE('1', '8', 'C', 'H'):
case FOUR_CHAR_CODE('1', '9', 'C', 'H'):
case FOUR_CHAR_CODE('2', '0', 'C', 'H'):
case FOUR_CHAR_CODE('2', '1', 'C', 'H'):
case FOUR_CHAR_CODE('2', '2', 'C', 'H'):
case FOUR_CHAR_CODE('2', '3', 'C', 'H'):
case FOUR_CHAR_CODE('2', '4', 'C', 'H'):
case FOUR_CHAR_CODE('2', '5', 'C', 'H'):
case FOUR_CHAR_CODE('2', '6', 'C', 'H'):
case FOUR_CHAR_CODE('2', '7', 'C', 'H'):
case FOUR_CHAR_CODE('2', '8', 'C', 'H'):
case FOUR_CHAR_CODE('2', '9', 'C', 'H'):
case FOUR_CHAR_CODE('3', '0', 'C', 'H'):
case FOUR_CHAR_CODE('3', '1', 'C', 'H'):
case FOUR_CHAR_CODE('3', '2', 'C', 'H'):
case FOUR_CHAR_CODE('3', '3', 'C', 'H'):
case FOUR_CHAR_CODE('3', '4', 'C', 'H'):
case FOUR_CHAR_CODE('3', '5', 'C', 'H'):
case FOUR_CHAR_CODE('3', '6', 'C', 'H'):
case FOUR_CHAR_CODE('3', '7', 'C', 'H'):
case FOUR_CHAR_CODE('3', '8', 'C', 'H'):
case FOUR_CHAR_CODE('3', '9', 'C', 'H'):
case FOUR_CHAR_CODE('4', '0', 'C', 'H'):
case FOUR_CHAR_CODE('4', '1', 'C', 'H'):
case FOUR_CHAR_CODE('4', '2', 'C', 'H'):
case FOUR_CHAR_CODE('4', '3', 'C', 'H'):
case FOUR_CHAR_CODE('4', '4', 'C', 'H'):
case FOUR_CHAR_CODE('4', '5', 'C', 'H'):
case FOUR_CHAR_CODE('4', '6', 'C', 'H'):
case FOUR_CHAR_CODE('4', '7', 'C', 'H'):
case FOUR_CHAR_CODE('4', '8', 'C', 'H'):
case FOUR_CHAR_CODE('4', '9', 'C', 'H'):
case FOUR_CHAR_CODE('5', '0', 'C', 'H'):
case FOUR_CHAR_CODE('5', '1', 'C', 'H'):
case FOUR_CHAR_CODE('5', '2', 'C', 'H'):
case FOUR_CHAR_CODE('5', '3', 'C', 'H'):
case FOUR_CHAR_CODE('5', '4', 'C', 'H'):
case FOUR_CHAR_CODE('5', '5', 'C', 'H'):
case FOUR_CHAR_CODE('5', '6', 'C', 'H'):
case FOUR_CHAR_CODE('5', '7', 'C', 'H'):
case FOUR_CHAR_CODE('5', '8', 'C', 'H'):
case FOUR_CHAR_CODE('5', '9', 'C', 'H'):
case FOUR_CHAR_CODE('6', '0', 'C', 'H'):
case FOUR_CHAR_CODE('6', '1', 'C', 'H'):
case FOUR_CHAR_CODE('6', '2', 'C', 'H'):
case FOUR_CHAR_CODE('6', '3', 'C', 'H'):
case FOUR_CHAR_CODE('6', '4', 'C', 'H'):
return -3; // Too many channels
break;
default:
return -1; // Unrecognised MOD type
break;
}
// 'FLT4', 'FLT8': Startrekker 4/8 channel file. ('FLT6' doesn't exist)
// 'CD81' : Falcon 8 channel MODs
// '2CHN' : FastTracker 2 Channel MODs
// 'yyCH' where yy can be 10, 12, .. 30, 32: FastTracker yy Channel MODs
// 'yyCH' where yy can be 11, 13, 15: TakeTracker 11, 13, 15 channel MODs
// 'TDZx' where x can be 1, 2 or 3: TakeTracker 1, 2, 3 channel MODs
// ModPlug Tracker saves 33-64 channel MODs as '33CH' to '64CH'
}
static void MOD_ConvMod(FILE *out_file, DATAPACK *samples, DATAPACK *patterns,
const char *filename, int mod_num) {
FILE *in_file;
mod_num_chans[mod_num] = 0;
in_file = fopen(filename, "rb");
if (in_file) {
struct ModSampleTemp samps_temp[32];
char temp[23];
int i, tmp, line, chan;
UBYTE song_length, last_pattern;
UBYTE song_data[128];
int pat[64][16];
UWORD tmp_uword;
UBYTE tmp_ubyte;
ULONG notes_temp[16][64];
int effect_count[32] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
BOOL first;
ULONG new_temp;
int num_chans;
UBYTE song_restart_pos;
// printf( "\nMOD_ConvMod( %s ): Reading...\n", filename );
fread(temp, 20, 1, in_file); // mod name
for (i = 1; i <= 31; ++i) {
fread(temp, 22, 1, in_file); // sample name
fread(&tmp_uword, 2, 1, in_file); // sample length
samps_temp[i].length = SwapUWORD(tmp_uword);
fread(&tmp_ubyte, 1, 1, in_file); // finetune
// if ( tmp_ubyte & 8 )
// tmp_ubyte -= 8;
// else
// tmp_ubyte += 8;
samps_temp[i].finetune = tmp_ubyte;
if (tmp_ubyte > 15)
printf("MOD_ConvMod( %s ): Error: finetune %u > 15...\n",
filename, tmp_ubyte);
fread(&tmp_ubyte, 1, 1, in_file); // volume
samps_temp[i].volume = tmp_ubyte;
if (tmp_ubyte > 64) {
printf("MOD_ConvMod( %s ): Error: sample vol %u > 64\n",
filename, tmp_ubyte);
return;
}
fread(&tmp_uword, 2, 1, in_file);
samps_temp[i].repeat = SwapUWORD(tmp_uword);
fread(&tmp_uword, 2, 1, in_file);
tmp = SwapUWORD(tmp_uword);
// samps_temp[i].truelen = samps_temp[i].length;
if (tmp <= 1) {
samps_temp[i].repeat = 65535;
samps_temp[i].truelen = samps_temp[i].length;
} else {
samps_temp[i].truelen =
Min(samps_temp[i].repeat + tmp, samps_temp[i].length);
}
// printf( "i:%d len:%d vol:%d rep:%d fine:%d\n", i,
// samps_temp[i].truelen, samps_temp[i].volume, samps_temp[i].repeat,
// samps_temp[i].finetune );
}
fread(&song_length, 1, 1, in_file);
fread(&song_restart_pos, 1, 1, in_file);
if ((song_length < 1) || (song_length > 128))
printf("MOD_ConvMod( %s ): song_length:%d\n", filename, song_length);
last_pattern = 0;
for (i = 0; i <= 127; ++i) {
fread(&tmp_ubyte, 1, 1, in_file);
song_data[i] = tmp_ubyte;
if (tmp_ubyte > last_pattern)
last_pattern = tmp_ubyte;
}
if (last_pattern > 63)
printf("MOD_ConvMod( %s ): last_pattern:%d\n", filename, last_pattern);
fread(&new_temp, 4, 1, in_file);
num_chans = MOD_GetNumChans(new_temp);
if (num_chans <= 0) {
switch (num_chans) {
case -2: // Unsupported MOD type
printf("Failed! Reason: Unsupported MOD type (%u)\n", new_temp);
break;
case -3: // Too many channels
printf("Failed! Reason: Too many channels\n");
break;
default: // Unrecognised MOD type
printf("Failed! Reason: Unrecognised MOD type (%u)\n", new_temp);
break;
}
return;
} else {
if (num_chans == 1)
printf("%d channel...", num_chans);
else
printf("%d channels...", num_chans);
mod_num_chans[mod_num] = num_chans;
}
for (i = 0; i <= last_pattern; ++i) {
for (line = 0; line < 64; ++line) {
for (chan = 0; chan < num_chans; ++chan) {
UBYTE byte1, byte2, byte3, byte4;
int samp_num, period, effect;
fread(&byte1, 1, 1, in_file);
fread(&byte2, 1, 1, in_file);
fread(&byte3, 1, 1, in_file);
fread(&byte4, 1, 1, in_file);
samp_num = (byte1 & 0xf0) + (byte3 >> 4);
period = (((int)(byte1 & 0xf)) << 8) + ((int)byte2);
effect = (((int)(byte3 & 0xf)) << 8) + byte4;
if (effect != 0) {
if ((effect >> 8) == 0xe)
++effect_count[((effect & 0xf0) >> 4) + 16];
else {
if ((effect >> 8) == 0xf) {
if ((effect & 0xff) > 31)
++effect_count[14];
else
++effect_count[15];
} else {
if ((effect >> 8) == 0xc)
if ((effect & 0xff) > 64)
effect = 0xc40;
if ((effect >> 8) == 0xd) // pattern break
effect = (effect & 0xf00) + (((effect >> 4) & 0xf) * 10) +
(effect & 0xf);
++effect_count[effect >> 8];
}
}
}
notes_temp[chan][line] =
(samp_num << 24) + (MOD_FindNote(period) << 12) + effect;
}
}
for (chan = 0; chan < num_chans; ++chan) {
pat[i][chan] = DATA_AppendAligned(
patterns, (UBYTE *)(¬es_temp[chan][0]), 256, 256);
}
}
for (i = 0; i <= 127; ++i) {
if (i >= song_length) {
for (chan = 0; chan < num_chans; ++chan)
patts[mod_num][i][chan] = -1;
} else {
for (chan = 0; chan < num_chans; ++chan)
patts[mod_num][i][chan] = pat[song_data[i]][chan];
}
}
if (song_length > max_song_length)
max_song_length = song_length;
if (song_restart_pos < 127) {
if (patts[mod_num][song_restart_pos][0] == -1)
song_restart_pos = 0;
} else {
song_restart_pos = 0;
}
mod_song_restart_pos[mod_num] = song_restart_pos;
for (i = 1; i <= 31; ++i) {
if (samps_temp[i].length > 0) {
MOD_LoadSound(&samps[mod_num][i - 1], in_file, samples,
samps_temp[i].length, samps_temp[i].truelen,
samps_temp[i].repeat);
samps[mod_num][i - 1].volume = samps_temp[i].volume;
samps[mod_num][i - 1].finetune = samps_temp[i].finetune;
samps[mod_num][i - 1].repeat = samps_temp[i].repeat;
}
}
printf("Done!\n");
first = TRUE;
for (i = 0; i <= 31; ++i)
if (effect_count[i] > 0)
if (*(effect_name[i]) != '*') {
if (first) {
printf("Unsupported effects:\n");
first = FALSE;
}
printf("%s (%d)\n", effect_name[i], effect_count[i]);
}
printf("song_length:%d last_pattern:%d\n\n", song_length, last_pattern);
fclose(in_file);
} else {
printf("MOD_ConvMod( %s ): Unable to open file for reading...\n", filename);
}
}
static void MOD_WriteSamples(FILE *out_file, int num_mods) {
int i, s;
fprintf(out_file, "\n.ALIGN\n.GLOBAL AAS_ModSamples\nAAS_ModSamples:");
for (i = 0; i < num_mods; ++i) {
fprintf(out_file, "\n.word");
for (s = 0; s < 31; ++s) {
if (s == 0)
fprintf(out_file, " %u, %u, %u", samps[i][s].data,
(samps[i][s].length << 16) + samps[i][s].repeat,
((samps[i][s].volume & 0xff) << 8) +
(samps[i][s].finetune & 0xff));
else
fprintf(out_file, ", %u, %u, %u", samps[i][s].data,
(samps[i][s].length << 16) + samps[i][s].repeat,
((samps[i][s].volume & 0xff) << 8) +
(samps[i][s].finetune & 0xff));
}
}
fprintf(out_file, "\n");
}
static void MOD_WritePatterns(FILE *out_file, int num_mods) {
int mod_num, pattern_num, line_num, channel_num;
BOOL first;
fprintf(out_file, "\n.ALIGN\n.GLOBAL AAS_Sequence\nAAS_Sequence:");
for (mod_num = 0; mod_num < num_mods; ++mod_num) {
fprintf(out_file, "\n.short");
first = TRUE;
for (pattern_num = 0; pattern_num < 128; ++pattern_num) {
for (channel_num = 0; channel_num < 16; ++channel_num) {
if (first) {
first = FALSE;
fprintf(out_file, " %d", patts[mod_num][pattern_num][channel_num]);
} else {
fprintf(out_file, ", %d", patts[mod_num][pattern_num][channel_num]);
}
}
}
}
fprintf(out_file, "\n");
}
static void MOD_WriteNumChans(FILE *out_file, int num_mods) {
int mod_num;
fprintf(out_file, "\n.ALIGN\n.GLOBAL AAS_NumChans\nAAS_NumChans:\n.byte");
for (mod_num = 0; mod_num < num_mods; ++mod_num) {
if (mod_num)
fprintf(out_file, ", %d", mod_num_chans[mod_num]);
else
fprintf(out_file, " %d", mod_num_chans[mod_num]);
}
fprintf(out_file, "\n");
}
static void MOD_WriteSongRestartPos(FILE *out_file, int num_mods) {
int mod_num;
fprintf(out_file, "\n.ALIGN\n.GLOBAL AAS_RestartPos\nAAS_RestartPos:\n.byte");
for (mod_num = 0; mod_num < num_mods; ++mod_num) {
if (mod_num)
fprintf(out_file, ", %d", mod_song_restart_pos[mod_num]);
else
fprintf(out_file, " %d", mod_song_restart_pos[mod_num]);
}
fprintf(out_file, "\n");
}
/*
static void MOD_WritePeriodConvTable( FILE* out_file, int mix_rate )
{
int i, freq;
fprintf( out_file, "\nconst UWORD AAS_MOD_period_conv_table[2048] = {
65535" );
for( i = 1; i < 2048; ++i )
{
freq = (int)((((double)7093789.2)/((double)(2*i))));
if ( freq > 65535 )
freq = 65535;
fprintf( out_file, ", %d", freq );
}
fprintf( out_file, " };\n" );
}
*/
static int last_samp_length = 0;
static int RAW_LoadSound(const char *filename, DATAPACK *sfx) {
struct stat file_info;
if (stat(filename, &file_info) != 0) {
printf("\nRAW_LoadSound( %s ): Unable to open...\n", filename);
return -1;
}
int length = file_info.st_size;
FILE *in_file = fopen(filename, "rb");
if (!in_file) {
printf("\nRAW_LoadSound( %s ): Unable to open...\n", filename);
return -1;
}
BYTE *samp = (BYTE *)malloc(length + 16);
last_samp_length = length;
fread(samp + 16, 1, length, in_file);
fclose(in_file);
memmove(samp, samp + length, 16);
MISC_ProcessSound(samp, length + 16);
int data = DATA_Append(sfx, samp, length + 16) + 16;
free(samp);
printf("Done!\n\n");
return data;
}
static BOOL WAV_CheckHeaders(FILE* in_file, const char *filename) {
ULONG tmp;
fread(&tmp, 4, 1, in_file);
if (tmp != 0x46464952) {
printf("\nWAV_LoadSound( %s ): Failed: RIFF header missing...\n",
filename);
return FALSE;
}
fread(&tmp, 4, 1, in_file);
fread(&tmp, 4, 1, in_file);
if (tmp != 0x45564157) {
printf("\nWAV_LoadSound( %s ): Failed: Not a WAVE file...\n", filename);
return FALSE;
}
fread(&tmp, 4, 1, in_file);
if (tmp != 0x20746d66) {
printf("\nWAV_LoadSound( %s ): Failed: Missing fmt subchunk...\n",
filename);
return FALSE;
}
unsigned short format;
fread(&tmp, 4, 1, in_file);
fread(&format, 2, 1, in_file);
if (format != 1) { // PCM format
printf("\nWAV_LoadSound( %s ): Failed: Not in PCM format...\n",
filename);
return FALSE;
}
unsigned short channels;
fread(&channels, 2, 1, in_file);
if (channels != 1) { // mono
printf("\nWAV_LoadSound( %s ): Failed: Not mono...\n", filename);
return FALSE;
}
unsigned short bits_per_sample;
fread(&tmp, 4, 1, in_file); // sample rate in hz
fread(&tmp, 4, 1, in_file);
fread(&tmp, 2, 1, in_file);
fread(&bits_per_sample, 2, 1, in_file);
if (bits_per_sample != 8) {
printf("\nWAV_LoadSound( %s ): Failed: Not 8 bit...\n",
filename);
return FALSE;
}
return TRUE;
}
static int WAV_LoadSound(const char *filename, DATAPACK *sfx) {
FILE *in_file;
in_file = fopen(filename, "rb");
if (!in_file) {
printf("\nWAV_LoadSound( %s ): Failed: Unable to open...\n", filename);
return -1;
}
if (!WAV_CheckHeaders(in_file, filename)) {
// we've already shown an error message when checking headers
return -1;
}
ULONG tmp;
int ret, length;
BOOL done = FALSE;
int data = -1;
last_samp_length = 0;
length = 0;
do {
ret = fread(&tmp, 4, 1, in_file);
if (ret == 1) {
if (tmp == 0x61746164) { // "data"
ret = fread(&length, 4, 1, in_file);
if (ret == 1) {
if (length > 0) {
done = TRUE;
}
} else {
done = TRUE;
}
} else {
int size;
ret = fread(&size, 4, 1, in_file);
if (ret == 1) {
fseek(in_file, size, SEEK_CUR);
} else {
done = TRUE;
}
}
} else {
done = TRUE;
}
} while (!done);
if (length > 0) {
BYTE *samp = (BYTE *)malloc(length + 16);
last_samp_length = length;
fread(samp + 16, 1, length, in_file);
memmove(samp, samp + length, 16);
MISC_ConvSoundToSigned((UBYTE *)samp, length + 16);
MISC_ProcessSound(samp, length + 16);
data = DATA_Append(sfx, samp, length + 16) + 16;
free(samp);
printf("Done!\n\n");
} else {
printf("\nWAV_LoadSound( %s ): Unable to find valid data subchunk...\n",
filename);
}
fclose(in_file);
return data;
}
__inline static char String_GetChar(const char *txt, int offset) {
return *(txt + offset);
}
static BOOL String_EndsWithMOD(const char *txt) {
int txt_len = strlen(txt);
if (txt_len > 4) {
if ((String_GetChar(txt, txt_len - 4) == '.') &&
((String_GetChar(txt, txt_len - 3) == 'm') ||
(String_GetChar(txt, txt_len - 3) == 'M')) &&
((String_GetChar(txt, txt_len - 2) == 'o') ||
(String_GetChar(txt, txt_len - 2) == 'O')) &&
((String_GetChar(txt, txt_len - 1) == 'd') ||
(String_GetChar(txt, txt_len - 1) == 'D'))) {
return TRUE;
}
}
return FALSE;
}
static BOOL String_EndsWithRAW(const char *txt) {
int txt_len = strlen(txt);
if (txt_len > 4) {
if ((String_GetChar(txt, txt_len - 4) == '.') &&
((String_GetChar(txt, txt_len - 3) == 'r') ||
(String_GetChar(txt, txt_len - 3) == 'R')) &&
((String_GetChar(txt, txt_len - 2) == 'a') ||
(String_GetChar(txt, txt_len - 2) == 'A')) &&
((String_GetChar(txt, txt_len - 1) == 'w') ||
(String_GetChar(txt, txt_len - 1) == 'W'))) {
return TRUE;
}
}
return FALSE;
}
static BOOL String_EndsWithWAV(const char *txt) {
int txt_len = strlen(txt);
if (txt_len > 4) {
if ((String_GetChar(txt, txt_len - 4) == '.') &&
((String_GetChar(txt, txt_len - 3) == 'w') ||
(String_GetChar(txt, txt_len - 3) == 'W')) &&
((String_GetChar(txt, txt_len - 2) == 'a') ||
(String_GetChar(txt, txt_len - 2) == 'A')) &&
((String_GetChar(txt, txt_len - 1) == 'v') ||
(String_GetChar(txt, txt_len - 1) == 'V'))) {
return TRUE;
}
}
return FALSE;
}
static void String_MakeSafe(char *temp) {
char c;
while (*temp != (char)0) {
c = *temp;
if (!(((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')) ||
((c >= '0') && (c <= '9'))))
*temp = '_';
++temp;
}
}
static void ShowHelp() {
printf(" Usage: Conv2AAS input_dir\n\n");
printf(" input_dir Directory containing all Protracker\n");
printf(" MODs & sample data\n\n");
printf(" Output goes to files AAS_Data.s & AAS_Data.h\n");
}
int main(int argc, char *argv[]) {
setbuf(stdout, 0);
printf("\n");
printf("/---------------------------------------------\\\n");
printf("| Conv2AAS v1.13 WAV, RAW & MOD -> AAS |\n");
printf("| Copyright (c) 2005, Apex Designs |\n");
printf("\\---------------------------------------------/\n\n");
if (argc < 2) {
ShowHelp();
return 1;
} else if ((argc == 2) && ((strcmp(argv[1], "-help") == 0) ||
(strcmp(argv[1], "-?") == 0))) {
ShowHelp();
return 0;
}
FILE *out_file_s;
out_file_s = fopen("./AAS_Data.s", "w");
if (!out_file_s) {
printf("Unable to open AASData.s for writing...\n");
return 1;
}
FILE *out_file_h;
out_file_h = fopen("./AAS_Data.h", "w");
if (!out_file_h) {
printf("Unable to open AASData.h for writing...\n");
return 1;
}
DIR *dir_info;
dir_info = opendir(argv[1]);
if (!dir_info) {
printf("Unable to open directory %s...\n", argv[1]);
return 1;
}
int files_converted = 0;
int mods_found = 0;
DATAPACK *samples;
DATAPACK *patterns;
struct dirent *file_info;
samples = DATA_Create("AAS_SampleData");
patterns = DATA_Create("AAS_PatternData");
fprintf(
out_file_h,
"#ifndef __AAS_DATA__\n#define __AAS_DATA__\n\n#include "
"\"AAS.h\"\n\n#if AAS_VERSION != 0x113\n#error AAS version does "
"not match Conv2AAS version\n#endif\n\nAAS_BEGIN_DECLS\n");
fprintf(out_file_s,
".TEXT\n.SECTION .rodata\n.ALIGN\n.ARM\n\n.ALIGN\n.EXTERN "
"AAS_lib_v113\n.GLOBAL AAS_data_v113\nAAS_data_v113:\n.word "
"AAS_lib_v113\n");
do {
file_info = readdir(dir_info);
if (file_info) {
char temp[512];
strcpy(temp, argv[1]);
strcat(temp, "/");
strcat(temp, file_info->d_name);
if (String_EndsWithMOD(file_info->d_name)) {
++files_converted;
printf("Adding MOD %s...", file_info->d_name);
MOD_ConvMod(out_file_h, samples, patterns, temp, mods_found);
// printf( "Done!\n" );
strcpy(temp, file_info->d_name);
*(temp + strlen(temp) - 4) = 0;
String_MakeSafe(temp);
fprintf(out_file_h, "\nextern const AAS_u8 AAS_DATA_MOD_%s;\n",
temp);
fprintf(out_file_s,
"\n.ALIGN\n.GLOBAL "
"AAS_DATA_MOD_%s\nAAS_DATA_MOD_%s:\n.byte %d\n",
temp, temp, mods_found);
++mods_found;
} else if (String_EndsWithRAW(file_info->d_name)) {
int val;
++files_converted;
printf("Adding RAW %s...", file_info->d_name);
val = RAW_LoadSound(temp, samples);
if (val >= 0) {
strcpy(temp, file_info->d_name);
*(temp + strlen(temp) - 4) = 0;
String_MakeSafe(temp);
fprintf(
out_file_h,
"\nextern const AAS_s8* const AAS_DATA_SFX_START_%s;\n",
temp);
fprintf(out_file_s,
"\n.ALIGN\n.GLOBAL "
"AAS_DATA_SFX_START_%s\nAAS_DATA_SFX_START_%s:\n."
"word AAS_SampleData + %d\n",
temp, temp, val);
fprintf(out_file_h,
"\nextern const AAS_s8* const AAS_DATA_SFX_END_%s;\n",
temp);
fprintf(out_file_s,
"\n.ALIGN\n.GLOBAL "
"AAS_DATA_SFX_END_%s\nAAS_DATA_SFX_END_%s:\n.word "
"AAS_SampleData + %d\n",
temp, temp, val + last_samp_length);
}
} else if (String_EndsWithWAV(file_info->d_name)) {
int val;
++files_converted;
printf("Adding WAV %s...", file_info->d_name);
val = WAV_LoadSound(temp, samples);
if (val >= 0) {
strcpy(temp, file_info->d_name);
*(temp + strlen(temp) - 4) = 0;
String_MakeSafe(temp);
fprintf(
out_file_h,
"\nextern const AAS_s8* const AAS_DATA_SFX_START_%s;\n",
temp);
fprintf(out_file_s,
"\n.ALIGN\n.GLOBAL "
"AAS_DATA_SFX_START_%s\nAAS_DATA_SFX_START_%s:\n."
"word AAS_SampleData + %d\n",
temp, temp, val);
fprintf(out_file_h,
"\nextern const AAS_s8* const AAS_DATA_SFX_END_%s;\n",
temp);
fprintf(out_file_s,
"\n.ALIGN\n.GLOBAL "
"AAS_DATA_SFX_END_%s\nAAS_DATA_SFX_END_%s:\n.word "
"AAS_SampleData + %d\n",
temp, temp, val + last_samp_length);
}
}
}
} while (file_info);
closedir(dir_info);
fprintf(out_file_s,
"\n.ALIGN\n.GLOBAL "
"AAS_DATA_NUM_MODS\nAAS_DATA_NUM_MODS:\n.short %d\n",
mods_found);
MOD_WriteSamples(out_file_s, mods_found);
MOD_WritePatterns(out_file_s, mods_found);
MOD_WriteNumChans(out_file_s, mods_found);
MOD_WriteSongRestartPos(out_file_s, mods_found);
// MOD_WritePeriodConvTable( out_file_h, 24002 );
DATA_Write(samples, out_file_s);
DATA_Write(patterns, out_file_s);
printf("\n");
fprintf(out_file_h, "\nAAS_END_DECLS\n\n#endif\n");
fclose(out_file_h);
fclose(out_file_s);
return 0;
}
|
the_stack_data/37636673.c | #include <stdio.h>
#define MAX 10
void InsertionSort(int a[], int n);
int main()
{
int a[MAX] ={0},n, i;
printf("Enter the number of elements :");
scanf(" %d", &n);
printf("\n");
printf("Enter the numbers : ");
for(i=0; i< n; i++){
scanf ("%d", &a[i]);
}
InsertionSort(a, n);
return 0;
}
void InsertionSort(int a[], int n){
int i, j, temp;
for(i=0; i<n-1 ; i++){
temp = a[i+1];
for(j = i; j >= 0; j--){
if(temp < a[j]){
a[j+1] = a[j];
}
else{
break;
}
}
a[j+1] =temp;
}
printf("\n Sorted array : \t");
for(i=0; i< n; i++ ){
printf("%d \t", a[i]);
}
} |
the_stack_data/1052329.c |
int removeDuplicates(int* nums, int numsSize){
if(numsSize == 0) return 0;
int i, counter = 1, * record = nums;
for(i=1; i<numsSize; ++i){
if(nums[i] != *record){
*(++record) = nums[i];
++counter;
}
}
return counter;
} |
the_stack_data/231394653.c | /*
************************************************
username : smmehrab
fullname : s.m.mehrabul islam
email : [email protected]
institute : university of dhaka, bangladesh
session : 2017-2018
************************************************
*/
#include<stdio.h>
int main()
{
char s[200];int i=0;
gets(s); int n=0;
while(s[i]!='\0')
{
n++;
i++;
}
for(i=0;i<n;i++)
{
if(s[i]<'a')
{
s[i]= s[i] + 32;
}
if(s[i]!='a'&&s[i]!='e'&&s[i]!='i'&&s[i]!='o'&&s[i]!='u'&&s[i]!='y')
{
printf(".");
printf("%c",s[i]);
}
}
printf("\n");
return 0;
}
|
the_stack_data/62838.c | #include<stdio.h>
int main()
{
int x[8]={10,20,30,40,50,60,70,80};
printf("x: %p\n",x);
printf("x+2: %p\n",x+2);
printf("x: %d\n",*x);
printf("x: %d\n",(*x+2));
printf("x: %d\n",*(x+2));
return 0;
}
|
the_stack_data/73575225.c | #include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#define THR_N 20
#define F_NAME "/tmp/out"
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
static pthread_t pth[THR_N] = {};
static int _read_file(const char *path, int *count);
static void *pth_job(void *arg);
int main(void)
{
int err;
int fd, res;
for (int i = 0; i < THR_N; i++)
{
err = pthread_create(pth+i, NULL, pth_job, NULL);
if (err != 0)
{
fprintf(stderr, "pthread_create() %s\n", strerror(err));
exit(1);
}
}
pthread_mutex_lock(&mutex);
do {
fd = open(F_NAME, O_WRONLY | O_CREAT | O_TRUNC, 0666);
if (fd == -1)
{
if (errno == EINTR)
continue;
perror("open()");
exit(1);
}
} while(fd < 0);
res = write(fd, "0", 1);
if (res == -1)
{
if (errno != EINTR)
{
perror("write()");
close(fd);
exit(1);
}
}
close(fd);
printf("%d\n", _read_file(F_NAME, NULL));
exit(0);
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
while (1)
{
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex);
if (_read_file(F_NAME, NULL) == 20)
break;
pthread_mutex_unlock(&mutex);
}
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
exit(0);
}
static int _read_file(const char *path, int *count)
{
int fd, res;
char buf[128] = {};
printf("1\n");
do {
fd = open(path, O_RDONLY);
printf("1\n");
if (fd == -1)
{
if (errno == EINTR)
continue;
perror("open()");
exit(1);
}
} while(fd < 0);
printf("1\n");
while (1)
{
res = read(fd, buf, 128);
if (res == 0)
break;
if (res == -1)
{
if (errno == EINTR)
continue;
perror("read()");
close(fd);
return -1;
}
}
printf("1\n");
close(fd);
printf("res:%d\n", res);
//memcpy(count, &res, sizeof(int));
*count = res;
printf("1\n");
res = atoi(buf);
printf("1\n");
printf("count:%d res:%d\n", *count, res);
return res;
}
static void *pth_job(void *arg)
{
int num, count, i = 0;
char str[128] = {};
int fd, res;
while (1)
{
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex);
num = _read_file(F_NAME, &count);
if (num == 20)
{
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
pthread_exit((void *)0);
}
num ++;
while (num != 0)
{
str[i++] = num%10 + '0';
num /= 10;
}
str[i] = '\0';
do {
fd = open(F_NAME, O_WRONLY);
if (fd == -1)
{
if (errno == EINTR)
continue;
perror("open()");
exit(1);
}
} while(fd < 0);
res = write(fd, str, strlen(str));
if (res == -1)
{
if (errno != EINTR)
{
perror("write()");
close(fd);
exit(1);
}
}
close(fd);
printf("%d\n", _read_file(F_NAME, NULL));
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
}
}
|
the_stack_data/162642305.c | #define _GNU_SOURCE
#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <poll.h>
#include <errno.h>
#include <limits.h>
#include <sys/stat.h>
#include <sys/signalfd.h>
#include <fcntl.h>
#include <linux/fanotify.h>
#include <sys/fanotify.h>
typedef struct {
char *path;
} monitored_t;
#define FANOTIFY_BUFFER_SIZE 8192
enum {
FD_POLL_SIGNAL = 0,
FD_POLL_FANOTIFY,
FD_POLL_MAX
};
static uint64_t event_mask =
//(FAN_OPEN_PERM); // Open permission control
(
FAN_MARK_MOUNT |
FAN_OPEN_PERM|
// FAN_ACCESS | /* File accessed */
// FAN_MODIFY | /* File modified */
FAN_CLOSE_WRITE | /* Writtable file closed */
FAN_CLOSE_NOWRITE | /* Unwrittable file closed */
// FAN_OPEN | /* File was opened */
FAN_ONDIR | /* We want to be reported of events in the directory */
FAN_EVENT_ON_CHILD); /* We want to be reported of events in files of the directory */
static monitored_t *monitors = NULL;
static int n_monitors = 0;
static char *
get_program_name_from_pid (int pid,
char *buffer,
size_t buffer_size)
{
int fd = 0;
ssize_t len = 0;
char *aux = NULL;
// Try to get program name by PID
sprintf (buffer, "/proc/%d/cmdline", pid);
if ((fd = open (buffer, O_RDONLY)) < 0)
return NULL;
if ((len = read (fd, buffer, buffer_size - 1)) <= 0)
{
close (fd);
return NULL;
}
close (fd);
buffer[len] = '\0';
aux = strstr (buffer, "^@");
if (aux)
*aux = '\0';
return buffer;
}
static char *
get_file_path_from_fd (int fd,
char *buffer,
size_t buffer_size)
{
ssize_t len = 0;
if (fd <= 0)
return NULL;
sprintf (buffer, "/proc/self/fd/%d", fd);
if ((len = readlink (buffer, buffer, buffer_size - 1)) < 0)
return NULL;
buffer[len] = '\0';
return buffer;
}
static void
event_process (struct fanotify_event_metadata *event,
int fanotify_fd)
{
char file_path[PATH_MAX] = {0};
char program_path[PATH_MAX] = {0};
if (NULL == get_file_path_from_fd (event->fd, file_path, PATH_MAX))
{
struct fanotify_response access = {0};
access.fd = event->fd;
access.response = FAN_ALLOW;
write (fanotify_fd, &access, sizeof (access));
return;
}
// if (strncmp(file_path, "/media/", sizeof("/media/")) != 0)
// {
// struct fanotify_response access = {0};
// access.fd = event->fd;
// access.response = FAN_ALLOW;
// write (fanotify_fd, &access, sizeof (access));
// return;
// }
printf ("Received event in path '%s'=>[%d]", file_path, event->mask);
printf (" pid=%d (%s): \n",
event->pid,
(get_program_name_from_pid (event->pid, program_path, PATH_MAX) ?
program_path :
"unknown"));
//if (event->mask & FAN_OPEN_PERM)
{
struct fanotify_response access = {0};
access.fd = event->fd;
// if (strstr (file_path, "666") != NULL)
// {
// printf ("\tFAN_OPEN_PERM: denying\n");
// access.response = FAN_DENY;
// }
// else
{
//printf ("\tFAN_OPEN_PERM: allowing\n");
access.response = FAN_ALLOW;
}
write (fanotify_fd, &access, sizeof (access));
}
fflush (stdout);
close (event->fd);
}
static void
shutdown_fanotify (int fanotify_fd)
{
int i;
for (i = 0; i < n_monitors; ++i)
{
/* Remove the mark, using same event mask as when creating it */
fanotify_mark (fanotify_fd,
FAN_MARK_REMOVE,
event_mask,
AT_FDCWD,
monitors[i].path);
free (monitors[i].path);
}
free (monitors);
close (fanotify_fd);
}
static int
initialize_fanotify (int argc,
const char **argv)
{
int i = 0;
int fanotify_fd = 0;
if ((fanotify_fd = fanotify_init (FAN_CLOEXEC| FAN_CLASS_CONTENT,
O_RDONLY | O_CLOEXEC | O_LARGEFILE | O_NOATIME)) < 0)
{
fprintf (stderr,
"Couldn't setup new fanotify device: %s\n",
strerror (errno));
return -1;
}
//n_monitors = argc - 1;
//monitors = malloc (n_monitors * sizeof (monitored_t));
n_monitors = 1;
monitors = (monitored_t*)malloc (n_monitors * sizeof (monitored_t));
/* Loop all input directories, setting up marks */
//for (i = 0; i < n_monitors; ++i)
{
//monitors[i].path = strdup (argv[i + 1]);
monitors[i].path = strdup ( "/media/somansa/1493-193A" );
/* Add new fanotify mark */
if (fanotify_mark (fanotify_fd,
FAN_MARK_ADD | FAN_MARK_MOUNT,
event_mask,
AT_FDCWD,
monitors[i].path) < 0)
{
fprintf (stderr,
"Couldn't add monitor in mount '%s': '%s'\n",
monitors[i].path,
strerror (errno));
return -1;
}
printf ("Started monitoring mount '%s'...\n",
monitors[i].path);
}
return fanotify_fd;
}
static void
shutdown_signals (int signal_fd)
{
close (signal_fd);
}
static int
initialize_signals (void)
{
int signal_fd;
sigset_t sigmask;
/* We want to handle SIGINT and SIGTERM in the signal_fd, so we block them. */
sigemptyset (&sigmask);
sigaddset (&sigmask, SIGINT);
sigaddset (&sigmask, SIGTERM);
if (sigprocmask (SIG_BLOCK, &sigmask, NULL) < 0)
{
fprintf (stderr,
"Couldn't block signals: '%s'\n",
strerror (errno));
return -1;
}
/* Get new FD to read signals from it */
if ((signal_fd = signalfd (-1, &sigmask, 0)) < 0)
{
fprintf (stderr,
"Couldn't setup signal FD: '%s'\n",
strerror (errno));
return -1;
}
return signal_fd;
}
int
main (int argc,
const char **argv)
{
int signal_fd;
int fanotify_fd;
struct pollfd fds[FD_POLL_MAX];
/* Input arguments... */
// if (argc < 2)
// {
// fprintf (stderr, "Usage: %s directory1 [directory2 ...]\n", argv[0]);
// exit (EXIT_FAILURE);
// }
/* Initialize signals FD */
if ((signal_fd = initialize_signals ()) < 0)
{
fprintf (stderr, "Couldn't initialize signals\n");
exit (EXIT_FAILURE);
}
/* Initialize fanotify FD and the marks */
if ((fanotify_fd = initialize_fanotify (argc, argv)) < 0)
{
fprintf (stderr, "Couldn't initialize fanotify\n");
exit (EXIT_FAILURE);
}
/* Setup polling */
fds[FD_POLL_SIGNAL].fd = signal_fd;
fds[FD_POLL_SIGNAL].events = POLLIN;
fds[FD_POLL_FANOTIFY].fd = fanotify_fd;
fds[FD_POLL_FANOTIFY].events = POLLIN;
/* Now loop */
for (;;)
{
/* Block until there is something to be read */
if (poll (fds, FD_POLL_MAX, -1) < 0)
{
fprintf (stderr,
"Couldn't poll(): '%s'\n",
strerror (errno));
exit (EXIT_FAILURE);
}
/* Signal received? */
if (fds[FD_POLL_SIGNAL].revents & POLLIN)
{
struct signalfd_siginfo fdsi;
if (read (fds[FD_POLL_SIGNAL].fd,
&fdsi,
sizeof (fdsi)) != sizeof (fdsi))
{
fprintf (stderr,
"Couldn't read signal, wrong size read\n");
exit (EXIT_FAILURE);
}
/* Break loop if we got the expected signal */
if (fdsi.ssi_signo == SIGINT ||
fdsi.ssi_signo == SIGTERM)
{
break;
}
fprintf (stderr,
"Received unexpected signal\n");
}
/* fanotify event received? */
if (fds[FD_POLL_FANOTIFY].revents & POLLIN)
{
char buffer[FANOTIFY_BUFFER_SIZE];
ssize_t length;
/* Read from the FD. It will read all events available up to
* the given buffer size. */
if ((length = read (fds[FD_POLL_FANOTIFY].fd,
buffer,
FANOTIFY_BUFFER_SIZE)) > 0)
{
struct fanotify_event_metadata *metadata;
metadata = (struct fanotify_event_metadata *)buffer;
while (FAN_EVENT_OK (metadata, length))
{
event_process (metadata, fanotify_fd);
if (metadata->fd > 0)
close (metadata->fd);
metadata = FAN_EVENT_NEXT (metadata, length);
}
}
}
}
/* Clean exit */
shutdown_fanotify (fanotify_fd);
shutdown_signals (signal_fd);
printf ("Exiting fanotify example...\n");
return EXIT_SUCCESS;
}
|
the_stack_data/103443.c | #include <stdio.h>
#include <expat.h>
static void XMLCALL
startElement(void *userData, const XML_Char *name, const XML_Char **atts)
{
int i;
int *depthPtr = (int *)userData;
(void)atts;
for (i = 0; i < *depthPtr; i++)
putchar('\t');
printf("%s\n", name);
*depthPtr += 1;
}
static void XMLCALL
endElement(void *userData, const XML_Char *name)
{
int *depthPtr = (int *)userData;
(void)name;
*depthPtr -= 1;
}
static void XMLCALL
characterData(void *userData, const XML_Char *str, int len)
{
int *depthPtr = (int *)userData;
fwrite(str, 1, len, stdout);
}
int
main(int argc, char *argv[])
{
char buf[BUFSIZ];
XML_Parser parser = XML_ParserCreate(NULL);
int done;
int depth = 0;
(void)argc;
(void)argv;
XML_SetUserData(parser, &depth);
XML_SetElementHandler(parser, startElement, endElement);
XML_SetCharacterDataHandler(parser, characterData);
do {
size_t len = fread(buf, 1, sizeof(buf), stdin);
done = len < sizeof(buf);
if (XML_Parse(parser, buf, (int)len, done) == XML_STATUS_ERROR) {
fprintf(stderr, "%s at line %lu\n",
XML_ErrorString(XML_GetErrorCode(parser)),
XML_GetCurrentLineNumber(parser));
return 1;
}
} while (!done);
XML_ParserFree(parser);
return 0;
}
|
the_stack_data/124305.c | // Test that misexpect emits no warning when switch condition is non-const
// RUN: llvm-profdata merge %S/Inputs/misexpect-switch-nonconst.proftext -o %t.profdata
// RUN: %clang_cc1 %s -O2 -o - -disable-llvm-passes -emit-llvm -fprofile-instrument-use-path=%t.profdata -verify
// expected-no-diagnostics
int sum(int *buff, int size);
int random_sample(int *buff, int size);
int rand();
void init_arry();
const int inner_loop = 1000;
const int outer_loop = 20;
enum { arry_size = 25 };
int arry[arry_size] = {0};
int main() {
init_arry();
int val = 0;
int j, k;
for (j = 0; j < outer_loop; ++j) {
for (k = 0; k < inner_loop; ++k) {
unsigned condition = rand() % 10000;
switch (__builtin_expect(condition, rand())) {
case 0:
val += sum(arry, arry_size);
break;
case 1:
case 2:
case 3:
case 4:
val += random_sample(arry, arry_size);
break;
default:
__builtin_unreachable();
} // end switch
} // end inner_loop
} // end outer_loop
return 0;
}
|
the_stack_data/384411.c | /*
* RFC 1186/1320 compliant MD4 implementation
*
* Based on XySSL: Copyright (C) 2006-2008 Christophe Devine
*
* Copyright (C) 2009 Paul Bakker <polarssl_maintainer at polarssl dot org>
*
* 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 names of PolarSSL or XySSL 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.
*/
/*
* The MD4 algorithm was designed by Ron Rivest in 1990.
*
* http://www.ietf.org/rfc/rfc1186.txt
* http://www.ietf.org/rfc/rfc1320.txt
*/
#ifdef LIBOHIBOARD_ETHERNET_LWIP_2_0_3
#include "netif/ppp/ppp_opts.h"
#if PPP_SUPPORT && LWIP_INCLUDED_POLARSSL_MD4
#include "netif/ppp/polarssl/md4.h"
#include <string.h>
/*
* 32-bit integer manipulation macros (little endian)
*/
#ifndef GET_ULONG_LE
#define GET_ULONG_LE(n,b,i) \
{ \
(n) = ( (unsigned long) (b)[(i) ] ) \
| ( (unsigned long) (b)[(i) + 1] << 8 ) \
| ( (unsigned long) (b)[(i) + 2] << 16 ) \
| ( (unsigned long) (b)[(i) + 3] << 24 ); \
}
#endif
#ifndef PUT_ULONG_LE
#define PUT_ULONG_LE(n,b,i) \
{ \
(b)[(i) ] = (unsigned char) ( (n) ); \
(b)[(i) + 1] = (unsigned char) ( (n) >> 8 ); \
(b)[(i) + 2] = (unsigned char) ( (n) >> 16 ); \
(b)[(i) + 3] = (unsigned char) ( (n) >> 24 ); \
}
#endif
/*
* MD4 context setup
*/
void md4_starts( md4_context *ctx )
{
ctx->total[0] = 0;
ctx->total[1] = 0;
ctx->state[0] = 0x67452301;
ctx->state[1] = 0xEFCDAB89;
ctx->state[2] = 0x98BADCFE;
ctx->state[3] = 0x10325476;
}
static void md4_process( md4_context *ctx, const unsigned char data[64] )
{
unsigned long X[16], A, B, C, D;
GET_ULONG_LE( X[ 0], data, 0 );
GET_ULONG_LE( X[ 1], data, 4 );
GET_ULONG_LE( X[ 2], data, 8 );
GET_ULONG_LE( X[ 3], data, 12 );
GET_ULONG_LE( X[ 4], data, 16 );
GET_ULONG_LE( X[ 5], data, 20 );
GET_ULONG_LE( X[ 6], data, 24 );
GET_ULONG_LE( X[ 7], data, 28 );
GET_ULONG_LE( X[ 8], data, 32 );
GET_ULONG_LE( X[ 9], data, 36 );
GET_ULONG_LE( X[10], data, 40 );
GET_ULONG_LE( X[11], data, 44 );
GET_ULONG_LE( X[12], data, 48 );
GET_ULONG_LE( X[13], data, 52 );
GET_ULONG_LE( X[14], data, 56 );
GET_ULONG_LE( X[15], data, 60 );
#define S(x,n) ((x << n) | ((x & 0xFFFFFFFF) >> (32 - n)))
A = ctx->state[0];
B = ctx->state[1];
C = ctx->state[2];
D = ctx->state[3];
#define F(x, y, z) ((x & y) | ((~x) & z))
#define P(a,b,c,d,x,s) { a += F(b,c,d) + x; a = S(a,s); }
P( A, B, C, D, X[ 0], 3 );
P( D, A, B, C, X[ 1], 7 );
P( C, D, A, B, X[ 2], 11 );
P( B, C, D, A, X[ 3], 19 );
P( A, B, C, D, X[ 4], 3 );
P( D, A, B, C, X[ 5], 7 );
P( C, D, A, B, X[ 6], 11 );
P( B, C, D, A, X[ 7], 19 );
P( A, B, C, D, X[ 8], 3 );
P( D, A, B, C, X[ 9], 7 );
P( C, D, A, B, X[10], 11 );
P( B, C, D, A, X[11], 19 );
P( A, B, C, D, X[12], 3 );
P( D, A, B, C, X[13], 7 );
P( C, D, A, B, X[14], 11 );
P( B, C, D, A, X[15], 19 );
#undef P
#undef F
#define F(x,y,z) ((x & y) | (x & z) | (y & z))
#define P(a,b,c,d,x,s) { a += F(b,c,d) + x + 0x5A827999; a = S(a,s); }
P( A, B, C, D, X[ 0], 3 );
P( D, A, B, C, X[ 4], 5 );
P( C, D, A, B, X[ 8], 9 );
P( B, C, D, A, X[12], 13 );
P( A, B, C, D, X[ 1], 3 );
P( D, A, B, C, X[ 5], 5 );
P( C, D, A, B, X[ 9], 9 );
P( B, C, D, A, X[13], 13 );
P( A, B, C, D, X[ 2], 3 );
P( D, A, B, C, X[ 6], 5 );
P( C, D, A, B, X[10], 9 );
P( B, C, D, A, X[14], 13 );
P( A, B, C, D, X[ 3], 3 );
P( D, A, B, C, X[ 7], 5 );
P( C, D, A, B, X[11], 9 );
P( B, C, D, A, X[15], 13 );
#undef P
#undef F
#define F(x,y,z) (x ^ y ^ z)
#define P(a,b,c,d,x,s) { a += F(b,c,d) + x + 0x6ED9EBA1; a = S(a,s); }
P( A, B, C, D, X[ 0], 3 );
P( D, A, B, C, X[ 8], 9 );
P( C, D, A, B, X[ 4], 11 );
P( B, C, D, A, X[12], 15 );
P( A, B, C, D, X[ 2], 3 );
P( D, A, B, C, X[10], 9 );
P( C, D, A, B, X[ 6], 11 );
P( B, C, D, A, X[14], 15 );
P( A, B, C, D, X[ 1], 3 );
P( D, A, B, C, X[ 9], 9 );
P( C, D, A, B, X[ 5], 11 );
P( B, C, D, A, X[13], 15 );
P( A, B, C, D, X[ 3], 3 );
P( D, A, B, C, X[11], 9 );
P( C, D, A, B, X[ 7], 11 );
P( B, C, D, A, X[15], 15 );
#undef F
#undef P
ctx->state[0] += A;
ctx->state[1] += B;
ctx->state[2] += C;
ctx->state[3] += D;
}
/*
* MD4 process buffer
*/
void md4_update( md4_context *ctx, const unsigned char *input, int ilen )
{
int fill;
unsigned long left;
if( ilen <= 0 )
return;
left = ctx->total[0] & 0x3F;
fill = 64 - left;
ctx->total[0] += ilen;
ctx->total[0] &= 0xFFFFFFFF;
if( ctx->total[0] < (unsigned long) ilen )
ctx->total[1]++;
if( left && ilen >= fill )
{
MEMCPY( (void *) (ctx->buffer + left),
input, fill );
md4_process( ctx, ctx->buffer );
input += fill;
ilen -= fill;
left = 0;
}
while( ilen >= 64 )
{
md4_process( ctx, input );
input += 64;
ilen -= 64;
}
if( ilen > 0 )
{
MEMCPY( (void *) (ctx->buffer + left),
input, ilen );
}
}
static const unsigned char md4_padding[64] =
{
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
/*
* MD4 final digest
*/
void md4_finish( md4_context *ctx, unsigned char output[16] )
{
unsigned long last, padn;
unsigned long high, low;
unsigned char msglen[8];
high = ( ctx->total[0] >> 29 )
| ( ctx->total[1] << 3 );
low = ( ctx->total[0] << 3 );
PUT_ULONG_LE( low, msglen, 0 );
PUT_ULONG_LE( high, msglen, 4 );
last = ctx->total[0] & 0x3F;
padn = ( last < 56 ) ? ( 56 - last ) : ( 120 - last );
md4_update( ctx, md4_padding, padn );
md4_update( ctx, msglen, 8 );
PUT_ULONG_LE( ctx->state[0], output, 0 );
PUT_ULONG_LE( ctx->state[1], output, 4 );
PUT_ULONG_LE( ctx->state[2], output, 8 );
PUT_ULONG_LE( ctx->state[3], output, 12 );
}
/*
* output = MD4( input buffer )
*/
void md4( unsigned char *input, int ilen, unsigned char output[16] )
{
md4_context ctx;
md4_starts( &ctx );
md4_update( &ctx, input, ilen );
md4_finish( &ctx, output );
}
#endif /* PPP_SUPPORT && LWIP_INCLUDED_POLARSSL_MD4 */
#endif /* LIBOHIBOARD_ETHERNET_LWIP_2_0_3 */
|
the_stack_data/92326367.c | #include <stdio.h>
#define TRUE 1
#define FALSE 0
void getCanPlaceNumber();
int setNumber();
int main(void){
/*Sudoku Data*/
int sudoku[][9] = {
{5,0,0,4,0,1,0,6,9},
{0,0,0,0,0,3,5,0,0},
{6,0,0,0,2,0,0,0,0},
{0,0,0,0,0,4,0,0,8},
{0,0,0,0,0,0,7,0,6},
{3,0,9,0,7,5,0,0,0},
{0,0,0,0,0,0,0,4,0},
{2,1,4,0,0,0,9,0,7},
{0,8,0,0,0,0,0,0,0}
};
/*Question*/
puts("Question:");
for(int i = 0; i < 9; i++){
for(int j = 0; j < 9; j++){
printf("%d ",sudoku[i][j]);
}
putchar('\n');
}
/*Solve*/
if(setNumber(sudoku, 0, 0))
puts("Complete!");
else
puts("Failed");
/*Answer*/
puts("Answer:");
for(int i = 0; i < 9; i++){
for(int j = 0; j < 9; j++){
printf("%d ",sudoku[i][j]);
}
putchar('\n');
}
return 0;
}
/*
checking number can put.
*/
void getCanPlaceNumber(int sudoku[][9], int pn[9], int line, int column){
int i,j;
for(i = 0; i < 9; i++) pn[i] = 1;
/*line-number search*/
for(i = 0; i < 9; i++)
if(sudoku[line][i] != 0)
pn[sudoku[line][i]-1] = 0;
/*column-number search*/
for(i = 0; i < 9; i++)
if(sudoku[i][column] != 0)
pn[sudoku[i][column]-1] = 0;
/*3x3 block-number search*/
for(i = line / 3 * 3; i < (line / 3 * 3) + 3; i++)
for(j = column / 3 * 3; j < (column / 3 * 3) + 3; j++)
if(sudoku[i][j] != 0)
pn[sudoku[i][j]-1] = 0;
}
/*
set number
*/
int setNumber(int sudoku[][9], int line, int column){
if(sudoku[line][column] == 0){
int pn[9];
getCanPlaceNumber(sudoku, pn, line, column);
for(int i = 0; i < 9; i++){
if(pn[i]){
sudoku[line][column] = i + 1;
if(line == 8 && column == 8)
return TRUE;
else if(setNumber(sudoku, (column + 1 == 9 ? line + 1 : line), (column + 1 == 9 ? 0 : column + 1))) //check next position
return TRUE;
}
}
//if number can place wasn't exist, re-answer previous position.
sudoku[line][column] = 0;
return FALSE;
}else{
if(line == 8 && column == 8)
return TRUE;
else if(setNumber(sudoku, (column + 1 == 9 ? line + 1 : line), (column + 1 == 9 ? 0 : column + 1)))
return TRUE;
return FALSE;
}
} |
the_stack_data/51700439.c | /*
<TAGS>signal_processing transform</TAGS>
DESCRIPTION:
- reduce data to averaged bins of a fixed size
- non-finite values (INF, NAN) do not contribute to the averages
- allows for different numbers of elements to go into different bins to evenly spread the results (fractional bin-widths)
- allows definition of a "zero" sample which is guaranteed to be the first sample in the bin corresponding with the new "zero"
- guarantees no bins will be under-sampled - edge bins will contain between 1x and just-under-2x bindwidth samples
- exception - a single partial-bin just before zero can be included, as data around zero is usually too important to exclude
USES:
Downsampling data
DEPENDENCY TREE:
No dependencies
ARGUMENTS:
float *data : pointer to input array, which will be overwritten
long *setn : number of elements in data (overwritten - pass as address)
long *setz : element to treat as "zero" (overwritten - pass as address)
double setbinsize : desired bin-width (samples - can be a fraction)
char *message : array to hold error message
RETURN VALUE:
- status (0=success, -1=fail)
- setz and setn are also updated
- can be used to reconstruct timestamps
SAMPLE CALL:
char message[256];
float data[19];
double aa,bb,nbins,sampinterval=1,setbinsize=3.5;
long ii,setn=19, setz=6;
for(ii=0;ii<setn;ii++) { data[ii]=(flaot)ii; printf("%g\n",data[ii]); }
printf("setz=item number %ld\n",setz);
printf("\n");
nbins= xf_bin1b_f(data,&setn,&setz,setbinsize,message);
if(nbins==0) {fprintf(stderr,"*** %s\n",message); exit(1);}
aa=(double)(setz)*(-1)*setbinsize*sampinterval;
bb=setbinsize*sampinterval;
for(ii=0;ii<setn;ii++) { printf("%g\t%f\n",aa,data[ii]); aa+=bb; }
printf("new setz=item number %ld\n",setz);
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int xf_bin1b_f(float *data, long *setn, long *setz, double setbinsize, char *message) {
char *thisfunc="xf_bin1b_f\0";
long ii,jj,n1,n2=0,zero,nsums=0,start;
double aa,bb,cc,prebins,limit,sum=0.0;
n1=*setn;
zero=*setz;
sprintf(message,"%s (incomplete))",thisfunc);
//TEST: fprintf(stderr,"n1=%ld\tzero=%ld\tsetbinsize=%.9f\n",n1,zero,setbinsize);
/* CHECK PARAMETERS */
if(n1<1) {
sprintf(message,"%s [ERROR]: number of samples (%ld) must be >0",thisfunc,n1);
return(-1);
}
if(setbinsize==1.0) {
return(n1);
}
if(setbinsize<=0) {
sprintf(message,"%s [ERROR]: bin size (%g) must be >0",thisfunc,setbinsize);
return(-1);
}
if(zero>=n1) {
sprintf(message,"%s [ERROR]: specified zero-sample (%ld) must be less than data array length (%ld)",thisfunc,zero,n1);
return(-1);
}
//TEST: for(ii=0;ii<n1;ii++) printf("%g\n",data[ii]); exit(1);
/* IF "ZERO" IS SET, CALCULATE THE NUMBER OF BINS BEFORE "ZERO" (PREBINS) */
/* note that if prebins is not an integer, a portion will be combined with another bin */
if(zero>0) prebins=(double)(zero)/setbinsize;
else prebins=0.0;
/* PRE-BIN AND SET START FOR MAIN BINNING SECTION */
/* if prebins is zero or an integer, we can start from sample-zero with no special measures */
if(fmod(prebins,1)==0.0) {
start= 0;
limit= setbinsize - 1.0;
}
/* otherwise, build a fractional bin and proceed from the first full-bin */
else {
// define limits for first bin which will include the partial bin + 1 full bin
limit= (double)(zero-1) - ((long)(prebins-1.0)*setbinsize);
if(limit>=zero) limit= zero-1;
// build the bin
for(ii=0;ii<=limit;ii++) if(isfinite(data[ii])) { sum+= data[ii]; nsums++;}
if(nsums>0) data[n2]= (sum/(double)nsums);
else data[n2]=NAN;
n2++;
// set parameters for main loop
start= (long)limit+1;
limit+= setbinsize;
}
//TEST: fprintf(stderr,"start: %ld zero: %ld setbinsize:%.4f prebins=%g limit:%.16f\n",start,zero,setbinsize,prebins,limit);
/* START BINNING: LEFTOVER DATA AT THE END IS ADDED TO THE PRECEDING BIN */
sum= 0.0;
nsums= 0;
for(ii=start;ii<n1;ii++) {
/* build runing sum and total data-points - good data only */
if(isfinite(data[ii])) { sum+= (double)data[ii]; nsums++; }
// if the current sample-number is >= the limit defining the right edge of the curent window...
if(ii>=limit) {
//TEST: printf("\tii=%ld bin=%ld nsums=%ld limits: %f to %f: next=%f\n",ii,n2,nsums,(limit-setbinsize),(limit),(limit+setbinsize));
if(nsums>0) data[n2]= (float)(sum/(double)nsums);
else data[n2]=NAN;
n2++;
sum=0.0; // reset the run1ing sum
nsums=0; // reset the count within the window
limit+= setbinsize; // readjust limit
}
}
//TEST: fprintf(stderr,"ii: %ld limit:%g nsums:%ld sum:%g\n",ii,limit,nsums,sum);
/* MAKE ONE MORE BIN IF THERE IS LEFTOVER DATA (IE. IF LAST SAMPLE DIDN'T TIP THE LIMIT) */
if( ((ii-1)+setbinsize) != limit ) {
jj= n1-(long)setbinsize;
if(jj<zero) jj=zero; // cannot integrate data from before zero!
sum=0.0; nsums=0;
for(ii=jj;ii<n1;ii++) {
if(isfinite(data[ii])) { sum+= data[ii]; nsums++;}
}
if(nsums>=0) data[n2]= sum/(double)nsums;
else data[n2]=NAN;
n2++;
}
/* REASSIGN SETZ AND N */
(*setz)= prebins;
(*setn)= n2;
sprintf(message,"%s (success))",thisfunc);
return(0);
}
|
the_stack_data/90762593.c | #include <assert.h>
#include <openacc.h>
typedef struct {
int x, y;
} vec2;
typedef struct {
int x, y, z;
int attr[13];
} vec3_attr;
/* Test of gang-private variables declared in local scope with parallel
directive. */
void local_g_1()
{
int i, arr[32];
for (i = 0; i < 32; i++)
arr[i] = 3;
#pragma acc parallel copy(arr) num_gangs(32) num_workers(8) vector_length(32)
{
int x;
#pragma acc loop gang(static:1)
for (i = 0; i < 32; i++)
x = i * 2;
#pragma acc loop gang(static:1)
for (i = 0; i < 32; i++)
{
if (acc_on_device (acc_device_host))
x = i * 2;
arr[i] += x;
}
}
for (i = 0; i < 32; i++)
assert (arr[i] == 3 + i * 2);
}
/* Test of worker-private variables declared in a local scope, broadcasting
to vector-partitioned mode. Back-to-back worker loops. */
void local_w_1()
{
int i, arr[32 * 32 * 32];
for (i = 0; i < 32 * 32 * 32; i++)
arr[i] = i;
#pragma acc parallel copy(arr) num_gangs(32) num_workers(32) vector_length(32)
{
int j;
#pragma acc loop gang
for (i = 0; i < 32; i++)
{
#pragma acc loop worker
for (j = 0; j < 32; j++)
{
int k;
int x = i ^ j * 3;
#pragma acc loop vector
for (k = 0; k < 32; k++)
arr[i * 1024 + j * 32 + k] += x * k;
}
#pragma acc loop worker
for (j = 0; j < 32; j++)
{
int k;
int x = i | j * 5;
#pragma acc loop vector
for (k = 0; k < 32; k++)
arr[i * 1024 + j * 32 + k] += x * k;
}
}
}
for (i = 0; i < 32; i++)
for (int j = 0; j < 32; j++)
for (int k = 0; k < 32; k++)
{
int idx = i * 1024 + j * 32 + k;
assert (arr[idx] == idx + (i ^ j * 3) * k + (i | j * 5) * k);
}
}
/* Test of worker-private variables declared in a local scope, broadcasting
to vector-partitioned mode. Successive vector loops. */
void local_w_2()
{
int i, arr[32 * 32 * 32];
for (i = 0; i < 32 * 32 * 32; i++)
arr[i] = i;
#pragma acc parallel copy(arr) num_gangs(32) num_workers(32) vector_length(32)
{
int j;
#pragma acc loop gang
for (i = 0; i < 32; i++)
{
#pragma acc loop worker
for (j = 0; j < 32; j++)
{
int k;
int x = i ^ j * 3;
#pragma acc loop vector
for (k = 0; k < 32; k++)
arr[i * 1024 + j * 32 + k] += x * k;
x = i | j * 5;
#pragma acc loop vector
for (k = 0; k < 32; k++)
arr[i * 1024 + j * 32 + k] += x * k;
}
}
}
for (i = 0; i < 32; i++)
for (int j = 0; j < 32; j++)
for (int k = 0; k < 32; k++)
{
int idx = i * 1024 + j * 32 + k;
assert (arr[idx] == idx + (i ^ j * 3) * k + (i | j * 5) * k);
}
}
/* Test of worker-private variables declared in a local scope, broadcasting
to vector-partitioned mode. Aggregate worker variable. */
void local_w_3()
{
int i, arr[32 * 32 * 32];
for (i = 0; i < 32 * 32 * 32; i++)
arr[i] = i;
#pragma acc parallel copy(arr) num_gangs(32) num_workers(32) vector_length(32)
{
int j;
#pragma acc loop gang
for (i = 0; i < 32; i++)
{
#pragma acc loop worker
for (j = 0; j < 32; j++)
{
int k;
vec2 pt;
pt.x = i ^ j * 3;
pt.y = i | j * 5;
#pragma acc loop vector
for (k = 0; k < 32; k++)
arr[i * 1024 + j * 32 + k] += pt.x * k;
#pragma acc loop vector
for (k = 0; k < 32; k++)
arr[i * 1024 + j * 32 + k] += pt.y * k;
}
}
}
for (i = 0; i < 32; i++)
for (int j = 0; j < 32; j++)
for (int k = 0; k < 32; k++)
{
int idx = i * 1024 + j * 32 + k;
assert (arr[idx] == idx + (i ^ j * 3) * k + (i | j * 5) * k);
}
}
/* Test of worker-private variables declared in a local scope, broadcasting
to vector-partitioned mode. Addressable worker variable. */
void local_w_4()
{
int i, arr[32 * 32 * 32];
for (i = 0; i < 32 * 32 * 32; i++)
arr[i] = i;
#pragma acc parallel copy(arr) num_gangs(32) num_workers(32) vector_length(32)
{
int j;
#pragma acc loop gang
for (i = 0; i < 32; i++)
{
#pragma acc loop worker
for (j = 0; j < 32; j++)
{
int k;
vec2 pt, *ptp;
ptp = &pt;
pt.x = i ^ j * 3;
#pragma acc loop vector
for (k = 0; k < 32; k++)
arr[i * 1024 + j * 32 + k] += ptp->x * k;
ptp->y = i | j * 5;
#pragma acc loop vector
for (k = 0; k < 32; k++)
arr[i * 1024 + j * 32 + k] += pt.y * k;
}
}
}
for (i = 0; i < 32; i++)
for (int j = 0; j < 32; j++)
for (int k = 0; k < 32; k++)
{
int idx = i * 1024 + j * 32 + k;
assert (arr[idx] == idx + (i ^ j * 3) * k + (i | j * 5) * k);
}
}
/* Test of worker-private variables declared in a local scope, broadcasting
to vector-partitioned mode. Array worker variable. */
void local_w_5()
{
int i, arr[32 * 32 * 32];
for (i = 0; i < 32 * 32 * 32; i++)
arr[i] = i;
#pragma acc parallel copy(arr) num_gangs(32) num_workers(32) vector_length(32)
{
int j;
#pragma acc loop gang
for (i = 0; i < 32; i++)
{
#pragma acc loop worker
for (j = 0; j < 32; j++)
{
int k;
int pt[2];
pt[0] = i ^ j * 3;
#pragma acc loop vector
for (k = 0; k < 32; k++)
arr[i * 1024 + j * 32 + k] += pt[0] * k;
pt[1] = i | j * 5;
#pragma acc loop vector
for (k = 0; k < 32; k++)
arr[i * 1024 + j * 32 + k] += pt[1] * k;
}
}
}
for (i = 0; i < 32; i++)
for (int j = 0; j < 32; j++)
for (int k = 0; k < 32; k++)
{
int idx = i * 1024 + j * 32 + k;
assert (arr[idx] == idx + (i ^ j * 3) * k + (i | j * 5) * k);
}
}
/* Test of gang-private variables declared on loop directive. */
void loop_g_1()
{
int x = 5, i, arr[32];
for (i = 0; i < 32; i++)
arr[i] = i;
#pragma acc parallel copy(arr) num_gangs(32) num_workers(8) vector_length(32)
{
#pragma acc loop gang private(x)
for (i = 0; i < 32; i++)
{
x = i * 2;
arr[i] += x;
}
}
for (i = 0; i < 32; i++)
assert (arr[i] == i * 3);
}
/* Test of gang-private variables declared on loop directive, with broadcasting
to partitioned workers. */
void loop_g_2()
{
int x = 5, i, arr[32 * 32];
for (i = 0; i < 32 * 32; i++)
arr[i] = i;
#pragma acc parallel copy(arr) num_gangs(32) num_workers(8) vector_length(32)
{
#pragma acc loop gang private(x)
for (i = 0; i < 32; i++)
{
x = i * 2;
#pragma acc loop worker
for (int j = 0; j < 32; j++)
arr[i * 32 + j] += x;
}
}
for (i = 0; i < 32 * 32; i++)
assert (arr[i] == i + (i / 32) * 2);
}
/* Test of gang-private variables declared on loop directive, with broadcasting
to partitioned vectors. */
void loop_g_3()
{
int x = 5, i, arr[32 * 32];
for (i = 0; i < 32 * 32; i++)
arr[i] = i;
#pragma acc parallel copy(arr) num_gangs(32) num_workers(8) vector_length(32)
{
#pragma acc loop gang private(x)
for (i = 0; i < 32; i++)
{
x = i * 2;
#pragma acc loop vector
for (int j = 0; j < 32; j++)
arr[i * 32 + j] += x;
}
}
for (i = 0; i < 32 * 32; i++)
assert (arr[i] == i + (i / 32) * 2);
}
/* Test of gang-private addressable variable declared on loop directive, with
broadcasting to partitioned workers. */
void loop_g_4()
{
int x = 5, i, arr[32 * 32];
for (i = 0; i < 32 * 32; i++)
arr[i] = i;
#pragma acc parallel copy(arr) num_gangs(32) num_workers(8) vector_length(32)
{
#pragma acc loop gang private(x)
for (i = 0; i < 32; i++)
{
int *p = &x;
x = i * 2;
#pragma acc loop worker
for (int j = 0; j < 32; j++)
arr[i * 32 + j] += x;
(*p)--;
}
}
for (i = 0; i < 32 * 32; i++)
assert (arr[i] == i + (i / 32) * 2);
}
/* Test of gang-private array variable declared on loop directive, with
broadcasting to partitioned workers. */
void loop_g_5()
{
int x[8], i, arr[32 * 32];
for (i = 0; i < 32 * 32; i++)
arr[i] = i;
#pragma acc parallel copy(arr) num_gangs(32) num_workers(8) vector_length(32)
{
#pragma acc loop gang private(x)
for (i = 0; i < 32; i++)
{
for (int j = 0; j < 8; j++)
x[j] = j * 2;
#pragma acc loop worker
for (int j = 0; j < 32; j++)
arr[i * 32 + j] += x[j % 8];
}
}
for (i = 0; i < 32 * 32; i++)
assert (arr[i] == i + (i % 8) * 2);
}
/* Test of gang-private aggregate variable declared on loop directive, with
broadcasting to partitioned workers. */
void loop_g_6()
{
int i, arr[32 * 32];
vec3_attr pt;
for (i = 0; i < 32 * 32; i++)
arr[i] = i;
#pragma acc parallel copy(arr) num_gangs(32) num_workers(8) vector_length(32)
{
#pragma acc loop gang private(pt)
for (i = 0; i < 32; i++)
{
pt.x = i;
pt.y = i * 2;
pt.z = i * 4;
pt.attr[5] = i * 6;
#pragma acc loop worker
for (int j = 0; j < 32; j++)
arr[i * 32 + j] += pt.x + pt.y + pt.z + pt.attr[5];
}
}
for (i = 0; i < 32 * 32; i++)
assert (arr[i] == i + (i / 32) * 13);
}
/* Test of vector-private variables declared on loop directive. */
void loop_v_1()
{
int x, i, arr[32 * 32 * 32];
for (i = 0; i < 32 * 32 * 32; i++)
arr[i] = i;
#pragma acc parallel copy(arr) num_gangs(32) num_workers(32) vector_length(32)
{
int j;
#pragma acc loop gang
for (i = 0; i < 32; i++)
{
#pragma acc loop worker
for (j = 0; j < 32; j++)
{
int k;
#pragma acc loop vector private(x)
for (k = 0; k < 32; k++)
{
x = i ^ j * 3;
arr[i * 1024 + j * 32 + k] += x * k;
}
#pragma acc loop vector private(x)
for (k = 0; k < 32; k++)
{
x = i | j * 5;
arr[i * 1024 + j * 32 + k] += x * k;
}
}
}
}
for (i = 0; i < 32; i++)
for (int j = 0; j < 32; j++)
for (int k = 0; k < 32; k++)
{
int idx = i * 1024 + j * 32 + k;
assert (arr[idx] == idx + (i ^ j * 3) * k + (i | j * 5) * k);
}
}
/* Test of vector-private variables declared on loop directive. Array type. */
void loop_v_2()
{
int pt[2], i, arr[32 * 32 * 32];
for (i = 0; i < 32 * 32 * 32; i++)
arr[i] = i;
#pragma acc parallel copy(arr) num_gangs(32) num_workers(32) vector_length(32)
{
int j;
#pragma acc loop gang
for (i = 0; i < 32; i++)
{
#pragma acc loop worker
for (j = 0; j < 32; j++)
{
int k;
#pragma acc loop vector private(pt)
for (k = 0; k < 32; k++)
{
pt[0] = i ^ j * 3;
pt[1] = i | j * 5;
arr[i * 1024 + j * 32 + k] += pt[0] * k;
arr[i * 1024 + j * 32 + k] += pt[1] * k;
}
}
}
}
for (i = 0; i < 32; i++)
for (int j = 0; j < 32; j++)
for (int k = 0; k < 32; k++)
{
int idx = i * 1024 + j * 32 + k;
assert (arr[idx] == idx + (i ^ j * 3) * k + (i | j * 5) * k);
}
}
/* Test of worker-private variables declared on a loop directive. */
void loop_w_1()
{
int x = 5, i, arr[32 * 32];
for (i = 0; i < 32 * 32; i++)
arr[i] = i;
#pragma acc parallel copy(arr) num_gangs(32) num_workers(8) vector_length(32)
{
int j;
#pragma acc loop gang
for (i = 0; i < 32; i++)
{
#pragma acc loop worker private(x)
for (j = 0; j < 32; j++)
{
x = i ^ j * 3;
/* Try to ensure 'x' accesses doesn't get optimized into a
temporary. */
__asm__ __volatile__ ("");
arr[i * 32 + j] += x;
}
}
}
for (i = 0; i < 32 * 32; i++)
assert (arr[i] == i + ((i / 32) ^ (i % 32) * 3));
}
/* Test of worker-private variables declared on a loop directive, broadcasting
to vector-partitioned mode. */
void loop_w_2()
{
int x = 5, i, arr[32 * 32 * 32];
for (i = 0; i < 32 * 32 * 32; i++)
arr[i] = i;
#pragma acc parallel copy(arr) num_gangs(32) num_workers(32) vector_length(32)
{
int j;
#pragma acc loop gang
for (i = 0; i < 32; i++)
{
#pragma acc loop worker private(x)
for (j = 0; j < 32; j++)
{
int k;
x = i ^ j * 3;
#pragma acc loop vector
for (k = 0; k < 32; k++)
arr[i * 1024 + j * 32 + k] += x * k;
}
}
}
for (i = 0; i < 32; i++)
for (int j = 0; j < 32; j++)
for (int k = 0; k < 32; k++)
{
int idx = i * 1024 + j * 32 + k;
assert (arr[idx] == idx + (i ^ j * 3) * k);
}
}
/* Test of worker-private variables declared on a loop directive, broadcasting
to vector-partitioned mode. Back-to-back worker loops. */
void loop_w_3()
{
int x = 5, i, arr[32 * 32 * 32];
for (i = 0; i < 32 * 32 * 32; i++)
arr[i] = i;
#pragma acc parallel copy(arr) num_gangs(32) num_workers(32) vector_length(32)
{
int j;
#pragma acc loop gang
for (i = 0; i < 32; i++)
{
#pragma acc loop worker private(x)
for (j = 0; j < 32; j++)
{
int k;
x = i ^ j * 3;
#pragma acc loop vector
for (k = 0; k < 32; k++)
arr[i * 1024 + j * 32 + k] += x * k;
}
#pragma acc loop worker private(x)
for (j = 0; j < 32; j++)
{
int k;
x = i | j * 5;
#pragma acc loop vector
for (k = 0; k < 32; k++)
arr[i * 1024 + j * 32 + k] += x * k;
}
}
}
for (i = 0; i < 32; i++)
for (int j = 0; j < 32; j++)
for (int k = 0; k < 32; k++)
{
int idx = i * 1024 + j * 32 + k;
assert (arr[idx] == idx + (i ^ j * 3) * k + (i | j * 5) * k);
}
}
/* Test of worker-private variables declared on a loop directive, broadcasting
to vector-partitioned mode. Successive vector loops. */
void loop_w_4()
{
int x = 5, i, arr[32 * 32 * 32];
for (i = 0; i < 32 * 32 * 32; i++)
arr[i] = i;
#pragma acc parallel copy(arr) num_gangs(32) num_workers(32) vector_length(32)
{
int j;
#pragma acc loop gang
for (i = 0; i < 32; i++)
{
#pragma acc loop worker private(x)
for (j = 0; j < 32; j++)
{
int k;
x = i ^ j * 3;
#pragma acc loop vector
for (k = 0; k < 32; k++)
arr[i * 1024 + j * 32 + k] += x * k;
x = i | j * 5;
#pragma acc loop vector
for (k = 0; k < 32; k++)
arr[i * 1024 + j * 32 + k] += x * k;
}
}
}
for (i = 0; i < 32; i++)
for (int j = 0; j < 32; j++)
for (int k = 0; k < 32; k++)
{
int idx = i * 1024 + j * 32 + k;
assert (arr[idx] == idx + (i ^ j * 3) * k + (i | j * 5) * k);
}
}
/* Test of worker-private variables declared on a loop directive, broadcasting
to vector-partitioned mode. Addressable worker variable. */
void loop_w_5()
{
int x = 5, i, arr[32 * 32 * 32];
for (i = 0; i < 32 * 32 * 32; i++)
arr[i] = i;
#pragma acc parallel copy(arr) num_gangs(32) num_workers(32) vector_length(32)
{
int j;
#pragma acc loop gang
for (i = 0; i < 32; i++)
{
#pragma acc loop worker private(x)
for (j = 0; j < 32; j++)
{
int k;
int *p = &x;
x = i ^ j * 3;
#pragma acc loop vector
for (k = 0; k < 32; k++)
arr[i * 1024 + j * 32 + k] += x * k;
*p = i | j * 5;
#pragma acc loop vector
for (k = 0; k < 32; k++)
arr[i * 1024 + j * 32 + k] += x * k;
}
}
}
for (i = 0; i < 32; i++)
for (int j = 0; j < 32; j++)
for (int k = 0; k < 32; k++)
{
int idx = i * 1024 + j * 32 + k;
assert (arr[idx] == idx + (i ^ j * 3) * k + (i | j * 5) * k);
}
}
/* Test of worker-private variables declared on a loop directive, broadcasting
to vector-partitioned mode. Aggregate worker variable. */
void loop_w_6()
{
int i, arr[32 * 32 * 32];
vec2 pt;
for (i = 0; i < 32 * 32 * 32; i++)
arr[i] = i;
#pragma acc parallel copy(arr) num_gangs(32) num_workers(32) vector_length(32)
{
int j;
#pragma acc loop gang
for (i = 0; i < 32; i++)
{
#pragma acc loop worker private(pt)
for (j = 0; j < 32; j++)
{
int k;
pt.x = i ^ j * 3;
pt.y = i | j * 5;
#pragma acc loop vector
for (k = 0; k < 32; k++)
arr[i * 1024 + j * 32 + k] += pt.x * k;
#pragma acc loop vector
for (k = 0; k < 32; k++)
arr[i * 1024 + j * 32 + k] += pt.y * k;
}
}
}
for (i = 0; i < 32; i++)
for (int j = 0; j < 32; j++)
for (int k = 0; k < 32; k++)
{
int idx = i * 1024 + j * 32 + k;
assert (arr[idx] == idx + (i ^ j * 3) * k + (i | j * 5) * k);
}
}
/* Test of worker-private variables declared on loop directive, broadcasting
to vector-partitioned mode. Array worker variable. */
void loop_w_7()
{
int i, arr[32 * 32 * 32];
int pt[2];
for (i = 0; i < 32 * 32 * 32; i++)
arr[i] = i;
/* "pt" is treated as "present_or_copy" on the parallel directive because it
is an array variable. */
#pragma acc parallel copy(arr) num_gangs(32) num_workers(32) vector_length(32)
{
int j;
#pragma acc loop gang
for (i = 0; i < 32; i++)
{
/* But here, it is made private per-worker. */
#pragma acc loop worker private(pt)
for (j = 0; j < 32; j++)
{
int k;
pt[0] = i ^ j * 3;
#pragma acc loop vector
for (k = 0; k < 32; k++)
arr[i * 1024 + j * 32 + k] += pt[0] * k;
pt[1] = i | j * 5;
#pragma acc loop vector
for (k = 0; k < 32; k++)
arr[i * 1024 + j * 32 + k] += pt[1] * k;
}
}
}
for (i = 0; i < 32; i++)
for (int j = 0; j < 32; j++)
for (int k = 0; k < 32; k++)
{
int idx = i * 1024 + j * 32 + k;
assert (arr[idx] == idx + (i ^ j * 3) * k + (i | j * 5) * k);
}
}
/* Test of gang-private variables declared on the parallel directive. */
void parallel_g_1()
{
int x = 5, i, arr[32];
for (i = 0; i < 32; i++)
arr[i] = 3;
#pragma acc parallel private(x) copy(arr) num_gangs(32) num_workers(8) vector_length(32)
{
#pragma acc loop gang(static:1)
for (i = 0; i < 32; i++)
x = i * 2;
#pragma acc loop gang(static:1)
for (i = 0; i < 32; i++)
{
if (acc_on_device (acc_device_host))
x = i * 2;
arr[i] += x;
}
}
for (i = 0; i < 32; i++)
assert (arr[i] == 3 + i * 2);
}
/* Test of gang-private array variable declared on the parallel directive. */
void parallel_g_2()
{
int x[32], i, arr[32 * 32];
for (i = 0; i < 32 * 32; i++)
arr[i] = i;
#pragma acc parallel private(x) copy(arr) num_gangs(32) num_workers(2) vector_length(32)
{
#pragma acc loop gang
for (i = 0; i < 32; i++)
{
int j;
for (j = 0; j < 32; j++)
x[j] = j * 2;
#pragma acc loop worker
for (j = 0; j < 32; j++)
arr[i * 32 + j] += x[31 - j];
}
}
for (i = 0; i < 32 * 32; i++)
assert (arr[i] == i + (31 - (i % 32)) * 2);
}
int main ()
{
local_g_1();
local_w_1();
local_w_2();
local_w_3();
local_w_4();
local_w_5();
loop_g_1();
loop_g_2();
loop_g_3();
loop_g_4();
loop_g_5();
loop_g_6();
loop_v_1();
loop_v_2();
loop_w_1();
loop_w_2();
loop_w_3();
loop_w_4();
loop_w_5();
loop_w_6();
loop_w_7();
parallel_g_1();
parallel_g_2();
return 0;
}
|
the_stack_data/232955763.c |
int main(int argc, char *argv[]) {
asm("mov 0x0F, %eax");
}
|
the_stack_data/104826877.c | /*Copying files using cmd line arg(s)*/
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv []) {
FILE *in, *out ;
in = fopen("copy1.txt", "r") ;
out = fopen("result.txt", "w") ;
char c ; //Var Deck
if(argc != 3) { //Check for correct number of cmd line arg(s)
fprintf(stderr, "Incomplete arguments\n") ;
return 1 ;
}
if ( (in = fopen(argv[1], "r")) == NULL ) { //Check if input file exists
fprintf(stderr, "Incorrect input file\n") ;
return 2 ;
}
goto click ;
printf("I'm gonna skip this\n") ;
click: if ( (out = fopen(argv[2], "w")) == NULL ) { //Check if output file exists
fprintf(stderr, "Incorrect output file\n") ;
return 3 ;
}
while( (c = getc(in)) != EOF ) //Copy file
putc(c, out) ;
printf("FILE COPIED\n") ;
fclose(in) ;
fclose(out) ;
return 0 ;
} |
the_stack_data/64199578.c | #include <stdio.h>
int main(){
/**** The sizeof operator ****/
// Tells us how many bytes does a variable take
long longVar, longArr[10];
printf("Size of this long variable is %d bytes \n", sizeof(longVar));
// It even works for a datatype
printf("Size of any char variable is %d byte\n", sizeof(char));
// For arrays it prints the total size of the array in bytes
printf("Total space required by this long array with 10 elements is %d bytes\n", sizeof(longArr));
/**** Referencing a variable ****/
// To get the location of a variable, simply use the & operator
int i = 101;
printf("This integer is stored at internal address %ld\n", &i); // Will print the address where i is stored
/**** Creating and dereferencing pointers ****/
// To access/modify the value at the location given by a pointer,
// use the deferencing operator *
int *ptr = &i;
printf("The integer value stored at a location pointed by ptr is %d\n", *ptr);
*ptr = 20/5; // We can use *ptr just as we would have used i
printf("The new value of i is %d\n", i);
(*ptr)++; // We can use *ptr just as we would have used i
printf("The newer value of i is %d\n", i);
printf("It takes %d bytes to store a pointer\n", sizeof(ptr)); // pointer variables always take 8 bytes
// Pointers in printf and scanf
// Scanf requires the address where input is to be stored
// So far we have been giving this address using &i
// but we can just as well send a pointer which contains the address too
scanf("%d", ptr);
printf("The value input by the user is %d\n", i);
printf("I can print value of i using ptr as well %d\n", *ptr);
// NULL pointers and dangers
int *qtr;
qtr = NULL; // Never try to read or write to the NULL address
printf("The NULL address is actually %ld\n", NULL);
// The following line will cause code to crash - uncomment it and try
// printf("The integer stored at NULL address is %d", *qtr);
qtr = 10101020103123; // Should never hardcode addresses either
// Internal addresses change everytime code is run
// The following line will also cause code to crash - uncomment and try
// printf("The integer stored at my address is %d", *qtr);
// Only use addresses already allocated to program e.g. using &i.
return 0;
} |
the_stack_data/126701813.c | #include <stdio.h>
int main ()
{
int valor;
int multlip;
scanf ("%d", &valor);
for (multlip = 1; multlip <= 9; ++multlip) {
printf ("%d X %d = %d\n", valor, multlip, valor * multlip);
}
return 0;
}
|
the_stack_data/474710.c | #include <openacc.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv) {
acc_device_t type = acc_device_nvidia;
const char *type_name = "acc_device_nvidia";
int naccelerators = acc_get_num_devices(type);
printf("This OpenACC installation has %d accelerators of type %s(%d)\n",
naccelerators, type_name, type);
for (int i = 0; i < naccelerators; i++) {
acc_set_device_num(i, type);
printf("Switched to accelerator %d, device type=%d\n",
acc_get_device_num(type), acc_get_device_type());
}
acc_set_device_type(type);
printf("Using acc_set_device_type put us on accelerator %d, type %d\n",
acc_get_device_num(type), acc_get_device_type());
return 0;
}
|
the_stack_data/192331369.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 */
/*
* This test verifies that Pin properly saves and restores the applicaton's
* XMM registers when emulating a synchronous signal (i.e. fault). The
* application's main thread does a memory copy operation using the XMM
* registers. However, the copy causes a fault by accessing an illegal memory
* location. A handler catches the fault and fixes the address of the illegal
* memory location. It also modifies the XMM registers. If Pin doesn't
* properly save/restore the XMM registers in the handler, the main thread's
* memory copy will be corrupted.
*/
// features.h does not exist on FreeBSD
#ifdef TARGET_LINUX
// features initializes the system's state, including the state of __USE_GNU
#include <features.h>
#endif
// If __USE_GNU is defined, we don't need to do anything.
// If we defined it ourselves, we need to undefine it later.
#ifndef __USE_GNU
#define __USE_GNU
#define APP_UNDEF_USE_GNU
#endif
#if defined(TARGET_MAC)
# include <sys/ucontext.h>
#else
# include <ucontext.h>
#endif
// If we defined __USE_GNU ourselves, we need to undefine it here.
#ifdef APP_UNDEF_USE_GNU
#undef __USE_GNU
#undef APP_UNDEF_USE_GNU
#endif
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <stdlib.h>
#define SIZE 32
#define ALIGN 16
char *SigBuf1;
char *SigBuf2;
unsigned long Glob;
static void XmmCheck();
static void CheckBuf(const char *, size_t);
static char *Allocate(size_t, size_t);
static void Handle(int, siginfo_t *, void *);
extern void CopyWithXmmFault(char *, char *, int);
extern void CopyWithXmm(char *, char *, int);
int main()
{
struct sigaction sigact;
int i;
SigBuf1 = Allocate(SIZE, ALIGN);
SigBuf2 = Allocate(SIZE, ALIGN);
for (i = 0; i < SIZE; i++)
SigBuf1[i] = (char)i;
sigact.sa_sigaction = Handle;
sigact.sa_flags = SA_SIGINFO;
sigemptyset(&sigact.sa_mask);
if (sigaction(SIGSEGV, &sigact, 0) == -1)
{
fprintf(stderr, "Unable to set up handler\n");
return 1;
}
if (sigaction(SIGBUS, &sigact, 0) == -1)
{
fprintf(stderr, "Unable to set up handler\n");
return 1;
}
XmmCheck();
return 0;
}
static void XmmCheck()
{
char *p1;
char *p2;
int i;
p1 = Allocate(SIZE, ALIGN);
p2 = Allocate(SIZE, ALIGN);
memset(p2, 0, SIZE);
for (i = 0; i < SIZE; i++)
p1[i] = "abcdefghijklmnopqrstuvwxyz"[i%26];
/* This routine causes a fault by accessing an illegal memory location */
CopyWithXmmFault(p2, p1, SIZE);
/* Verify that the memory was copied correctly */
CheckBuf(p2, SIZE);
}
static void CheckBuf(const char *p, size_t size)
{
int i;
char c;
for (i = 0; i < size; i++)
{
c = "abcdefghijklmnopqrstuvwxyz"[i%26];
if (p[i] != c)
{
fprintf(stderr, "Element %d wrong: is '%c' should be '%c'\n", i, p[i], c);
exit(1);
}
}
}
static char *Allocate(size_t size, size_t align)
{
char *p;
size_t low;
p = malloc(size + (align-1));
low = (size_t)p % align;
if (low)
return p + (align-low);
else
return p;
}
static void Handle(int sig, siginfo_t *i, void *vctxt)
{
ucontext_t *ctxt = vctxt;
/* Fix the illegal memory address access */
#if defined(TARGET_IA32)
#if defined(TARGET_MAC)
ctxt->uc_mcontext->__ss.__eax = (unsigned long)&Glob;
#else
ctxt->uc_mcontext.gregs[REG_EAX] = (unsigned long)&Glob;
#endif
#elif defined(TARGET_IA32E)
#if defined(TARGET_BSD)
ctxt->uc_mcontext.mc_rax = (unsigned long)&Glob;
#elif defined(TARGET_MAC)
ctxt->uc_mcontext->__ss.__rax = (unsigned long)&Glob;
#else
ctxt->uc_mcontext.gregs[REG_RAX] = (unsigned long)&Glob;
#endif
#endif
/* This changes the values of the XMM registers */
CopyWithXmm(SigBuf2, SigBuf1, SIZE);
}
|
the_stack_data/34512383.c | /*
size_t fread (void * ptr, size_t size, zise_t count, FILE * stream);
Esta funcion lee un bloque de un "stream" de datos
Efectua la lectura de un arreglo de elementos "count",
cada uno de los cuales tiene un tamanio definido por "size"
Luego los guarda en un bloque de memoria especifica por "prt"
El indicador de posicion de la cadena de caracteres avanza
hasta leer la totalidad de bytes...
PARAMETROS:
ptr: Puntero a un bloque de memoria con un tamanio maximo de (size*count) bytes.
size: Tamanio de bytes de cada elemento(de los que voy que leer)
count: Numero de elementos
stream: Puntero a objetos FILE, que se especifica la cadena de entreada
*/
#include <stdio.h>
#include <stdlib.h>
int main(void){
printf("Hola Mundo");
return 0;
}//fin int main
|
the_stack_data/75137471.c | // Warning: This is a generated file, do not edit it!
#include <stdint.h>
#include <stddef.h>
const char anim_intro_20_png[] = {
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d,
0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x01, 0x40, 0x00, 0x00, 0x00, 0xf0,
0x04, 0x03, 0x00, 0x00, 0x00, 0x83, 0x03, 0xa0, 0x58, 0x00, 0x00, 0x00,
0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0b, 0x12, 0x00, 0x00, 0x0b,
0x12, 0x01, 0xd2, 0xdd, 0x7e, 0xfc, 0x00, 0x00, 0x00, 0x1b, 0x74, 0x45,
0x58, 0x74, 0x53, 0x6f, 0x66, 0x74, 0x77, 0x61, 0x72, 0x65, 0x00, 0x43,
0x65, 0x6c, 0x73, 0x79, 0x73, 0x20, 0x53, 0x74, 0x75, 0x64, 0x69, 0x6f,
0x20, 0x54, 0x6f, 0x6f, 0x6c, 0xc1, 0xa7, 0xe1, 0x7c, 0x00, 0x00, 0x00,
0x30, 0x50, 0x4c, 0x54, 0x45, 0x1e, 0xa2, 0xc2, 0x24, 0xc3, 0xea, 0x38,
0x2e, 0x11, 0x4c, 0x4b, 0x32, 0x72, 0xb2, 0x32, 0x85, 0x30, 0xaf, 0x8e,
0xdc, 0x3f, 0xa6, 0x3c, 0xda, 0xba, 0x8d, 0x6e, 0xbe, 0x19, 0x58, 0xbf,
0xf1, 0xf1, 0xd0, 0xaa, 0x2c, 0xf3, 0xf1, 0xe7, 0xf4, 0x1f, 0x71, 0xf7,
0xbf, 0x9c, 0xfd, 0xce, 0x35, 0x0c, 0xf2, 0xb0, 0xf1, 0x00, 0x00, 0x05,
0xb7, 0x49, 0x44, 0x41, 0x54, 0x78, 0xda, 0xed, 0xdd, 0x3b, 0x6f, 0xe3,
0x46, 0x10, 0x07, 0x70, 0xe6, 0x3e, 0x81, 0xe9, 0x3a, 0x85, 0x6f, 0x18,
0x25, 0x8a, 0x72, 0x76, 0x41, 0x76, 0x2c, 0x0f, 0xfe, 0x04, 0x04, 0x08,
0xf5, 0x41, 0xa0, 0x0f, 0x20, 0x40, 0x50, 0xcf, 0x8a, 0x55, 0x8a, 0xeb,
0xdc, 0x7a, 0x3b, 0x95, 0x69, 0x5d, 0x04, 0xd7, 0xa4, 0x72, 0x10, 0x20,
0xbd, 0x1b, 0x57, 0xaa, 0x58, 0xa4, 0x4d, 0xe1, 0xcc, 0x2e, 0x25, 0x99,
0xf2, 0x59, 0x12, 0x1f, 0xeb, 0xdd, 0x3f, 0x2e, 0xc3, 0xc2, 0x8f, 0xee,
0x87, 0x99, 0xdd, 0xe1, 0xf0, 0x81, 0x61, 0xb0, 0x02, 0x3f, 0x02, 0x01,
0x0a, 0x50, 0x80, 0x02, 0x14, 0xa0, 0x00, 0x05, 0x28, 0x40, 0x01, 0x0a,
0x50, 0x80, 0x02, 0x14, 0xa0, 0x00, 0x05, 0x28, 0x40, 0x01, 0x0a, 0x50,
0x80, 0x02, 0x14, 0xa0, 0x00, 0x05, 0x28, 0x40, 0x01, 0x0a, 0x50, 0x80,
0x02, 0x14, 0xa0, 0x00, 0x05, 0x28, 0x40, 0x01, 0x0a, 0x50, 0x80, 0x02,
0x14, 0xa0, 0x00, 0xff, 0xaf, 0xc0, 0x14, 0x1d, 0x98, 0xd4, 0x3f, 0x53,
0x54, 0xa0, 0x22, 0x4d, 0xbb, 0x25, 0x4a, 0x51, 0x81, 0x45, 0xc4, 0x3f,
0x63, 0x3a, 0xa7, 0x08, 0x13, 0x18, 0x97, 0x45, 0xba, 0x4a, 0xe8, 0xdb,
0xcf, 0xe7, 0xd6, 0x63, 0x68, 0x0b, 0x58, 0x46, 0x09, 0xd1, 0xfd, 0xe7,
0xd0, 0x7a, 0x08, 0xad, 0x01, 0xcb, 0xb2, 0x78, 0x1f, 0x86, 0xe1, 0x39,
0x26, 0x50, 0x6d, 0x81, 0x67, 0xef, 0x40, 0x81, 0x63, 0x0d, 0xbc, 0x08,
0xc3, 0x00, 0x13, 0x98, 0xf2, 0x06, 0xd6, 0x47, 0x10, 0x04, 0x98, 0x6b,
0x30, 0x49, 0x34, 0xaf, 0x30, 0x40, 0x4a, 0x00, 0x81, 0x66, 0x8f, 0x94,
0x85, 0x89, 0xa2, 0xed, 0x10, 0xda, 0x01, 0x56, 0x55, 0xb9, 0x7e, 0xa4,
0xd1, 0x5b, 0x08, 0x6d, 0x01, 0xab, 0xea, 0x91, 0x72, 0x3e, 0xe6, 0xb6,
0x85, 0xd6, 0x80, 0x1c, 0xc0, 0xe9, 0x72, 0xb9, 0xcc, 0x99, 0x69, 0x55,
0x68, 0x07, 0x78, 0x55, 0x55, 0x44, 0x23, 0xf6, 0x2d, 0x17, 0xd9, 0x68,
0x9a, 0x67, 0x13, 0x30, 0xa0, 0x22, 0xf6, 0x51, 0xae, 0x81, 0xcb, 0x9c,
0x03, 0x99, 0x67, 0x04, 0x56, 0xa8, 0x93, 0x24, 0x89, 0x37, 0xc0, 0x45,
0xc6, 0xbf, 0x2d, 0xc6, 0xd0, 0x5a, 0xcb, 0xaf, 0xcc, 0x12, 0xac, 0x73,
0xac, 0x97, 0xe2, 0x04, 0x0d, 0x18, 0x9b, 0x25, 0xc8, 0x47, 0x66, 0x42,
0x99, 0x13, 0x1c, 0x30, 0xdf, 0x00, 0x73, 0xb3, 0x5b, 0xac, 0x25, 0xd9,
0x1e, 0x70, 0xba, 0x01, 0xd6, 0x39, 0xb6, 0x16, 0xc2, 0xc0, 0xf2, 0x12,
0x64, 0x60, 0x4e, 0xd3, 0xfa, 0xd7, 0x04, 0x0b, 0xb8, 0x5c, 0xee, 0x72,
0x6c, 0xb2, 0xcd, 0xb5, 0x66, 0x02, 0x04, 0xdc, 0x2d, 0x41, 0x93, 0xe3,
0x1a, 0x9a, 0x81, 0x03, 0x39, 0xc9, 0xc9, 0xf0, 0x2b, 0xe5, 0xc0, 0xf6,
0x12, 0x34, 0x39, 0x9e, 0x6e, 0x42, 0xc8, 0x8d, 0x43, 0x8a, 0x01, 0x8c,
0xf3, 0x26, 0x30, 0xdb, 0xfc, 0x93, 0x7d, 0x78, 0x22, 0x18, 0xe0, 0xb2,
0x71, 0x64, 0xb9, 0xf1, 0x2e, 0xb2, 0xa7, 0xbf, 0xfe, 0x41, 0x04, 0xea,
0xd4, 0xea, 0xff, 0x17, 0xf4, 0xf4, 0xf4, 0x1b, 0x06, 0x50, 0x8d, 0xf6,
0x80, 0xdc, 0xda, 0xe8, 0x9e, 0x26, 0xa7, 0xdf, 0xff, 0x85, 0x01, 0x4e,
0x9b, 0x19, 0xfe, 0x7e, 0xf6, 0x33, 0xf7, 0xad, 0x1c, 0xc7, 0xbb, 0x3b,
0x90, 0x35, 0x18, 0xef, 0x80, 0xba, 0xed, 0xa7, 0xd9, 0x3d, 0x0b, 0x39,
0x8a, 0xf4, 0xd3, 0xdd, 0xe0, 0xee, 0xda, 0x16, 0xb0, 0x2e, 0x7c, 0x26,
0x6c, 0x44, 0xb3, 0x3f, 0x34, 0x70, 0x64, 0xfe, 0x01, 0x01, 0x9a, 0x3d,
0x51, 0xeb, 0x34, 0x70, 0x36, 0xfb, 0x48, 0xfa, 0x1a, 0x8a, 0x2f, 0x96,
0xc7, 0x89, 0x7f, 0x20, 0x5f, 0xb7, 0xeb, 0x2e, 0x5a, 0xef, 0x0d, 0x5d,
0x5f, 0x72, 0xba, 0x9e, 0xfd, 0xf2, 0xb1, 0xfe, 0xab, 0x7c, 0x1c, 0x47,
0xfe, 0x81, 0xb1, 0xbe, 0x60, 0x32, 0xb5, 0x25, 0xaf, 0x7b, 0xd5, 0xef,
0xae, 0xaf, 0x49, 0x57, 0xc2, 0x05, 0x95, 0x15, 0x15, 0xa9, 0x6f, 0xa0,
0xa2, 0x4b, 0xb6, 0x65, 0xbc, 0xe6, 0xea, 0xd3, 0xc9, 0x22, 0xab, 0xcb,
0x8c, 0x06, 0xfe, 0x5a, 0x3d, 0x96, 0x91, 0x77, 0xe0, 0xe5, 0xc3, 0xdf,
0x94, 0x6b, 0xdf, 0xb6, 0x21, 0xcc, 0xb7, 0xc0, 0x8c, 0x81, 0xe3, 0x61,
0x95, 0xc6, 0x02, 0x30, 0xbe, 0xbc, 0x67, 0x21, 0x35, 0xda, 0x19, 0x4e,
0x75, 0x5d, 0x77, 0x18, 0x58, 0x8d, 0x0b, 0xff, 0xc0, 0x3f, 0x19, 0xf8,
0x43, 0xa3, 0x52, 0xeb, 0x18, 0xe6, 0x5b, 0x20, 0x01, 0x00, 0x1f, 0x1e,
0x3e, 0x51, 0xf3, 0x54, 0xa2, 0x4f, 0xc7, 0xcf, 0xc0, 0x61, 0x8b, 0xd0,
0xc6, 0x1a, 0xfc, 0xf1, 0xe6, 0xe6, 0x25, 0x70, 0xd3, 0xb4, 0x6a, 0xe0,
0xa3, 0x7f, 0x20, 0xdd, 0xdc, 0xd0, 0xe8, 0x0b, 0xe0, 0x74, 0x0b, 0x1c,
0x47, 0x00, 0x75, 0x90, 0xf6, 0xfa, 0x41, 0x4d, 0x33, 0xfd, 0x8d, 0x01,
0x92, 0x77, 0xa0, 0xda, 0xd6, 0xbd, 0x66, 0x08, 0x4d, 0xce, 0xb3, 0x2b,
0x06, 0xc6, 0xa9, 0x7f, 0xe0, 0xb8, 0xa0, 0xfc, 0x45, 0x8e, 0x4d, 0x4c,
0xb9, 0x64, 0x57, 0x91, 0xf2, 0x0f, 0x1c, 0x13, 0x03, 0xf3, 0x57, 0x16,
0xa1, 0x85, 0xab, 0x26, 0x2b, 0x6b, 0x70, 0x4d, 0x65, 0xf1, 0x32, 0xc9,
0x35, 0x30, 0x4a, 0x10, 0x1a, 0x56, 0x0d, 0x2c, 0xcb, 0x17, 0xfb, 0xc4,
0x94, 0x6a, 0x0b, 0x97, 0xee, 0x76, 0x80, 0x05, 0xad, 0xcb, 0x62, 0xef,
0xba, 0xa4, 0x5e, 0x84, 0x39, 0x0e, 0xf0, 0x6a, 0x5d, 0xd2, 0x9e, 0xd0,
0x94, 0x6a, 0x14, 0x60, 0xc5, 0xc0, 0x8a, 0x85, 0xcd, 0x9d, 0x6c, 0x76,
0xc9, 0x02, 0x02, 0xa8, 0xa8, 0x2a, 0x89, 0x85, 0xbc, 0x51, 0x9a, 0x21,
0xcc, 0xb8, 0x12, 0x2e, 0x08, 0x02, 0x78, 0x55, 0x03, 0xab, 0xfd, 0x24,
0xeb, 0x5d, 0x02, 0x03, 0x5c, 0xf3, 0xb9, 0xa4, 0xd2, 0xc2, 0x46, 0x92,
0xb9, 0x85, 0x9d, 0x62, 0x00, 0xf5, 0x63, 0x9c, 0x62, 0xa2, 0x81, 0xd5,
0x5e, 0xdb, 0x9a, 0xc1, 0x00, 0x59, 0x56, 0xd0, 0xed, 0x95, 0xe9, 0x0b,
0x9e, 0x85, 0x90, 0xc0, 0xe8, 0xb6, 0x71, 0x42, 0xe1, 0x45, 0x08, 0x01,
0x54, 0xf5, 0xea, 0x5b, 0x11, 0xfb, 0xd2, 0x15, 0x3d, 0xdf, 0xe7, 0x5a,
0xd0, 0x08, 0x03, 0xc8, 0xa1, 0xab, 0xd6, 0xc5, 0x24, 0x26, 0x73, 0xde,
0x7d, 0xde, 0xc9, 0x73, 0x6e, 0xc2, 0x22, 0x00, 0xa0, 0x79, 0x58, 0xbc,
0x2e, 0x22, 0xb5, 0xb9, 0xc7, 0xb1, 0x4b, 0xb2, 0x9d, 0x87, 0xdb, 0xc1,
0xf0, 0x0c, 0xeb, 0x08, 0x56, 0xc5, 0x8e, 0xb2, 0x5d, 0x86, 0x73, 0x0a,
0xcf, 0x21, 0x80, 0xc9, 0xa6, 0x04, 0xee, 0xfa, 0xaa, 0x4d, 0x7b, 0x3d,
0x7f, 0x7f, 0x6f, 0xe3, 0x35, 0x1f, 0x0b, 0xbb, 0x38, 0xa9, 0x6f, 0x69,
0x3d, 0x37, 0x7e, 0x75, 0x35, 0xc4, 0x01, 0xea, 0xa7, 0xc5, 0x49, 0xf3,
0x89, 0x48, 0x7d, 0x0d, 0x35, 0x0f, 0xf9, 0xc0, 0x00, 0x7e, 0x71, 0x18,
0xe1, 0xfc, 0x9b, 0x30, 0x3c, 0x23, 0x4c, 0xa0, 0x11, 0x6a, 0x60, 0x80,
0x0a, 0xd4, 0x1b, 0x25, 0x0b, 0xc2, 0x33, 0x5c, 0xe0, 0x2d, 0x51, 0x76,
0x11, 0x04, 0xef, 0x60, 0x81, 0x5a, 0x48, 0x17, 0x0c, 0x4c, 0x51, 0x81,
0xe6, 0x76, 0x03, 0x11, 0x30, 0x70, 0xa5, 0x22, 0x70, 0x60, 0x7d, 0x53,
0x09, 0x1a, 0xa8, 0x62, 0x70, 0xa0, 0x16, 0x62, 0x03, 0x37, 0x6f, 0xa8,
0x03, 0x03, 0x57, 0x31, 0x3a, 0x50, 0x09, 0x70, 0x70, 0x31, 0x14, 0xe0,
0x57, 0x0e, 0x5c, 0x25, 0x02, 0xfc, 0xda, 0x81, 0x71, 0x2a, 0x40, 0xcf,
0x95, 0xfa, 0xcd, 0x81, 0x91, 0x00, 0x3d, 0x6f, 0xe3, 0x37, 0x07, 0xaa,
0x54, 0x80, 0x7e, 0x73, 0xfc, 0xf6, 0xc0, 0x38, 0x05, 0x07, 0x2a, 0x74,
0xe0, 0xc0, 0x1c, 0x3b, 0x00, 0x2a, 0x78, 0x60, 0x02, 0x0e, 0x5c, 0xc1,
0x03, 0x07, 0x6d, 0x13, 0x27, 0xc0, 0x08, 0x1c, 0x38, 0xa8, 0x14, 0xba,
0x01, 0x46, 0xe0, 0xc0, 0x21, 0xf7, 0x90, 0xdc, 0x8c, 0xd2, 0x18, 0x10,
0x42, 0x37, 0xc0, 0x01, 0x21, 0x74, 0x34, 0x8c, 0xa4, 0x7f, 0x08, 0x1d,
0x01, 0x55, 0xef, 0x8d, 0xec, 0x6a, 0x9c, 0x4b, 0xef, 0x5a, 0xe8, 0x6c,
0xde, 0x4c, 0x9c, 0x80, 0x03, 0xfb, 0x26, 0xd9, 0xdd, 0xc4, 0x1e, 0xd5,
0xef, 0x5d, 0x4c, 0x87, 0xc0, 0x18, 0x1c, 0xd8, 0x73, 0x9f, 0xb8, 0x1c,
0xca, 0xd4, 0x2b, 0x84, 0x2e, 0x81, 0xbd, 0x5a, 0x6b, 0xa7, 0x63, 0xad,
0xfa, 0x74, 0xae, 0x6e, 0x81, 0x3d, 0x5e, 0x5a, 0x76, 0x3b, 0x18, 0xac,
0xc7, 0x3e, 0x71, 0x0c, 0xec, 0xbe, 0x4f, 0x1c, 0x8f, 0x56, 0xeb, 0x5e,
0xad, 0x5d, 0xcf, 0x7e, 0xeb, 0xdc, 0x77, 0xb9, 0x06, 0x76, 0x6e, 0x5d,
0x9d, 0x4f, 0xcf, 0x4b, 0x3a, 0x26, 0xd9, 0xfd, 0x78, 0xbf, 0x18, 0x1d,
0xd8, 0x71, 0x72, 0x80, 0x87, 0x01, 0x89, 0xdd, 0x8a, 0xa1, 0x0f, 0x60,
0xa7, 0x24, 0xfb, 0x18, 0x31, 0xd9, 0x29, 0x84, 0x5e, 0x80, 0x5d, 0x4a,
0x8d, 0x97, 0x21, 0x9d, 0x71, 0x87, 0x52, 0xe3, 0x05, 0xa8, 0x3a, 0x9c,
0x4f, 0xfc, 0x8c, 0x39, 0xed, 0x90, 0x64, 0x4f, 0x73, 0x58, 0xdb, 0x27,
0xd9, 0x13, 0xb0, 0x7d, 0x92, 0x7d, 0x4d, 0xb2, 0x6d, 0x9d, 0x64, 0x6f,
0xa3, 0x76, 0xdb, 0x86, 0xd0, 0x1b, 0x50, 0xb5, 0x9c, 0xa4, 0xe8, 0x6f,
0x58, 0x71, 0xcb, 0x97, 0x1f, 0xfd, 0x01, 0x5b, 0xee, 0x13, 0x8f, 0xe3,
0x9e, 0xdb, 0xed, 0x13, 0x9f, 0xf3, 0xa8, 0x5b, 0x85, 0xd0, 0x27, 0xb0,
0x55, 0x08, 0xbd, 0x4e, 0xf4, 0x6e, 0x73, 0x7d, 0xe2, 0x77, 0xe4, 0x78,
0x8b, 0x24, 0xfb, 0x05, 0xb6, 0x48, 0xb2, 0xe7, 0xa1, 0xed, 0xa7, 0x43,
0xe8, 0x19, 0xa8, 0x4e, 0xde, 0xfc, 0xf7, 0x3d, 0xf6, 0xfe, 0x64, 0x92,
0xbd, 0xcf, 0xe5, 0x3f, 0x95, 0x64, 0xef, 0xc0, 0x53, 0x21, 0xf4, 0x0f,
0x3c, 0x11, 0x42, 0xff, 0x9f, 0x5e, 0x38, 0x11, 0x42, 0x04, 0x60, 0x84,
0x0d, 0x5c, 0x25, 0x47, 0x43, 0x88, 0xf0, 0x75, 0x8d, 0xa3, 0xab, 0x10,
0x01, 0x78, 0x74, 0x15, 0x42, 0x7c, 0x9f, 0xe4, 0x58, 0x08, 0x21, 0x80,
0xc7, 0x56, 0x21, 0xc6, 0x17, 0x5e, 0x8e, 0x84, 0x10, 0x03, 0xa8, 0xd0,
0x81, 0x47, 0xde, 0x68, 0x40, 0x01, 0x46, 0xe0, 0xc0, 0xc3, 0x95, 0x06,
0xe5, 0x33, 0x48, 0x07, 0x43, 0x88, 0x02, 0x3c, 0x18, 0x42, 0x01, 0x0e,
0xcd, 0x31, 0x0c, 0xf0, 0x50, 0x08, 0x71, 0xbe, 0x15, 0x16, 0xa3, 0x03,
0x0f, 0x3c, 0x8c, 0x07, 0x02, 0x12, 0x38, 0xf0, 0xc0, 0xa3, 0x09, 0x20,
0xe0, 0xeb, 0x17, 0x27, 0x48, 0x1f, 0xd4, 0x7b, 0xb5, 0xd2, 0xfc, 0x07,
0x49, 0x06, 0x78, 0x16, 0x5c, 0x27, 0x6f, 0xbc, 0x00, 0x00, 0x00, 0x00,
0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82
};
const size_t anim_intro_20_png_len = sizeof(anim_intro_20_png) / sizeof(char);
|
the_stack_data/15336.c | /* Generated by CIL v. 1.7.0 */
/* print_CIL_Input is false */
struct _IO_FILE;
struct timeval;
extern void signal(int sig , void *func ) ;
extern float strtof(char const *str , char const *endptr ) ;
typedef struct _IO_FILE FILE;
extern int atoi(char const *s ) ;
extern double strtod(char const *str , char const *endptr ) ;
extern int fclose(void *stream ) ;
extern void *fopen(char const *filename , char const *mode ) ;
extern void abort() ;
extern void exit(int status ) ;
extern int raise(int sig ) ;
extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ;
extern int strcmp(char const *a , char const *b ) ;
extern int rand() ;
extern unsigned long strtoul(char const *str , char const *endptr , int base ) ;
void RandomFunc(unsigned short input[1] , unsigned short output[1] ) ;
extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ;
extern int gettimeofday(struct timeval *tv , void *tz , ...) ;
extern int printf(char const *format , ...) ;
int main(int argc , char *argv[] ) ;
void megaInit(void) ;
extern unsigned long strlen(char const *s ) ;
extern long strtol(char const *str , char const *endptr , int base ) ;
extern unsigned long strnlen(char const *s , unsigned long maxlen ) ;
extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ;
struct timeval {
long tv_sec ;
long tv_usec ;
};
extern void *malloc(unsigned long size ) ;
extern int scanf(char const *format , ...) ;
void megaInit(void)
{
{
}
}
void RandomFunc(unsigned short input[1] , unsigned short output[1] )
{
unsigned short state[1] ;
unsigned short local1 ;
{
state[0UL] = input[0UL] + (unsigned short)2885;
local1 = 0UL;
while (local1 < (unsigned short)0) {
if (state[0UL] > local1) {
}
if (state[0UL] == local1) {
}
local1 += 2UL;
}
output[0UL] = state[0UL] + 316086328UL;
}
}
int main(int argc , char *argv[] )
{
unsigned short input[1] ;
unsigned short output[1] ;
int randomFuns_i5 ;
unsigned short randomFuns_value6 ;
int randomFuns_main_i7 ;
{
megaInit();
if (argc != 2) {
printf("Call this program with %i arguments\n", 1);
exit(-1);
} else {
}
randomFuns_i5 = 0;
while (randomFuns_i5 < 1) {
randomFuns_value6 = (unsigned short )strtoul(argv[randomFuns_i5 + 1], 0, 10);
input[randomFuns_i5] = randomFuns_value6;
randomFuns_i5 ++;
}
RandomFunc(input, output);
if (output[0] == 21430) {
printf("You win!\n");
} else {
}
randomFuns_main_i7 = 0;
while (randomFuns_main_i7 < 1) {
printf("%u\n", output[randomFuns_main_i7]);
randomFuns_main_i7 ++;
}
}
}
|
the_stack_data/32470.c | #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;
#ifdef _MSC_VER
static inline _Fcomplex Cf(complex *z) {_Fcomplex zz={z->r , z->i}; return zz;}
static inline _Dcomplex Cd(doublecomplex *z) {_Dcomplex zz={z->r , z->i};return zz;}
static inline _Fcomplex * _pCf(complex *z) {return (_Fcomplex*)z;}
static inline _Dcomplex * _pCd(doublecomplex *z) {return (_Dcomplex*)z;}
#else
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;}
#endif
#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)); }
#ifdef _MSC_VER
#define c_div(c, a, b) {Cf(c)._Val[0] = (Cf(a)._Val[0]/Cf(b)._Val[0]); Cf(c)._Val[1]=(Cf(a)._Val[1]/Cf(b)._Val[1]);}
#define z_div(c, a, b) {Cd(c)._Val[0] = (Cd(a)._Val[0]/Cd(b)._Val[0]); Cd(c)._Val[1]=(Cd(a)._Val[1]/df(b)._Val[1]);}
#else
#define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);}
#define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);}
#endif
#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) = conjf(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) (cimagf(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;
}
#ifdef _MSC_VER
static _Fcomplex cpow_ui(complex x, integer n) {
complex pow={1.0,0.0}; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x.r = 1/x.r, x.i=1/x.i;
for(u = n; ; ) {
if(u & 01) pow.r *= x.r, pow.i *= x.i;
if(u >>= 1) x.r *= x.r, x.i *= x.i;
else break;
}
}
_Fcomplex p={pow.r, pow.i};
return p;
}
#else
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;
}
#endif
#ifdef _MSC_VER
static _Dcomplex zpow_ui(_Dcomplex x, integer n) {
_Dcomplex pow={1.0,0.0}; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x._Val[0] = 1/x._Val[0], x._Val[1] =1/x._Val[1];
for(u = n; ; ) {
if(u & 01) pow._Val[0] *= x._Val[0], pow._Val[1] *= x._Val[1];
if(u >>= 1) x._Val[0] *= x._Val[0], x._Val[1] *= x._Val[1];
else break;
}
}
_Dcomplex p = {pow._Val[0], pow._Val[1]};
return p;
}
#else
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;
}
#endif
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;
#ifdef _MSC_VER
_Fcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conjf(Cf(&x[i]))._Val[0] * Cf(&y[i])._Val[0];
zdotc._Val[1] += conjf(Cf(&x[i]))._Val[1] * Cf(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conjf(Cf(&x[i*incx]))._Val[0] * Cf(&y[i*incy])._Val[0];
zdotc._Val[1] += conjf(Cf(&x[i*incx]))._Val[1] * Cf(&y[i*incy])._Val[1];
}
}
pCf(z) = zdotc;
}
#else
_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;
}
#endif
static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Dcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conj(Cd(&x[i]))._Val[0] * Cd(&y[i])._Val[0];
zdotc._Val[1] += conj(Cd(&x[i]))._Val[1] * Cd(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conj(Cd(&x[i*incx]))._Val[0] * Cd(&y[i*incy])._Val[0];
zdotc._Val[1] += conj(Cd(&x[i*incx]))._Val[1] * Cd(&y[i*incy])._Val[1];
}
}
pCd(z) = zdotc;
}
#else
_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;
}
#endif
static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Fcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cf(&x[i])._Val[0] * Cf(&y[i])._Val[0];
zdotc._Val[1] += Cf(&x[i])._Val[1] * Cf(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cf(&x[i*incx])._Val[0] * Cf(&y[i*incy])._Val[0];
zdotc._Val[1] += Cf(&x[i*incx])._Val[1] * Cf(&y[i*incy])._Val[1];
}
}
pCf(z) = zdotc;
}
#else
_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;
}
#endif
static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Dcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cd(&x[i])._Val[0] * Cd(&y[i])._Val[0];
zdotc._Val[1] += Cd(&x[i])._Val[1] * Cd(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cd(&x[i*incx])._Val[0] * Cd(&y[i*incy])._Val[0];
zdotc._Val[1] += Cd(&x[i*incx])._Val[1] * Cd(&y[i*incy])._Val[1];
}
}
pCd(z) = zdotc;
}
#else
_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)
*/
/* Table of constant values */
static integer c__1 = 1;
/* > \brief \b DGEQR2P computes the QR factorization of a general rectangular matrix with non-negative diagona
l elements using an unblocked algorithm. */
/* =========== DOCUMENTATION =========== */
/* Online html documentation available at */
/* http://www.netlib.org/lapack/explore-html/ */
/* > \htmlonly */
/* > Download DGEQR2P + dependencies */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/dgeqr2p
.f"> */
/* > [TGZ]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/dgeqr2p
.f"> */
/* > [ZIP]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/dgeqr2p
.f"> */
/* > [TXT]</a> */
/* > \endhtmlonly */
/* Definition: */
/* =========== */
/* SUBROUTINE DGEQR2P( M, N, A, LDA, TAU, WORK, INFO ) */
/* INTEGER INFO, LDA, M, N */
/* DOUBLE PRECISION A( LDA, * ), TAU( * ), WORK( * ) */
/* > \par Purpose: */
/* ============= */
/* > */
/* > \verbatim */
/* > */
/* > DGEQR2P computes a QR factorization of a real m-by-n matrix A: */
/* > */
/* > A = Q * ( R ), */
/* > ( 0 ) */
/* > */
/* > where: */
/* > */
/* > Q is a m-by-m orthogonal matrix; */
/* > R is an upper-triangular n-by-n matrix with nonnegative diagonal */
/* > entries; */
/* > 0 is a (m-n)-by-n zero matrix, if m > n. */
/* > */
/* > \endverbatim */
/* Arguments: */
/* ========== */
/* > \param[in] M */
/* > \verbatim */
/* > M is INTEGER */
/* > The number of rows of the matrix A. M >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in] N */
/* > \verbatim */
/* > N is INTEGER */
/* > The number of columns of the matrix A. N >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in,out] A */
/* > \verbatim */
/* > A is DOUBLE PRECISION array, dimension (LDA,N) */
/* > On entry, the m by n matrix A. */
/* > On exit, the elements on and above the diagonal of the array */
/* > contain the f2cmin(m,n) by n upper trapezoidal matrix R (R is */
/* > upper triangular if m >= n). The diagonal entries of R are */
/* > nonnegative; the elements below the diagonal, */
/* > with the array TAU, represent the orthogonal matrix Q as a */
/* > product of elementary reflectors (see Further Details). */
/* > \endverbatim */
/* > */
/* > \param[in] LDA */
/* > \verbatim */
/* > LDA is INTEGER */
/* > The leading dimension of the array A. LDA >= f2cmax(1,M). */
/* > \endverbatim */
/* > */
/* > \param[out] TAU */
/* > \verbatim */
/* > TAU is DOUBLE PRECISION array, dimension (f2cmin(M,N)) */
/* > The scalar factors of the elementary reflectors (see Further */
/* > Details). */
/* > \endverbatim */
/* > */
/* > \param[out] WORK */
/* > \verbatim */
/* > WORK is DOUBLE PRECISION array, dimension (N) */
/* > \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 2019 */
/* > \ingroup doubleGEcomputational */
/* > \par Further Details: */
/* ===================== */
/* > */
/* > \verbatim */
/* > */
/* > The matrix Q is represented as a product of elementary reflectors */
/* > */
/* > Q = H(1) H(2) . . . H(k), where k = f2cmin(m,n). */
/* > */
/* > Each H(i) has the form */
/* > */
/* > H(i) = I - tau * v * v**T */
/* > */
/* > where tau is a real scalar, and v is a real vector with */
/* > v(1:i-1) = 0 and v(i) = 1; v(i+1:m) is stored on exit in A(i+1:m,i), */
/* > and tau in TAU(i). */
/* > */
/* > See Lapack Working Note 203 for details */
/* > \endverbatim */
/* > */
/* ===================================================================== */
/* Subroutine */ int dgeqr2p_(integer *m, integer *n, doublereal *a, integer *
lda, doublereal *tau, doublereal *work, integer *info)
{
/* System generated locals */
integer a_dim1, a_offset, i__1, i__2, i__3;
/* Local variables */
integer i__, k;
extern /* Subroutine */ int dlarf_(char *, integer *, integer *,
doublereal *, integer *, doublereal *, doublereal *, integer *,
doublereal *), xerbla_(char *, integer *, ftnlen);
doublereal aii;
extern /* Subroutine */ int dlarfgp_(integer *, doublereal *, doublereal *
, integer *, doublereal *);
/* -- LAPACK computational routine (version 3.9.0) -- */
/* -- LAPACK is a software package provided by Univ. of Tennessee, -- */
/* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */
/* November 2019 */
/* ===================================================================== */
/* Test the input arguments */
/* Parameter adjustments */
a_dim1 = *lda;
a_offset = 1 + a_dim1 * 1;
a -= a_offset;
--tau;
--work;
/* Function Body */
*info = 0;
if (*m < 0) {
*info = -1;
} else if (*n < 0) {
*info = -2;
} else if (*lda < f2cmax(1,*m)) {
*info = -4;
}
if (*info != 0) {
i__1 = -(*info);
xerbla_("DGEQR2P", &i__1, (ftnlen)7);
return 0;
}
k = f2cmin(*m,*n);
i__1 = k;
for (i__ = 1; i__ <= i__1; ++i__) {
/* Generate elementary reflector H(i) to annihilate A(i+1:m,i) */
i__2 = *m - i__ + 1;
/* Computing MIN */
i__3 = i__ + 1;
dlarfgp_(&i__2, &a[i__ + i__ * a_dim1], &a[f2cmin(i__3,*m) + i__ *
a_dim1], &c__1, &tau[i__]);
if (i__ < *n) {
/* Apply H(i) to A(i:m,i+1:n) from the left */
aii = a[i__ + i__ * a_dim1];
a[i__ + i__ * a_dim1] = 1.;
i__2 = *m - i__ + 1;
i__3 = *n - i__;
dlarf_("Left", &i__2, &i__3, &a[i__ + i__ * a_dim1], &c__1, &tau[
i__], &a[i__ + (i__ + 1) * a_dim1], lda, &work[1]);
a[i__ + i__ * a_dim1] = aii;
}
/* L10: */
}
return 0;
/* End of DGEQR2P */
} /* dgeqr2p_ */
|
the_stack_data/475498.c | //sumcalc3 by zawa-ch.
//1から指定した数値まで足しつづけるプログラム(rev.3)
#include<stdio.h>
int main(void) {
int i;
int va, sum=0;
puts("整数を入力してください。\n"
"1からその数値まで足し続けた数値を返します。");
do {
printf("整数 : ");
scanf("%d", &va);
if (va <= 0)
puts("\a入力された値が不適切です。\n1以上の整数を入力してください。");
} while (va <= 0); //負の値を入力したときの処理を追加(0以下の値を入力するともう一度入力を求められる)
for (i = 1; i <= va; i++) {
sum += i;
printf("計算中...(i=%d,sum=%d) \r", i, sum); //計算中の状態を表示((処理は多少重くなります
if (sum < 0) //計算のオーバーフロー処理
break;
}
if (i >= va && sum > 0) {
printf("計算完了!(i=%d,sum=%d) \n", i, sum);
printf("結果は%dです。\nまた、n(1+n)/2で計算した結果は%dです。\n", sum, va * (1 + va) / 2);
} else {
printf("計算中...(i=%d,sum=%d) \n", i, sum);
printf("計算がオーバーフローしました。\n");
}
return 0;
}
|
the_stack_data/12638902.c | //Online Exam2 versionE
//including header files
#include <stdio.h>
//main function
int main()
{
// declare and initializing variables
int mark = 0, min = 0, max = 0;
// input first mark
printf("Enter Marks, -99 to terminate : ");
scanf("%d", &mark);
if(mark != -99)
min =mark;
while(mark != -99)
{
while (mark <= 100 && mark >= 0)
{
if(mark > max)
max = mark;
if(mark < min)
min = mark;
printf("Enter Marks, -99 to terminate : ");
scanf("%d", &mark);
}
if(mark != -99)
{
//print an error message
printf("Invalid mark, marks should be between 0 and 100\n");
printf("Enter Marks, -99 to terminate : ");
scanf("%d", &mark);
}
}
//print minimum and maximum marks
printf("Your minimum mark is : %d\n", min);
printf("Your maximum mark is : %d\n", max);
return 0;
}
//end main function
|
the_stack_data/125141131.c | #include<stdio.h>
#include<math.h>
#include<string.h>
int gcd (int a,int b){
if(a%b==0)
return b;
return gcd(b,a%b);
}
int main ()
{
int a, b, c, prop=0;
scanf("%d %d %d",&a,&b,&c);
int x=gcd(a,b);
if(c%x==0) printf("Yes");
else printf("No");
return 0;
}
|
the_stack_data/58361.c | /*
Interviewer: Gary.
*/
/*
Scratch
AMI - SCI. // UEFI shell vs. Linux.
*/ |
the_stack_data/151558.c | #include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
void tripleRecursion(int n, int m, int k) {
for(int i = 0; i < n; ++i) {
for(int j = 0; j < n; ++j) {
int x;
if (i + j == 0) x = m;
else if (i == j) x = m + (i * k);
else if (i < j) x = m + (i * k) - (j - i);
else x = m + (j * k) - (i - j);
printf("%d ", x);
}
puts("");
}
}
int main() {
int n;
int m;
int k;
scanf("%i %i %i", &n, &m, &k);
tripleRecursion(n, m, k);
return 0;
} |
the_stack_data/215768596.c | #include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
#define STATS 200
#define BILLION 1000000000L
long int cost(unsigned int nbytes) {
char buf[1];
// defined in /usr/include/bits/types/struct_timespec.h
struct timespec start, end;
if (clock_gettime(CLOCK_REALTIME, &start) == -1) {
fprintf(stderr, "error in clock_getres\n");
exit(1);
}
for (int i = 0; i < nbytes; i++) {
read(STDIN_FILENO, buf, 0);
}
if (clock_gettime(CLOCK_REALTIME, &end) == -1) {
fprintf(stderr, "error in clock_getres\n");
exit(1);
}
// convert seconds to nanoseconds and add to nanoseconds
long int res = (BILLION * (end.tv_sec - start.tv_sec) +
(end.tv_nsec - start.tv_nsec)) /
nbytes;
return res;
}
void statistics() {
int nbytes[] = {100, 1000, 10000, 100000};
long int average_nsec[sizeof(nbytes) / sizeof(int)] = {0};
int length = sizeof(nbytes) / sizeof(int);
long int average = 0;
for (int i = 0; i < length; i++) {
for (int j = 0; j < STATS; j++) {
average_nsec[i] += cost(nbytes[i]);
}
average_nsec[i] /= STATS;
printf("average for read %d times : %ld ns\n", nbytes[i],
(average_nsec[i]));
}
for (int i = 0; i < length; i++) {
average += average_nsec[i];
}
printf("average total : %ld ns\n", average / length);
return;
}
int main(int argc, char **argv) {
statistics();
printf("without STATS the result would be a bit higher (around 400 ns) ");
printf("on my machine, while with STATS is around 350 ns.\n");
return 0;
}
/*
* asm inline to compute syscall cost, doesn't work.
void syscall_time()
{
int a = 10;
int b;
__asm__ (
"rdtsc;"
"xor %%eax, %%eax;"
"movl %1, %%eax;"
"movl %%eax, %0;"
:"=r" (b)
:"r" (a)
:"%eax", "%ecx"
);
printf("%d\n", b);
}
*/
|
the_stack_data/30923.c | /*
* ARM64 signal handling routines
*
* Copyright 2010-2013 André Hentschel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#ifdef __aarch64__
#include "config.h"
#include "wine/port.h"
#include <assert.h>
#include <signal.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#ifdef HAVE_SYS_PARAM_H
# include <sys/param.h>
#endif
#ifdef HAVE_SYSCALL_H
# include <syscall.h>
#else
# ifdef HAVE_SYS_SYSCALL_H
# include <sys/syscall.h>
# endif
#endif
#ifdef HAVE_SYS_SIGNAL_H
# include <sys/signal.h>
#endif
#ifdef HAVE_SYS_UCONTEXT_H
# include <sys/ucontext.h>
#endif
#define NONAMELESSUNION
#define NONAMELESSSTRUCT
#include "ntstatus.h"
#define WIN32_NO_STATUS
#include "windef.h"
#include "winternl.h"
#include "wine/library.h"
#include "wine/exception.h"
#include "ntdll_misc.h"
#include "wine/debug.h"
#include "winnt.h"
WINE_DEFAULT_DEBUG_CHANNEL(seh);
WINE_DECLARE_DEBUG_CHANNEL(relay);
static pthread_key_t teb_key;
/***********************************************************************
* signal context platform-specific definitions
*/
#ifdef linux
/* All Registers access - only for local access */
# define REG_sig(reg_name, context) ((context)->uc_mcontext.reg_name)
# define REGn_sig(reg_num, context) ((context)->uc_mcontext.regs[reg_num])
/* Special Registers access */
# define SP_sig(context) REG_sig(sp, context) /* Stack pointer */
# define PC_sig(context) REG_sig(pc, context) /* Program counter */
# define PSTATE_sig(context) REG_sig(pstate, context) /* Current State Register */
# define FP_sig(context) REGn_sig(29, context) /* Frame pointer */
# define LR_sig(context) REGn_sig(30, context) /* Link Register */
/* Exceptions */
# define FAULT_sig(context) REG_sig(fault_address, context)
#endif /* linux */
static const size_t teb_size = 0x2000; /* we reserve two pages for the TEB */
static size_t signal_stack_size;
typedef void (WINAPI *raise_func)( EXCEPTION_RECORD *rec, CONTEXT *context );
typedef int (*wine_signal_handler)(unsigned int sig);
static wine_signal_handler handlers[256];
/***********************************************************************
* dispatch_signal
*/
static inline int dispatch_signal(unsigned int sig)
{
if (handlers[sig] == NULL) return 0;
return handlers[sig](sig);
}
/*******************************************************************
* is_valid_frame
*/
static inline BOOL is_valid_frame( void *frame )
{
if ((ULONG_PTR)frame & 3) return FALSE;
return (frame >= NtCurrentTeb()->Tib.StackLimit &&
(void **)frame < (void **)NtCurrentTeb()->Tib.StackBase - 1);
}
/***********************************************************************
* save_context
*
* Set the register values from a sigcontext.
*/
static void save_context( CONTEXT *context, const ucontext_t *sigcontext )
{
DWORD i;
context->ContextFlags = CONTEXT_FULL;
context->Fp = FP_sig(sigcontext); /* Frame pointer */
context->Lr = LR_sig(sigcontext); /* Link register */
context->Sp = SP_sig(sigcontext); /* Stack pointer */
context->Pc = PC_sig(sigcontext); /* Program Counter */
context->Cpsr = PSTATE_sig(sigcontext); /* Current State Register */
for (i = 0; i <= 28; i++) context->u.X[i] = REGn_sig( i, sigcontext );
}
/***********************************************************************
* restore_context
*
* Build a sigcontext from the register values.
*/
static void restore_context( const CONTEXT *context, ucontext_t *sigcontext )
{
DWORD i;
FP_sig(sigcontext) = context->Fp; /* Frame pointer */
LR_sig(sigcontext) = context->Lr; /* Link register */
SP_sig(sigcontext) = context->Sp; /* Stack pointer */
PC_sig(sigcontext) = context->Pc; /* Program Counter */
PSTATE_sig(sigcontext) = context->Cpsr; /* Current State Register */
for (i = 0; i <= 28; i++) REGn_sig( i, sigcontext ) = context->u.X[i];
}
/***********************************************************************
* save_fpu
*
* Set the FPU context from a sigcontext.
*/
static inline void save_fpu( CONTEXT *context, const ucontext_t *sigcontext )
{
FIXME( "Not implemented on ARM64\n" );
}
/***********************************************************************
* restore_fpu
*
* Restore the FPU context to a sigcontext.
*/
static inline void restore_fpu( CONTEXT *context, const ucontext_t *sigcontext )
{
FIXME( "Not implemented on ARM64\n" );
}
/***********************************************************************
* RtlCaptureContext (NTDLL.@)
*/
/* FIXME: Use the Stack instead of the actual register values? */
__ASM_STDCALL_FUNC( RtlCaptureContext, 8,
"stp x0, x1, [sp, #-32]!\n\t"
"mov w1, #0x400000\n\t" /* CONTEXT_ARM64 */
"add w1, w1, #0x3\n\t" /* CONTEXT_FULL */
"str w1, [x0]\n\t" /* context->ContextFlags */ /* 32-bit, look at cpsr */
"mrs x1, NZCV\n\t"
"str w1, [x0, #0x4]\n\t" /* context->Cpsr */
"ldp x0, x1, [sp], #32\n\t"
"str x0, [x0, #0x8]\n\t" /* context->X0 */
"str x1, [x0, #0x10]\n\t" /* context->X1 */
"str x2, [x0, #0x18]\n\t" /* context->X2 */
"str x3, [x0, #0x20]\n\t" /* context->X3 */
"str x4, [x0, #0x28]\n\t" /* context->X4 */
"str x5, [x0, #0x30]\n\t" /* context->X5 */
"str x6, [x0, #0x38]\n\t" /* context->X6 */
"str x7, [x0, #0x40]\n\t" /* context->X7 */
"str x8, [x0, #0x48]\n\t" /* context->X8 */
"str x9, [x0, #0x50]\n\t" /* context->X9 */
"str x10, [x0, #0x58]\n\t" /* context->X10 */
"str x11, [x0, #0x60]\n\t" /* context->X11 */
"str x12, [x0, #0x68]\n\t" /* context->X12 */
"str x13, [x0, #0x70]\n\t" /* context->X13 */
"str x14, [x0, #0x78]\n\t" /* context->X14 */
"str x15, [x0, #0x80]\n\t" /* context->X15 */
"str x16, [x0, #0x88]\n\t" /* context->X16 */
"str x17, [x0, #0x90]\n\t" /* context->X17 */
"str x18, [x0, #0x98]\n\t" /* context->X18 */
"str x19, [x0, #0xa0]\n\t" /* context->X19 */
"str x20, [x0, #0xa8]\n\t" /* context->X20 */
"str x21, [x0, #0xb0]\n\t" /* context->X21 */
"str x22, [x0, #0xb8]\n\t" /* context->X22 */
"str x23, [x0, #0xc0]\n\t" /* context->X23 */
"str x24, [x0, #0xc8]\n\t" /* context->X24 */
"str x25, [x0, #0xd0]\n\t" /* context->X25 */
"str x26, [x0, #0xd8]\n\t" /* context->X26 */
"str x27, [x0, #0xe0]\n\t" /* context->X27 */
"str x28, [x0, #0xe8]\n\t" /* context->X28 */
"str x29, [x0, #0xf0]\n\t" /* context->Fp */
"str x30, [x0, #0xf8]\n\t" /* context->Lr */
"mov x1, sp\n\t"
"str x1, [x0, #0x100]\n\t" /* context->Sp */
"adr x1, 1f\n\t"
"1: str x1, [x0, #0x108]\n\t" /* context->Pc */
"ret"
)
/***********************************************************************
* set_cpu_context
*
* Set the new CPU context.
*/
static void set_cpu_context( const CONTEXT *context )
{
FIXME( "Not implemented on ARM64\n" );
}
/***********************************************************************
* copy_context
*
* Copy a register context according to the flags.
*/
static void copy_context( CONTEXT *to, const CONTEXT *from, DWORD flags )
{
flags &= ~CONTEXT_ARM64; /* get rid of CPU id */
if (flags & CONTEXT_CONTROL)
{
to->Fp = from->Fp;
to->Lr = from->Lr;
to->Sp = from->Sp;
to->Pc = from->Pc;
to->Cpsr = from->Cpsr;
}
if (flags & CONTEXT_INTEGER)
{
memcpy( to->u.X, from->u.X, sizeof(to->u.X) );
}
if (flags & CONTEXT_FLOATING_POINT)
{
memcpy( to->V, from->V, sizeof(to->V) );
to->Fpcr = from->Fpcr;
to->Fpsr = from->Fpsr;
}
if (flags & CONTEXT_DEBUG_REGISTERS)
{
memcpy( to->Bcr, from->Bcr, sizeof(to->Bcr) );
memcpy( to->Bvr, from->Bvr, sizeof(to->Bvr) );
memcpy( to->Wcr, from->Wcr, sizeof(to->Wcr) );
memcpy( to->Wvr, from->Wvr, sizeof(to->Wvr) );
}
}
/***********************************************************************
* context_to_server
*
* Convert a register context to the server format.
*/
NTSTATUS context_to_server( context_t *to, const CONTEXT *from )
{
DWORD i, flags = from->ContextFlags & ~CONTEXT_ARM64; /* get rid of CPU id */
memset( to, 0, sizeof(*to) );
to->cpu = CPU_ARM64;
if (flags & CONTEXT_CONTROL)
{
to->flags |= SERVER_CTX_CONTROL;
to->integer.arm64_regs.x[29] = from->Fp;
to->integer.arm64_regs.x[30] = from->Lr;
to->ctl.arm64_regs.sp = from->Sp;
to->ctl.arm64_regs.pc = from->Pc;
to->ctl.arm64_regs.pstate = from->Cpsr;
}
if (flags & CONTEXT_INTEGER)
{
to->flags |= SERVER_CTX_INTEGER;
for (i = 0; i <= 28; i++) to->integer.arm64_regs.x[i] = from->u.X[i];
}
if (flags & CONTEXT_FLOATING_POINT)
{
to->flags |= SERVER_CTX_FLOATING_POINT;
for (i = 0; i < 64; i++) to->fp.arm64_regs.d[i] = from->V[i / 2].D[i % 2];
to->fp.arm64_regs.fpcr = from->Fpcr;
to->fp.arm64_regs.fpsr = from->Fpsr;
}
if (flags & CONTEXT_DEBUG_REGISTERS)
{
to->flags |= SERVER_CTX_DEBUG_REGISTERS;
for (i = 0; i < ARM64_MAX_BREAKPOINTS; i++) to->debug.arm64_regs.bcr[i] = from->Bcr[i];
for (i = 0; i < ARM64_MAX_BREAKPOINTS; i++) to->debug.arm64_regs.bvr[i] = from->Bvr[i];
for (i = 0; i < ARM64_MAX_WATCHPOINTS; i++) to->debug.arm64_regs.wcr[i] = from->Wcr[i];
for (i = 0; i < ARM64_MAX_WATCHPOINTS; i++) to->debug.arm64_regs.wvr[i] = from->Wvr[i];
}
return STATUS_SUCCESS;
}
/***********************************************************************
* context_from_server
*
* Convert a register context from the server format.
*/
NTSTATUS context_from_server( CONTEXT *to, const context_t *from )
{
DWORD i;
if (from->cpu != CPU_ARM64) return STATUS_INVALID_PARAMETER;
to->ContextFlags = CONTEXT_ARM64;
if (from->flags & SERVER_CTX_CONTROL)
{
to->ContextFlags |= CONTEXT_CONTROL;
to->Fp = from->integer.arm64_regs.x[29];
to->Lr = from->integer.arm64_regs.x[30];
to->Sp = from->ctl.arm64_regs.sp;
to->Pc = from->ctl.arm64_regs.pc;
to->Cpsr = from->ctl.arm64_regs.pstate;
}
if (from->flags & SERVER_CTX_INTEGER)
{
to->ContextFlags |= CONTEXT_INTEGER;
for (i = 0; i <= 28; i++) to->u.X[i] = from->integer.arm64_regs.x[i];
}
if (from->flags & SERVER_CTX_FLOATING_POINT)
{
to->ContextFlags |= CONTEXT_FLOATING_POINT;
for (i = 0; i < 64; i++) to->V[i / 2].D[i % 2] = from->fp.arm64_regs.d[i];
to->Fpcr = from->fp.arm64_regs.fpcr;
to->Fpsr = from->fp.arm64_regs.fpsr;
}
if (from->flags & SERVER_CTX_DEBUG_REGISTERS)
{
to->ContextFlags |= CONTEXT_DEBUG_REGISTERS;
for (i = 0; i < ARM64_MAX_BREAKPOINTS; i++) to->Bcr[i] = from->debug.arm64_regs.bcr[i];
for (i = 0; i < ARM64_MAX_BREAKPOINTS; i++) to->Bvr[i] = from->debug.arm64_regs.bvr[i];
for (i = 0; i < ARM64_MAX_WATCHPOINTS; i++) to->Wcr[i] = from->debug.arm64_regs.wcr[i];
for (i = 0; i < ARM64_MAX_WATCHPOINTS; i++) to->Wvr[i] = from->debug.arm64_regs.wvr[i];
}
return STATUS_SUCCESS;
}
/***********************************************************************
* NtSetContextThread (NTDLL.@)
* ZwSetContextThread (NTDLL.@)
*/
NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
{
NTSTATUS ret;
BOOL self;
ret = set_thread_context( handle, context, &self );
if (self && ret == STATUS_SUCCESS) set_cpu_context( context );
return ret;
}
/***********************************************************************
* NtGetContextThread (NTDLL.@)
* ZwGetContextThread (NTDLL.@)
*/
NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
{
NTSTATUS ret;
DWORD needed_flags = context->ContextFlags;
BOOL self = (handle == GetCurrentThread());
if (!self)
{
if ((ret = get_thread_context( handle, context, &self ))) return ret;
needed_flags &= ~context->ContextFlags;
}
if (self && needed_flags)
{
CONTEXT ctx;
RtlCaptureContext( &ctx );
copy_context( context, &ctx, ctx.ContextFlags & needed_flags );
context->ContextFlags |= ctx.ContextFlags & needed_flags;
}
return STATUS_SUCCESS;
}
/***********************************************************************
* setup_exception_record
*
* Setup the exception record and context on the thread stack.
*/
static EXCEPTION_RECORD *setup_exception( ucontext_t *sigcontext, raise_func func )
{
struct stack_layout
{
CONTEXT context;
EXCEPTION_RECORD rec;
} *stack;
DWORD exception_code = 0;
/* push the stack_layout structure */
stack = (struct stack_layout *)((SP_sig(sigcontext) - sizeof(*stack)) & ~15);
stack->rec.ExceptionRecord = NULL;
stack->rec.ExceptionCode = exception_code;
stack->rec.ExceptionFlags = EXCEPTION_CONTINUABLE;
stack->rec.ExceptionAddress = (LPVOID)PC_sig(sigcontext);
stack->rec.NumberParameters = 0;
save_context( &stack->context, sigcontext );
/* now modify the sigcontext to return to the raise function */
SP_sig(sigcontext) = (ULONG_PTR)stack;
PC_sig(sigcontext) = (ULONG_PTR)func;
REGn_sig(0, sigcontext) = (ULONG_PTR)&stack->rec; /* first arg for raise_func */
REGn_sig(1, sigcontext) = (ULONG_PTR)&stack->context; /* second arg for raise_func */
return &stack->rec;
}
/**********************************************************************
* raise_segv_exception
*/
static void WINAPI raise_segv_exception( EXCEPTION_RECORD *rec, CONTEXT *context )
{
NTSTATUS status;
switch(rec->ExceptionCode)
{
case EXCEPTION_ACCESS_VIOLATION:
if (rec->NumberParameters == 2)
{
if (!(rec->ExceptionCode = virtual_handle_fault( (void *)rec->ExceptionInformation[1],
rec->ExceptionInformation[0], FALSE )))
goto done;
}
break;
}
status = NtRaiseException( rec, context, TRUE );
if (status) raise_status( status, rec );
done:
set_cpu_context( context );
}
/**********************************************************************
* call_stack_handlers
*
* Call the stack handlers chain.
*/
static NTSTATUS call_stack_handlers( EXCEPTION_RECORD *rec, CONTEXT *context )
{
EXCEPTION_REGISTRATION_RECORD *frame, *dispatch, *nested_frame;
DWORD res;
frame = NtCurrentTeb()->Tib.ExceptionList;
nested_frame = NULL;
while (frame != (EXCEPTION_REGISTRATION_RECORD*)~0UL)
{
/* Check frame address */
if (!is_valid_frame( frame ))
{
rec->ExceptionFlags |= EH_STACK_INVALID;
break;
}
/* Call handler */
TRACE( "calling handler at %p code=%x flags=%x\n",
frame->Handler, rec->ExceptionCode, rec->ExceptionFlags );
res = frame->Handler( rec, frame, context, &dispatch );
TRACE( "handler at %p returned %x\n", frame->Handler, res );
if (frame == nested_frame)
{
/* no longer nested */
nested_frame = NULL;
rec->ExceptionFlags &= ~EH_NESTED_CALL;
}
switch(res)
{
case ExceptionContinueExecution:
if (!(rec->ExceptionFlags & EH_NONCONTINUABLE)) return STATUS_SUCCESS;
return STATUS_NONCONTINUABLE_EXCEPTION;
case ExceptionContinueSearch:
break;
case ExceptionNestedException:
if (nested_frame < dispatch) nested_frame = dispatch;
rec->ExceptionFlags |= EH_NESTED_CALL;
break;
default:
return STATUS_INVALID_DISPOSITION;
}
frame = frame->Prev;
}
return STATUS_UNHANDLED_EXCEPTION;
}
/*******************************************************************
* raise_exception
*
* Implementation of NtRaiseException.
*/
static NTSTATUS raise_exception( EXCEPTION_RECORD *rec, CONTEXT *context, BOOL first_chance )
{
NTSTATUS status;
if (first_chance)
{
DWORD c;
for (c = 0; c < rec->NumberParameters; c++)
TRACE( " info[%d]=%016lx\n", c, rec->ExceptionInformation[c] );
if (rec->ExceptionCode == EXCEPTION_WINE_STUB)
{
if (rec->ExceptionInformation[1] >> 16)
MESSAGE( "wine: Call from %p to unimplemented function %s.%s, aborting\n",
rec->ExceptionAddress,
(char*)rec->ExceptionInformation[0], (char*)rec->ExceptionInformation[1] );
else
MESSAGE( "wine: Call from %p to unimplemented function %s.%ld, aborting\n",
rec->ExceptionAddress,
(char*)rec->ExceptionInformation[0], rec->ExceptionInformation[1] );
}
else
{
/* FIXME: dump context */
}
status = send_debug_event( rec, TRUE, context );
if (status == DBG_CONTINUE || status == DBG_EXCEPTION_HANDLED)
return STATUS_SUCCESS;
if (call_vectored_handlers( rec, context ) == EXCEPTION_CONTINUE_EXECUTION)
return STATUS_SUCCESS;
if ((status = call_stack_handlers( rec, context )) != STATUS_UNHANDLED_EXCEPTION)
return status;
}
/* last chance exception */
status = send_debug_event( rec, FALSE, context );
if (status != DBG_CONTINUE)
{
if (rec->ExceptionFlags & EH_STACK_INVALID)
ERR("Exception frame is not in stack limits => unable to dispatch exception.\n");
else if (rec->ExceptionCode == STATUS_NONCONTINUABLE_EXCEPTION)
ERR("Process attempted to continue execution after noncontinuable exception.\n");
else
ERR("Unhandled exception code %x flags %x addr %p\n",
rec->ExceptionCode, rec->ExceptionFlags, rec->ExceptionAddress );
NtTerminateProcess( NtCurrentProcess(), rec->ExceptionCode );
}
return STATUS_SUCCESS;
}
static inline DWORD is_write_fault( ucontext_t *context )
{
DWORD inst = *(DWORD *)PC_sig(context);
if ((inst & 0xbfff0000) == 0x0c000000 /* C3.3.1 */ ||
(inst & 0xbfe00000) == 0x0c800000 /* C3.3.2 */ ||
(inst & 0xbfdf0000) == 0x0d000000 /* C3.3.3 */ ||
(inst & 0xbfc00000) == 0x0d800000 /* C3.3.4 */ ||
(inst & 0x3f400000) == 0x08000000 /* C3.3.6 */ ||
(inst & 0x3bc00000) == 0x38000000 /* C3.3.8-12 */ ||
(inst & 0x3fe00000) == 0x3c800000 /* C3.3.8-12 128bit */ ||
(inst & 0x3bc00000) == 0x39000000 /* C3.3.13 */ ||
(inst & 0x3fc00000) == 0x3d800000 /* C3.3.13 128bit */ ||
(inst & 0x3a400000) == 0x28000000) /* C3.3.7,14-16 */
return EXCEPTION_WRITE_FAULT;
return EXCEPTION_READ_FAULT;
}
/**********************************************************************
* segv_handler
*
* Handler for SIGSEGV and related errors.
*/
static void segv_handler( int signal, siginfo_t *info, void *ucontext )
{
EXCEPTION_RECORD *rec;
ucontext_t *context = ucontext;
/* check for page fault inside the thread stack */
if (signal == SIGSEGV &&
(char *)info->si_addr >= (char *)NtCurrentTeb()->DeallocationStack &&
(char *)info->si_addr < (char *)NtCurrentTeb()->Tib.StackBase &&
virtual_handle_stack_fault( info->si_addr ))
{
/* check if this was the last guard page */
if ((char *)info->si_addr < (char *)NtCurrentTeb()->DeallocationStack + 2*4096)
{
rec = setup_exception( context, raise_segv_exception );
rec->ExceptionCode = EXCEPTION_STACK_OVERFLOW;
}
return;
}
rec = setup_exception( context, raise_segv_exception );
if (rec->ExceptionCode == EXCEPTION_STACK_OVERFLOW) return;
switch(signal)
{
case SIGILL: /* Invalid opcode exception */
rec->ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION;
break;
case SIGSEGV: /* Segmentation fault */
rec->ExceptionCode = EXCEPTION_ACCESS_VIOLATION;
rec->NumberParameters = 2;
rec->ExceptionInformation[0] = is_write_fault(context);
rec->ExceptionInformation[1] = (ULONG_PTR)info->si_addr;
break;
case SIGBUS: /* Alignment check exception */
rec->ExceptionCode = EXCEPTION_DATATYPE_MISALIGNMENT;
break;
default:
ERR("Got unexpected signal %i\n", signal);
rec->ExceptionCode = EXCEPTION_ILLEGAL_INSTRUCTION;
break;
}
}
/**********************************************************************
* trap_handler
*
* Handler for SIGTRAP.
*/
static void trap_handler( int signal, siginfo_t *info, void *ucontext )
{
EXCEPTION_RECORD rec;
CONTEXT context;
NTSTATUS status;
switch ( info->si_code )
{
case TRAP_TRACE:
rec.ExceptionCode = EXCEPTION_SINGLE_STEP;
break;
case TRAP_BRKPT:
default:
rec.ExceptionCode = EXCEPTION_BREAKPOINT;
break;
}
save_context( &context, ucontext );
rec.ExceptionFlags = EXCEPTION_CONTINUABLE;
rec.ExceptionRecord = NULL;
rec.ExceptionAddress = (LPVOID)context.Pc;
rec.NumberParameters = 0;
status = raise_exception( &rec, &context, TRUE );
if (status) raise_status( status, &rec );
restore_context( &context, ucontext );
}
/**********************************************************************
* fpe_handler
*
* Handler for SIGFPE.
*/
static void fpe_handler( int signal, siginfo_t *siginfo, void *sigcontext )
{
EXCEPTION_RECORD rec;
CONTEXT context;
NTSTATUS status;
save_fpu( &context, sigcontext );
save_context( &context, sigcontext );
switch (siginfo->si_code & 0xffff )
{
#ifdef FPE_FLTSUB
case FPE_FLTSUB:
rec.ExceptionCode = EXCEPTION_ARRAY_BOUNDS_EXCEEDED;
break;
#endif
#ifdef FPE_INTDIV
case FPE_INTDIV:
rec.ExceptionCode = EXCEPTION_INT_DIVIDE_BY_ZERO;
break;
#endif
#ifdef FPE_INTOVF
case FPE_INTOVF:
rec.ExceptionCode = EXCEPTION_INT_OVERFLOW;
break;
#endif
#ifdef FPE_FLTDIV
case FPE_FLTDIV:
rec.ExceptionCode = EXCEPTION_FLT_DIVIDE_BY_ZERO;
break;
#endif
#ifdef FPE_FLTOVF
case FPE_FLTOVF:
rec.ExceptionCode = EXCEPTION_FLT_OVERFLOW;
break;
#endif
#ifdef FPE_FLTUND
case FPE_FLTUND:
rec.ExceptionCode = EXCEPTION_FLT_UNDERFLOW;
break;
#endif
#ifdef FPE_FLTRES
case FPE_FLTRES:
rec.ExceptionCode = EXCEPTION_FLT_INEXACT_RESULT;
break;
#endif
#ifdef FPE_FLTINV
case FPE_FLTINV:
#endif
default:
rec.ExceptionCode = EXCEPTION_FLT_INVALID_OPERATION;
break;
}
rec.ExceptionFlags = EXCEPTION_CONTINUABLE;
rec.ExceptionRecord = NULL;
rec.ExceptionAddress = (LPVOID)context.Pc;
rec.NumberParameters = 0;
status = raise_exception( &rec, &context, TRUE );
if (status) raise_status( status, &rec );
restore_context( &context, sigcontext );
restore_fpu( &context, sigcontext );
}
/**********************************************************************
* int_handler
*
* Handler for SIGINT.
*/
static void int_handler( int signal, siginfo_t *siginfo, void *sigcontext )
{
if (!dispatch_signal(SIGINT))
{
EXCEPTION_RECORD rec;
CONTEXT context;
NTSTATUS status;
save_context( &context, sigcontext );
rec.ExceptionCode = CONTROL_C_EXIT;
rec.ExceptionFlags = EXCEPTION_CONTINUABLE;
rec.ExceptionRecord = NULL;
rec.ExceptionAddress = (LPVOID)context.Pc;
rec.NumberParameters = 0;
status = raise_exception( &rec, &context, TRUE );
if (status) raise_status( status, &rec );
restore_context( &context, sigcontext );
}
}
/**********************************************************************
* abrt_handler
*
* Handler for SIGABRT.
*/
static void abrt_handler( int signal, siginfo_t *siginfo, void *sigcontext )
{
EXCEPTION_RECORD rec;
CONTEXT context;
NTSTATUS status;
save_context( &context, sigcontext );
rec.ExceptionCode = EXCEPTION_WINE_ASSERTION;
rec.ExceptionFlags = EH_NONCONTINUABLE;
rec.ExceptionRecord = NULL;
rec.ExceptionAddress = (LPVOID)context.Pc;
rec.NumberParameters = 0;
status = raise_exception( &rec, &context, TRUE );
if (status) raise_status( status, &rec );
restore_context( &context, sigcontext );
}
/**********************************************************************
* quit_handler
*
* Handler for SIGQUIT.
*/
static void quit_handler( int signal, siginfo_t *siginfo, void *sigcontext )
{
abort_thread(0);
}
/**********************************************************************
* usr1_handler
*
* Handler for SIGUSR1, used to signal a thread that it got suspended.
*/
static void usr1_handler( int signal, siginfo_t *siginfo, void *sigcontext )
{
CONTEXT context;
save_context( &context, sigcontext );
wait_suspend( &context );
restore_context( &context, sigcontext );
}
/***********************************************************************
* __wine_set_signal_handler (NTDLL.@)
*/
int CDECL __wine_set_signal_handler(unsigned int sig, wine_signal_handler wsh)
{
if (sig >= sizeof(handlers) / sizeof(handlers[0])) return -1;
if (handlers[sig] != NULL) return -2;
handlers[sig] = wsh;
return 0;
}
/**********************************************************************
* signal_alloc_thread
*/
NTSTATUS signal_alloc_thread( TEB **teb )
{
static size_t sigstack_zero_bits;
SIZE_T size;
NTSTATUS status;
if (!sigstack_zero_bits)
{
size_t min_size = teb_size + max( MINSIGSTKSZ, 8192 );
/* find the first power of two not smaller than min_size */
sigstack_zero_bits = 12;
while ((1u << sigstack_zero_bits) < min_size) sigstack_zero_bits++;
signal_stack_size = (1 << sigstack_zero_bits) - teb_size;
assert( sizeof(TEB) <= teb_size );
}
size = 1 << sigstack_zero_bits;
*teb = NULL;
if (!(status = NtAllocateVirtualMemory( NtCurrentProcess(), (void **)teb, sigstack_zero_bits,
&size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE )))
{
(*teb)->Tib.Self = &(*teb)->Tib;
(*teb)->Tib.ExceptionList = (void *)~0UL;
}
return status;
}
/**********************************************************************
* signal_free_thread
*/
void signal_free_thread( TEB *teb )
{
SIZE_T size = 0;
NtFreeVirtualMemory( NtCurrentProcess(), (void **)&teb, &size, MEM_RELEASE );
}
/**********************************************************************
* signal_init_thread
*/
void signal_init_thread( TEB *teb )
{
static BOOL init_done;
if (!init_done)
{
pthread_key_create( &teb_key, NULL );
init_done = TRUE;
}
/* Win64/ARM applications expect the TEB pointer to be in the x18 platform register. */
__asm__ __volatile__( "mov x18, %0" : : "r" (teb) );
pthread_setspecific( teb_key, teb );
}
/**********************************************************************
* signal_init_process
*/
void signal_init_process(void)
{
struct sigaction sig_act;
sig_act.sa_mask = server_block_set;
sig_act.sa_flags = SA_RESTART | SA_SIGINFO;
sig_act.sa_sigaction = int_handler;
if (sigaction( SIGINT, &sig_act, NULL ) == -1) goto error;
sig_act.sa_sigaction = fpe_handler;
if (sigaction( SIGFPE, &sig_act, NULL ) == -1) goto error;
sig_act.sa_sigaction = abrt_handler;
if (sigaction( SIGABRT, &sig_act, NULL ) == -1) goto error;
sig_act.sa_sigaction = quit_handler;
if (sigaction( SIGQUIT, &sig_act, NULL ) == -1) goto error;
sig_act.sa_sigaction = usr1_handler;
if (sigaction( SIGUSR1, &sig_act, NULL ) == -1) goto error;
sig_act.sa_sigaction = segv_handler;
if (sigaction( SIGSEGV, &sig_act, NULL ) == -1) goto error;
if (sigaction( SIGILL, &sig_act, NULL ) == -1) goto error;
#ifdef SIGBUS
if (sigaction( SIGBUS, &sig_act, NULL ) == -1) goto error;
#endif
#ifdef SIGTRAP
sig_act.sa_sigaction = trap_handler;
if (sigaction( SIGTRAP, &sig_act, NULL ) == -1) goto error;
#endif
return;
error:
perror("sigaction");
exit(1);
}
/**********************************************************************
* __wine_enter_vm86 (NTDLL.@)
*/
void __wine_enter_vm86( CONTEXT *context )
{
MESSAGE("vm86 mode not supported on this platform\n");
}
/***********************************************************************
* RtlUnwind (NTDLL.@)
*/
void WINAPI RtlUnwind( PVOID pEndFrame, PVOID targetIp, PEXCEPTION_RECORD pRecord, PVOID retval )
{
FIXME( "Not implemented on ARM64\n" );
}
/*******************************************************************
* NtRaiseException (NTDLL.@)
*/
NTSTATUS WINAPI NtRaiseException( EXCEPTION_RECORD *rec, CONTEXT *context, BOOL first_chance )
{
NTSTATUS status = raise_exception( rec, context, first_chance );
if (status == STATUS_SUCCESS) NtSetContextThread( GetCurrentThread(), context );
return status;
}
/***********************************************************************
* RtlRaiseException (NTDLL.@)
*/
void WINAPI RtlRaiseException( EXCEPTION_RECORD *rec )
{
CONTEXT context;
NTSTATUS status;
RtlCaptureContext( &context );
rec->ExceptionAddress = (LPVOID)context.Pc;
status = raise_exception( rec, &context, TRUE );
if (status) raise_status( status, rec );
}
/*************************************************************************
* RtlCaptureStackBackTrace (NTDLL.@)
*/
USHORT WINAPI RtlCaptureStackBackTrace( ULONG skip, ULONG count, PVOID *buffer, ULONG *hash )
{
FIXME( "(%d, %d, %p, %p) stub!\n", skip, count, buffer, hash );
return 0;
}
/***********************************************************************
* call_thread_entry_point
*/
static void WINAPI call_thread_entry_point( LPTHREAD_START_ROUTINE entry, void *arg )
{
__TRY
{
TRACE_(relay)( "\1Starting thread proc %p (arg=%p)\n", entry, arg );
RtlExitUserThread( entry( arg ));
}
__EXCEPT(unhandled_exception_filter)
{
NtTerminateThread( GetCurrentThread(), GetExceptionCode() );
}
__ENDTRY
abort(); /* should not be reached */
}
typedef void (WINAPI *thread_start_func)(LPTHREAD_START_ROUTINE,void *);
struct startup_info
{
thread_start_func start;
LPTHREAD_START_ROUTINE entry;
void *arg;
BOOL suspend;
};
/***********************************************************************
* thread_startup
*/
static void thread_startup( void *param )
{
CONTEXT context = { 0 };
struct startup_info *info = param;
/* build the initial context */
context.ContextFlags = CONTEXT_FULL;
context.u.s.X0 = (DWORD_PTR)info->entry;
context.u.s.X1 = (DWORD_PTR)info->arg;
context.Sp = (DWORD_PTR)NtCurrentTeb()->Tib.StackBase;
context.Pc = (DWORD_PTR)info->start;
if (info->suspend) wait_suspend( &context );
attach_dlls( &context );
((thread_start_func)context.Pc)( (LPTHREAD_START_ROUTINE)context.u.s.X0, (void *)context.u.s.X1 );
}
/***********************************************************************
* signal_start_thread
*
* Thread startup sequence:
* signal_start_thread()
* -> thread_startup()
* -> call_thread_entry_point()
*/
void signal_start_thread( LPTHREAD_START_ROUTINE entry, void *arg, BOOL suspend )
{
struct startup_info info = { call_thread_entry_point, entry, arg, suspend };
wine_switch_to_stack( thread_startup, &info, NtCurrentTeb()->Tib.StackBase );
}
/**********************************************************************
* signal_start_process
*
* Process startup sequence:
* signal_start_process()
* -> thread_startup()
* -> kernel32_start_process()
*/
void signal_start_process( LPTHREAD_START_ROUTINE entry, BOOL suspend )
{
struct startup_info info = { kernel32_start_process, entry, NtCurrentTeb()->Peb, suspend };
wine_switch_to_stack( thread_startup, &info, NtCurrentTeb()->Tib.StackBase );
}
/***********************************************************************
* signal_exit_thread
*/
void signal_exit_thread( int status )
{
exit_thread( status );
}
/***********************************************************************
* signal_exit_process
*/
void signal_exit_process( int status )
{
exit( status );
}
/**********************************************************************
* DbgBreakPoint (NTDLL.@)
*/
void WINAPI DbgBreakPoint(void)
{
kill(getpid(), SIGTRAP);
}
/**********************************************************************
* DbgUserBreakPoint (NTDLL.@)
*/
void WINAPI DbgUserBreakPoint(void)
{
kill(getpid(), SIGTRAP);
}
/**********************************************************************
* NtCurrentTeb (NTDLL.@)
*/
TEB * WINAPI NtCurrentTeb(void)
{
return pthread_getspecific( teb_key );
}
#endif /* __aarch64__ */
|
the_stack_data/517074.c | /**
* Calling the main() ... within proftpd.so
*
* Note: yes, we have a "shared library" with a main() !!
*
* Note 2: you're not supposed to call main directly,
* you may want to pass its address as an argument
* to __libc_start_main() instead.
*
* endrazine for Defcon 24 // August 2016
*/
#include <stdio.h>
#include <unistd.h>
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
static int (*__main)(int argc, char **argv) = NULL;
int get_symbol(char *filename, char *symbolname){
void *handle;
char *error = 0;
handle = dlopen(filename, RTLD_LAZY);
if (!handle) {
fprintf(stderr, "%s\n", dlerror());
exit(EXIT_FAILURE);
}
__main = dlsym(handle, symbolname);
if ((error = dlerror()) != NULL) {
fprintf(stderr, "%s\n", error);
exit(EXIT_FAILURE);
}
return 0;
}
int main(void){
char *argz[] = {"/bin/foo", 0x00};
get_symbol("/tmp/proftpd.so", "main");
__main(1, argz); // call main() from proftpd.so
return 0;
}
|
the_stack_data/1267726.c | #ifdef WITH_PLATFORM_NRF52840
#include <libpull/security.h>
pull_error rng_init(rng_ctx_t* ctx) {
return PULL_SUCCESS;
}
pull_error rng_generate(rng_ctx_t* ctx, nonce_t* nonce) {
*nonce = sys_rand32_get();
return PULL_SUCCESS;
}
#endif /* WITH_PLATFORM_NRF52840 */
|
the_stack_data/101910.c | #include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
struct _stu {
int no;
char name[21];
int seat;
} *stu[100];
bool f[101];
int cmp(const void *p1, const void *p2) {
struct _stu *const *ps1 = p1, *const *ps2 = p2;
int r = (*ps1)->seat - (*ps2)->seat;
return r != 0 ? r : (*ps1)->no - (*ps2)->no;
}
int cmp_no(const void *p1, const void *p2) {
struct _stu *const *ps1 = p1, *const *ps2 = p2;
return (*ps1)->no - (*ps2)->no;
}
int main() {
int n;
scanf("%d", &n);
FILE *fin = fopen("in.txt", "r");
int m = 0;
for (int i = 0; i < n; i++) {
stu[i] = malloc(sizeof(struct _stu));
fscanf(fin, "%d%s%d", &stu[i]->no, stu[i]->name, &stu[i]->seat);
if (stu[i]->seat > m) m = stu[i]->seat;
f[stu[i]->seat] = true;
}
qsort(stu, n, sizeof(struct _stu *), cmp);
if (n < m) m = n;
for (int i = 1, j = n; i <= m && i < stu[j - 1]->seat; i++) {
if (!f[i]) {
stu[--j]->seat = i;
}
}
qsort(stu, n, sizeof(struct _stu *), cmp);
m = stu[n - 1]->seat;
for (int i = 1; i < n; i++) {
if (stu[i]->seat == stu[i - 1]->seat) {
stu[i]->seat = ++m;
}
}
qsort(stu, n, sizeof(struct _stu *), cmp_no);
FILE *fout = fopen("out.txt", "w");
for (int i = 0; i < n; i++) {
fprintf(fout, "%d %s %d\n", stu[i]->no, stu[i]->name, stu[i]->seat);
}
}
|
the_stack_data/190768982.c | /* **********************************************************
* Copyright (c) 2003 VMware, Inc. 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 VMware, Inc. 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 VMWARE, INC. 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.
*/
/* Build with:
* gcc -o pthreads pthreads.c -lpthread -D_REENTRANT -I../lib -L../lib -ldynamo -ldl -lbfd -liberty
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#ifdef USE_DYNAMO
#include "dynamorio.h"
#endif
volatile double pi = 0.0; /* Approximation to pi (shared) */
pthread_mutex_t pi_lock; /* Lock for above */
volatile double intervals; /* How many intervals? */
void *
process(void *arg)
{
char *id = (char *) arg;
register double width, localsum;
register int i;
register int iproc;
#if VERBOSE
fprintf(stderr, "\tthread %s starting\n", id);
#endif
iproc = (*((char *) arg) - '0');
/* Set width */
width = 1.0 / intervals;
/* Do the local computations */
localsum = 0;
for (i=iproc; i<intervals; i+=2) {
register double x = (i + 0.5) * width;
localsum += 4.0 / (1.0 + x * x);
}
localsum *= width;
/* Lock pi for update, update it, and unlock */
pthread_mutex_lock(&pi_lock);
pi += localsum;
pthread_mutex_unlock(&pi_lock);
#if VERBOSE
fprintf(stderr, "\tthread %s exiting\n", id);
#endif
return(NULL);
}
int
main(int argc, char **argv)
{
pthread_t thread0, thread1;
void * retval;
#ifdef USE_DYNAMO
dynamorio_app_init();
dynamorio_app_start();
#endif
#if 0
/* Get the number of intervals */
if (argc != 2) {
fprintf(stderr, "Usage: %s <intervals>\n", argv[0]);
exit(0);
}
intervals = atoi(argv[1]);
#else /* for batch mode */
intervals = 10;
#endif
/* Initialize the lock on pi */
pthread_mutex_init(&pi_lock, NULL);
/* Make the two threads */
if (pthread_create(&thread0, NULL, process, (void *)"0") ||
pthread_create(&thread1, NULL, process, (void *)"1")) {
fprintf(stderr, "%s: cannot make thread\n", argv[0]);
exit(1);
}
/* Join (collapse) the two threads */
if (pthread_join(thread0, &retval) ||
pthread_join(thread1, &retval)) {
fprintf(stderr, "%s: thread join failed\n", argv[0]);
exit(1);
}
/* Print the result */
printf("Estimation of pi is %16.15f\n", pi);
#ifdef USE_DYNAMO
dynamorio_app_stop();
dynamorio_app_exit();
#endif
}
|
the_stack_data/93887563.c | /*
Linux Real Mode Interface - A library of DPMI-like functions for Linux.
Copyright (C) 1998 by Josh Vanderhoof
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 JOSH VANDERHOOF 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.
*/
#if defined(__i386__) && (defined(__linux__) || defined(__NetBSD__) \
|| defined(__FreeBSD__) || defined(__OpenBSD__))
#include <stdio.h>
#include <string.h>
#if defined(__linux__)
#include <asm/vm86.h>
#include <signal.h>
#ifdef USE_LIBC_VM86
#include <sys/vm86.h>
#endif
#elif defined(__NetBSD__) || defined(__FreeBSD__) || defined(__OpenBSD__)
#include <sys/param.h>
#include <signal.h>
#include <setjmp.h>
#include <machine/psl.h>
#include <machine/vm86.h>
#include <machine/sysarch.h>
#endif /* __NetBSD__ || __FreeBSD__ || __OpenBSD__ */
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <unistd.h>
#include <fcntl.h>
#include "lrmi.h"
#define REAL_MEM_BASE ((void *)0x10000)
#define REAL_MEM_SIZE 0x40000
#define REAL_MEM_BLOCKS 0x100
struct mem_block {
unsigned int size : 20;
unsigned int free : 1;
};
static struct {
int ready;
int count;
struct mem_block blocks[REAL_MEM_BLOCKS];
} mem_info = { 0 };
static int
real_mem_init(void)
{
void *m;
int fd_zero;
if (mem_info.ready)
return 1;
fd_zero = open("/dev/zero", O_RDONLY);
if (fd_zero == -1) {
perror("open /dev/zero");
return 0;
}
m = mmap((void *)REAL_MEM_BASE, REAL_MEM_SIZE,
PROT_READ | PROT_WRITE | PROT_EXEC,
MAP_FIXED | MAP_PRIVATE, fd_zero, 0);
if (m == (void *)-1) {
perror("mmap /dev/zero");
close(fd_zero);
return 0;
}
close(fd_zero);
mem_info.ready = 1;
mem_info.count = 1;
mem_info.blocks[0].size = REAL_MEM_SIZE;
mem_info.blocks[0].free = 1;
return 1;
}
static void
real_mem_deinit(void)
{
if (mem_info.ready) {
munmap((void *)REAL_MEM_BASE, REAL_MEM_SIZE);
mem_info.ready = 0;
}
}
static void
insert_block(int i)
{
memmove(
mem_info.blocks + i + 1,
mem_info.blocks + i,
(mem_info.count - i) * sizeof(struct mem_block));
mem_info.count++;
}
static void
delete_block(int i)
{
mem_info.count--;
memmove(
mem_info.blocks + i,
mem_info.blocks + i + 1,
(mem_info.count - i) * sizeof(struct mem_block));
}
void *
LRMI_alloc_real(int size)
{
int i;
char *r = (char *)REAL_MEM_BASE;
if (!mem_info.ready)
return NULL;
if (mem_info.count == REAL_MEM_BLOCKS)
return NULL;
size = (size + 15) & ~15;
for (i = 0; i < mem_info.count; i++) {
if (mem_info.blocks[i].free && size < mem_info.blocks[i].size) {
insert_block(i);
mem_info.blocks[i].size = size;
mem_info.blocks[i].free = 0;
mem_info.blocks[i + 1].size -= size;
return (void *)r;
}
r += mem_info.blocks[i].size;
}
return NULL;
}
void
LRMI_free_real(void *m)
{
int i;
char *r = (char *)REAL_MEM_BASE;
if (!mem_info.ready)
return;
i = 0;
while (m != (void *)r) {
r += mem_info.blocks[i].size;
i++;
if (i == mem_info.count)
return;
}
mem_info.blocks[i].free = 1;
if (i + 1 < mem_info.count && mem_info.blocks[i + 1].free) {
mem_info.blocks[i].size += mem_info.blocks[i + 1].size;
delete_block(i + 1);
}
if (i - 1 >= 0 && mem_info.blocks[i - 1].free) {
mem_info.blocks[i - 1].size += mem_info.blocks[i].size;
delete_block(i);
}
}
#if defined(__linux__)
#define DEFAULT_VM86_FLAGS (IF_MASK | IOPL_MASK)
#elif defined(__NetBSD__) || defined(__FreeBSD__) || defined(__OpenBSD__)
#define DEFAULT_VM86_FLAGS (PSL_I | PSL_IOPL)
#define TF_MASK PSL_T
#define VIF_MASK PSL_VIF
#endif
#define DEFAULT_STACK_SIZE 0x1000
#define RETURN_TO_32_INT 255
#if defined(__linux__)
#define CONTEXT_REGS context.vm.regs
#define REG(x) x
#elif defined(__NetBSD__) || defined(__OpenBSD__)
#define CONTEXT_REGS context.vm.substr.regs
#define REG(x) vmsc.sc_ ## x
#elif defined(__FreeBSD__)
#define CONTEXT_REGS context.vm.uc
#define REG(x) uc_mcontext.mc_ ## x
#endif
static struct {
int ready;
unsigned short ret_seg, ret_off;
unsigned short stack_seg, stack_off;
#if defined(__linux__) || defined(__NetBSD__) || defined(__OpenBSD__)
struct vm86_struct vm;
#elif defined(__FreeBSD__)
struct {
struct vm86_init_args init;
ucontext_t uc;
} vm;
#endif
#if defined(__NetBSD__) || defined(__FreeBSD__) || defined(__OpenBSD__)
int success;
jmp_buf env;
void *old_sighandler;
int vret;
#endif
} context = { 0 };
static inline void
set_bit(unsigned int bit, void *array)
{
unsigned char *a = array;
a[bit / 8] |= (1 << (bit % 8));
}
static inline unsigned int
get_int_seg(int i)
{
return *(unsigned short *)(i * 4 + 2);
}
static inline unsigned int
get_int_off(int i)
{
return *(unsigned short *)(i * 4);
}
static inline void
pushw(unsigned short i)
{
CONTEXT_REGS.REG(esp) -= 2;
*(unsigned short *)(((unsigned int)CONTEXT_REGS.REG(ss) << 4) +
CONTEXT_REGS.REG(esp)) = i;
}
int
LRMI_init(void)
{
void *m;
int fd_mem;
if (context.ready)
return 1;
if (!real_mem_init())
return 0;
/*
Map the Interrupt Vectors (0x0 - 0x400) + BIOS data (0x400 - 0x502)
and the ROM (0xa0000 - 0x100000)
*/
fd_mem = open("/dev/mem", O_RDWR);
if (fd_mem == -1) {
real_mem_deinit();
perror("open /dev/mem");
return 0;
}
m = mmap((void *)0, 0x502,
PROT_READ | PROT_WRITE | PROT_EXEC,
MAP_FIXED | MAP_PRIVATE, fd_mem, 0);
if (m == (void *)-1) {
close(fd_mem);
real_mem_deinit();
perror("mmap /dev/mem");
return 0;
}
m = mmap((void *)0xa0000, 0x100000 - 0xa0000,
PROT_READ | PROT_WRITE,
MAP_FIXED | MAP_SHARED, fd_mem, 0xa0000);
if (m == (void *)-1) {
munmap((void *)0, 0x502);
close(fd_mem);
real_mem_deinit();
perror("mmap /dev/mem");
return 0;
}
close(fd_mem);
/*
Allocate a stack
*/
m = LRMI_alloc_real(DEFAULT_STACK_SIZE);
context.stack_seg = (unsigned int)m >> 4;
context.stack_off = DEFAULT_STACK_SIZE;
/*
Allocate the return to 32 bit routine
*/
m = LRMI_alloc_real(2);
context.ret_seg = (unsigned int)m >> 4;
context.ret_off = (unsigned int)m & 0xf;
((unsigned char *)m)[0] = 0xcd; /* int opcode */
((unsigned char *)m)[1] = RETURN_TO_32_INT;
memset(&context.vm, 0, sizeof(context.vm));
/*
Enable kernel emulation of all ints except RETURN_TO_32_INT
*/
#if defined(__linux__)
memset(&context.vm.int_revectored, 0, sizeof(context.vm.int_revectored));
set_bit(RETURN_TO_32_INT, &context.vm.int_revectored);
#elif defined(__NetBSD__) || defined(__OpenBSD__)
set_bit(RETURN_TO_32_INT, &context.vm.int_byuser);
#elif defined(__FreeBSD__)
set_bit(RETURN_TO_32_INT, &context.vm.init.int_map);
#endif
context.ready = 1;
return 1;
}
static void
set_regs(struct LRMI_regs *r)
{
CONTEXT_REGS.REG(edi) = r->edi;
CONTEXT_REGS.REG(esi) = r->esi;
CONTEXT_REGS.REG(ebp) = r->ebp;
CONTEXT_REGS.REG(ebx) = r->ebx;
CONTEXT_REGS.REG(edx) = r->edx;
CONTEXT_REGS.REG(ecx) = r->ecx;
CONTEXT_REGS.REG(eax) = r->eax;
CONTEXT_REGS.REG(eflags) = DEFAULT_VM86_FLAGS;
CONTEXT_REGS.REG(es) = r->es;
CONTEXT_REGS.REG(ds) = r->ds;
CONTEXT_REGS.REG(fs) = r->fs;
CONTEXT_REGS.REG(gs) = r->gs;
}
static void
get_regs(struct LRMI_regs *r)
{
r->edi = CONTEXT_REGS.REG(edi);
r->esi = CONTEXT_REGS.REG(esi);
r->ebp = CONTEXT_REGS.REG(ebp);
r->ebx = CONTEXT_REGS.REG(ebx);
r->edx = CONTEXT_REGS.REG(edx);
r->ecx = CONTEXT_REGS.REG(ecx);
r->eax = CONTEXT_REGS.REG(eax);
r->flags = CONTEXT_REGS.REG(eflags);
r->es = CONTEXT_REGS.REG(es);
r->ds = CONTEXT_REGS.REG(ds);
r->fs = CONTEXT_REGS.REG(fs);
r->gs = CONTEXT_REGS.REG(gs);
}
#define DIRECTION_FLAG (1 << 10)
enum {
CSEG = 0x2e, SSEG = 0x36, DSEG = 0x3e,
ESEG = 0x26, FSEG = 0x64, GSEG = 0x65,
};
static void
em_ins(int size)
{
unsigned int edx, edi;
edx = CONTEXT_REGS.REG(edx) & 0xffff;
edi = CONTEXT_REGS.REG(edi) & 0xffff;
edi += (unsigned int)CONTEXT_REGS.REG(es) << 4;
if (CONTEXT_REGS.REG(eflags) & DIRECTION_FLAG) {
if (size == 4)
asm volatile ("std; insl; cld"
: "=D" (edi) : "d" (edx), "0" (edi));
else if (size == 2)
asm volatile ("std; insw; cld"
: "=D" (edi) : "d" (edx), "0" (edi));
else
asm volatile ("std; insb; cld"
: "=D" (edi) : "d" (edx), "0" (edi));
} else {
if (size == 4)
asm volatile ("cld; insl"
: "=D" (edi) : "d" (edx), "0" (edi));
else if (size == 2)
asm volatile ("cld; insw"
: "=D" (edi) : "d" (edx), "0" (edi));
else
asm volatile ("cld; insb"
: "=D" (edi) : "d" (edx), "0" (edi));
}
edi -= (unsigned int)CONTEXT_REGS.REG(es) << 4;
CONTEXT_REGS.REG(edi) &= 0xffff0000;
CONTEXT_REGS.REG(edi) |= edi & 0xffff;
}
static void
em_rep_ins(int size)
{
unsigned int cx;
cx = CONTEXT_REGS.REG(ecx) & 0xffff;
while (cx--)
em_ins(size);
CONTEXT_REGS.REG(ecx) &= 0xffff0000;
}
static void
em_outs(int size, int seg)
{
unsigned int edx, esi, base;
edx = CONTEXT_REGS.REG(edx) & 0xffff;
esi = CONTEXT_REGS.REG(esi) & 0xffff;
switch (seg) {
case CSEG: base = CONTEXT_REGS.REG(cs); break;
case SSEG: base = CONTEXT_REGS.REG(ss); break;
case ESEG: base = CONTEXT_REGS.REG(es); break;
case FSEG: base = CONTEXT_REGS.REG(fs); break;
case GSEG: base = CONTEXT_REGS.REG(gs); break;
default:
case DSEG: base = CONTEXT_REGS.REG(ds); break;
}
esi += base << 4;
if (CONTEXT_REGS.REG(eflags) & DIRECTION_FLAG) {
if (size == 4)
asm volatile ("std; outsl; cld"
: "=S" (esi) : "d" (edx), "0" (esi));
else if (size == 2)
asm volatile ("std; outsw; cld"
: "=S" (esi) : "d" (edx), "0" (esi));
else
asm volatile ("std; outsb; cld"
: "=S" (esi) : "d" (edx), "0" (esi));
} else {
if (size == 4)
asm volatile ("cld; outsl"
: "=S" (esi) : "d" (edx), "0" (esi));
else if (size == 2)
asm volatile ("cld; outsw"
: "=S" (esi) : "d" (edx), "0" (esi));
else
asm volatile ("cld; outsb"
: "=S" (esi) : "d" (edx), "0" (esi));
}
esi -= base << 4;
CONTEXT_REGS.REG(esi) &= 0xffff0000;
CONTEXT_REGS.REG(esi) |= esi & 0xffff;
}
static void
em_rep_outs(int size, int seg)
{
unsigned int cx;
cx = CONTEXT_REGS.REG(ecx) & 0xffff;
while (cx--)
em_outs(size, seg);
CONTEXT_REGS.REG(ecx) &= 0xffff0000;
}
static void
em_inbl(unsigned char literal)
{
asm volatile ("inb %w1, %b0"
: "=a" (CONTEXT_REGS.REG(eax))
: "d" (literal), "0" (CONTEXT_REGS.REG(eax)));
}
static void
em_inb(void)
{
asm volatile ("inb %w1, %b0"
: "=a" (CONTEXT_REGS.REG(eax))
: "d" (CONTEXT_REGS.REG(edx)), "0" (CONTEXT_REGS.REG(eax)));
}
static void
em_inw(void)
{
asm volatile ("inw %w1, %w0"
: "=a" (CONTEXT_REGS.REG(eax))
: "d" (CONTEXT_REGS.REG(edx)), "0" (CONTEXT_REGS.REG(eax)));
}
static void
em_inl(void)
{
asm volatile ("inl %w1, %0"
: "=a" (CONTEXT_REGS.REG(eax))
: "d" (CONTEXT_REGS.REG(edx)));
}
static void
em_outbl(unsigned char literal)
{
asm volatile ("outb %b0, %w1"
: : "a" (CONTEXT_REGS.REG(eax)),
"d" (literal));
}
static void
em_outb(void)
{
asm volatile ("outb %b0, %w1"
: : "a" (CONTEXT_REGS.REG(eax)),
"d" (CONTEXT_REGS.REG(edx)));
}
static void
em_outw(void)
{
asm volatile ("outw %w0, %w1"
: : "a" (CONTEXT_REGS.REG(eax)),
"d" (CONTEXT_REGS.REG(edx)));
}
static void
em_outl(void)
{
asm volatile ("outl %0, %w1"
: : "a" (CONTEXT_REGS.REG(eax)),
"d" (CONTEXT_REGS.REG(edx)));
}
static int
emulate(void)
{
unsigned char *insn;
struct {
unsigned char seg;
unsigned int size : 1;
unsigned int rep : 1;
} prefix = { DSEG, 0, 0 };
int i = 0;
insn = (unsigned char *)((unsigned int)CONTEXT_REGS.REG(cs) << 4);
insn += CONTEXT_REGS.REG(eip);
while (1) {
if (insn[i] == 0x66) {
prefix.size = 1 - prefix.size;
i++;
} else if (insn[i] == 0xf3) {
prefix.rep = 1;
i++;
} else if (insn[i] == CSEG || insn[i] == SSEG
|| insn[i] == DSEG || insn[i] == ESEG
|| insn[i] == FSEG || insn[i] == GSEG) {
prefix.seg = insn[i];
i++;
} else if (insn[i] == 0xf0 || insn[i] == 0xf2
|| insn[i] == 0x67) {
/* these prefixes are just ignored */
i++;
} else if (insn[i] == 0x6c) {
if (prefix.rep)
em_rep_ins(1);
else
em_ins(1);
i++;
break;
} else if (insn[i] == 0x6d) {
if (prefix.rep) {
if (prefix.size)
em_rep_ins(4);
else
em_rep_ins(2);
} else {
if (prefix.size)
em_ins(4);
else
em_ins(2);
}
i++;
break;
} else if (insn[i] == 0x6e) {
if (prefix.rep)
em_rep_outs(1, prefix.seg);
else
em_outs(1, prefix.seg);
i++;
break;
} else if (insn[i] == 0x6f) {
if (prefix.rep) {
if (prefix.size)
em_rep_outs(4, prefix.seg);
else
em_rep_outs(2, prefix.seg);
} else {
if (prefix.size)
em_outs(4, prefix.seg);
else
em_outs(2, prefix.seg);
}
i++;
break;
} else if (insn[i] == 0xe4) {
em_inbl(insn[i + 1]);
i += 2;
break;
} else if (insn[i] == 0xec) {
em_inb();
i++;
break;
} else if (insn[i] == 0xed) {
if (prefix.size)
em_inl();
else
em_inw();
i++;
break;
} else if (insn[i] == 0xe6) {
em_outbl(insn[i + 1]);
i += 2;
break;
} else if (insn[i] == 0xee) {
em_outb();
i++;
break;
} else if (insn[i] == 0xef) {
if (prefix.size)
em_outl();
else
em_outw();
i++;
break;
} else
return 0;
}
CONTEXT_REGS.REG(eip) += i;
return 1;
}
#if defined(__linux__)
/*
I don't know how to make sure I get the right vm86() from libc.
The one I want is syscall # 113 (vm86old() in libc 5, vm86() in glibc)
which should be declared as "int vm86(struct vm86_struct *);" in
<sys/vm86.h>.
This just does syscall 113 with inline asm, which should work
for both libc's (I hope).
*/
#if !defined(USE_LIBC_VM86)
static int
lrmi_vm86(struct vm86_struct *vm)
{
int r;
#ifdef __PIC__
asm volatile (
"pushl %%ebx\n\t"
"movl %2, %%ebx\n\t"
"int $0x80\n\t"
"popl %%ebx"
: "=a" (r)
: "0" (113), "r" (vm));
#else
asm volatile (
"int $0x80"
: "=a" (r)
: "0" (113), "b" (vm));
#endif
return r;
}
#else
#define lrmi_vm86 vm86
#endif
#endif /* __linux__ */
static void
debug_info(int vret)
{
#ifdef LRMI_DEBUG
int i;
unsigned char *p;
fputs("vm86() failed\n", stderr);
fprintf(stderr, "return = 0x%x\n", vret);
fprintf(stderr, "eax = 0x%08x\n", CONTEXT_REGS.REG(eax));
fprintf(stderr, "ebx = 0x%08x\n", CONTEXT_REGS.REG(ebx));
fprintf(stderr, "ecx = 0x%08x\n", CONTEXT_REGS.REG(ecx));
fprintf(stderr, "edx = 0x%08x\n", CONTEXT_REGS.REG(edx));
fprintf(stderr, "esi = 0x%08x\n", CONTEXT_REGS.REG(esi));
fprintf(stderr, "edi = 0x%08x\n", CONTEXT_REGS.REG(edi));
fprintf(stderr, "ebp = 0x%08x\n", CONTEXT_REGS.REG(ebp));
fprintf(stderr, "eip = 0x%08x\n", CONTEXT_REGS.REG(eip));
fprintf(stderr, "cs = 0x%04x\n", CONTEXT_REGS.REG(cs));
fprintf(stderr, "esp = 0x%08x\n", CONTEXT_REGS.REG(esp));
fprintf(stderr, "ss = 0x%04x\n", CONTEXT_REGS.REG(ss));
fprintf(stderr, "ds = 0x%04x\n", CONTEXT_REGS.REG(ds));
fprintf(stderr, "es = 0x%04x\n", CONTEXT_REGS.REG(es));
fprintf(stderr, "fs = 0x%04x\n", CONTEXT_REGS.REG(fs));
fprintf(stderr, "gs = 0x%04x\n", CONTEXT_REGS.REG(gs));
fprintf(stderr, "eflags = 0x%08x\n", CONTEXT_REGS.REG(eflags));
fputs("cs:ip = [ ", stderr);
p = (unsigned char *)((CONTEXT_REGS.REG(cs) << 4) + (CONTEXT_REGS.REG(eip) & 0xffff));
for (i = 0; i < 16; ++i)
fprintf(stderr, "%02x ", (unsigned int)p[i]);
fputs("]\n", stderr);
#endif
}
#if defined(__linux__)
static int
run_vm86(void)
{
unsigned int vret;
sigset_t all_sigs, old_sigs;
unsigned long old_gs, old_fs;
while (1) {
// FIXME: may apply this to BSD equivalents?
sigfillset(&all_sigs);
sigprocmask(SIG_SETMASK, &all_sigs, &old_sigs);
asm volatile ("movl %%gs, %0" : "=rm" (old_gs));
asm volatile ("movl %%fs, %0" : "=rm" (old_fs));
vret = lrmi_vm86(&context.vm);
asm volatile ("movl %0, %%gs" :: "rm" (old_gs));
asm volatile ("movl %0, %%fs" :: "rm" (old_fs));
sigprocmask(SIG_SETMASK, &old_sigs, NULL);
if (VM86_TYPE(vret) == VM86_INTx) {
unsigned int v = VM86_ARG(vret);
if (v == RETURN_TO_32_INT)
return 1;
pushw(CONTEXT_REGS.REG(eflags));
pushw(CONTEXT_REGS.REG(cs));
pushw(CONTEXT_REGS.REG(eip));
CONTEXT_REGS.REG(cs) = get_int_seg(v);
CONTEXT_REGS.REG(eip) = get_int_off(v);
CONTEXT_REGS.REG(eflags) &= ~(VIF_MASK | TF_MASK);
continue;
}
if (VM86_TYPE(vret) != VM86_UNKNOWN)
break;
if (!emulate())
break;
}
debug_info(vret);
return 0;
}
#elif defined(__NetBSD__) || defined(__FreeBSD__) || defined(__OpenBSD__)
#if defined(__NetBSD__) || defined(__OpenBSD__)
static void
vm86_callback(int sig, int code, struct sigcontext *sc)
{
/* Sync our context with what the kernel develivered to us. */
memcpy(&CONTEXT_REGS, sc, sizeof(*sc));
switch (VM86_TYPE(code)) {
case VM86_INTx:
{
unsigned int v = VM86_ARG(code);
if (v == RETURN_TO_32_INT) {
context.success = 1;
longjmp(context.env, 1);
}
pushw(CONTEXT_REGS.REG(eflags));
pushw(CONTEXT_REGS.REG(cs));
pushw(CONTEXT_REGS.REG(eip));
CONTEXT_REGS.REG(cs) = get_int_seg(v);
CONTEXT_REGS.REG(eip) = get_int_off(v);
CONTEXT_REGS.REG(eflags) &= ~(VIF_MASK | TF_MASK);
break;
}
case VM86_UNKNOWN:
if (emulate() == 0) {
context.success = 0;
context.vret = code;
longjmp(context.env, 1);
}
break;
default:
context.success = 0;
context.vret = code;
longjmp(context.env, 1);
return;
}
/* ...and sync our context back to the kernel. */
memcpy(sc, &CONTEXT_REGS, sizeof(*sc));
}
#elif defined(__FreeBSD__)
static void
vm86_callback(int sig, int code, struct sigcontext *sc)
{
unsigned char *addr;
/* Sync our context with what the kernel develivered to us. */
memcpy(&CONTEXT_REGS, sc, sizeof(*sc));
if (code) {
/* XXX probably need to call original signal handler here */
context.success = 0;
context.vret = code;
longjmp(context.env, 1);
}
addr = (unsigned char *)((CONTEXT_REGS.REG(cs) << 4) +
CONTEXT_REGS.REG(eip));
if (addr[0] == 0xcd) { /* int opcode */
if (addr[1] == RETURN_TO_32_INT) {
context.success = 1;
longjmp(context.env, 1);
}
pushw(CONTEXT_REGS.REG(eflags));
pushw(CONTEXT_REGS.REG(cs));
pushw(CONTEXT_REGS.REG(eip));
CONTEXT_REGS.REG(cs) = get_int_seg(addr[1]);
CONTEXT_REGS.REG(eip) = get_int_off(addr[1]);
CONTEXT_REGS.REG(eflags) &= ~(VIF_MASK | TF_MASK);
} else {
if (emulate() == 0) {
context.success = 0;
longjmp(context.env, 1);
}
}
/* ...and sync our context back to the kernel. */
memcpy(sc, &CONTEXT_REGS, sizeof(*sc));
}
#endif /* __FreeBSD__ */
static int
run_vm86(void)
{
if (context.old_sighandler) {
#ifdef LRMI_DEBUG
fprintf(stderr, "run_vm86: callback already installed\n");
#endif
return (0);
}
#if defined(__NetBSD__) || defined(__OpenBSD__)
context.old_sighandler = signal(SIGURG, (void (*)(int))vm86_callback);
#elif defined(__FreeBSD__)
context.old_sighandler = signal(SIGBUS, (void (*)(int))vm86_callback);
#endif
if (context.old_sighandler == (void *)-1) {
context.old_sighandler = NULL;
#ifdef LRMI_DEBUG
fprintf(stderr, "run_vm86: cannot install callback\n");
#endif
return (0);
}
if (setjmp(context.env)) {
#if defined(__NetBSD__) || defined(__OpenBSD__)
(void) signal(SIGURG, context.old_sighandler);
#elif defined(__FreeBSD__)
(void) signal(SIGBUS, context.old_sighandler);
#endif
context.old_sighandler = NULL;
if (context.success)
return (1);
debug_info(context.vret);
return (0);
}
#if defined(__NetBSD__) || defined(__OpenBSD__)
if (i386_vm86(&context.vm) == -1)
return (0);
#elif defined(__FreeBSD__)
if (i386_vm86(VM86_INIT, &context.vm.init))
return 0;
CONTEXT_REGS.REG(eflags) |= PSL_VM | PSL_VIF;
sigreturn(&context.vm.uc);
#endif /* __FreeBSD__ */
/* NOTREACHED */
return (0);
}
#endif /* __NetBSD__ || __FreeBSD__ || __OpenBSD__ */
int
LRMI_call(struct LRMI_regs *r)
{
unsigned int vret;
memset(&CONTEXT_REGS, 0, sizeof(CONTEXT_REGS));
set_regs(r);
CONTEXT_REGS.REG(cs) = r->cs;
CONTEXT_REGS.REG(eip) = r->ip;
if (r->ss == 0 && r->sp == 0) {
CONTEXT_REGS.REG(ss) = context.stack_seg;
CONTEXT_REGS.REG(esp) = context.stack_off;
} else {
CONTEXT_REGS.REG(ss) = r->ss;
CONTEXT_REGS.REG(esp) = r->sp;
}
pushw(context.ret_seg);
pushw(context.ret_off);
vret = run_vm86();
get_regs(r);
return vret;
}
int
LRMI_int(int i, struct LRMI_regs *r)
{
unsigned int vret;
unsigned int seg, off;
seg = get_int_seg(i);
off = get_int_off(i);
/*
If the interrupt is in regular memory, it's probably
still pointing at a dos TSR (which is now gone).
*/
if (seg < 0xa000 || (seg << 4) + off >= 0x100000) {
#ifdef LRMI_DEBUG
fprintf(stderr, "Int 0x%x is not in rom (%04x:%04x)\n", i, seg, off);
#endif
return 0;
}
memset(&CONTEXT_REGS, 0, sizeof(CONTEXT_REGS));
set_regs(r);
CONTEXT_REGS.REG(cs) = seg;
CONTEXT_REGS.REG(eip) = off;
if (r->ss == 0 && r->sp == 0) {
CONTEXT_REGS.REG(ss) = context.stack_seg;
CONTEXT_REGS.REG(esp) = context.stack_off;
} else {
CONTEXT_REGS.REG(ss) = r->ss;
CONTEXT_REGS.REG(esp) = r->sp;
}
pushw(DEFAULT_VM86_FLAGS);
pushw(context.ret_seg);
pushw(context.ret_off);
vret = run_vm86();
get_regs(r);
return vret;
}
#else /* (__linux__ || __NetBSD__ || __FreeBSD__ || __OpenBSD__) && __i386__ */
#warning "LRMI is not supported on your system!"
#endif
|
the_stack_data/115766785.c | #include<stdio.h>
#include<stdlib.h>
typedef struct node {
int data;
struct node *left;
struct node *right;
}NODE;
NODE *root;
NODE * create_root_node(int value){
NODE * r= (NODE *)malloc(sizeof(NODE));
r->data = value;
r->left = '\0';
r->right= '\0';
return r;
}
NODE * search_node(NODE * root, int value){
if (root == '\0'){
printf("%d not exist in the BST\n", value);
return root;
}
if (root->data == value){
printf("%d exist in the BST\n", value);
return root;
}
if (root->data < value){
return search_node(root->right, value);
}
if (root->data > value){
return search_node(root->left, value);
}
}
NODE * insert_node_to_bst(NODE *t, int value){
if (t=='\0'){
return create_root_node(value);
}
if(t->data < value){
t->right = insert_node_to_bst(t->right, value);
}
if(t->data > value){
t->left = insert_node_to_bst(t->left, value);
}
return t;
}
void inorder(NODE *root){
if(root == NULL){
return;
}
inorder(root->left);
printf("%d ->", root->data);
inorder(root->right);
}
void preorder(NODE *root){
if(root == NULL){
return;
}
printf("%d ->", root->data);
preorder(root->left);
preorder(root->right);
}
void postorder(NODE *root){
if(root == NULL){
return;
}
postorder(root->left);
postorder(root->right);
printf("%d ->", root->data);
}
void main(){
int data, n, value, search_item;
printf("\nEnter element to create root node\n");
scanf("%d", &data);
root = create_root_node(data);
printf("\nEnter number of nodes to be added in BST\n");
scanf("%d", &n);
for(int i=0; i<n; i++){
printf("Enter value to be inserted in BST\n");
scanf("%d",&value);
insert_node_to_bst(root, value);
}
printf("Enter value to be search in BST\n");
scanf("%d",&search_item);
search_node(root, search_item);
// printf("\n Inorder BST\n");
// inorder(root);
// printf("\n Postorder BST\n");
// preorder(root);
// printf("\n Preorder BST\n");
// postorder(root);
}
|
the_stack_data/154830637.c | /*
* ****************************************************************************
* Copyright (c) 2013-2021, PyInstaller Development Team.
*
* Distributed under the terms of the GNU General Public License (version 2
* or later) with exception for distributing the bootloader.
*
* The full license is in the file COPYING.txt, distributed with this software.
*
* SPDX-License-Identifier: (GPL-2.0-or-later WITH Bootloader-exception)
* ****************************************************************************
*/
/*
* Handling of Apple Events in macOS windowed (app bundle) mode:
* - argv emulation
* - event forwarding to child process
*/
#if defined(__APPLE__) && defined(WINDOWED)
#include <Carbon/Carbon.h> /* AppleEventsT */
#include <ApplicationServices/ApplicationServices.h> /* GetProcessForPID, etc */
#include "pyi_global.h"
#include "pyi_utils.h"
/* Not declared in modern headers but exists in Carbon libs since time immemorial
* See: https://applescriptlibrary.files.wordpress.com/2013/11/apple-events-programming-guide.pdf */
extern Boolean ConvertEventRefToEventRecord(EventRef inEvent, EventRecord *outEvent);
/*
* On Mac OS X this converts events from kAEOpenDocuments and kAEGetURL into sys.argv.
* After startup, it also forwards kAEOpenDocuments and KAEGetURL events at runtime to the child process.
*
* TODO: The below can be simplified considerably if re-written in Objective C (e.g. put into pyi_utils_osx.m).
*/
/* Static context structure for keeping track of data */
static struct AppleEventHandlerContext
{
/* Event handlers for argv-emu / event forwarding */
Boolean installed; /* Are handlers installed? */
EventHandlerUPP upp_handler; /* UPP for event handler callback */
AEEventHandlerUPP upp_handler_ae; /* UPP for AppleEvent handler callback */
EventHandlerRef handler_ref; /* Reference to installer event handler */
} _ae_ctx = {
false, /* installed */
NULL, /* handler */
NULL, /* handler_ae */
NULL, /* handler_ref */
};
/* Event types list: used to register handler and to listen for events */
static const EventTypeSpec event_types_ae[] = {
{ kEventClassAppleEvent, kEventAppleEvent },
};
/* Convert a FourCharCode into a string (useful for debug). Returned buffer is a static buffer, so subsequent calls
* may overwrite the same buffer. */
static const char *CC2Str(FourCharCode code) {
/* support up to 3 calls on the same debug print line */
static char bufs[3][5];
static unsigned int bufsidx = 0;
char *buf = bufs[bufsidx++ % 3u];
snprintf(buf, 5, "%c%c%c%c", (code >> 24) & 0xFF, (code >> 16) & 0xFF, (code >> 8) & 0xFF, code & 0xFF);
/* buffer is guaranteed to be nul terminated here */
return buf;
}
/* Generic event forwarder -- forwards an event destined for this process to the child process,
* copying its param object, if any. Parameter `theAppleEvent` may be NULL, in which case a new
* event is created with the specified class and id (containing 0 params / no param object). */
static OSErr generic_forward_apple_event(const AppleEvent *const theAppleEvent /* NULL ok */,
const AEEventClass eventClass, const AEEventID evtID,
const char *const descStr)
{
const FourCharCode evtCode = (FourCharCode)evtID;
OSErr err;
AppleEvent childEvent;
AEAddressDesc target;
DescType actualType = 0, typeCode = typeWildCard;
char *buf = NULL; /* dynamic buffer to hold copied event param data */
Size bufSize = 0, actualSize = 0;
pid_t child_pid;
VS("LOADER [AppleEvent]: Forwarder called for \"%s\".\n", descStr);
child_pid = pyi_utils_get_child_pid();
if (!child_pid) {
/* Child not up yet -- there is no way to "forward" this before child started!. */
VS("LOADER [AppleEvent]: Child not up yet (child_pid is 0)\n");
return errAEEventNotHandled;
}
VS("LOADER [AppleEvent]: Forwarding '%s' event.\n", CC2Str(evtCode));
err = AECreateDesc(typeKernelProcessID, &child_pid, sizeof(child_pid), &target);
if (err != noErr) {
OTHERERROR("LOADER [AppleEvent]: Failed to create AEAddressDesc: %d\n", (int)err);
goto out;
}
VS("LOADER [AppleEvent]: Created AEAddressDesc.\n");
err = AECreateAppleEvent(eventClass, evtID, &target, kAutoGenerateReturnID, kAnyTransactionID,
&childEvent);
if (err != noErr) {
OTHERERROR("LOADER [AppleEvent]: Failed to create event copy: %d\n", (int)err);
goto release_desc;
}
VS("LOADER [AppleEvent]: Created AppleEvent instance for child process.\n");
if (!theAppleEvent) {
/* Calling code wants a new event created from scratch, we do so
* here and it will have 0 params. Assumption: caller knows that
* the event type in question normally has 0 params. */
VS("LOADER [AppleEvent]: New AppleEvent class: '%s' code: '%s'\n",
CC2Str((FourCharCode)eventClass), CC2Str((FourCharCode)evtID));
} else {
err = AESizeOfParam(theAppleEvent, keyDirectObject, &typeCode, &bufSize);
if (err != noErr) {
/* No params for this event */
VS("LOADER [AppleEvent]: Failed to get size of param (error=%d) -- event '%s' may lack params.\n",
(int)err, CC2Str(evtCode));
} else {
/* This event has a param object, copy it. */
VS("LOADER [AppleEvent]: Got size of param: %ld\n", (long)bufSize);
buf = malloc(bufSize);
if (!buf) {
/* Failed to allocate buffer! */
OTHERERROR("LOADER [AppleEvent]: Failed to allocate buffer of size %ld: %s\n",
(long)bufSize, strerror(errno));
goto release_evt;
}
VS("LOADER [AppleEvent]: Allocated buffer of size: %ld\n", (long)bufSize);
VS("LOADER [AppleEvent]: Getting param.\n");
err = AEGetParamPtr(theAppleEvent, keyDirectObject, typeWildCard,
&actualType, buf, bufSize, &actualSize);
if (err != noErr) {
OTHERERROR("LOADER [AppleEvent]: Failed to get param data.\n");
goto release_evt;
}
if (actualSize > bufSize) {
/* From reading the Apple API docs, this should never happen, but it pays
* to program defensively here. */
OTHERERROR("LOADER [AppleEvent]: Got param size=%ld > bufSize=%ld, error!\n",
(long)actualSize, (long)bufSize);
goto release_evt;
}
VS("LOADER [AppleEvent]: Got param type=%x ('%s') size=%ld\n",
(UInt32)actualType, CC2Str((FourCharCode)actualType), (long)actualSize);
VS("LOADER [AppleEvent]: Putting param.\n");
err = AEPutParamPtr(&childEvent, keyDirectObject, actualType, buf, actualSize);
if (err != noErr) {
OTHERERROR("LOADER [AppleEvent]: Failed to put param data.\n");
goto release_evt;
}
}
}
VS("LOADER [AppleEvent]: Sending message...\n");
err = AESendMessage(&childEvent, NULL, kAENoReply, kAEDefaultTimeout);
VS("LOADER [AppleEvent]: Handler sent \"%s\" message to child pid %ld.\n", descStr, (long)child_pid);
/* In onefile build, we may encounter a race condition between parent
* and child process, because child_pid becomes valid immediately after
* fork, but the child process may not be able to receive the events yet.
* In such cases, AESendMessage fails with procNotFound (-600). Accommodate
* such cases with 10 retries, spaced 0.5 second apart (for 5 seconds
* of total retry time) */
if (err == procNotFound) {
int retry = 0;
while (err == procNotFound && retry++ < 5) {
VS("LOADER [AppleEvent]: Sending failed with procNotFound; re-trying in 1 second (attempt %d)\n", retry);
usleep(500000); /* sleep 0.5 second (kAENoReply = no timeout) */
err = AESendMessage(&childEvent, NULL, kAENoReply, kAEDefaultTimeout);
}
}
release_evt:
free(buf);
AEDisposeDesc(&childEvent);
release_desc:
AEDisposeDesc(&target);
out:
return err;
}
static Boolean realloc_checked(void **bufptr, Size size)
{
void *tmp = realloc(*bufptr, size);
if (!tmp) {
OTHERERROR("LOADER [AppleEvents]: Failed to allocate a buffer of size %ld.\n", (long)size);
return false;
}
VS("LOADER [AppleEvents]: (re)allocated a buffer of size %ld\n", (long)size);
*bufptr = tmp;
return true;
}
/* Handles apple events 'odoc' and 'GURL', both before and after the child_pid is up, Copying them to argv if child
* not up yet, or otherwise forwarding them to the child if the child is started. */
static OSErr handle_odoc_GURL_events(const AppleEvent *theAppleEvent, const AEEventID evtID)
{
const FourCharCode evtCode = (FourCharCode)evtID;
const Boolean apple_event_is_open_doc = evtID == kAEOpenDocuments;
const char *const descStr = apple_event_is_open_doc ? "OpenDoc" : "GetURL";
VS("LOADER [AppleEvent]: %s handler called.\n", descStr);
if (!pyi_utils_get_child_pid()) {
/* Child process is not up yet -- so we pick up kAEOpen and/or kAEGetURL events and append them to argv. */
AEDescList docList;
OSErr err;
long index;
long count = 0;
char *buf = NULL; /* Dynamic buffer for URL/file path data -- gets realloc'd as we iterate */
VS("LOADER [AppleEvent ARGV_EMU]: Processing args for forward...\n");
err = AEGetParamDesc(theAppleEvent, keyDirectObject, typeAEList, &docList);
if (err != noErr) return err;
err = AECountItems(&docList, &count);
if (err != noErr) return err;
for (index = 1; index <= count; ++index) /* AppleEvent lists are 1-indexed (I guess because of Pascal?) */
{
DescType returnedType;
AEKeyword keywd;
Size actualSize = 0, bufSize = 0;
DescType typeCode = typeWildCard;
err = AESizeOfNthItem(&docList, index, &typeCode, &bufSize);
if (err != noErr) {
OTHERERROR("LOADER [AppleEvent ARGV_EMU]: Failed to get size of Nth item %ld, error: %d\n",
index, (int)err);
continue;
}
if (!realloc_checked((void **)&buf, bufSize+1)) {
/* Not enough memory -- very unlikely but if so keep going */
OTHERERROR("LOADER [AppleEvent ARGV_EMU]: Not enough memory for Nth item %ld, skipping%d\n", index);
continue;
}
err = AEGetNthPtr(&docList, index, apple_event_is_open_doc ? typeFileURL : typeUTF8Text, &keywd,
&returnedType, buf, bufSize, &actualSize);
if (err != noErr) {
VS("LOADER [AppleEvent ARGV_EMU]: err[%ld] = %d\n", index-1L, (int)err);
} else if (actualSize > bufSize) {
/* This should never happen but is here for thoroughness */
VS("LOADER [AppleEvent ARGV_EMU]: err[%ld]: not enough space in buffer (%ld > %ld)\n",
index-1L, (long)actualSize, (long)bufSize);
} else {
/* Copied data to buf, now ensure data is a simple file path and then append it to argv_pyi */
char *tmp_str = NULL;
Boolean ok;
buf[actualSize] = 0; /* Ensure NUL-char termination. */
if (apple_event_is_open_doc) {
/* Now, convert file:/// style URLs to an actual filesystem path for argv emu. */
CFURLRef url = CFURLCreateWithBytes(NULL, (UInt8 *)buf, actualSize, kCFStringEncodingUTF8,
NULL);
if (url) {
CFStringRef path = CFURLCopyFileSystemPath(url, kCFURLPOSIXPathStyle);
ok = false;
if (path) {
const Size newLen = (Size)CFStringGetMaximumSizeOfFileSystemRepresentation(path);
if (realloc_checked((void **)&buf, newLen+1)) {
bufSize = newLen;
ok = CFStringGetFileSystemRepresentation(path, buf, bufSize);
buf[bufSize] = 0; /* Ensure NUL termination */
}
CFRelease(path); /* free */
}
CFRelease(url); /* free */
if (!ok) {
VS("LOADER [AppleEvent ARGV_EMU]: "
"Failed to convert file:/// path to POSIX filesystem representation for arg %ld!\n",
index);
continue;
}
}
}
/* Append URL to argv_pyi array, reallocating as necessary */
VS("LOADER [AppleEvent ARGV_EMU]: appending '%s' to argv_pyi\n", buf);
if (pyi_utils_append_to_args(buf) < 0) {
OTHERERROR("LOADER [AppleEvent ARGV_EMU]: failed to append to argv_pyi: %s\n",
buf, strerror(errno));
} else {
VS("LOADER [AppleEvent ARGV_EMU]: argv entry appended.\n");
}
}
}
free(buf); /* free of possible-NULL ok */
err = AEDisposeDesc(&docList);
return err;
} /* else ... */
/* The child process exists.. so we forward events to it */
return generic_forward_apple_event(theAppleEvent,
apple_event_is_open_doc ? kCoreEventClass : kInternetEventClass,
evtID,
descStr);
}
/* This brings the child process's windows to the foreground when the user double-clicks the
* app's icon again in the macOS UI. 'rapp' is accepted by us only when the child is
* already running. */
static OSErr handle_rapp_event(const AppleEvent *const theAppleEvent, const AEEventID evtID)
{
OSErr err;
VS("LOADER [AppleEvent]: ReopenApp handler called.\n");
/* First, forward the 'rapp' event to the child */
err = generic_forward_apple_event(theAppleEvent, kCoreEventClass, evtID, "ReopenApp");
if (err == noErr) {
/* Next, create a new activate ('actv') event. We never receive this event because
* we have no window, but if we did this event would come next. So we synthesize an
* event that should normally come for a windowed app, so that the child process
* is brought to the foreground properly. */
generic_forward_apple_event(NULL /* create new event with 0 params */,
kAEMiscStandards, kAEActivate, "Activate");
}
return err;
}
/* Top-level event handler -- dispatches 'odoc', 'GURL', 'rapp', or 'actv' events. */
static pascal OSErr handle_apple_event(const AppleEvent *theAppleEvent, AppleEvent *reply, SRefCon handlerRefCon)
{
const FourCharCode evtCode = (FourCharCode)(intptr_t)handlerRefCon;
const AEEventID evtID = (AEEventID)(intptr_t)handlerRefCon;
(void)reply; /* unused */
VS("LOADER [AppleEvent]: %s called with code '%s'.\n", __FUNCTION__, CC2Str(evtCode));
switch(evtID) {
case kAEOpenApplication:
/* Nothing to do here, just make sure we report event as handled. */
return noErr;
case kAEOpenDocuments:
case kAEGetURL:
return handle_odoc_GURL_events(theAppleEvent, evtID);
case kAEReopenApplication:
return handle_rapp_event(theAppleEvent, evtID);
case kAEActivate:
/* This is not normally reached since the bootloader process lacks a window, and it
* turns out macOS never sends this event to processes lacking a window. However,
* since the Apple API docs are very sparse, this has been left-in here just in case. */
return generic_forward_apple_event(theAppleEvent, kAEMiscStandards, evtID, "Activate");
default:
/* Not 'GURL', 'odoc', 'rapp', or 'actv' -- this is not reached unless there is a
* programming error in the code that sets up the handler(s) in pyi_process_apple_events. */
OTHERERROR("LOADER [AppleEvent]: %s called with unexpected event type '%s'!\n",
__FUNCTION__, CC2Str(evtCode));
return errAEEventNotHandled;
}
}
/* This function gets installed as the process-wide UPP event handler.
* It is responsible for dequeuing events and telling Carbon to forward
* them to our installed handlers. */
static OSStatus evt_handler_proc(EventHandlerCallRef href, EventRef eref, void *data) {
VS("LOADER [AppleEvent]: App event handler proc called.\n");
Boolean release = false;
EventRecord eventRecord;
OSStatus err;
/* Events of type kEventAppleEvent must be removed from the queue
* before being passed to AEProcessAppleEvent. */
if (IsEventInQueue(GetMainEventQueue(), eref)) {
/* RemoveEventFromQueue will release the event, which will
* destroy it if we don't retain it first. */
VS("LOADER [AppleEvent]: Event was in queue, will release.\n");
RetainEvent(eref);
release = true;
RemoveEventFromQueue(GetMainEventQueue(), eref);
}
/* Convert the event ref to the type AEProcessAppleEvent expects. */
ConvertEventRefToEventRecord(eref, &eventRecord);
VS("LOADER [AppleEvent]: what=%hu message=%lx ('%s') modifiers=%hu\n",
eventRecord.what, eventRecord.message, CC2Str((FourCharCode)eventRecord.message), eventRecord.modifiers);
/* This will end up calling one of the callback functions
* that we installed in pyi_process_apple_events() */
err = AEProcessAppleEvent(&eventRecord);
if (err == errAEEventNotHandled) {
VS("LOADER [AppleEvent]: Ignored event.\n");
} else if (err != noErr) {
VS("LOADER [AppleEvent]: Error processing event: %d\n", (int)err);
}
if (release) {
ReleaseEvent(eref);
}
return noErr;
}
/*
* Install Apple Event handlers. The handlers must be install prior to
* calling pyi_apple_process_events().
*/
int pyi_apple_install_event_handlers()
{
OSStatus err;
/* Already installed; nothing to do */
if (_ae_ctx.installed) {
return 0;
}
VS("LOADER [AppleEvent]: Installing event handlers...\n");
/* Allocate UPP (universal procedure pointer) for handler functions */
_ae_ctx.upp_handler = NewEventHandlerUPP(evt_handler_proc);
_ae_ctx.upp_handler_ae = NewAEEventHandlerUPP(handle_apple_event);
/* Register Apple Event handlers */
/* 'oapp' (open application) */
err = AEInstallEventHandler(kCoreEventClass, kAEOpenApplication, _ae_ctx.upp_handler_ae, (SRefCon)kAEOpenApplication, false);
if (err != noErr) {
goto end;
}
/* 'odoc' (open document) */
err = AEInstallEventHandler(kCoreEventClass, kAEOpenDocuments, _ae_ctx.upp_handler_ae, (SRefCon)kAEOpenDocuments, false);
if (err != noErr) {
goto end;
}
/* 'GURL' (open url) */
err = AEInstallEventHandler(kInternetEventClass, kAEGetURL, _ae_ctx.upp_handler_ae, (SRefCon)kAEGetURL, false);
if (err != noErr) {
goto end;
}
/* 'rapp' (re-open application) */
err = AEInstallEventHandler(kCoreEventClass, kAEReopenApplication, _ae_ctx.upp_handler_ae, (SRefCon)kAEReopenApplication, false);
if (err != noErr) {
goto end;
}
/* register 'actv' (activate) */
err = AEInstallEventHandler(kAEMiscStandards, kAEActivate, _ae_ctx.upp_handler_ae, (SRefCon)kAEActivate, false);
if (err != noErr) {
goto end;
}
/* Install application event handler */
err = InstallApplicationEventHandler(_ae_ctx.upp_handler, 1, event_types_ae, NULL, &_ae_ctx.handler_ref);
end:
if (err != noErr) {
/* Failed to install one of AE handlers or application event handler.
* Remove everything. */
AERemoveEventHandler(kAEMiscStandards, kAEActivate, _ae_ctx.upp_handler_ae, false);
AERemoveEventHandler(kCoreEventClass, kAEReopenApplication, _ae_ctx.upp_handler_ae, false);
AERemoveEventHandler(kInternetEventClass, kAEGetURL, _ae_ctx.upp_handler_ae, false);
AERemoveEventHandler(kCoreEventClass, kAEOpenDocuments, _ae_ctx.upp_handler_ae, false);
AERemoveEventHandler(kCoreEventClass, kAEOpenApplication, _ae_ctx.upp_handler_ae, false);
DisposeEventHandlerUPP(_ae_ctx.upp_handler);
DisposeAEEventHandlerUPP(_ae_ctx.upp_handler_ae);
OTHERERROR("LOADER [AppleEvent]: Failed to install event handlers!\n");
return -1;
}
VS("LOADER [AppleEvent]: Installed event handlers.\n");
_ae_ctx.installed = true;
return 0;
}
/*
* Uninstall Apple Event handlers.
*/
int pyi_apple_uninstall_event_handlers()
{
/* Not installed; nothing to do */
if (!_ae_ctx.installed) {
return 0;
}
VS("LOADER [AppleEvent]: Uninstalling event handlers...\n");
/* Remove application event handler */
RemoveEventHandler(_ae_ctx.handler_ref);
_ae_ctx.handler_ref = NULL;
/* Remove Apple Event handlers */
AERemoveEventHandler(kAEMiscStandards, kAEActivate, _ae_ctx.upp_handler_ae, false);
AERemoveEventHandler(kCoreEventClass, kAEReopenApplication, _ae_ctx.upp_handler_ae, false);
AERemoveEventHandler(kInternetEventClass, kAEGetURL, _ae_ctx.upp_handler_ae, false);
AERemoveEventHandler(kCoreEventClass, kAEOpenDocuments, _ae_ctx.upp_handler_ae, false);
AERemoveEventHandler(kCoreEventClass, kAEOpenApplication, _ae_ctx.upp_handler_ae, false);
/* Cleanup UPPs */
DisposeEventHandlerUPP(_ae_ctx.upp_handler);
DisposeAEEventHandlerUPP(_ae_ctx.upp_handler_ae);
_ae_ctx.upp_handler = NULL;
_ae_ctx.upp_handler_ae = NULL;
_ae_ctx.installed = false;
VS("LOADER [AppleEvent]: Uninstalled event handlers.\n");
return 0;
}
/*
* Apple event message pump; retrieves and processes Apple Events until
* the specified timeout (in seconds) or an error is reached.
*/
void pyi_apple_process_events(float timeout)
{
/* No-op if we failed to install event handlers */
if (!_ae_ctx.installed) {
return;
}
VS("LOADER [AppleEvent]: Processing Apple Events...\n");
/* Event pump: process events until timeout (in seconds) or error */
for (;;) {
OSStatus status;
EventRef event_ref; /* Event that caused ReceiveNextEvent to return. */
VS("LOADER [AppleEvent]: Calling ReceiveNextEvent\n");
status = ReceiveNextEvent(1, event_types_ae, timeout, kEventRemoveFromQueue, &event_ref);
if (status == eventLoopTimedOutErr) {
VS("LOADER [AppleEvent]: ReceiveNextEvent timed out\n");
break;
} else if (status != 0) {
VS("LOADER [AppleEvent]: ReceiveNextEvent fetching events failed\n");
break;
} else {
/* We actually pulled an event off the queue, so process it.
We now 'own' the event_ref and must release it. */
VS("LOADER [AppleEvent]: ReceiveNextEvent got an EVENT\n");
VS("LOADER [AppleEvent]: Dispatching event...\n");
status = SendEventToEventTarget(event_ref, GetEventDispatcherTarget());
ReleaseEvent(event_ref);
event_ref = NULL;
if (status != 0) {
VS("LOADER [AppleEvent]: processing events failed\n");
break;
}
}
}
VS("LOADER [AppleEvent]: Out of the event loop.\n");
}
/*
* Submit oapp (open application) event to ourselves. This is an attempt
* to mitigate the issues with some UI frameworks (Tcl/Tk, in particular)
* that are causes by argv-emu being enabled in onedir mode. In this case,
* argv-emu swallows initial activation event (usually oapp; or odoc/GURL
* if launched via file/url open request). This function attempts to
* mitigate that by submitting a manual oapp event to itself so that the
* UI framework finds the activation even in the event queue, as if no
* Apple Event processing took place in the bootloader.
*/
void pyi_apple_submit_oapp_event()
{
AppleEvent event = {typeNull, nil};
AEAddressDesc target = {typeNull, nil};
EventRef event_ref;
ProcessSerialNumber psn;
OSErr err;
VS("LOADER [AppleEvent]: Submitting 'oapp' event...\n");
// Get PSN via GetCurrentProcess. This function is deprecated, but
// we cannot use {0, kCurrentProcess} because we need our event
// to be queued.
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
#endif
err = GetCurrentProcess(&psn);
#ifdef __clang__
#pragma clang diagnostic pop
#endif
if (err != noErr) {
OTHERERROR("LOADER [AppleEvent]: Failed to obtain PSN: %d\n", (int)err);
goto cleanup;
}
// Create target address using the PSN, ...
err = AECreateDesc(typeProcessSerialNumber, &psn, sizeof(psn), &target);
if (err != noErr) {
OTHERERROR("LOADER [AppleEvent]: Failed to create AEAddressDesc: %d\n", (int)err);
goto cleanup;
}
// ... create OAPP event, ...
err = AECreateAppleEvent(kCoreEventClass, kAEOpenApplication, &target, kAutoGenerateReturnID, kAnyTransactionID, &event);
if (err != noErr) {
OTHERERROR("LOADER [AppleEvent]: Failed to create OAPP event: %d\n", (int)err);
goto cleanup;
}
// ... and send it
err = AESendMessage(&event, NULL, kAENoReply, 60 /* 60 = about 1.0 seconds timeout */);
if (err != noErr) {
OTHERERROR("LOADER [AppleEvent]: Failed to send event: %d\n", (int)err);
goto cleanup;
} else {
VS("LOADER [AppleEvent]: Submitted 'oapp' event.\n");
}
// Now wait for the event to show up in event queue (this implicitly
// assumes that no other activation event shows up, but those would
// also solve the problem we are trying to mitigate).
VS("LOADER [AppleEvent]: Waiting for 'oapp' event to show up in queue...\n");
err = ReceiveNextEvent(1, event_types_ae, 10.0, kEventLeaveInQueue, &event_ref);
if (err != noErr) {
OTHERERROR("LOADER [AppleEvent]: Timed out while waiting for submitted 'oapp' event to show up in queue!\n");
} else {
VS("LOADER [AppleEvent]: Submitted 'oapp' event is available in the queue.\n");
}
cleanup:
AEDisposeDesc(&event);
AEDisposeDesc(&target);
return;
}
#endif /* if defined(__APPLE__) && defined(WINDOWED) */
|
the_stack_data/187643482.c | /*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*/
#if defined(TARGET_ARM64)
#include "mth_intrinsics.h"
vrs4_t
__gs_tanh_4(vrs4_t x)
{
return (__ZGVxN4v__mth_i_vr4(x, __mth_i_tanh));
}
vrs4_t
__gs_tanh_4m(vrs4_t x, vis4_t mask)
{
return (__ZGVxM4v__mth_i_vr4(x, mask, __mth_i_tanh));
}
vcs1_t
__gc_tanh_1(vcs1_t x)
{
return (__ZGVxN1v__mth_i_vc4(x, ctanhf));
}
vcs2_t
__gc_tanh_2(vcs2_t x)
{
return (__ZGVxN2v__mth_i_vc4(x, ctanhf));
}
#endif
|
the_stack_data/126703540.c | /*BEGIN_LEGAL
Intel Open Source License
Copyright (c) 2002-2014 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>
int main()
{
printf(".");
return 0;
}
|
the_stack_data/207633.c | #include <stdio.h>
#define p(a) x##a
int main(int argc, char const *argv[])
{
int x3 = 1;
printf("%d\n", p(3));
return 0;
} |
the_stack_data/232955628.c | // LANGUAGE: C
// ENV: C
// AUTHOR: Naomichi Kubota
// GITHUB: "https://github.com/Nao000"
#include <stdio.h>
int main(void){
printf("hello world");
return 0;
}
|
the_stack_data/102680.c | #include <stdio.h>
#include <stdlib.h>
static int data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
static int size = 10;
int binSearch(int element) {
int min = 0,
max = size - 1;
while (min <= max) {
int mid = (min + max) / 2;
if (element == data[mid])
return mid;
else if (element < data[mid])
max = mid - 1;
else min = mid + 1;
}
return -1;
}
int main(int argc, char *argv[]) {
int i = 0;
do {
printf("Element %i is at location %i\n", i, binSearch(i));
} while(++i < size);
int result = 0;
for (int k = 0; k < 1000000; k++) {
result += binSearch(k); // add to result to prevent call from being optimized away
}
printf("Interim result: %i\n", result);
for (int k = 0; k < 1000000; k++) {
result -= binSearch(k); // add to result to prevent call from being optimized away
}
printf("Done: %i\n", result);
return 0;
}
|
the_stack_data/51700572.c | #include <stdio.h>
#define MAX_WORD_LENGTH 1002
int main()
{
FILE *from, *to;
char word[MAX_WORD_LENGTH] = {'\0'};
int len = 0, num_word_a = 0;
char c;
from = fopen("input.txt", "r");
to = fopen("output.txt", "w");
while((c = fgetc(from)) != EOF && c != '\n') {
if (c == ' ') {
if (word[len-1] == 'a') {
num_word_a++;
}
word[len] = '\0';
len = 0;
} else {
word[len++] = c;
}
}
if (len > 0) {
if (word[len-1] == 'a') {
num_word_a++;
}
}
fprintf(to, "%i", num_word_a);
fclose(to);
fclose(from);
}
|
the_stack_data/64199433.c | #define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mymutex2 = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
pthread_mutex_t mymutex3 = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
void *thread_function(void *arg) {
int i = *(int*)(arg);
printf("thread_function %d.\n", i);
if (i == 1) {
pthread_mutex_lock(&mymutex);
printf("mymutex lock success 1.\n");
pthread_mutex_unlock(&mymutex);
pthread_mutex_destroy(&mymutex);
int r = pthread_mutex_lock(&mymutex);
printf("mymutex lock success 2 %d.\n", r);
}
if (i == 2) {
pthread_mutex_lock(&mymutex2);
printf("mymutex2 lock success 1.\n");
pthread_mutex_lock(&mymutex2);
printf("mymutex2 lock success 2.\n");
pthread_mutex_unlock(&mymutex2);
}
if (i == 3) {
pthread_mutex_lock(&mymutex3);
printf("mymutex3 lock success 1.\n");
pthread_mutex_lock(&mymutex3);
printf("mymutex3 lock success 2.\n");
pthread_mutex_unlock(&mymutex3);
}
return NULL;
}
int main(void) {
pthread_t tids1;
pthread_t tids2;
pthread_t tids3;
int i = 1, j = 2, k = 3;
if (pthread_create(&tids1, NULL, thread_function, &i) ) {
printf("error creating thread.");
abort();
}
if (pthread_create(&tids2, NULL, thread_function, &j) ) {
printf("error creating thread.");
abort();
}
if (pthread_create(&tids3, NULL, thread_function, &k) ) {
printf("error creating thread.");
abort();
}
if (pthread_join(tids1, NULL)) {
printf("error joining thread %d\n.", tids1);
abort();
}
if (pthread_join(tids2, NULL)) {
printf("error joining thread %d\n.", tids2);
abort();
}
if (pthread_join(tids3, NULL)) {
printf("error joining thread %d\n.", tids3);
abort();
}
// printf("\nmyglobal equals %d\n",myglobal);
return 0;
}
int func() {
char v11[100] = "/data/data/com.netmarble.sknightsgb/files/Resources/GameSettings.txt";
char *v37[1024];
char *v38[1024];
char* v13;
char *v36 = NULL;
int v12 = 0;
printf("----\n");
v37[0] = strtok_r(v11, "/", &v36);
printf("v37[0] :%s\n", v37[0]);
do {
v13 = strtok_r(0, "/", &v36);
printf("v13 :%s\n", v13);
v37[v12++ + 1] = v13;
} while (v13);
printf("v11 :%s\n", v11);
return 0;
}
// #include <stdio.h>
// #include <string.h>
//
// int main(void)
// {
// int j,in = 0;
// char buffer[100] = "Fred male 25,John male 62,Anna female 16";
// char *p[20];
// char *buf = buffer;
// char *outer_ptr = NULL;
// char *inner_ptr = NULL;
// while ((p[in] = strtok_r(buf, ",", &outer_ptr)) != NULL)
// {
// buf = p[in];
// while ((p[in] = strtok_r(buf, " ", &inner_ptr)) != NULL)
// {
// in++;
// buf = NULL;
// }
// buf = NULL;
// }
// printf("Here we have %d strings\n", in);
// for (j = 0; j < in; j++)
// {
// printf(">%s<\n", p[j]);
// }
// return 0;
// }
|
the_stack_data/126701958.c | // Program for reading DHT11 temperature/humidity sensor data on the NTC CHIP.
// Uses sysfs for reading, so may sometimes fail due to timing issues. Recommend
// running with a very aggressive nice value to mitigate this.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
// open(2)/close(2)
#include <fcntl.h>
// pread/pwrite
#define _XOPEN_SOURCE 500
#include <unistd.h>
#define BUFSIZE 256
typedef struct GPIO {
// We keep that as a char here because everything that needs to interact with
// it uses strings, so there's no point in turning it from a string to an int
// when parsing argv and then back into a string everywhere we use it.
const char* pin;
// FDs for pin direction (write-only) and value (read-write).
int direction;
int value;
} GPIO;
typedef enum GPIO_DIRECTION {
IN = 0,
OUT = 1,
} GPIO_DIRECTION;
void GPIO_direction(GPIO* gpio, GPIO_DIRECTION dir) {
if (dir == IN) {
pwrite(gpio->direction, "in", 2, 0);
} else {
pwrite(gpio->direction, "out", 3, 0);
}
}
uint8_t GPIO_read(GPIO* gpio) {
char buf;
pread(gpio->value, &buf, 1, 0);
return buf == '1';
}
void GPIO_write(GPIO* gpio, uint8_t val) {
static const char vals[] = { '0', '1' };
pwrite(gpio->value, &vals[val], 1, 0);
}
// Open a file, write the string to it, and close it. Don't use in performance-
// sensitive code!
int tryWrite(const char* path, const char* buf) {
FILE* fd = fopen(path, "wb");
if (!fd) {
perror(path);
return 0;
}
if (fprintf(fd, "%s", buf) < 0) {
perror(path);
fclose(fd);
return 0;
}
if (fclose(fd) < 0) {
perror(path);
return 0;
}
return 1;
}
// Open the GPIO pin with the given pin identifier.
// On success, returns nonzero and initializes *gpio for use.
// On failure, outputs an error message, returns 0, and leaves *gpio in an
// unspecified but invalid state.
int GPIO_open(GPIO* gpio, const char* pin) {
static char buf[BUFSIZE];
if (!tryWrite("/sys/class/gpio/export", pin)) {
return 0;
}
snprintf(buf, BUFSIZE, "/sys/class/gpio/gpio%s/direction", pin);
gpio->direction = open(buf, O_WRONLY);
if (gpio->direction < 0) {
perror(buf);
return 0;
}
snprintf(buf, BUFSIZE, "/sys/class/gpio/gpio%s/value", pin);
gpio->value = open(buf, O_RDWR);
if (gpio->value < 0) {
perror(buf);
close(gpio->direction);
return 0;
}
gpio->pin = pin;
return 1;
}
// Shut down a GPIO handle.
int GPIO_close(GPIO* gpio) {
int errors = 0;
if (close(gpio->direction) < 0) {
perror("Closing GPIO direction channel");
++errors;
}
if (close(gpio->value) < 0) {
perror("Closing GPIO value channel");
++errors;
}
gpio->value = gpio->direction = -1;
if (!tryWrite("/sys/class/gpio/unexport", gpio->pin)) {
perror("Unexporting GPIO");
++errors;
}
gpio->pin = NULL;
return !errors;
}
// Wait for the given GPIO to have the corresponding val.
// Waits for at most 255 cycles. Returns the number of cycles waited, or 0 if
// we exceed that limit.
int GPIO_wait(GPIO* gpio, uint8_t val) {
for (uint8_t us = 0; us < 32; ++us) {
if (GPIO_read(gpio) == val) return us;
}
return 0;
}
uint8_t DHT11_read_byte(GPIO* gpio) {
uint8_t byte = 0;
GPIO_wait(gpio, 0);
for (int i = 0; i < 8; ++i) {
// wait for end of lead-in
GPIO_wait(gpio, 1);
// measure size of payload
unsigned int cycles = GPIO_wait(gpio, 0);
// 4 cycles is a good cutoff for running on the CHIP compiled with -O0 -g
// it's 1-2 for 0 and 5-6 for 1
byte = (byte << 1) | (cycles >= 4);
}
return byte;
}
// The DHT11 uses a custom one-wire protocol.
// The host initiates a read by pulling the pin low for at least 18ms, then
// high for 20-40us, then lets it float.
// The guest responds by pulling it low for 80us, then high for 80us, then
// sending 40 bits of data.
// Each bit consists of 50us of lead-in where the line is pulled low, then
// a payload where it is pulled high for 27us (0) or 70us (1).
// When the transmission is complete it pulls it low for 50us and then pulls
// it high until the next transmission.
// If after attempting to initiate a read the connection remains high, something
// has gone wrong.
int readDHT11Frame(GPIO* gpio, float* temperature, float* humidity) {
*temperature = 0.0f;
*humidity = 0.0f;
// send initial request to communicate: _18ms ^20us -float
GPIO_direction(gpio, OUT);
GPIO_write(gpio, 0);
usleep(20*1000);
GPIO_write(gpio, 1);
usleep(20);
GPIO_direction(gpio, IN);
// The DHT11 is meant to hold it low for 80us, then high for 80us, before
// sending the first bit. In practice if we look for this header we miss the
// first bit -- maybe setting the direction to IN takes too long?
// if (!GPIO_wait(gpio, 0)) return 0; // should go to 0 ~immediately
// if (!GPIO_wait(gpio, 1)) return 0; // then stay low for 80us
// if (!GPIO_wait(gpio, 0)) return 0; // then stay high for 80us
// once it goes back to 0 we're into the lead-in
uint8_t humidity_h, humidity_l, temperature_h, temperature_l, check;
humidity_h = DHT11_read_byte(gpio);
humidity_l = DHT11_read_byte(gpio);
temperature_h = DHT11_read_byte(gpio);
temperature_l = DHT11_read_byte(gpio);
check = DHT11_read_byte(gpio);
if (check != ((humidity_h + humidity_l + temperature_h + temperature_l) & 0xFF)) {
// checksum failure
return 0;
}
*humidity = humidity_h + (humidity_l / 10.0);
*temperature = temperature_h + (temperature_l / 10.0);
// printf("DHT11 frame read complete: %d %d %d %d %d\n", humidity_h, humidity_l, temperature_h, temperature_l, check);
if (humidity_h == 0 && temperature_h == 0) return 0; // if we get all zeroes, the checksum will pass but it was not a good read
return 1;
}
int main(int argc, const char** argv) {
if (argc < 2) {
fprintf(stderr, "Usage: dht11-read <pin-id>\n");
return 1;
}
const char* pin = argv[1];
GPIO gpio;
if (!GPIO_open(&gpio, pin)) return 2;
float temperature, humidity;
for (int i = 0; i < 16; ++i) {
// Retry a bunch of times until we successfully read from it.
if (readDHT11Frame(&gpio, &temperature, &humidity)) {
printf("temperature\t%f\n", temperature);
printf("humidity\t%f\n", humidity);
if (!GPIO_close(&gpio)) return 4;
return 0;
}
usleep(10000);
}
printf("Error reading from DHT11\n");
if (!GPIO_close(&gpio)) return 4;
return 8;
}
|
the_stack_data/115765815.c | // Copyright (c) 2015 by Silicon Laboratories Inc. All rights reserved.
//
// http://developer.silabs.com/legal/version/v11/Silicon_Labs_Software_License_Agreement.txt
// With modifications by:
// jem@seethis (c) 2018
/*********************************************************************
* GetStatus *
*********************************************************************/
#if 0
static USB_Status_TypeDef GetStatus(void)
{
USB_Status_TypeDef retVal = USB_STATUS_REQ_ERR;
if ((setup.wLength == 2)
&& (setup.wValue == 0)
&& (setup.bmRequestType.Direction == USB_SETUP_DIR_IN)
&& (s_usb_state >= USBD_STATE_ADDRESSED))
{
pStatus = htole16(0); // Default return value is 0x0000
switch (setup.bmRequestType.Recipient)
{
case USB_SETUP_RECIPIENT_DEVICE:
if (setup.wIndex == 0)
{
#if SLAB_USB_REMOTE_WAKEUP_ENABLED
// Remote wakeup feature status
if (remoteWakeupEnabled)
{
pStatus |= htole16(REMOTE_WAKEUP_ENABLED);
}
#endif // SLAB_USB_REMOTE_WAKEUP_ENABLED
#if SLAB_USB_IS_SELF_POWERED_CB
// Current self/bus power status
if (USBD_IsSelfPoweredCb())
{
pStatus |= htole16(DEVICE_IS_SELFPOWERED);
}
#elif (SLAB_USB_BUS_POWERED == 0)
pStatus |= htole16(DEVICE_IS_SELFPOWERED);
#endif // SLAB_USB_IS_SELF_POWERED_CB
retVal = USB_STATUS_OK;
}
break;
case USB_SETUP_RECIPIENT_INTERFACE:
if (setup.wIndex < SLAB_USB_NUM_INTERFACES)
{
retVal = USB_STATUS_OK;
}
break;
case USB_SETUP_RECIPIENT_ENDPOINT:
// Device does not support halting endpoint 0, but do not give
// an error as this is a valid request
if (((setup.wIndex & ~USB_EP_DIR_IN) == 0)
&& (s_usb_state == USBD_STATE_ADDRESSED))
{
retVal = USB_STATUS_OK;
}
else if (s_usb_state == USBD_STATE_CONFIGURED)
{
switch (setup.wIndex & 0xFF)
{
#if SLAB_USB_EP1OUT_USED
case (USB_EP_DIR_OUT | 1):
if (ep1out.state == D_EP_HALT)
{
pStatus = htole16(1);
}
retVal = USB_STATUS_OK;
break;
#endif
#if SLAB_USB_EP2OUT_USED
case (USB_EP_DIR_OUT | 2):
if (ep2out.state == D_EP_HALT)
{
pStatus = htole16(1);
}
retVal = USB_STATUS_OK;
break;
#endif
#if SLAB_USB_EP3OUT_USED
case (USB_EP_DIR_OUT | 3):
if (ep3out.state == D_EP_HALT)
{
pStatus = htole16(1);
}
retVal = USB_STATUS_OK;
break;
#endif
#if SLAB_USB_EP1IN_USED
case (USB_EP_DIR_IN | 1):
if (ep1in.state == D_EP_HALT)
{
pStatus = htole16(1);
}
retVal = USB_STATUS_OK;
break;
#endif
#if SLAB_USB_EP2IN_USED
case (USB_EP_DIR_IN | 2):
if (ep2in.state == D_EP_HALT)
{
pStatus = htole16(1);
}
retVal = USB_STATUS_OK;
break;
#endif
#if SLAB_USB_EP3IN_USED
case (USB_EP_DIR_IN | 3):
if (ep3in.state == D_EP_HALT)
{
pStatus = htole16(1);
}
retVal = USB_STATUS_OK;
break;
#endif
}
}
break;
}
// If the command was valid, send the requested status.
if (retVal == USB_STATUS_OK)
{
EP0_Write((SI_VARIABLE_SEGMENT_POINTER(, uint8_t, SI_SEG_GENERIC))&pStatus, 2);
}
}
return retVal;
}
#endif
/*********************************************************************
* ClearFeature *
*********************************************************************/
#if 0
static USB_Status_TypeDef ClearFeature(void)
{
USB_Status_TypeDef retVal = USB_STATUS_REQ_ERR;
if (setup.wLength == 0)
{
switch (setup.bmRequestType.Recipient)
{
#if SLAB_USB_REMOTE_WAKEUP_ENABLED
case USB_SETUP_RECIPIENT_DEVICE:
if ((setup.wIndex == 0)
&& (setup.wValue == USB_FEATURE_DEVICE_REMOTE_WAKEUP)
&& (s_usb_state >= USBD_STATE_ADDRESSED))
{
// Remote wakeup feature clear
remoteWakeupEnabled = false;
retVal = USB_STATUS_OK;
}
break;
#endif // SLAB_USB_REMOTE_WAKEUP_ENABLED
case USB_SETUP_RECIPIENT_ENDPOINT:
if (setup.wValue == USB_FEATURE_ENDPOINT_HALT)
{
// Device does not support halting endpoint 0, but do not return
// an error as this is a valid request
if (((setup.wIndex & ~USB_EP_DIR_IN) == 0)
&& (s_usb_state >= USBD_STATE_ADDRESSED))
{
retVal = USB_STATUS_OK;
}
else if (((setup.wIndex & ~USB_SETUP_DIR_D2H) < SLAB_USB_NUM_EPS_USED)
&& (s_usb_state == USBD_STATE_CONFIGURED))
{
retVal = USB_STATUS_OK;
USB_SetIndex((setup.wIndex & 0xFF) & ~USB_SETUP_DIR_D2H);
#if (SLAB_USB_EP1IN_USED || SLAB_USB_EP2IN_USED || SLAB_USB_EP3IN_USED)
if ((setup.wIndex & 0xFF) & USB_EP_DIR_IN)
{
USB_EpnInEndStallAndClearDataToggle();
}
#endif
#if (SLAB_USB_EP1OUT_USED || SLAB_USB_EP2OUT_USED || SLAB_USB_EP3OUT_USED)
if (((setup.wIndex & 0xFF) & USB_EP_DIR_IN) == 0)
{
USB_EpnOutEndStallAndClearDataToggle();
}
#endif
switch (setup.wIndex & 0xFF)
{
#if SLAB_USB_EP1OUT_USED
case (USB_EP_DIR_OUT | 1):
if (ep1out.state != D_EP_RECEIVING)
{
ep1out.state = D_EP_IDLE;
}
break;
#endif
#if SLAB_USB_EP2OUT_USED
case (USB_EP_DIR_OUT | 2):
if (ep2out.state != D_EP_RECEIVING)
{
ep2out.state = D_EP_IDLE;
}
break;
#endif
#if SLAB_USB_EP3OUT_USED
case (USB_EP_DIR_OUT | 3):
if (ep3out.state != D_EP_RECEIVING)
{
ep3out.state = D_EP_IDLE;
}
break;
#endif
#if SLAB_USB_EP1IN_USED
case (USB_EP_DIR_IN | 1):
if (ep1in.state != D_EP_TRANSMITTING)
{
ep1in.state = D_EP_IDLE;
}
break;
#endif
#if SLAB_USB_EP2IN_USED
case (USB_EP_DIR_IN | 2):
if (ep2in.state != D_EP_TRANSMITTING)
{
ep2in.state = D_EP_IDLE;
}
break;
#endif
#if SLAB_USB_EP3IN_USED
case (USB_EP_DIR_IN | 3):
if (ep3in.state != D_EP_TRANSMITTING)
{
ep3in.state = D_EP_IDLE;
}
break;
#endif
}
}
}
}
}
return retVal;
}
#endif
#if 0
bool USBD_EpIsBusy(uint8_t epAddr) {
SI_VARIABLE_SEGMENT_POINTER(ep, USBD_Ep_TypeDef, MEM_MODEL_SEG);
// Verify this is a valid endpoint address
if (epAddr >= SLAB_USB_NUM_EPS_USED)
{
SLAB_ASSERT(false);
return true;
}
ep = GetEp(epAddr);
if (ep->state == D_EP_IDLE)
{
return false;
}
return true;
}
#endif
|
the_stack_data/582224.c | /* Simple S/MIME encrypt example */
#include <openssl/pem.h>
#include <openssl/cms.h>
#include <openssl/err.h>
int main(int argc, char **argv)
{
BIO *in = NULL, *out = NULL, *tbio = NULL;
X509 *rcert = NULL;
STACK_OF(X509) *recips = NULL;
CMS_ContentInfo *cms = NULL;
int ret = 1;
/*
* On OpenSSL 1.0.0 and later only:
* for streaming set CMS_STREAM
*/
int flags = CMS_STREAM;
OpenSSL_add_all_algorithms();
ERR_load_crypto_strings();
/* Read in recipient certificate */
tbio = BIO_new_file("signer.pem", "r");
if (!tbio)
goto err;
rcert = PEM_read_bio_X509(tbio, NULL, 0, NULL);
if (!rcert)
goto err;
/* Create recipient STACK and add recipient cert to it */
recips = sk_X509_new_null();
if (!recips || !sk_X509_push(recips, rcert))
goto err;
/*
* sk_X509_pop_free will free up recipient STACK and its contents so set
* rcert to NULL so it isn't freed up twice.
*/
rcert = NULL;
/* Open content being encrypted */
in = BIO_new_file("encr.txt", "r");
if (!in)
goto err;
/* encrypt content */
cms = CMS_encrypt(recips, in, EVP_des_ede3_cbc(), flags);
if (!cms)
goto err;
out = BIO_new_file("smencr.txt", "w");
if (!out)
goto err;
/* Write out S/MIME message */
if (!SMIME_write_CMS(out, cms, in, flags))
goto err;
ret = 0;
err:
if (ret) {
fprintf(stderr, "Error Encrypting Data\n");
ERR_print_errors_fp(stderr);
}
CMS_ContentInfo_free(cms);
X509_free(rcert);
sk_X509_pop_free(recips, X509_free);
BIO_free(in);
BIO_free(out);
BIO_free(tbio);
return ret;
}
|
the_stack_data/62973.c | // RUN: %compile-run-and-check
#include <omp.h>
#include <stdio.h>
const int MaxThreads = 1024;
int main(int argc, char *argv[]) {
int cancellation = -1, dynamic = -1, nested = -1, maxActiveLevels = -1;
#pragma omp target map(cancellation, dynamic, nested, maxActiveLevels)
{
// libomptarget-nvptx doesn't support cancellation.
cancellation = omp_get_cancellation();
// No support for dynamic adjustment of the number of threads.
omp_set_dynamic(1);
dynamic = omp_get_dynamic();
// libomptarget-nvptx doesn't support nested parallelism.
omp_set_nested(1);
nested = omp_get_nested();
omp_set_max_active_levels(42);
maxActiveLevels = omp_get_max_active_levels();
}
// CHECK: cancellation = 0
printf("cancellation = %d\n", cancellation);
// CHECK: dynamic = 0
printf("dynamic = %d\n", dynamic);
// CHECK: nested = 0
printf("nested = %d\n", nested);
// CHECK: maxActiveLevels = 1
printf("maxActiveLevels = %d\n", maxActiveLevels);
return 0;
}
|
the_stack_data/103508.c | #include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void error_y_exit(char *s, int error) {
perror(s);
exit(error);
}
int main(int argc, char* argv[]) {
if (argc == 2) {
int ret = fork();
char s[50];
switch (ret) {
case 0:
sprintf(s, "Soy el proceso HIJO: %d de %s\n", getpid(), argv[1]);
write(1, s, strlen(s));
while(1);
break;
case -1:
sprintf(s,"Ha fallado el fork del proceso: %d\n", getpid());
error_y_exit(s, 1);
break;
default:
sprintf(s, "Soy el proceso PADRE: %d\n", getpid());
write(1, s, strlen(s));
while(1);
break;
}
}
}
|
the_stack_data/90763750.c | /*
* testmisc.c
*
* Miscellanous testcases
*/
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <time.h>
#include <signal.h>
#include <stdlib.h>
#include <setjmp.h>
extern char** environ;
/*
* Macro for assertions in unit test cases
*/
#define ASSERT(x) do { if (!(x)) { \
printf("Assertion %s failed at line %d in %s..", #x, __LINE__, __FILE__ ); \
return 1 ; \
} \
} while (0)
/*
* Set up statistics
*/
#define INIT int __failed=0; int __passed=0; int __rc=0 ; \
printf("------------------------------------------\n"); \
printf("Starting unit test %s\n", __FILE__); \
printf("------------------------------------------\n");
/*
* Print statistic and return
*/
#define END printf("------------------------------------------\n"); \
printf("Overall test results (%s):\n", __FILE__); \
printf("------------------------------------------\n"); \
printf("Failed: %d Passed: %d\n", __failed, __passed); \
printf("------------------------------------------\n"); return __rc;
/*
* Execute a test case
*/
#define RUN_CASE(x) do { __rc= do_test_case(x, testcase##x); \
if (__rc) __failed++; else __passed++;} while (0)
/*
* Forward declaration - this is in kunit.o
*/
int do_test_case(int x, int (*testcase)());
/*
* Testcase 1: test task switch after using the FPU
*/
int testcase1() {
double a;
double b;
double c;
a = 2.5;
b = 2.0;
int pid;
int stat;
int i;
/*
* Start a calculation
*/
c = a*b;
/*
* Fork off a new process which will also use the FPU
*/
pid = fork();
if (0 == pid) {
/*
* Child. Use FPU and exit
*/
for (i = 0; i < 10000; i++) {
c = 2.0;
c = c*a;
ASSERT(c == 5.0);
}
_exit(0);
}
/*
* Sleep to force task switch
*/
sleep(1);
/*
* Resume calculation
*/
c = c * a;
ASSERT(12.5 == c);
/*
* and wait for task
*/
waitpid(pid, &stat, 0);
ASSERT(0 == stat);
return 0;
}
/*
* Testcase 2: test execution of a signal handler during an FPU operation
*/
static int volatile __handler_called = 0;
static int volatile __handler_completed = 0;
void myhandler(int signo) {
double a;
double b;
double c;
__handler_called = 1;
a = 4.5;
b = 4.0;
c = a*b;
if (18.0 == c)
__handler_completed = 1;
return;
}
int testcase2() {
double a;
double b;
double c;
a = 2.5;
b = 2.0;
struct sigaction sa;
sigset_t sigmask;
/*
* Install signal handler
*/
sa.sa_flags = 0;
sa.sa_handler = myhandler;
sigemptyset(&sa.sa_mask);
ASSERT(0 == sigaction(SIGUSR1, &sa, 0));
/*
* Make sure that SIGUSR1 is not blocked
*/
sigemptyset(&sigmask);
sigaddset(&sigmask, SIGUSR1);
ASSERT(0 == sigprocmask(SIG_UNBLOCK, &sigmask, 0));
__handler_called = 0;
/*
* Start a calculation
*/
c = a*b;
/*
* Raise signal to execute signal handler
*/
raise(SIGUSR1);
ASSERT(__handler_called);
ASSERT(__handler_completed);
/*
* Resume calculation
*/
c = c * a;
ASSERT(12.5 == c);
return 0;
}
/*
* Testcase 3: combine test cases 2 with a task executing concurrently
*/
int testcase3() {
double a;
double b;
double c;
a = 2.5;
b = 2.0;
struct sigaction sa;
sigset_t sigmask;
int pid;
int i;
int stat;
/*
* Install signal handler
*/
sa.sa_flags = 0;
sa.sa_handler = myhandler;
sigemptyset(&sa.sa_mask);
ASSERT(0 == sigaction(SIGUSR1, &sa, 0));
/*
* Make sure that SIGUSR1 is not blocked
*/
sigemptyset(&sigmask);
sigaddset(&sigmask, SIGUSR1);
ASSERT(0 == sigprocmask(SIG_UNBLOCK, &sigmask, 0));
__handler_called = 0;
/*
* Start a calculation
*/
c = a*b;
/*
* Fork off a new process which will also use the FPU
*/
pid = fork();
if (0 == pid) {
/*
* Child. Use FPU and exit
*/
for (i = 0; i < 1000000; i++) {
c = 2.0;
c = c*a;
ASSERT(c == 5.0);
}
_exit(0);
}
/*
* Raise signal to execute signal handler
*/
raise(SIGUSR1);
ASSERT(__handler_called);
ASSERT(__handler_completed);
/*
* Resume calculation
*/
c = c * a;
ASSERT(12.5 == c);
/*
* and wait for task
*/
waitpid(pid, &stat, 0);
ASSERT(0 == stat);
return 0;
}
/* Testcase 4
* Do a longjmp
*/
int testcase4() {
int rc;
int flag = 0;
double value;
jmp_buf __jmp_buf;
memset((void*) __jmp_buf, 0, sizeof(__jmp_buf));
/*
* Do some floating point arithmetic to put the FPU into a non-trivial state
*/
value = 2.5;
value = value * value;
rc = setjmp(__jmp_buf);
if (0 == rc) {
/*
* This is the path which we take first
*/
ASSERT(0 == flag);
flag++;
longjmp(__jmp_buf, 1);
/*
* We should never get to this point
*/
ASSERT(0);
}
ASSERT(1 == rc);
ASSERT(1 == flag);
/*
* Is value still correct?
*/
ASSERT((double) 6.25 == value);
return 0;
}
/*
* Testcase 5: test the execl system call
* Here we fork off a process and in the child call
* testhello using exec. We then check that the file
* that testhello has created is there and remove it
* again
*/
int testcase5() {
struct stat mystat;
int pid = 0;
/*
* First check that the testfile is NOT there and
* remove it if it exists
*/
if (0 == stat("hello", &mystat)) {
unlink("hello");
ASSERT(stat("hello", &mystat));
}
/*
* Now fork off a process
*/
pid = fork();
if (pid < 0) {
printf("Could not fork child, exiting\n");
_exit(1);
}
if (0 == pid) {
/*
* Child
*/
execl("testhello", "testhello", 0);
/*
* We should never get here
*/
ASSERT(0);
}
/*
* We only reach this point if we are the parent
* Wait for child to complete
*/
waitpid(pid, 0, 0);
/*
* Now verify that the file has been created
*/
ASSERT(0 == stat("hello", &mystat));
unlink("hello");
return 0;
}
/*
* Testcase 6: test the execl system call with two arguments
* Here we fork off a process and in the child call
* testhello using exec. We then check that the file
* that testhello has created is there and remove it
* again
*/
int testcase6() {
struct stat mystat;
int pid = 0;
/*
* First check that the testfile is NOT there and
* remove it if it exists
*/
if (0 == stat("hello", &mystat)) {
unlink("hello");
ASSERT(stat("hello", &mystat));
}
/*
* Now fork off a process
*/
pid = fork();
if (pid < 0) {
printf("Could not fork child, exiting\n");
_exit(1);
}
if (0 == pid) {
/*
* Child
*/
execl("testhello", "testhello", "a", 0);
/*
* We should never get here
*/
ASSERT(0);
}
/*
* We only reach this point if we are the parent
* Wait for child to complete
*/
waitpid(pid, 0, 0);
/*
* Now verify that the file has been created
*/
ASSERT(0 == stat("hello", &mystat));
// unlink("hello");
return 0;
}
/*
* Testcase 7
* A simple environment test
*/
int testcase7() {
/*
* Add an environment entry using putenv
*/
char* env_string = "testcase7=x";
ASSERT(0 == putenv(env_string));
/*
* Now check that a call to getenv
* gives us the correct value
*/
ASSERT(getenv("testcase7"));
ASSERT(0 == strcmp("x", getenv("testcase7")));
return 0;
}
/*
* Testcase 8
* Now we simulate an application taking over environ
*/
int testcase8() {
char** newenv;
char** lastenv;
int entries;
/*
* First we add an environment entry
*/
ASSERT(0 == putenv("x=a"));
/*
* Now assume that an application comes with its own
* putenv implementation. First the application will
* allocate memory for a new array and copy
* the old environment there
*/
entries = 0;
while(environ[entries]) {
entries++;
}
newenv = (char**) malloc(sizeof(char*) * (2 + entries));
memcpy ((void *) newenv, (void *) environ, entries*sizeof (char *));
newenv[entries] = "testcase8=1";
newenv[entries +1] = 0;
lastenv = newenv;
environ = newenv;
/*
* Now a call to getenv should give us the correct
* result
*/
ASSERT(getenv("testcase8"));
ASSERT(0 == strcmp("1", getenv("testcase8")));
/*
* also for old entries
*/
ASSERT(getenv("x"));
ASSERT(0 == strcmp("a", getenv("x")));
/*
* The getenv implementation should have changed environ again
*/
ASSERT(lastenv != environ);
/*
* and we should be able to free lastenv
*/
free(lastenv);
return 0;
}
/*
* Testcase 9. Test system
*/
int testcase9() {
struct stat mystat;
/*
* Make sure that the file /tmp/testmisc_tc9 does not exist
*/
unlink("/tmp/testmisc_tc9");
/*
* Check whether we have a shell
*/
int have_shell = system(0);
if (0 == have_shell)
return 0;
/*
* Now try to run echo 'test' > /tmp/testmisc_tc9
*/
system("echo \"test\" > /tmp/testmisc_tc9");
/*
* Check whether the file is there
*/
ASSERT(0 == stat("/tmp/testmisc_tc9", &mystat));
/*
* and remove it again
*/
unlink("/tmp/testmisc_tc9");
return 0;
}
/*
* Main
*/
int main() {
INIT;
RUN_CASE(1);
RUN_CASE(2);
RUN_CASE(3);
RUN_CASE(4);
RUN_CASE(5);
RUN_CASE(6);
RUN_CASE(7);
RUN_CASE(8);
RUN_CASE(9);
END;
}
|
the_stack_data/831292.c | /* Test for bogus diagnostics for dremf definition, as in bug 16666.
The GNU extension permitting a prototype to override the promotion
of old-style parameter declarations should only apply when the
prototype is visible, not for a built-in prototype. */
/* { dg-do compile } */
/* { dg-options "" } */
float
dremf(x, y) /* { dg-warning "conflicting types for built-in function 'dremf'" } */
float x, y;
{
return x + y;
}
|
the_stack_data/1212030.c | #include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <time.h>
#include <pwd.h>
#include <grp.h>
#define MAX_PATH_LEN 1024
void fsize(char *name);
void dir_walk(char *dir_name, void (*func)(char *));
void print_file_flags(mode_t st_mode);
void print_file_user(uid_t st_uid);
void print_file_group(gid_t st_gid);
void print_file_size(size_t size);
void print_file_time(time_t time);
int main(int argc, char *argv[])
{
if (argc == 1)
{
fsize(".");
}
else
{
while (--argc > 0)
{
fsize(*++argv);
}
}
return 0;
}
void fsize(char *name)
{
struct stat buffer;
if (stat(name, &buffer) == -1)
{
fprintf(stderr, "fsize: cannot access %s\n", name);
return;
}
if ((buffer.st_mode & S_IFMT) == S_IFDIR)
{
dir_walk(name, fsize);
}
/**
* off_t st_size File size, in bytes
* dev_t st_dev ID of device containing file
* ino_t st_ino File serial number
* mode_t st_mode Mode of file (see below)
* nlink_t st_nlink Number of hard links
* uid_t st_uid User ID of the file
* gid_t st_gid Group ID of the file
* dev_t st_rdev Device ID
* time_t st_atime Time of last access
* time_t st_mtime Last data modification time
* time_t st_ctime Time of last status change
* blkcnt_t st_blocks Blocks allocated for file
* blksize_t st_blksize Optimal blocksize for I/O
*/
// Printed in a similary fashion to ls -l
print_file_flags(buffer.st_mode);
printf("%lu ", buffer.st_nlink);
print_file_user(buffer.st_uid);
print_file_group(buffer.st_gid);
print_file_size(buffer.st_size);
print_file_time(buffer.st_atime);
printf("%s\n", name);
}
void dir_walk(char *dir_name, void (*func)(char *))
{
char name[MAX_PATH_LEN];
struct dirent *dir_entry;
DIR *dir;
if ((dir = opendir(dir_name)) == NULL)
{
fprintf(stderr, "dir_walk: cannot open %s\n", dir_name);
return;
}
while ((dir_entry = readdir(dir)) != NULL)
{
if (strcmp(dir_entry->d_name, ".") == 0 || strcmp(dir_entry->d_name, "..") == 0)
{
continue; // Skip self and parent.
}
if (strlen(dir_name) + strlen(dir_entry->d_name) + 2 > MAX_PATH_LEN)
{
fprintf(stderr, "dir_walk: path too long\n");
}
else
{
sprintf(name, "%s/%s", dir_name, dir_entry->d_name);
(*func)(name);
}
}
closedir(dir);
}
void print_file_flags(mode_t st_mode)
{
printf("%c", ((st_mode & S_IFMT) == S_IFDIR) ? 'd' : '-');
printf("%c", (st_mode & S_IRUSR) ? 'r' : '-');
printf("%c", (st_mode & S_IWUSR) ? 'w' : '-');
printf("%c", (st_mode & S_IXUSR) ? 'x' : '-');
printf("%c", (st_mode & S_IRGRP) ? 'r' : '-');
printf("%c", (st_mode & S_IWGRP) ? 'w' : '-');
printf("%c", (st_mode & S_IXGRP) ? 'x' : '-');
printf("%c", (st_mode & S_IROTH) ? 'r' : '-');
printf("%c", (st_mode & S_IWOTH) ? 'w' : '-');
printf("%c ", (st_mode & S_IXOTH) ? 'x' : '-');
}
void print_file_user(uid_t st_uid)
{
struct passwd *password;
password = getpwuid(st_uid);
if (password == NULL)
{
fprintf(stderr, "Error: cannot find user\n");
return;
}
printf("%s ", password->pw_name);
}
void print_file_group(gid_t st_gid)
{
struct group *group;
group = getgrgid(st_gid);
if (group == NULL)
{
fprintf(stderr, "Error: cannot find group\n");
return;
}
printf("%s ", group->gr_name);
}
void print_file_size(size_t size)
{
static const char *SIZES[] = {"B", "K", "M", "G"};
size_t div = 0;
size_t rem = 0;
while (size >= 1024 && div < (sizeof SIZES / sizeof *SIZES))
{
rem = (size % 1024);
div++;
size /= 1024;
}
printf("%6.1f%s ", (float)size + (float)rem / 1024.0, SIZES[div]);
}
void print_file_time(time_t time)
{
char time_str[32];
strftime(time_str, sizeof(time_str), "%d %b %H:%M", localtime(&time));
printf("%s ", time_str);
}
|
the_stack_data/1075524.c | #include <stdio.h>
#include <stdlib.h>
/**
* @file
*/
int main(int argc, char *argv[])
{
return EXIT_SUCCESS;
}
|
the_stack_data/89200036.c | //// _git source mask md5:cc8d16d55e44f3c471baa292457bedc0 ////
//////// /////////
/// //////// ///// //// ///////
//
/// ////////
/// //
/// //
/// / / //
/// / / //
/// / / //
/////////// ////
///// / // / / // ////
//
/////////// //// / ///
//// ////////
//
///// / ////
//
//// / //
//
//// / //
/// //
/// //
//
////
////
//// // //
//////
//// ////// / ///
/////////// //// / / / ///
//// ////// / ///
//
//// / //
/// //
/////
//// //
////////////// ///
//
|
the_stack_data/34513140.c | // 6 kyu
// Bit Counting
#include <stddef.h>
size_t
countBits(unsigned value)
{
return (value ? (value & 1) + countBits(value >> 1) : 0);
};
|
the_stack_data/12638849.c | #include <stdio.h>
#include <math.h>
#define DIM 10
int nperfetto(int);
int narmstrong(int);
int main(void)
{
int n, i, maxperf, maxarm;
int num[DIM];
maxperf = 0;
maxarm = 0;
do {
printf("Quanti valori vuoi inserire?(max10) ");
scanf("%d", &n);
}while(n<=0||n>10);
for(i=0;i<n;i++) {
printf("Inserisci numero: ");
scanf("%d", &num[i]);
}
for(i=0;i<n;i++){
if(nperfetto(num[i])){
if(num[i]>maxperf) {
maxperf = num[i];
}
}
if(narmstrong(num[i])){
if(num[i]>maxarm) {
maxarm = num[i];
}
}
}
if(maxperf==0)
{
printf("Non ci sono numeri perfetti!\n");
}
else
{
printf("Numero perfetto massimo: %d\n", maxperf);
}
if(maxarm==0)
{
printf("Non ci sono numeri di Armstrong!\n");
}
else
{
printf("Numero di Armstrong massimo: %d\n", maxarm);
}
return 0;
}
int nperfetto(int n)
{
int sommadiv, div;
sommadiv = 1;
div = 2;
while(div<=n/2) {
if(n%div==0) {
sommadiv += div;
}
div++;
}
if(sommadiv == n)
return 1;
else
return 0;
}
int narmstrong(int n)
{
int len, somma, tempn, ultimacifra;
tempn = n;
somma = 0;
len=0;
while(tempn>0) {
len++;
tempn /= 10;
}
tempn = n;
while(tempn>0) {
ultimacifra = tempn % 10;
somma += pow(ultimacifra, len);
tempn /= 10;
}
if(somma==n)
return 1;
else
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.