file
stringlengths 18
26
| data
stringlengths 3
1.04M
|
---|---|
the_stack_data/176705789.c |
/* -*- Last-Edit: Fri Jan 29 11:13:27 1993 by Tarak S. Goradia; -*- */
/* $Log: tcas.c,v $
* Revision 1.2 1993/03/12 19:29:50 foster
* Correct logic bug which didn't allow output of 2 - hf
* */
#include <stdio.h>
#define OLEV 600 /* in feets/minute */
#define MAXALTDIFF 600 /* max altitude difference in feet */
#define MINSEP 300 /* min separation in feet */
#define NOZCROSS 100 /* in feet */
/* variables */
typedef int bool;
int Cur_Vertical_Sep;
bool High_Confidence;
bool Two_of_Three_Reports_Valid;
int Own_Tracked_Alt;
int Own_Tracked_Alt_Rate;
int Other_Tracked_Alt;
int Alt_Layer_Value; /* 0, 1, 2, 3 */
int Positive_RA_Alt_Thresh[4];
int Up_Separation;
int Down_Separation;
/* state variables */
int Other_RAC; /* NO_INTENT, DO_NOT_CLIMB, DO_NOT_DESCEND */
#define NO_INTENT 0
#define DO_NOT_CLIMB 1
#define DO_NOT_DESCEND 2
int Other_Capability; /* TCAS_TA, OTHER */
#define TCAS_TA 1
#define OTHER 2
int Climb_Inhibit; /* true/false */
#define UNRESOLVED 0
#define UPWARD_RA 1
#define DOWNWARD_RA 2
void initialize()
{
Positive_RA_Alt_Thresh[0] = 400;
Positive_RA_Alt_Thresh[1] = 500;
Positive_RA_Alt_Thresh[2] = 640;
Positive_RA_Alt_Thresh[3] = 740;
}
int ALIM ()
{
return Positive_RA_Alt_Thresh[Alt_Layer_Value];
}
int Inhibit_Biased_Climb ()
{
return (Up_Separation);
}
bool Non_Crossing_Biased_Climb()
{
int upward_preferred;
int upward_crossing_situation;
bool result;
upward_preferred = Inhibit_Biased_Climb() > Down_Separation;
if (upward_preferred)
{
result = !(Own_Below_Threat()) || ((Own_Below_Threat()) && (!(Down_Separation >= ALIM())));
}
else
{
result = Own_Above_Threat() && (Cur_Vertical_Sep >= MINSEP) && (Up_Separation >= ALIM());
}
return result;
}
bool Non_Crossing_Biased_Descend()
{
int upward_preferred;
int upward_crossing_situation;
bool result;
upward_preferred = Inhibit_Biased_Climb() > Down_Separation;
if (upward_preferred)
{
result = Own_Below_Threat() && (Cur_Vertical_Sep >= MINSEP) && (Down_Separation >= ALIM());
}
else
{
result = !(Own_Above_Threat()) || ((Own_Above_Threat()) && (Up_Separation >= ALIM()));
}
return result;
}
bool Own_Below_Threat()
{
return (Own_Tracked_Alt < Other_Tracked_Alt);
}
bool Own_Above_Threat()
{
return (Other_Tracked_Alt < Own_Tracked_Alt);
}
int alt_sep_test()
{
bool enabled, tcas_equipped, intent_not_known;
bool need_upward_RA, need_downward_RA;
int alt_sep;
enabled = High_Confidence && (Own_Tracked_Alt_Rate <= OLEV) && (Cur_Vertical_Sep > MAXALTDIFF);
tcas_equipped = Other_Capability == TCAS_TA;
intent_not_known = Two_of_Three_Reports_Valid && Other_RAC == NO_INTENT;
alt_sep = UNRESOLVED;
if (enabled && ((tcas_equipped && intent_not_known) || !tcas_equipped))
{
need_upward_RA = Non_Crossing_Biased_Climb() && Own_Below_Threat();
need_downward_RA = Non_Crossing_Biased_Descend() && Own_Above_Threat();
if (need_upward_RA && need_downward_RA)
/* unreachable: requires Own_Below_Threat and Own_Above_Threat
to both be true - that requires Own_Tracked_Alt < Other_Tracked_Alt
and Other_Tracked_Alt < Own_Tracked_Alt, which isn't possible */
alt_sep = UNRESOLVED;
else if (need_upward_RA)
alt_sep = UPWARD_RA;
else if (need_downward_RA)
alt_sep = DOWNWARD_RA;
else
alt_sep = UNRESOLVED;
}
return alt_sep;
}
main(argc, argv)
int argc;
char *argv[];
{
if(argc < 13)
{
fprintf(stdout, "Error: Command line arguments are\n");
fprintf(stdout, "Cur_Vertical_Sep, High_Confidence, Two_of_Three_Reports_Valid\n");
fprintf(stdout, "Own_Tracked_Alt, Own_Tracked_Alt_Rate, Other_Tracked_Alt\n");
fprintf(stdout, "Alt_Layer_Value, Up_Separation, Down_Separation\n");
fprintf(stdout, "Other_RAC, Other_Capability, Climb_Inhibit\n");
exit(1);
}
initialize();
Cur_Vertical_Sep = atoi(argv[1]);
High_Confidence = atoi(argv[2]);
Two_of_Three_Reports_Valid = atoi(argv[3]);
Own_Tracked_Alt = atoi(argv[4]);
Own_Tracked_Alt_Rate = atoi(argv[5]);
Other_Tracked_Alt = atoi(argv[6]);
Alt_Layer_Value = atoi(argv[7]);
Up_Separation = atoi(argv[8]);
Down_Separation = atoi(argv[9]);
Other_RAC = atoi(argv[10]);
Other_Capability = atoi(argv[11]);
Climb_Inhibit = atoi(argv[12]);
fprintf(stdout, "%d\n", alt_sep_test());
exit(0);
}
|
the_stack_data/806816.c | /*
* File: main.c
* Author: Tricio
*
* Created on July 7, 2014, 4:09 PM
*/
int main(void) {
euler001();
return (0);
}
|
the_stack_data/1105159.c | #include <time.h>
int __clock_gettime(clockid_t, struct timespec *);
time_t time(time_t *t)
{
struct timespec ts;
__clock_gettime(CLOCK_REALTIME, &ts);
if (t) *t = ts.tv_sec;
return ts.tv_sec;
}
|
the_stack_data/176704401.c | #include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main()
{
FILE *write_fp;
char buffer[BUFSIZ + 1];
sprintf(buffer, "Once upon a time, there was...\n");
write_fp = popen("od -c", "w");
if (write_fp != NULL) {
fwrite(buffer, sizeof(char), strlen(buffer), write_fp);
pclose(write_fp);
exit(EXIT_SUCCESS);
}
exit(EXIT_FAILURE);
}
|
the_stack_data/26699921.c | /*Exercise 2 - Selection
Write a program to calculate the amount to be paid for a rented vehicle.
• Input the distance the van has travelled
• The first 30 km is at a rate of 50/= per km.
• The remaining distance is calculated at the rate of 40/= per km.
e.g.
Distance -> 20
Amount = 20 x 50 = 1000
Distance -> 50
Amount = 30 x 50 + (50-30) x 40 = 2300*/
#include <stdio.h>
int main() {
int x,y;
printf("Input the total distance van has travelled :");
scanf("%d",&x);
if ( x<=30){
printf("Amount to be paid : %d/=\n",x*50);
}
else{
y=x-30;
printf("Amount to be paid : %d/=\n",30*50+y*40);
}
return 0;
}
|
the_stack_data/73739.c | int main(void) {
return (42 / 2) + ((21 + 21) / 2);
}
|
the_stack_data/394898.c | extern void a(void);
extern void b(void);
void dummy (void)
{
a();
}
int
compare (void (*f)(void))
{
return a == f;
}
int
main (void)
{
b ();
return 0;
}
|
the_stack_data/413097.c | int main() {
int a = 1;
if (a == 1)
a = 100;
return a;
}
|
the_stack_data/763732.c | /*
* Copyright 2021 NXP
*
* SPDX-License-Identifier: BSD-3-Clause
*
*/
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include <unistd.h>
#define NUM_MEM_BLOCK 1
#define FOUR_BYTE_ALIGN 4
#define EIGHT_BYTE_ALIGN 8
#define SIZE_TWO_PBL_CMD 24
/* Define for add_boot_ptr_cmd() */
#define BOOTPTR_ADDR 0x09570604
#define CSF_ADDR_SB 0x09ee0200
/* CCSR write command to address 0x1e00400 i.e BOOTLOCPTR */
#define BOOTPTR_ADDR_CH3 0x31e00400
/* Load CSF header command */
#define CSF_ADDR_SB_CH3 0x80220000
#define MAND_ARG_MASK 0xFFF3
#define ARG_INIT_MASK 0xFF00
#define RCW_FILE_NAME_ARG_MASK 0x0080
#define IN_FILE_NAME_ARG_MASK 0x0040
#define CHASSIS_ARG_MASK 0x0020
#define BOOT_SRC_ARG_MASK 0x0010
#define ENTRY_POINT_ADDR_ARG_MASK 0x0008
#define BL2_BIN_STRG_LOC_BOOT_SRC_ARG_MASK 0x0004
#define BL2_BIN_CPY_DEST_ADDR_ARG_MASK 0x0002
#define OP_FILE_NAME_ARG_MASK 0x0001
/* Define for add_cpy_cmd() */
#define OFFSET_MASK 0x00ffffff
#define WRITE_CMD_BASE 0x81000000
#define MAX_PBI_DATA_LEN_BYTE 64
/* 140 Bytes = Preamble + LOAD RCW command + RCW (128 bytes) + Checksum */
#define CHS3_CRC_PAYLOAD_START_OFFSET 140
#define PBI_CRC_POLYNOMIAL 0x04c11db7
typedef enum {
CHASSIS_UNKNOWN,
CHASSIS_2,
CHASSIS_3,
CHASSIS_3_2,
CHASSIS_MAX /* must be last item in list */
} chassis_t;
typedef enum {
UNKNOWN_BOOT = 0,
IFC_NOR_BOOT,
IFC_NAND_BOOT,
QSPI_BOOT,
SD_BOOT,
EMMC_BOOT,
FLXSPI_NOR_BOOT,
FLXSPI_NAND_BOOT,
FLXSPI_NAND4K_BOOT,
MAX_BOOT /* must be last item in list */
} boot_src_t;
/* Base Addresses where PBL image is copied depending on the boot source.
* Boot address map varies as per Chassis architecture.
*/
#define BASE_ADDR_UNDEFINED 0xFFFFFFFF
#define BASE_ADDR_QSPI 0x20000000
#define BASE_ADDR_SD 0x00001000
#define BASE_ADDR_IFC_NOR 0x30000000
#define BASE_ADDR_EMMC 0x00001000
#define BASE_ADDR_FLX_NOR 0x20000000
#define BASE_ADDR_NAND 0x20000000
uint32_t base_addr_ch3[MAX_BOOT] = {
BASE_ADDR_UNDEFINED,
BASE_ADDR_IFC_NOR,
BASE_ADDR_UNDEFINED, /*IFC NAND */
BASE_ADDR_QSPI,
BASE_ADDR_SD,
BASE_ADDR_EMMC,
BASE_ADDR_UNDEFINED, /*FLXSPI NOR */
BASE_ADDR_UNDEFINED, /*FLXSPI NAND 2K */
BASE_ADDR_UNDEFINED /*FLXSPI NAND 4K */
};
uint32_t base_addr_ch32[MAX_BOOT] = {
BASE_ADDR_UNDEFINED,
BASE_ADDR_UNDEFINED, /* IFC NOR */
BASE_ADDR_UNDEFINED, /* IFC NAND */
BASE_ADDR_UNDEFINED, /* QSPI */
BASE_ADDR_SD,
BASE_ADDR_EMMC,
BASE_ADDR_FLX_NOR,
BASE_ADDR_UNDEFINED, /*FLXSPI NAND 2K */
BASE_ADDR_UNDEFINED /*FLXSPI NAND 4K */
};
/* for Chassis 3 */
uint32_t blk_cpy_hdr_map_ch3[] = {
0, /* Unknown Boot Source */
0x80000020, /* NOR_BOOT */
0x0, /* NAND_BOOT */
0x80000062, /* QSPI_BOOT */
0x80000040, /* SD_BOOT */
0x80000041, /* EMMC_BOOT */
0x0, /* FLEXSPI NOR_BOOT */
0x0, /* FLEX SPI NAND2K BOOT */
0x0, /* CHASIS3_2_NAND4K_BOOT */
};
uint32_t blk_cpy_hdr_map_ch32[] = {
0, /* Unknown Boot Source */
0x0, /* NOR_BOOT */
0x0, /* NAND_BOOT */
0x0, /* QSPI_BOOT */
0x80000008, /* SD_BOOT */
0x80000009, /* EMMC_BOOT */
0x8000000F, /* FLEXSPI NOR_BOOT */
0x8000000C, /* FLEX SPI NAND2K BOOT */
0x8000000D, /* CHASIS3_2_NAND4K_BOOT */
};
char *boot_src_string[] = {
"UNKNOWN_BOOT",
"IFC_NOR_BOOT",
"IFC_NAND_BOOT",
"QSPI_BOOT",
"SD_BOOT",
"EMMC_BOOT",
"FLXSPI_NOR_BOOT",
"FLXSPI_NAND_BOOT",
"FLXSPI_NAND4K_BOOT",
};
enum stop_command {
STOP_COMMAND = 0,
CRC_STOP_COMMAND
};
/* Structure will get populated in the main function
* as part of parsing the command line arguments.
* All member parameters are mandatory except:
* -ep
* -src_addr
*/
struct pbl_image {
char *rcw_nm; /* Input RCW File */
char *sec_imgnm; /* Input BL2 binary */
char *imagefile; /* Generated output file */
boot_src_t boot_src; /* Boot Source - QSPI, SD, NOR, NAND etc */
uint32_t src_addr; /* Source Address */
uint32_t addr; /* Load address */
uint32_t ep; /* Entry point <opt> default is load address */
chassis_t chassis; /* Chassis type */
} pblimg;
#define SUCCESS 0
#define FAILURE -1
#define CRC_STOP_CMD_ARM 0x08610040
#define CRC_STOP_CMD_ARM_CH3 0x808f0000
#define STOP_CMD_ARM_CH3 0x80ff0000
#define BYTE_SWAP_32(word) ((((word) & 0xff000000) >> 24)| \
(((word) & 0x00ff0000) >> 8) | \
(((word) & 0x0000ff00) << 8) | \
(((word) & 0x000000ff) << 24))
#define PBI_LEN_MASK 0xFFF00000
#define PBI_LEN_SHIFT 20
#define NUM_RCW_WORD 35
#define PBI_LEN_ADD 6
#define MAX_CRC_ENTRIES 256
/* SoC numeric identifier */
#define SOC_LS1012 1012
#define SOC_LS1023 1023
#define SOC_LS1026 1026
#define SOC_LS1028 1028
#define SOC_LS1043 1043
#define SOC_LS1046 1046
#define SOC_LS1088 1088
#define SOC_LS2080 2080
#define SOC_LS2088 2088
#define SOC_LX2160 2160
static uint32_t pbl_size;
bool sb_flag;
/***************************************************************************
* Description : CRC32 Lookup Table
***************************************************************************/
static uint32_t crc32_lookup[] = {
0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA,
0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940,
0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116,
0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A,
0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818,
0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C,
0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086,
0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4,
0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE,
0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252,
0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60,
0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04,
0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A,
0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E,
0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0,
0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6,
0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
};
static void print_usage(void)
{
printf("\nCorrect Usage of Tool is:\n");
printf("\n ./create_pbl [options] (mentioned below):\n\n");
printf("\t-r <RCW file-name> - name of RCW binary file.\n");
printf("\t-i <BL2 Bin file-name> - file to be added to rcw file.\n");
printf("\t-c <Number> - Chassis Architecture (=2 or =3\n");
printf("\t or =4 for 3.2).\n");
printf("\t-b <qspi/nor/nand/sd> - Boot source.\n");
printf("\t-d <Address> - Destination address where BL2\n");
printf("\t image is to be copied\n");
printf("\t-o <output filename> - Name of PBL image generated\n");
printf("\t as an output of the tool.\n");
printf("\t-f <Address> - BL2 image Src Offset\n");
printf("\t on Boot Source for block copy.\n");
printf("\t command for chassis >=3.)\n");
printf("\t-e <Address> - [Optional] Entry Point Address\n");
printf("\t of the BL2.bin\n");
printf("\t-s Secure Boot.\n");
printf("\t-h Help.\n");
printf("\n\n");
exit(0);
}
/***************************************************************************
* Function : crypto_calculate_checksum()
* Arguments : data - Pointer to FILE
* num - Number of 32 bit words for checksum
* Return : Checksum Value
* Description : Calculate Checksum over the data
***************************************************************************/
uint32_t crypto_calculate_checksum(FILE *fp_rcw_pbi_op, uint32_t num)
{
uint32_t i;
uint64_t sum = 0;
uint32_t word;
fseek(fp_rcw_pbi_op, 0L, SEEK_SET);
for (i = 0; i < num ; i++) {
if ((fread(&word, sizeof(word), NUM_MEM_BLOCK, fp_rcw_pbi_op))
< NUM_MEM_BLOCK) {
printf("%s: Error reading word.\n", __func__);
return FAILURE;
}
sum = sum + word;
sum = sum & 0xFFFFFFFF;
}
return (uint32_t)sum;
}
/***************************************************************************
* Function : add_pbi_stop_cmd
* Arguments : fp_rcw_pbi_op - output rcw_pbi file pointer
* Return : SUCCESS or FAILURE
* Description : This function insert pbi stop command.
***************************************************************************/
int add_pbi_stop_cmd(FILE *fp_rcw_pbi_op, enum stop_command flag)
{
int ret = FAILURE;
int32_t pbi_stop_cmd;
uint32_t pbi_crc = 0xffffffff, i, j, c;
uint32_t crc_table[MAX_CRC_ENTRIES];
uint8_t data;
switch (pblimg.chassis) {
case CHASSIS_2:
pbi_stop_cmd = BYTE_SWAP_32(CRC_STOP_CMD_ARM);
break;
case CHASSIS_3:
case CHASSIS_3_2:
/* Based on flag add the corresponsding cmd
* -- stop cmd or stop with CRC cmd
*/
if (flag == CRC_STOP_COMMAND) {
pbi_stop_cmd = CRC_STOP_CMD_ARM_CH3;
} else {
pbi_stop_cmd = STOP_CMD_ARM_CH3;
}
break;
case CHASSIS_UNKNOWN:
case CHASSIS_MAX:
default:
printf("Internal Error: Invalid Chassis val = %d.\n",
pblimg.chassis);
goto pbi_stop_err;
}
if (fwrite(&pbi_stop_cmd, sizeof(pbi_stop_cmd), NUM_MEM_BLOCK,
fp_rcw_pbi_op) != NUM_MEM_BLOCK) {
printf("%s: Error in Writing PBI STOP CMD\n", __func__);
goto pbi_stop_err;
}
if (flag == CRC_STOP_COMMAND) {
for (i = 0; i < MAX_CRC_ENTRIES; i++) {
c = i << 24;
for (j = 0; j < 8; j++) {
c = (c & 0x80000000) ?
PBI_CRC_POLYNOMIAL ^ (c << 1) : c << 1;
}
crc_table[i] = c;
}
}
switch (pblimg.chassis) {
case CHASSIS_2:
/* Chassis 2: CRC is calculated on RCW + PBL cmd.*/
fseek(fp_rcw_pbi_op, 0L, SEEK_SET);
break;
case CHASSIS_3:
case CHASSIS_3_2:
/* Chassis 3: CRC is calculated on PBL cmd only. */
fseek(fp_rcw_pbi_op, CHS3_CRC_PAYLOAD_START_OFFSET, SEEK_SET);
break;
case CHASSIS_UNKNOWN:
case CHASSIS_MAX:
printf("%s: Unknown Chassis.\n", __func__);
goto pbi_stop_err;
}
while ((fread(&data, sizeof(data), NUM_MEM_BLOCK, fp_rcw_pbi_op))
== NUM_MEM_BLOCK) {
if (flag == CRC_STOP_COMMAND) {
if (pblimg.chassis == CHASSIS_2) {
pbi_crc = crc_table
[((pbi_crc >> 24) ^ (data)) & 0xff] ^
(pbi_crc << 8);
} else {
pbi_crc = (pbi_crc >> 8) ^
crc32_lookup[((pbi_crc) ^
(data)) & 0xff];
}
}
}
switch (pblimg.chassis) {
case CHASSIS_2:
pbi_crc = BYTE_SWAP_32(pbi_crc);
break;
case CHASSIS_3:
case CHASSIS_3_2:
if (flag == CRC_STOP_COMMAND) {
pbi_crc = pbi_crc ^ 0xFFFFFFFF;
} else {
pbi_crc = 0x00000000;
}
break;
case CHASSIS_UNKNOWN:
case CHASSIS_MAX:
printf("%s: Unknown Chassis.\n", __func__);
goto pbi_stop_err;
}
if (fwrite(&pbi_crc, sizeof(pbi_crc), NUM_MEM_BLOCK, fp_rcw_pbi_op)
!= NUM_MEM_BLOCK) {
printf("%s: Error in Writing PBI PBI CRC\n", __func__);
goto pbi_stop_err;
}
ret = SUCCESS;
pbi_stop_err:
return ret;
}
/*
* Returns:
* File size in bytes, on Success.
* FAILURE, on failure.
*/
int get_filesize(const char *c)
{
FILE *fp;
int ret = FAILURE;
fp = fopen(c, "rb");
if (fp == NULL) {
fprintf(stderr, "%s: Error in opening the file: %s\n",
__func__, c);
goto filesize_err;
}
fseek(fp, 0L, SEEK_END);
ret = ftell(fp);
fclose(fp);
filesize_err:
return ret;
}
/***************************************************************************
* Function : get_bootptr
* Arguments : fp_rcw_pbi_op - Pointer to output file
* Return : SUCCESS or FAILURE
* Description : Add bootptr pbi command to output file
***************************************************************************/
int add_boot_ptr_cmd(FILE *fp_rcw_pbi_op)
{
uint32_t bootptr_addr;
int ret = FAILURE;
switch (pblimg.chassis) {
case CHASSIS_2:
if (sb_flag == true)
bootptr_addr = BYTE_SWAP_32(CSF_ADDR_SB);
else
bootptr_addr = BYTE_SWAP_32(BOOTPTR_ADDR);
pblimg.ep = BYTE_SWAP_32(pblimg.ep);
break;
case CHASSIS_3:
case CHASSIS_3_2:
if (sb_flag == true)
bootptr_addr = CSF_ADDR_SB_CH3;
else
bootptr_addr = BOOTPTR_ADDR_CH3;
break;
case CHASSIS_UNKNOWN:
case CHASSIS_MAX:
default:
printf("Internal Error: Invalid Chassis val = %d.\n",
pblimg.chassis);
goto bootptr_err;
}
if (fwrite(&bootptr_addr, sizeof(bootptr_addr), NUM_MEM_BLOCK,
fp_rcw_pbi_op) != NUM_MEM_BLOCK) {
printf("%s: Error in Writing PBI Words:[%d].\n",
__func__, ret);
goto bootptr_err;
}
if (pblimg.ep != 0) {
if (fwrite(&pblimg.ep, sizeof(pblimg.ep), NUM_MEM_BLOCK,
fp_rcw_pbi_op) != NUM_MEM_BLOCK) {
printf("%s: Error in Writing PBI Words\n", __func__);
goto bootptr_err;
}
}
printf("\nBoot Location Pointer= %x\n", BYTE_SWAP_32(pblimg.ep));
ret = SUCCESS;
bootptr_err:
return ret;
}
/***************************************************************************
* Function : add_blk_cpy_cmd
* Arguments : pbi_word - pointer to pbi commands
* args - Command line args flag.
* Return : SUCCESS or FAILURE
* Description : Add pbi commands for block copy cmd in pbi_words
***************************************************************************/
int add_blk_cpy_cmd(FILE *fp_rcw_pbi_op, uint16_t args)
{
uint32_t blk_cpy_hdr;
uint32_t file_size, new_file_size;
uint32_t align = 4;
int ret = FAILURE;
int num_pad_bytes = 0;
if ((args & BL2_BIN_STRG_LOC_BOOT_SRC_ARG_MASK) == 0) {
printf("ERROR: Offset not specified for Block Copy Cmd.\n");
printf("\tSee Usage and use -f option\n");
goto blk_copy_err;
}
switch (pblimg.chassis) {
case CHASSIS_3:
/* Block copy command */
blk_cpy_hdr = blk_cpy_hdr_map_ch3[pblimg.boot_src];
pblimg.src_addr += base_addr_ch3[pblimg.boot_src];
break;
case CHASSIS_3_2:
/* Block copy command */
blk_cpy_hdr = blk_cpy_hdr_map_ch32[pblimg.boot_src];
pblimg.src_addr += base_addr_ch32[pblimg.boot_src];
break;
default:
printf("%s: Error invalid chassis type for this command.\n",
__func__);
goto blk_copy_err;
}
file_size = get_filesize(pblimg.sec_imgnm);
if (file_size > 0) {
new_file_size = (file_size + (file_size % align));
/* Add Block copy command */
if (fwrite(&blk_cpy_hdr, sizeof(blk_cpy_hdr), NUM_MEM_BLOCK,
fp_rcw_pbi_op) != NUM_MEM_BLOCK) {
printf("%s: Error writing blk_cpy_hdr to the file.\n",
__func__);
goto blk_copy_err;
}
if ((args & BL2_BIN_STRG_LOC_BOOT_SRC_ARG_MASK) == 0)
num_pad_bytes = pblimg.src_addr % 4;
/* Add Src address word */
if (fwrite(&pblimg.src_addr + num_pad_bytes,
sizeof(pblimg.src_addr), NUM_MEM_BLOCK,
fp_rcw_pbi_op) != NUM_MEM_BLOCK) {
printf("%s: Error writing BLK SRC Addr to the file.\n",
__func__);
goto blk_copy_err;
}
/* Add Dest address word */
if (fwrite(&pblimg.addr, sizeof(pblimg.addr),
NUM_MEM_BLOCK, fp_rcw_pbi_op) != NUM_MEM_BLOCK) {
printf("%s: Error writing DST Addr to the file.\n",
__func__);
goto blk_copy_err;
}
/* Add size */
if (fwrite(&new_file_size, sizeof(new_file_size),
NUM_MEM_BLOCK, fp_rcw_pbi_op) != NUM_MEM_BLOCK) {
printf("%s: Error writing size to the file.\n",
__func__);
goto blk_copy_err;
}
}
ret = SUCCESS;
blk_copy_err:
return ret;
}
/***************************************************************************
* Function : add_cpy_cmd
* Arguments : pbi_word - pointer to pbi commands
* Return : SUCCESS or FAILURE
* Description : Append pbi commands for copying BL2 image to the
* load address stored in pbl_image.addr
***************************************************************************/
int add_cpy_cmd(FILE *fp_rcw_pbi_op)
{
uint32_t ALTCBAR_ADDRESS = BYTE_SWAP_32(0x09570158);
uint32_t WAIT_CMD_WRITE_ADDRESS = BYTE_SWAP_32(0x096100c0);
uint32_t WAIT_CMD = BYTE_SWAP_32(0x000FFFFF);
int file_size;
uint32_t pbi_cmd, altcbar;
uint8_t pbi_data[MAX_PBI_DATA_LEN_BYTE];
uint32_t dst_offset;
FILE *fp_img = NULL;
int ret = FAILURE;
altcbar = pblimg.addr;
dst_offset = pblimg.addr;
fp_img = fopen(pblimg.sec_imgnm, "rb");
if (fp_img == NULL) {
printf("%s: Error in opening the file: %s\n", __func__,
pblimg.sec_imgnm);
goto add_cpy_err;
}
file_size = get_filesize(pblimg.sec_imgnm);
altcbar = 0xfff00000 & altcbar;
altcbar = BYTE_SWAP_32(altcbar >> 16);
if (fwrite(&ALTCBAR_ADDRESS, sizeof(ALTCBAR_ADDRESS), NUM_MEM_BLOCK,
fp_rcw_pbi_op) != NUM_MEM_BLOCK) {
printf("%s: Error in writing address of ALTCFG CMD.\n",
__func__);
goto add_cpy_err;
}
if (fwrite(&altcbar, sizeof(altcbar), NUM_MEM_BLOCK, fp_rcw_pbi_op)
!= NUM_MEM_BLOCK) {
printf("%s: Error in writing ALTCFG CMD.\n", __func__);
goto add_cpy_err;
}
if (fwrite(&WAIT_CMD_WRITE_ADDRESS, sizeof(WAIT_CMD_WRITE_ADDRESS),
NUM_MEM_BLOCK, fp_rcw_pbi_op) != NUM_MEM_BLOCK) {
printf("%s: Error in writing address of WAIT_CMD.\n",
__func__);
goto add_cpy_err;
}
if (fwrite(&WAIT_CMD, sizeof(WAIT_CMD), NUM_MEM_BLOCK, fp_rcw_pbi_op)
!= NUM_MEM_BLOCK) {
printf("%s: Error in writing WAIT_CMD.\n", __func__);
goto add_cpy_err;
}
do {
memset(pbi_data, 0, MAX_PBI_DATA_LEN_BYTE);
ret = fread(&pbi_data, MAX_PBI_DATA_LEN_BYTE,
NUM_MEM_BLOCK, fp_img);
if ((ret != NUM_MEM_BLOCK) && (!feof(fp_img))) {
printf("%s: Error writing ALTCFG Word: [%d].\n",
__func__, ret);
goto add_cpy_err;
}
dst_offset &= OFFSET_MASK;
pbi_cmd = WRITE_CMD_BASE | dst_offset;
pbi_cmd = BYTE_SWAP_32(pbi_cmd);
if (fwrite(&pbi_cmd, sizeof(pbi_cmd), NUM_MEM_BLOCK,
fp_rcw_pbi_op) != NUM_MEM_BLOCK) {
printf("%s: Error writing ALTCFG Word write cmd.\n",
__func__);
goto add_cpy_err;
}
if (fwrite(&pbi_data, MAX_PBI_DATA_LEN_BYTE, NUM_MEM_BLOCK,
fp_rcw_pbi_op) != NUM_MEM_BLOCK) {
printf("%s: Error writing ALTCFG_Word.\n", __func__);
goto add_cpy_err;
}
dst_offset += MAX_PBI_DATA_LEN_BYTE;
file_size -= MAX_PBI_DATA_LEN_BYTE;
} while (!feof(fp_img));
ret = SUCCESS;
add_cpy_err:
if (fp_img != NULL) {
fclose(fp_img);
}
return ret;
}
int main(int argc, char **argv)
{
FILE *file = NULL;
char *ptr;
int opt;
int tmp;
uint16_t args = ARG_INIT_MASK;
FILE *fp_rcw_pbi_ip = NULL, *fp_rcw_pbi_op = NULL;
uint32_t word, word_1;
int ret = FAILURE;
bool bootptr_flag = false;
enum stop_command flag_stop_cmd = CRC_STOP_COMMAND;
/* Initializing the global structure to zero. */
memset(&pblimg, 0x0, sizeof(struct pbl_image));
while ((opt = getopt(argc, argv,
":b:f:r:i:e:d:c:o:h:s")) != -1) {
switch (opt) {
case 'd':
pblimg.addr = strtoull(optarg, &ptr, 16);
if (*ptr != 0) {
fprintf(stderr, "CMD Error: invalid load or destination address %s\n", optarg);
goto exit_main;
}
args |= BL2_BIN_CPY_DEST_ADDR_ARG_MASK;
break;
case 'r':
pblimg.rcw_nm = optarg;
file = fopen(pblimg.rcw_nm, "r");
if (file == NULL) {
printf("CMD Error: Opening the RCW File.\n");
goto exit_main;
} else {
args |= RCW_FILE_NAME_ARG_MASK;
fclose(file);
}
break;
case 'e':
bootptr_flag = true;
pblimg.ep = strtoull(optarg, &ptr, 16);
if (*ptr != 0) {
fprintf(stderr,
"CMD Error: Invalid entry point %s\n", optarg);
goto exit_main;
}
break;
case 'h':
print_usage();
break;
case 'i':
pblimg.sec_imgnm = optarg;
file = fopen(pblimg.sec_imgnm, "r");
if (file == NULL) {
printf("CMD Error: Opening Input file.\n");
goto exit_main;
} else {
args |= IN_FILE_NAME_ARG_MASK;
fclose(file);
}
break;
case 'c':
tmp = atoi(optarg);
switch (tmp) {
case SOC_LS1012:
case SOC_LS1023:
case SOC_LS1026:
case SOC_LS1043:
case SOC_LS1046:
pblimg.chassis = CHASSIS_2;
break;
case SOC_LS1088:
case SOC_LS2080:
case SOC_LS2088:
pblimg.chassis = CHASSIS_3;
break;
case SOC_LS1028:
case SOC_LX2160:
pblimg.chassis = CHASSIS_3_2;
break;
default:
printf("CMD Error: Invalid SoC Val = %d.\n", tmp);
goto exit_main;
}
args |= CHASSIS_ARG_MASK;
break;
case 'o':
pblimg.imagefile = optarg;
args |= OP_FILE_NAME_ARG_MASK;
break;
case 's':
sb_flag = true;
break;
case 'b':
if (strcmp(optarg, "qspi") == 0) {
pblimg.boot_src = QSPI_BOOT;
} else if (strcmp(optarg, "nor") == 0) {
pblimg.boot_src = IFC_NOR_BOOT;
} else if (strcmp(optarg, "nand") == 0) {
pblimg.boot_src = IFC_NAND_BOOT;
} else if (strcmp(optarg, "sd") == 0) {
pblimg.boot_src = SD_BOOT;
} else if (strcmp(optarg, "emmc") == 0) {
pblimg.boot_src = EMMC_BOOT;
} else if (strcmp(optarg, "flexspi_nor") == 0) {
pblimg.boot_src = FLXSPI_NOR_BOOT;
} else if (strcmp(optarg, "flexspi_nand") == 0) {
pblimg.boot_src = FLXSPI_NAND_BOOT;
} else if (strcmp(optarg, "flexspi_nand2k") == 0) {
pblimg.boot_src = FLXSPI_NAND4K_BOOT;
} else {
printf("CMD Error: Invalid boot source.\n");
goto exit_main;
}
args |= BOOT_SRC_ARG_MASK;
break;
case 'f':
pblimg.src_addr = strtoull(optarg, &ptr, 16);
if (*ptr != 0) {
fprintf(stderr,
"CMD Error: Invalid src offset %s\n", optarg);
goto exit_main;
}
args |= BL2_BIN_STRG_LOC_BOOT_SRC_ARG_MASK;
break;
default:
/* issue a warning and skip the unknown arg */
printf("Cmd Warning: Invalid Arg = %c.\n", opt);
}
}
if ((args & MAND_ARG_MASK) != MAND_ARG_MASK) {
print_usage();
}
fp_rcw_pbi_ip = fopen(pblimg.rcw_nm, "rb");
if (fp_rcw_pbi_ip == NULL) {
printf("%s: Error in opening the rcw file: %s\n",
__func__, pblimg.rcw_nm);
goto exit_main;
}
fp_rcw_pbi_op = fopen(pblimg.imagefile, "wb+");
if (fp_rcw_pbi_op == NULL) {
printf("%s: Error opening the input file: %s\n",
__func__, pblimg.imagefile);
goto exit_main;
}
printf("\nInput Boot Source: %s\n", boot_src_string[pblimg.boot_src]);
printf("Input RCW File: %s\n", pblimg.rcw_nm);
printf("Input BL2 Binary File: %s\n", pblimg.sec_imgnm);
printf("Input load address for BL2 Binary File: 0x%x\n", pblimg.addr);
printf("Chassis Type: %d\n", pblimg.chassis);
switch (pblimg.chassis) {
case CHASSIS_2:
if (fread(&word, sizeof(word), NUM_MEM_BLOCK, fp_rcw_pbi_ip)
!= NUM_MEM_BLOCK) {
printf("%s: Error in reading word from the rcw file.\n",
__func__);
goto exit_main;
}
while (BYTE_SWAP_32(word) != 0x08610040) {
if (BYTE_SWAP_32(word) == 0x09550000
|| BYTE_SWAP_32(word) == 0x000f400c) {
break;
}
if (fwrite(&word, sizeof(word), NUM_MEM_BLOCK,
fp_rcw_pbi_op) != NUM_MEM_BLOCK) {
printf("%s: [CH2] Error in Writing PBI Words\n",
__func__);
goto exit_main;
}
if (fread(&word, sizeof(word), NUM_MEM_BLOCK,
fp_rcw_pbi_ip) != NUM_MEM_BLOCK) {
printf("%s: [CH2] Error in Reading PBI Words\n",
__func__);
goto exit_main;
}
}
if (bootptr_flag == true) {
/* Add command to set boot_loc ptr */
ret = add_boot_ptr_cmd(fp_rcw_pbi_op);
if (ret != SUCCESS) {
goto exit_main;
}
}
/* Write acs write commands to output file */
ret = add_cpy_cmd(fp_rcw_pbi_op);
if (ret != SUCCESS) {
goto exit_main;
}
/* Add stop command after adding pbi commands
* For Chasis 2.0 platforms it is always CRC &
* Stop command
*/
flag_stop_cmd = CRC_STOP_COMMAND;
ret = add_pbi_stop_cmd(fp_rcw_pbi_op, flag_stop_cmd);
if (ret != SUCCESS) {
goto exit_main;
}
break;
case CHASSIS_3:
case CHASSIS_3_2:
if (fread(&word, sizeof(word), NUM_MEM_BLOCK, fp_rcw_pbi_ip)
!= NUM_MEM_BLOCK) {
printf("%s: Error reading PBI Cmd.\n", __func__);
goto exit_main;
}
while (word != 0x808f0000 && word != 0x80ff0000) {
pbl_size++;
/* 11th words in RCW has PBL length. Update it
* with new length. 2 comamnds get added
* Block copy + CCSR Write/CSF header write
*/
if (pbl_size == 11) {
word_1 = (word & PBI_LEN_MASK)
+ (PBI_LEN_ADD << 20);
word = word & ~PBI_LEN_MASK;
word = word | word_1;
}
/* Update the CRC command */
/* Check load command..
* add a check if command is Stop with CRC
* or stop without checksum
*/
if (pbl_size == 35) {
word = crypto_calculate_checksum(fp_rcw_pbi_op,
NUM_RCW_WORD - 1);
if (word == FAILURE) {
goto exit_main;
}
}
if (fwrite(&word, sizeof(word), NUM_MEM_BLOCK,
fp_rcw_pbi_op) != NUM_MEM_BLOCK) {
printf("%s: [CH3] Error in Writing PBI Words\n",
__func__);
goto exit_main;
}
if (fread(&word, sizeof(word), NUM_MEM_BLOCK,
fp_rcw_pbi_ip) != NUM_MEM_BLOCK) {
printf("%s: [CH3] Error in Reading PBI Words\n",
__func__);
goto exit_main;
}
if (word == CRC_STOP_CMD_ARM_CH3) {
flag_stop_cmd = CRC_STOP_COMMAND;
} else if (word == STOP_CMD_ARM_CH3) {
flag_stop_cmd = STOP_COMMAND;
}
}
if (bootptr_flag == true) {
/* Add command to set boot_loc ptr */
ret = add_boot_ptr_cmd(fp_rcw_pbi_op);
if (ret != SUCCESS) {
printf("%s: add_boot_ptr_cmd return failure.\n",
__func__);
goto exit_main;
}
}
/* Write acs write commands to output file */
ret = add_blk_cpy_cmd(fp_rcw_pbi_op, args);
if (ret != SUCCESS) {
printf("%s: Function add_blk_cpy_cmd return failure.\n",
__func__);
goto exit_main;
}
/* Add stop command after adding pbi commands */
ret = add_pbi_stop_cmd(fp_rcw_pbi_op, flag_stop_cmd);
if (ret != SUCCESS) {
goto exit_main;
}
break;
default:
printf("%s: Unknown chassis type.\n",
__func__);
}
if (ret == SUCCESS) {
printf("Output file successfully created with name: %s\n\n",
pblimg.imagefile);
}
exit_main:
if (fp_rcw_pbi_op != NULL) {
fclose(fp_rcw_pbi_op);
}
if (fp_rcw_pbi_ip != NULL) {
fclose(fp_rcw_pbi_ip);
}
return ret;
}
|
the_stack_data/1034726.c | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
bool check_sorted(int *a, int n)
{
while ( --n >= 1 ) {
if ( a[n] < a[n-1] ) return false;
}
return true;
}
void shuffle(int *a, int n)
{
int i, t, r;
for(i=0; i < n; i++) {
t = a[i];
r = rand() % n;
a[i] = a[r];
a[r] = t;
}
}
void sort(int *a, int n)
{
while ( !check_sorted(a, n) ) shuffle(a, n);
}
int main()
{
int numbers[6];
int i;
printf("Enter 6 numbers unsorted \n\n");
for(i=0;i<6;i++){
scanf("%d",&numbers[i]);
}
sort(numbers, 6);
for (i=0; i < 6; i++) printf("%d ", numbers[i]);
printf("\n");
}
|
the_stack_data/15763651.c | #include <stdio.h>
#if defined(__LITEOS__) && defined(LOSCFG_LLTSER)
#include "gcov_ser.h"
#endif
void setbuf(FILE *restrict f, char *restrict buf)
{
#if defined(__LITEOS__) && defined(LOSCFG_LLTSER)
GCOV_SETBUF(f);
#endif
setvbuf(f, buf, buf ? _IOFBF : _IONBF, BUFSIZ);
}
|
the_stack_data/143482.c | // Copyright 2017 The Australian National University
//
// 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.
#ifdef __linux__
// RTLD_DEFAULT is not defined in POSIX. Linux gcc does not define it unless
// _GNU_SOURCE is also defined.
#define _GNU_SOURCE
#endif // __linux__
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <assert.h>
int tls_initialized = 0;
static pthread_key_t mu_tls;
void set_thread_local(void* thread) {
if(tls_initialized == 0){
tls_initialized = 1;
int result = pthread_key_create(&mu_tls, NULL);
if(result != 0){
printf("Set_Thread_Local(): PThread key create failed with error code = %d\n", result);
assert(0);
}
}
int result = pthread_setspecific(mu_tls, thread);
if(result != 0){
printf("Set_Thread_Local(): PThread set specific failed with error code = %d\n", result);
assert(0);
}
}
void* muentry_get_thread_local() {
if(tls_initialized == 0){
printf("Get_Thread_Local(): PThread key MUST be initialized before first use!!\n");
assert(0);
}
void * result = pthread_getspecific(mu_tls);
if(result == NULL){
printf("Get_Thread_Local(): NO pthread key found for current thread!!\n");
assert(0);
}
return result;
}
int32_t mu_retval;
void muentry_set_retval(int32_t x) {
mu_retval = x;
}
int32_t muentry_get_retval() {
return mu_retval;
}
int32_t c_check_result() {
return mu_retval;
}
char * alloc_mem(size_t size){
return (char *) malloc(size);
}
|
the_stack_data/37637828.c | #include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAXTOKEN 100
enum { NAME, PARENS, BRACKETS };
enum { NO, YES };
void dcl(void);
void dirdcl(void);
int gettoken(void);
int tokentype; /* type of last token */
char token[MAXTOKEN]; /* last token string */
char name[MAXTOKEN]; /* identifier name */
char datatype[MAXTOKEN]; /* data type = char, int, etc. */
char out[1000]; /* output string */
int errtoken = NO;
main() /* convert declaration to words */
{
while (gettoken() != EOF) { /* 1st token on line */
strcpy(datatype, token); /* is the datatype */
out[0] = '\0';
dcl(); /* parse rest of line */
if (tokentype != '\n')
printf("syntax error\n");
printf("%s: %s %s\n", name, out, datatype);
}
return 0;
}
int gettoken(void) /* return next token */
{
int c, getch(void);
void ungetch(int);
char *p = token;
if (errtoken == YES) {
errtoken = NO;
return tokentype;
}
while ((c = getch()) == ' ' || c == '\t')
;
if (c == '(') {
if ((c = getch()) == ')') {
strcpy(token, "()");
return tokentype = PARENS;
} else {
ungetch(c);
return tokentype = '(';
}
} else if (c == '[') {
for (*p++ = c; (*p++ = getch()) != ']'; )
;
*p = '\0';
return tokentype = BRACKETS;
} else if (isalpha(c)) {
for (*p++ = c; isalnum(c = getch()); )
*p++ = c;
*p = '\0';
ungetch(c);
return tokentype = NAME;
} else
return tokentype = c;
}
/* dcl: parse a declarator */
void dcl(void)
{
int ns;
for (ns = 0; gettoken() == '*';) /* count *'s */
ns++;
dirdcl();
while (ns-- > 0)
strcat(out, " pointer to");
}
/* dirdcl: parse a direct declarator */
void dirdcl(void)
{
int type;
void paramdcl(void);
if (tokentype == '(') { /* ( dcl ) */
dcl();
if (tokentype != ')') {
printf("error: missing )\n");
errtoken = YES;
}
} else if (tokentype == NAME) { /* variable name */
if (name[0] == '\0')
strcpy(name, token);
} else {
printf("error: expected name or (dcl)\n");
errtoken = YES;
}
while ((type=gettoken()) == PARENS || type == BRACKETS || type == '(')
if (type == PARENS)
strcat(out, " function returning");
else if (type == '(') {
strcat(out, " function taking");
paramdcl();
strcat(out, " and returning");
} else {
strcat(out, " array");
strcat(out, token);
strcat(out, " of");
}
}
#include <stdlib.h>
void declspec(void);
int typespec(void);
int typedesc(void);
void paramdcl(void)
{
do {
declspec();
} while (tokentype == ',');
if (tokentype != ')') {
printf("error: missing ) in declarator of parameters\n");
errtoken = YES;
}
}
void declspec(void)
{
char temp[MAXTOKEN];
temp[0] = '\0';
gettoken();
do {
if (tokentype != NAME) {
errtoken = YES;
dcl();
} else if (typespec() == YES || typedesc() == YES) {
strcat(temp, " ");
strcat(temp, token);
gettoken();
} else {
printf("error: unknown type in the parameter list\n");
errtoken = YES;
}
} while (tokentype != ',' && tokentype != ')');
strcat(out, temp);
if (tokentype == ',')
strcat(out, ",");
}
int typespec(void)
{
static char *types[] = { "char", "int", "void" };
char *ptypes = token;
int result, i;
result = NO;
for (i = 0; i < 3; i++)
if (strcmp(ptypes, *(types + i)) == 0)
return result = YES;
return result;
}
int typedesc(void)
{
static char *typed[] = { "const", "volatile" };
char *ptd = token;
int result, i;
result = NO;
for (i = 0; i < 2; i++)
if (strcmp(ptd, *(typed + i)) == 0)
return result = YES;
return result;
}
#define BUFSIZE 100
char buf[BUFSIZE]; /* buffer for ungetch */
int bufp = 0; /* next free position in buf */
int getch(void) /* get a (possibly pushed back) character */
{
return (bufp > 0) ? buf[--bufp] : getchar();
}
void ungetch(int c) /* push character back on input */
{
if (bufp >= BUFSIZE)
printf("ungetch: to many characters\n");
else
buf[bufp++] = c;
}
|
the_stack_data/21622.c | #ifdef CS333_P3
// A starting point for writing your own p3 test program(s).
// Notes
// 1. The parent never gets to the wait() call, so killing any child will cause that
// child to move to zombie indefinitely.
// 2. When running as a background process, the parent of the main process
// will be init. This is how background processes work. Read sh.c for details.
// 3. Useful test: run in background then kill a child. Child will be in zombie. Now
// kill parent. Should get "zombie!" equal to the number of zombies.
// ps or ^p should now show init as the parent of all child processes.
// init will then reap the zombies.
// 4. Can also be used to show that the RUNNABLE list is still round robin.
#include "types.h"
#include "user.h"
#include "param.h"
#include "pdx.h"
int
main(int argc, char *argv[])
{
int rc, i = 0, childCount = 20;
if(argc > 1)
childCount = atoi(argv[1]);
if(!childCount)
{
printf(2, "No children to create, so %s is exiting.\n", argv[0]);
exit();
}
printf(1, "Starting %d child process that will run forever\n", childCount);
do {
rc = fork();
if(rc < 0)
{
printf(2, "Fork Failed!\n");
exit();
}
if(rc == 0) {
while(1)
++i;
exit();
}
--childCount;
}while(childCount);
printf(1, "All child processes created\n");
wait();
while(1)
++i;
exit();
}
#endif
|
the_stack_data/148577744.c | /* Not copyrighted 1990 Mark Adler */
#include <stdio.h>
main()
/*
Generate a table for a byte-wise 32-bit CRC calculation on the polynomial:
x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.
Polynomials over GF(2) are represented in binary, one bit per coefficient,
with the lowest powers in the most significant bit. Then adding polynomials
is just exclusive-or, and multiplying a polynomial by x is a right shift by
one. If we call the above polynomial p, and represent a byte as the
polynomial q, also with the lowest power in the most significant bit (so the
byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
where a mod b means the remainder after dividing a by b.
This calculation is done using the shift-register method of multiplying and
taking the remainder. The register is initialized to zero, and for each
incoming bit, x^32 is added mod p to the register if the bit is a one (where
x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
x (which is shifting right by one and adding x^32 mod p if the bit shifted
out is a one). We start with the highest power (least significant bit) of
q and repeat for all eight bits of q.
The table is simply the CRC of all possible eight bit values. This is all
the information needed to generate CRC's on data a byte at a time for all
combinations of CRC register values and incoming bytes. The table is
written to stdout as 256 long hexadecimal values in C language format.
*/
{
unsigned long c; /* crc shift register */
unsigned long e; /* polynomial exclusive-or pattern */
int i; /* counter for all possible eight bit values */
int k; /* byte being shifted into crc apparatus */
/* terms of polynomial defining this crc (except x^32): */
static int p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
/* Make exclusive-or pattern from polynomial */
e = 0;
for (i = 0; i < sizeof(p)/sizeof(int); i++)
e |= 1L << (31 - p[i]);
/* Compute and print table of CRC's, five per line */
printf(" 0x00000000L");
for (i = 1; i < 256; i++)
{
c = 0;
for (k = i | 256; k != 1; k >>= 1)
{
c = c & 1 ? (c >> 1) ^ e : c >> 1;
if (k & 1)
c ^= e;
}
printf(i % 5 ? ", 0x%08lxL" : ",\n 0x%08lxL", c);
}
putchar('\n');
return 0;
}
|
the_stack_data/129393.c | /* f2c.h -- Standard Fortran to C header file */
/** barf [ba:rf] 2. "He suggested using FORTRAN, and everybody barfed."
- From The Shogakukan DICTIONARY OF NEW ENGLISH (Second edition) */
#ifndef F2C_INCLUDE
#define F2C_INCLUDE
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <complex.h>
#ifdef complex
#undef complex
#endif
#ifdef I
#undef I
#endif
#if defined(_WIN64)
typedef long long BLASLONG;
typedef unsigned long long BLASULONG;
#else
typedef long BLASLONG;
typedef unsigned long BLASULONG;
#endif
#ifdef LAPACK_ILP64
typedef BLASLONG blasint;
#if defined(_WIN64)
#define blasabs(x) llabs(x)
#else
#define blasabs(x) labs(x)
#endif
#else
typedef int blasint;
#define blasabs(x) abs(x)
#endif
typedef blasint integer;
typedef unsigned int uinteger;
typedef char *address;
typedef short int shortint;
typedef float real;
typedef double doublereal;
typedef struct { real r, i; } complex;
typedef struct { doublereal r, i; } doublecomplex;
static inline _Complex float Cf(complex *z) {return z->r + z->i*_Complex_I;}
static inline _Complex double Cd(doublecomplex *z) {return z->r + z->i*_Complex_I;}
static inline _Complex float * _pCf(complex *z) {return (_Complex float*)z;}
static inline _Complex double * _pCd(doublecomplex *z) {return (_Complex double*)z;}
#define pCf(z) (*_pCf(z))
#define pCd(z) (*_pCd(z))
typedef int logical;
typedef short int shortlogical;
typedef char logical1;
typedef char integer1;
#define TRUE_ (1)
#define FALSE_ (0)
/* Extern is for use with -E */
#ifndef Extern
#define Extern extern
#endif
/* I/O stuff */
typedef int flag;
typedef int ftnlen;
typedef int ftnint;
/*external read, write*/
typedef struct
{ flag cierr;
ftnint ciunit;
flag ciend;
char *cifmt;
ftnint cirec;
} cilist;
/*internal read, write*/
typedef struct
{ flag icierr;
char *iciunit;
flag iciend;
char *icifmt;
ftnint icirlen;
ftnint icirnum;
} icilist;
/*open*/
typedef struct
{ flag oerr;
ftnint ounit;
char *ofnm;
ftnlen ofnmlen;
char *osta;
char *oacc;
char *ofm;
ftnint orl;
char *oblnk;
} olist;
/*close*/
typedef struct
{ flag cerr;
ftnint cunit;
char *csta;
} cllist;
/*rewind, backspace, endfile*/
typedef struct
{ flag aerr;
ftnint aunit;
} alist;
/* inquire */
typedef struct
{ flag inerr;
ftnint inunit;
char *infile;
ftnlen infilen;
ftnint *inex; /*parameters in standard's order*/
ftnint *inopen;
ftnint *innum;
ftnint *innamed;
char *inname;
ftnlen innamlen;
char *inacc;
ftnlen inacclen;
char *inseq;
ftnlen inseqlen;
char *indir;
ftnlen indirlen;
char *infmt;
ftnlen infmtlen;
char *inform;
ftnint informlen;
char *inunf;
ftnlen inunflen;
ftnint *inrecl;
ftnint *innrec;
char *inblank;
ftnlen inblanklen;
} inlist;
#define VOID void
union Multitype { /* for multiple entry points */
integer1 g;
shortint h;
integer i;
/* longint j; */
real r;
doublereal d;
complex c;
doublecomplex z;
};
typedef union Multitype Multitype;
struct Vardesc { /* for Namelist */
char *name;
char *addr;
ftnlen *dims;
int type;
};
typedef struct Vardesc Vardesc;
struct Namelist {
char *name;
Vardesc **vars;
int nvars;
};
typedef struct Namelist Namelist;
#define abs(x) ((x) >= 0 ? (x) : -(x))
#define dabs(x) (fabs(x))
#define f2cmin(a,b) ((a) <= (b) ? (a) : (b))
#define f2cmax(a,b) ((a) >= (b) ? (a) : (b))
#define dmin(a,b) (f2cmin(a,b))
#define dmax(a,b) (f2cmax(a,b))
#define bit_test(a,b) ((a) >> (b) & 1)
#define bit_clear(a,b) ((a) & ~((uinteger)1 << (b)))
#define bit_set(a,b) ((a) | ((uinteger)1 << (b)))
#define abort_() { sig_die("Fortran abort routine called", 1); }
#define c_abs(z) (cabsf(Cf(z)))
#define c_cos(R,Z) { pCf(R)=ccos(Cf(Z)); }
#define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);}
#define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);}
#define c_exp(R, Z) {pCf(R) = cexpf(Cf(Z));}
#define c_log(R, Z) {pCf(R) = clogf(Cf(Z));}
#define c_sin(R, Z) {pCf(R) = csinf(Cf(Z));}
//#define c_sqrt(R, Z) {*(R) = csqrtf(Cf(Z));}
#define c_sqrt(R, Z) {pCf(R) = csqrtf(Cf(Z));}
#define d_abs(x) (fabs(*(x)))
#define d_acos(x) (acos(*(x)))
#define d_asin(x) (asin(*(x)))
#define d_atan(x) (atan(*(x)))
#define d_atn2(x, y) (atan2(*(x),*(y)))
#define d_cnjg(R, Z) { pCd(R) = conj(Cd(Z)); }
#define r_cnjg(R, Z) { pCf(R) = conj(Cf(Z)); }
#define d_cos(x) (cos(*(x)))
#define d_cosh(x) (cosh(*(x)))
#define d_dim(__a, __b) ( *(__a) > *(__b) ? *(__a) - *(__b) : 0.0 )
#define d_exp(x) (exp(*(x)))
#define d_imag(z) (cimag(Cd(z)))
#define r_imag(z) (cimag(Cf(z)))
#define d_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x)))
#define r_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x)))
#define d_lg10(x) ( 0.43429448190325182765 * log(*(x)) )
#define r_lg10(x) ( 0.43429448190325182765 * log(*(x)) )
#define d_log(x) (log(*(x)))
#define d_mod(x, y) (fmod(*(x), *(y)))
#define u_nint(__x) ((__x)>=0 ? floor((__x) + .5) : -floor(.5 - (__x)))
#define d_nint(x) u_nint(*(x))
#define u_sign(__a,__b) ((__b) >= 0 ? ((__a) >= 0 ? (__a) : -(__a)) : -((__a) >= 0 ? (__a) : -(__a)))
#define d_sign(a,b) u_sign(*(a),*(b))
#define r_sign(a,b) u_sign(*(a),*(b))
#define d_sin(x) (sin(*(x)))
#define d_sinh(x) (sinh(*(x)))
#define d_sqrt(x) (sqrt(*(x)))
#define d_tan(x) (tan(*(x)))
#define d_tanh(x) (tanh(*(x)))
#define i_abs(x) abs(*(x))
#define i_dnnt(x) ((integer)u_nint(*(x)))
#define i_len(s, n) (n)
#define i_nint(x) ((integer)u_nint(*(x)))
#define i_sign(a,b) ((integer)u_sign((integer)*(a),(integer)*(b)))
#define pow_dd(ap, bp) ( pow(*(ap), *(bp)))
#define pow_si(B,E) spow_ui(*(B),*(E))
#define pow_ri(B,E) spow_ui(*(B),*(E))
#define pow_di(B,E) dpow_ui(*(B),*(E))
#define pow_zi(p, a, b) {pCd(p) = zpow_ui(Cd(a), *(b));}
#define pow_ci(p, a, b) {pCf(p) = cpow_ui(Cf(a), *(b));}
#define pow_zz(R,A,B) {pCd(R) = cpow(Cd(A),*(B));}
#define s_cat(lpp, rpp, rnp, np, llp) { ftnlen i, nc, ll; char *f__rp, *lp; ll = (llp); lp = (lpp); for(i=0; i < (int)*(np); ++i) { nc = ll; if((rnp)[i] < nc) nc = (rnp)[i]; ll -= nc; f__rp = (rpp)[i]; while(--nc >= 0) *lp++ = *(f__rp)++; } while(--ll >= 0) *lp++ = ' '; }
#define s_cmp(a,b,c,d) ((integer)strncmp((a),(b),f2cmin((c),(d))))
#define s_copy(A,B,C,D) { int __i,__m; for (__i=0, __m=f2cmin((C),(D)); __i<__m && (B)[__i] != 0; ++__i) (A)[__i] = (B)[__i]; }
#define sig_die(s, kill) { exit(1); }
#define s_stop(s, n) {exit(0);}
static char junk[] = "\n@(#)LIBF77 VERSION 19990503\n";
#define z_abs(z) (cabs(Cd(z)))
#define z_exp(R, Z) {pCd(R) = cexp(Cd(Z));}
#define z_sqrt(R, Z) {pCd(R) = csqrt(Cd(Z));}
#define myexit_() break;
#define mycycle() continue;
#define myceiling(w) {ceil(w)}
#define myhuge(w) {HUGE_VAL}
//#define mymaxloc_(w,s,e,n) {if (sizeof(*(w)) == sizeof(double)) dmaxloc_((w),*(s),*(e),n); else dmaxloc_((w),*(s),*(e),n);}
#define mymaxloc(w,s,e,n) {dmaxloc_(w,*(s),*(e),n)}
/* procedure parameter types for -A and -C++ */
#define F2C_proc_par_types 1
#ifdef __cplusplus
typedef logical (*L_fp)(...);
#else
typedef logical (*L_fp)();
#endif
static float spow_ui(float x, integer n) {
float pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static double dpow_ui(double x, integer n) {
double pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static _Complex float cpow_ui(_Complex float x, integer n) {
_Complex float pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static _Complex double zpow_ui(_Complex double x, integer n) {
_Complex double pow=1.0; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x = 1/x;
for(u = n; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static integer pow_ii(integer x, integer n) {
integer pow; unsigned long int u;
if (n <= 0) {
if (n == 0 || x == 1) pow = 1;
else if (x != -1) pow = x == 0 ? 1/x : 0;
else n = -n;
}
if ((n > 0) || !(n == 0 || x == 1 || x != -1)) {
u = n;
for(pow = 1; ; ) {
if(u & 01) pow *= x;
if(u >>= 1) x *= x;
else break;
}
}
return pow;
}
static integer dmaxloc_(double *w, integer s, integer e, integer *n)
{
double m; integer i, mi;
for(m=w[s-1], mi=s, i=s+1; i<=e; i++)
if (w[i-1]>m) mi=i ,m=w[i-1];
return mi-s+1;
}
static integer smaxloc_(float *w, integer s, integer e, integer *n)
{
float m; integer i, mi;
for(m=w[s-1], mi=s, i=s+1; i<=e; i++)
if (w[i-1]>m) mi=i ,m=w[i-1];
return mi-s+1;
}
static inline void cdotc_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex float zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conjf(Cf(&x[i])) * Cf(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conjf(Cf(&x[i*incx])) * Cf(&y[i*incy]);
}
}
pCf(z) = zdotc;
}
static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex double zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conj(Cd(&x[i])) * Cd(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += conj(Cd(&x[i*incx])) * Cd(&y[i*incy]);
}
}
pCd(z) = zdotc;
}
static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex float zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cf(&x[i]) * Cf(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cf(&x[i*incx]) * Cf(&y[i*incy]);
}
}
pCf(z) = zdotc;
}
static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
_Complex double zdotc = 0.0;
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cd(&x[i]) * Cd(&y[i]);
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc += Cd(&x[i*incx]) * Cd(&y[i*incy]);
}
}
pCd(z) = zdotc;
}
#endif
/* -- translated by f2c (version 20000121).
You must link the resulting object file with the libraries:
-lf2c -lm (in that order)
*/
/* Table of constant values */
static integer c__1 = 1;
static doublereal c_b22 = 1.;
static doublereal c_b23 = 0.;
/* > \brief \b DLAED3 used by sstedc. Finds the roots of the secular equation and updates the eigenvectors. Us
ed when the original matrix is tridiagonal. */
/* =========== DOCUMENTATION =========== */
/* Online html documentation available at */
/* http://www.netlib.org/lapack/explore-html/ */
/* > \htmlonly */
/* > Download DLAED3 + dependencies */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/dlaed3.
f"> */
/* > [TGZ]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/dlaed3.
f"> */
/* > [ZIP]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/dlaed3.
f"> */
/* > [TXT]</a> */
/* > \endhtmlonly */
/* Definition: */
/* =========== */
/* SUBROUTINE DLAED3( K, N, N1, D, Q, LDQ, RHO, DLAMDA, Q2, INDX, */
/* CTOT, W, S, INFO ) */
/* INTEGER INFO, K, LDQ, N, N1 */
/* DOUBLE PRECISION RHO */
/* INTEGER CTOT( * ), INDX( * ) */
/* DOUBLE PRECISION D( * ), DLAMDA( * ), Q( LDQ, * ), Q2( * ), */
/* $ S( * ), W( * ) */
/* > \par Purpose: */
/* ============= */
/* > */
/* > \verbatim */
/* > */
/* > DLAED3 finds the roots of the secular equation, as defined by the */
/* > values in D, W, and RHO, between 1 and K. It makes the */
/* > appropriate calls to DLAED4 and then updates the eigenvectors by */
/* > multiplying the matrix of eigenvectors of the pair of eigensystems */
/* > being combined by the matrix of eigenvectors of the K-by-K system */
/* > which is solved here. */
/* > */
/* > This code makes very mild assumptions about floating point */
/* > arithmetic. It will work on machines with a guard digit in */
/* > add/subtract, or on those binary machines without guard digits */
/* > which subtract like the Cray X-MP, Cray Y-MP, Cray C-90, or Cray-2. */
/* > It could conceivably fail on hexadecimal or decimal machines */
/* > without guard digits, but we know of none. */
/* > \endverbatim */
/* Arguments: */
/* ========== */
/* > \param[in] K */
/* > \verbatim */
/* > K is INTEGER */
/* > The number of terms in the rational function to be solved by */
/* > DLAED4. K >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in] N */
/* > \verbatim */
/* > N is INTEGER */
/* > The number of rows and columns in the Q matrix. */
/* > N >= K (deflation may result in N>K). */
/* > \endverbatim */
/* > */
/* > \param[in] N1 */
/* > \verbatim */
/* > N1 is INTEGER */
/* > The location of the last eigenvalue in the leading submatrix. */
/* > f2cmin(1,N) <= N1 <= N/2. */
/* > \endverbatim */
/* > */
/* > \param[out] D */
/* > \verbatim */
/* > D is DOUBLE PRECISION array, dimension (N) */
/* > D(I) contains the updated eigenvalues for */
/* > 1 <= I <= K. */
/* > \endverbatim */
/* > */
/* > \param[out] Q */
/* > \verbatim */
/* > Q is DOUBLE PRECISION array, dimension (LDQ,N) */
/* > Initially the first K columns are used as workspace. */
/* > On output the columns 1 to K contain */
/* > the updated eigenvectors. */
/* > \endverbatim */
/* > */
/* > \param[in] LDQ */
/* > \verbatim */
/* > LDQ is INTEGER */
/* > The leading dimension of the array Q. LDQ >= f2cmax(1,N). */
/* > \endverbatim */
/* > */
/* > \param[in] RHO */
/* > \verbatim */
/* > RHO is DOUBLE PRECISION */
/* > The value of the parameter in the rank one update equation. */
/* > RHO >= 0 required. */
/* > \endverbatim */
/* > */
/* > \param[in,out] DLAMDA */
/* > \verbatim */
/* > DLAMDA is DOUBLE PRECISION array, dimension (K) */
/* > The first K elements of this array contain the old roots */
/* > of the deflated updating problem. These are the poles */
/* > of the secular equation. May be changed on output by */
/* > having lowest order bit set to zero on Cray X-MP, Cray Y-MP, */
/* > Cray-2, or Cray C-90, as described above. */
/* > \endverbatim */
/* > */
/* > \param[in] Q2 */
/* > \verbatim */
/* > Q2 is DOUBLE PRECISION array, dimension (LDQ2*N) */
/* > The first K columns of this matrix contain the non-deflated */
/* > eigenvectors for the split problem. */
/* > \endverbatim */
/* > */
/* > \param[in] INDX */
/* > \verbatim */
/* > INDX is INTEGER array, dimension (N) */
/* > The permutation used to arrange the columns of the deflated */
/* > Q matrix into three groups (see DLAED2). */
/* > The rows of the eigenvectors found by DLAED4 must be likewise */
/* > permuted before the matrix multiply can take place. */
/* > \endverbatim */
/* > */
/* > \param[in] CTOT */
/* > \verbatim */
/* > CTOT is INTEGER array, dimension (4) */
/* > A count of the total number of the various types of columns */
/* > in Q, as described in INDX. The fourth column type is any */
/* > column which has been deflated. */
/* > \endverbatim */
/* > */
/* > \param[in,out] W */
/* > \verbatim */
/* > W is DOUBLE PRECISION array, dimension (K) */
/* > The first K elements of this array contain the components */
/* > of the deflation-adjusted updating vector. Destroyed on */
/* > output. */
/* > \endverbatim */
/* > */
/* > \param[out] S */
/* > \verbatim */
/* > S is DOUBLE PRECISION array, dimension (N1 + 1)*K */
/* > Will contain the eigenvectors of the repaired matrix which */
/* > will be multiplied by the previously accumulated eigenvectors */
/* > to update the system. */
/* > \endverbatim */
/* > */
/* > \param[out] INFO */
/* > \verbatim */
/* > INFO is INTEGER */
/* > = 0: successful exit. */
/* > < 0: if INFO = -i, the i-th argument had an illegal value. */
/* > > 0: if INFO = 1, an eigenvalue did not converge */
/* > \endverbatim */
/* Authors: */
/* ======== */
/* > \author Univ. of Tennessee */
/* > \author Univ. of California Berkeley */
/* > \author Univ. of Colorado Denver */
/* > \author NAG Ltd. */
/* > \date June 2017 */
/* > \ingroup auxOTHERcomputational */
/* > \par Contributors: */
/* ================== */
/* > */
/* > Jeff Rutter, Computer Science Division, University of California */
/* > at Berkeley, USA \n */
/* > Modified by Francoise Tisseur, University of Tennessee */
/* > */
/* ===================================================================== */
/* Subroutine */ int dlaed3_(integer *k, integer *n, integer *n1, doublereal *
d__, doublereal *q, integer *ldq, doublereal *rho, doublereal *dlamda,
doublereal *q2, integer *indx, integer *ctot, doublereal *w,
doublereal *s, integer *info)
{
/* System generated locals */
integer q_dim1, q_offset, i__1, i__2;
doublereal d__1;
/* Local variables */
doublereal temp;
extern doublereal dnrm2_(integer *, doublereal *, integer *);
integer i__, j;
extern /* Subroutine */ int dgemm_(char *, char *, integer *, integer *,
integer *, doublereal *, doublereal *, integer *, doublereal *,
integer *, doublereal *, doublereal *, integer *),
dcopy_(integer *, doublereal *, integer *, doublereal *, integer
*), dlaed4_(integer *, integer *, doublereal *, doublereal *,
doublereal *, doublereal *, doublereal *, integer *);
integer n2;
extern doublereal dlamc3_(doublereal *, doublereal *);
integer n12, ii, n23;
extern /* Subroutine */ int dlacpy_(char *, integer *, integer *,
doublereal *, integer *, doublereal *, integer *),
dlaset_(char *, integer *, integer *, doublereal *, doublereal *,
doublereal *, integer *), xerbla_(char *, integer *, ftnlen);
integer iq2;
/* -- LAPACK computational routine (version 3.7.1) -- */
/* -- LAPACK is a software package provided by Univ. of Tennessee, -- */
/* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */
/* June 2017 */
/* ===================================================================== */
/* Test the input parameters. */
/* Parameter adjustments */
--d__;
q_dim1 = *ldq;
q_offset = 1 + q_dim1 * 1;
q -= q_offset;
--dlamda;
--q2;
--indx;
--ctot;
--w;
--s;
/* Function Body */
*info = 0;
if (*k < 0) {
*info = -1;
} else if (*n < *k) {
*info = -2;
} else if (*ldq < f2cmax(1,*n)) {
*info = -6;
}
if (*info != 0) {
i__1 = -(*info);
xerbla_("DLAED3", &i__1, (ftnlen)6);
return 0;
}
/* Quick return if possible */
if (*k == 0) {
return 0;
}
/* Modify values DLAMDA(i) to make sure all DLAMDA(i)-DLAMDA(j) can */
/* be computed with high relative accuracy (barring over/underflow). */
/* This is a problem on machines without a guard digit in */
/* add/subtract (Cray XMP, Cray YMP, Cray C 90 and Cray 2). */
/* The following code replaces DLAMDA(I) by 2*DLAMDA(I)-DLAMDA(I), */
/* which on any of these machines zeros out the bottommost */
/* bit of DLAMDA(I) if it is 1; this makes the subsequent */
/* subtractions DLAMDA(I)-DLAMDA(J) unproblematic when cancellation */
/* occurs. On binary machines with a guard digit (almost all */
/* machines) it does not change DLAMDA(I) at all. On hexadecimal */
/* and decimal machines with a guard digit, it slightly */
/* changes the bottommost bits of DLAMDA(I). It does not account */
/* for hexadecimal or decimal machines without guard digits */
/* (we know of none). We use a subroutine call to compute */
/* 2*DLAMBDA(I) to prevent optimizing compilers from eliminating */
/* this code. */
i__1 = *k;
for (i__ = 1; i__ <= i__1; ++i__) {
dlamda[i__] = dlamc3_(&dlamda[i__], &dlamda[i__]) - dlamda[i__];
/* L10: */
}
i__1 = *k;
for (j = 1; j <= i__1; ++j) {
dlaed4_(k, &j, &dlamda[1], &w[1], &q[j * q_dim1 + 1], rho, &d__[j],
info);
/* If the zero finder fails, the computation is terminated. */
if (*info != 0) {
goto L120;
}
/* L20: */
}
if (*k == 1) {
goto L110;
}
if (*k == 2) {
i__1 = *k;
for (j = 1; j <= i__1; ++j) {
w[1] = q[j * q_dim1 + 1];
w[2] = q[j * q_dim1 + 2];
ii = indx[1];
q[j * q_dim1 + 1] = w[ii];
ii = indx[2];
q[j * q_dim1 + 2] = w[ii];
/* L30: */
}
goto L110;
}
/* Compute updated W. */
dcopy_(k, &w[1], &c__1, &s[1], &c__1);
/* Initialize W(I) = Q(I,I) */
i__1 = *ldq + 1;
dcopy_(k, &q[q_offset], &i__1, &w[1], &c__1);
i__1 = *k;
for (j = 1; j <= i__1; ++j) {
i__2 = j - 1;
for (i__ = 1; i__ <= i__2; ++i__) {
w[i__] *= q[i__ + j * q_dim1] / (dlamda[i__] - dlamda[j]);
/* L40: */
}
i__2 = *k;
for (i__ = j + 1; i__ <= i__2; ++i__) {
w[i__] *= q[i__ + j * q_dim1] / (dlamda[i__] - dlamda[j]);
/* L50: */
}
/* L60: */
}
i__1 = *k;
for (i__ = 1; i__ <= i__1; ++i__) {
d__1 = sqrt(-w[i__]);
w[i__] = d_sign(&d__1, &s[i__]);
/* L70: */
}
/* Compute eigenvectors of the modified rank-1 modification. */
i__1 = *k;
for (j = 1; j <= i__1; ++j) {
i__2 = *k;
for (i__ = 1; i__ <= i__2; ++i__) {
s[i__] = w[i__] / q[i__ + j * q_dim1];
/* L80: */
}
temp = dnrm2_(k, &s[1], &c__1);
i__2 = *k;
for (i__ = 1; i__ <= i__2; ++i__) {
ii = indx[i__];
q[i__ + j * q_dim1] = s[ii] / temp;
/* L90: */
}
/* L100: */
}
/* Compute the updated eigenvectors. */
L110:
n2 = *n - *n1;
n12 = ctot[1] + ctot[2];
n23 = ctot[2] + ctot[3];
dlacpy_("A", &n23, k, &q[ctot[1] + 1 + q_dim1], ldq, &s[1], &n23);
iq2 = *n1 * n12 + 1;
if (n23 != 0) {
dgemm_("N", "N", &n2, k, &n23, &c_b22, &q2[iq2], &n2, &s[1], &n23, &
c_b23, &q[*n1 + 1 + q_dim1], ldq);
} else {
dlaset_("A", &n2, k, &c_b23, &c_b23, &q[*n1 + 1 + q_dim1], ldq);
}
dlacpy_("A", &n12, k, &q[q_offset], ldq, &s[1], &n12);
if (n12 != 0) {
dgemm_("N", "N", n1, k, &n12, &c_b22, &q2[1], n1, &s[1], &n12, &c_b23,
&q[q_offset], ldq);
} else {
dlaset_("A", n1, k, &c_b23, &c_b23, &q[q_dim1 + 1], ldq);
}
L120:
return 0;
/* End of DLAED3 */
} /* dlaed3_ */
|
the_stack_data/190767447.c | #include<stdio.h>
int main()
{
int i, j;
int count=1;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("%d",count++ %2);
if(j==i && i!=5)
printf("\n");
}
if(i%2==0)
count=1;
else
count=0;
}
return(0);
}
|
the_stack_data/1099237.c | #include <stdio.h>
int expo(int A, int N){
if (N==0)
{
return 1;
}
if (N==1)
{
return A;
}else{
N--;
return A*expo(A,N);
}
}
int main(void)
{
int A=3,N=0,resultado;
resultado = expo(A,N);
printf("%d\n",resultado);
return 0;
} |
the_stack_data/234519044.c | // Check the various ways in which the three classes of values
// (scalar, complex, aggregate) interact with parameter passing
// (function entry, function return, call argument, call result).
//
// We also check _Bool and empty structures, as these can have annoying
// corner cases.
// RUN: %clang_cc1 %s -triple i386-unknown-unknown -O3 -emit-llvm -o - | FileCheck %s
// RUN: %clang_cc1 %s -triple x86_64-unknown-unknown -O3 -emit-llvm -o - | FileCheck %s
// RUN: %clang_cc1 %s -triple powerpc-unknown-unknown -O3 -emit-llvm -o - | FileCheck %s
// CHECK-NOT: @g0
typedef _Bool BoolTy;
typedef int ScalarTy;
typedef _Complex int ComplexTy;
typedef struct { int a, b, c; } AggrTy;
typedef struct { int a[0]; } EmptyTy;
static int result;
static BoolTy bool_id(BoolTy a) { return a; }
static AggrTy aggr_id(AggrTy a) { return a; }
static EmptyTy empty_id(EmptyTy a) { return a; }
static ScalarTy scalar_id(ScalarTy a) { return a; }
static ComplexTy complex_id(ComplexTy a) { return a; }
static void bool_mul(BoolTy a) { result *= a; }
static void aggr_mul(AggrTy a) { result *= a.a * a.b * a.c; }
static void empty_mul(EmptyTy a) { result *= 53; }
static void scalar_mul(ScalarTy a) { result *= a; }
static void complex_mul(ComplexTy a) { result *= __real a * __imag a; }
extern void g0(void);
void f0(void) {
result = 1;
bool_mul(bool_id(1));
aggr_mul(aggr_id((AggrTy) { 2, 3, 5}));
empty_mul(empty_id((EmptyTy) {}));
scalar_mul(scalar_id(7));
complex_mul(complex_id(11 + 13i));
// This call should be eliminated.
if (result != 2 * 3 * 5 * 7 * 11 * 13 * 53)
g0();
}
|
the_stack_data/151704665.c | #include <stdio.h>
main(){
int c;
while((c=getchar())!= EOF){
if(c =='\t' ||c == '\n'|| c ==' ')
putchar('\n');
if(c!=' ')
putchar(c);
}
}
/*prints every word of input in seperate lines*/
|
the_stack_data/7951157.c | // RUN: rm -rf %t*
// RUN: 3c -base-dir=%S -addcr -alltypes -output-dir=%t.checkedALL2 %S/arrcallermulti1.c %s --
// RUN: 3c -base-dir=%S -addcr -output-dir=%t.checkedNOALL2 %S/arrcallermulti1.c %s --
// RUN: %clang -working-directory=%t.checkedNOALL2 -c arrcallermulti1.c arrcallermulti2.c
// RUN: FileCheck -match-full-lines -check-prefixes="CHECK_NOALL","CHECK" --input-file %t.checkedNOALL2/arrcallermulti2.c %s
// RUN: FileCheck -match-full-lines -check-prefixes="CHECK_ALL","CHECK" --input-file %t.checkedALL2/arrcallermulti2.c %s
// RUN: 3c -base-dir=%S -alltypes -output-dir=%t.checked %S/arrcallermulti1.c %s --
// RUN: 3c -base-dir=%t.checked -alltypes -output-dir=%t.convert_again %t.checked/arrcallermulti1.c %t.checked/arrcallermulti2.c --
// RUN: test ! -f %t.convert_again/arrcallermulti1.c
// RUN: test ! -f %t.convert_again/arrcallermulti2.c
/******************************************************************************/
/*This file tests three functions: two callers bar and foo, and a callee sus*/
/*In particular, this file tests: arrays through a for loop and pointer
arithmetic to assign into it*/
/*For robustness, this test is identical to
arrprotocaller.c and arrcaller.c except in that
the callee and callers are split amongst two files to see how
the tool performs conversions*/
/*In this test, foo and sus will treat their return values safely, but bar will
not, through invalid pointer arithmetic, an unsafe cast, etc.*/
/******************************************************************************/
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct general {
int data;
struct general *next;
//CHECK: _Ptr<struct general> next;
};
struct warr {
int data1[5];
//CHECK_NOALL: int data1[5];
//CHECK_ALL: int data1 _Checked[5];
char *name;
//CHECK: _Ptr<char> name;
};
struct fptrarr {
int *values;
//CHECK: _Ptr<int> values;
char *name;
//CHECK: _Ptr<char> name;
int (*mapper)(int);
//CHECK: _Ptr<int (int)> mapper;
};
struct fptr {
int *value;
//CHECK: _Ptr<int> value;
int (*func)(int);
//CHECK: _Ptr<int (int)> func;
};
struct arrfptr {
int args[5];
//CHECK_NOALL: int args[5];
//CHECK_ALL: int args _Checked[5];
int (*funcs[5])(int);
//CHECK_NOALL: int (*funcs[5])(int);
//CHECK_ALL: _Ptr<int (int)> funcs _Checked[5];
};
static int add1(int x) {
//CHECK: static int add1(int x) _Checked {
return x + 1;
}
static int sub1(int x) {
//CHECK: static int sub1(int x) _Checked {
return x - 1;
}
static int fact(int n) {
//CHECK: static int fact(int n) _Checked {
if (n == 0) {
return 1;
}
return n * fact(n - 1);
}
static int fib(int n) {
//CHECK: static int fib(int n) _Checked {
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
}
return fib(n - 1) + fib(n - 2);
}
static int zerohuh(int n) {
//CHECK: static int zerohuh(int n) _Checked {
return !n;
}
static int *mul2(int *x) {
//CHECK: static _Ptr<int> mul2(_Ptr<int> x) _Checked {
*x *= 2;
return x;
}
int *sus(int *x, int *y) {
//CHECK_NOALL: int *sus(int *x : itype(_Ptr<int>), _Ptr<int> y) : itype(_Ptr<int>) {
//CHECK_ALL: _Array_ptr<int> sus(int *x : itype(_Ptr<int>), _Ptr<int> y) : count(5) {
x = (int *)5;
//CHECK: x = (int *)5;
int *z = calloc(5, sizeof(int));
//CHECK_NOALL: int *z = calloc<int>(5, sizeof(int));
//CHECK_ALL: _Array_ptr<int> z : count(5) = calloc<int>(5, sizeof(int));
int i, fac;
int *p;
//CHECK_NOALL: int *p;
//CHECK_ALL: _Array_ptr<int> p = ((void *)0);
for (i = 0, p = z, fac = 1; i < 5; ++i, p++, fac *= i) {
//CHECK_NOALL: for (i = 0, p = z, fac = 1; i < 5; ++i, p++, fac *= i) {
//CHECK_ALL: for (i = 0, p = z, fac = 1; i < 5; ++i, p++, fac *= i) _Checked {
*p = fac;
}
return z;
}
|
the_stack_data/247017659.c | // EXPECT: 97
int main() {
char* p = "abc";
return p[0];
} |
the_stack_data/894.c | #include<stdio.h>
#include<stdlib.h>
int main(int argc, char *argv[]){
int ia, ib, ic, test_vec, nfin, tmp;
FILE *fin, *fout;
if(argc < 3){
printf("error: too less arguments!\n");
exit(1);
}
fin = fopen(argv[1], "r");
if(fin == NULL){
printf("error: '%s' is not found\n", argv[1]);
exit(1);
}
fscanf(fin, "%d %d %d %d %d", &nfin, &nfin, &nfin, &tmp, &tmp);
fclose(fin);
nfin += tmp;
int X[17];
fout = fopen("tmp.test", "w");
test_vec = atoi(argv[2]);
fprintf(fout, "%d\n", test_vec);
for(ia=0; ia<17; ia++){
if((ia % 3)^(ia % 5)^(ia < 10))
X[ia] = 1;
else
X[ia] = 0;
}
for(ia=0; ia<test_vec; ia++){
for(ib=0; ib<nfin; ib++){
for(ic=16; ic>=1; ic--)
X[ic] = X[ic-1];
X[5] ^= X[16];
X[4] ^= X[16];
X[3] ^= X[16];
X[0] = X[16];
fprintf(fout, " %d", X[16]);
}
fprintf(fout, "\n");
}
//fprintf(fout, "END\n");
fclose(fout);
return 0;
}
|
the_stack_data/111599.c | // RUN: %clang_cc1 -analyze -analyzer-checker=core.experimental.SizeofPtr -verify %s
struct s {
};
int f(struct s *p) {
return sizeof(p); // expected-warning{{The code calls sizeof() on a pointer type. This can produce an unexpected result.}}
}
|
the_stack_data/19028.c | /*
$ cat Makefile
main: main3.c
gcc -Wall -Wextra -std=c99 -pedantic main3.c -o main -lm
*/
#include <stdio.h> // I/O
#include <string.h> // strcmp()
#include <math.h> // log2()
#define PRECISION 63 //liczba bitow, ktore wczytujemy do znacznika
#define ONE 0x2000000000000000LLU // MAX*0.25
#define HALF 0x4000000000000000LLU // MAX*0.5
#define THREE 0x6000000000000000LLU // MAX*0.75
#define MAX 0x7FFFFFFFFFFFFFFFLLU // 2^63 - 1
unsigned long long int l=0, //lewy koniec przedzialu
r=MAX; //prawy koniec przedzialu
unsigned long int countAll = 257, //licznik wszystkich symboli
count[257], //licznik kazdego symbolu
bytesCoded=0; //licznik zakodowanych bajtow
//unsigned char byte; //bajt = 8bitow sluzacy do odbierania lub wysylania 8 bitow kodu
//char numberOfBits=0; //licznik wlozonych/wyjetych bitow do powyzszego bajta
int sendBit(FILE* out, unsigned char bit){ //funkcja dla kompresji - wysyla bit na wyjscie (tak naprawde to czeka, az sie uzbiera 8 bitow i dopiero wtedy wysyla)
static unsigned char byte=0;
static char numberOfBits=0;
byte = byte << 1 | bit;
numberOfBits += 1;
if(numberOfBits == 8){
fputc(byte,out);
bytesCoded+=1;
numberOfBits=0;
return 0;
}
return 1;
}
void compress(FILE* in, FILE* out){
int symbol=0;
unsigned int counter=0;
while (symbol!=256) { //dopoki symbol to nie EOT
if((symbol = getc(in)) == EOF)
symbol=256;
int i;
unsigned long int left_count=0;
for(i=0; i<symbol; i++)
left_count+=count[i];
unsigned long long int step = (r - l + 1) / countAll;
r=l+step*(left_count+count[i])-1;
l=l+step*left_count;
while(r<HALF || l>=HALF){
if (r<HALF){ //skalowanie 1: przedzial [0, 0.5)
l*=2;
r=r*2+1;
sendBit(out,0);
for(;counter>0;counter--)
sendBit(out,1);
}
else if (l>=HALF){ //skalowanie 2: przedzial [0.5, 1)
l=2*(l-HALF);
r=2*(r-HALF)+1;
sendBit(out,1);
for(;counter>0;counter--)
sendBit(out,0);
}
}
while (l>=ONE && r<THREE){ //skalowanie 3: przedzial [0.25, 0.75) (0.5 jest w tym przedziale)
l=2*(l-ONE);
r=2*(r-ONE)+1;
counter+=1;
}
if(symbol < 256){ //liczonko
count[symbol]+=1;
countAll+=1;
}
}
if(l<ONE){ //konczenie transmiji: sa dwie mozliwosci: 1)przedzial [0, 0,75)
sendBit(out,0);
for(unsigned int i=0; i<counter+1;i++)
sendBit(out,1);
}
else { //2) przedzial [0.25, 1)
sendBit(out,1);
}
while(sendBit(out,0)); //dopelniamy bajta zerami i wysylami
}
unsigned char readBit(FILE* in) { //funkcja wczytujaca bit z wejscia i zwracajaca jego wartosc
static unsigned char byte=0;
static char numberOfBits=0;
int i;
if(numberOfBits==0){ //tu tez mamy bufor w postaci jednago bajta, ktory uzupelniamy, jak nam sie skonczy
if ((i = getc(in)) != EOF) {
byte = (unsigned char) i;
bytesCoded+=1;
}
else{
byte=0;
}
numberOfBits=8;
}
unsigned char bit = byte >> 7; //wyciagamy bit z bajtu
byte <<= 1; //skracamy o bajt o tego bita
numberOfBits -= 1;
return bit;
}
void decompress(FILE* in, FILE* out){
unsigned long long int z=0;
for(int i=0; i<PRECISION; i++) //wczytujemy 63 bity do znacznika
z = (z<<1) + readBit(in);
//printf("z=%llu\n",z);
int symbol;
do{
unsigned long long int step = (r-l+1)/countAll; //liczymy "krok" miedzy dwoma znakami (niekoniecznie roznymi)
unsigned long long int value = (z-l)/step; //liczymy wartosc naszego znacznika w odniesieniu do krokow
//printf("l=%llu r=%llu countall=%lu step=%llu z=%llu value=%llu\n",l,r,countAll,step,z,value);
unsigned long int left_count=0;
for(symbol=0; left_count + count[symbol] <= value; symbol++){ //znajdujemy symbol, ktory odpowiada przedzialowi, w ktorym jest znacznik
left_count += count[symbol];
}
//printf("symbol =%d\n",symbol);
if(symbol < 256){
fputc(symbol,out);
//fputc(symbol,stdin);
}
r=l+step*(left_count+count[symbol])-1;
l=l+step*left_count;
while(r<HALF || l>=HALF){ //analogiczne skalowania jak w kompresji,
if (r<HALF){
l*=2;
r=r*2+1;
z=z*2+readBit(in); //przedzial [0, 0.5) - znacznik*2 i wczytujemy mu bit
}
else if (l>=HALF){
l=2*(l-HALF);
r=2*(r-HALF)+1;
z=2*(z-HALF)+readBit(in); //przedzial [0.5, 1) - znacznik*2-1 i wczytujemy mu bit
}
}
while (l>=ONE && r<THREE){
l=2*(l-ONE);
r=2*(r-ONE)+1;
z=2*(z-ONE)+readBit(in); //przedzial [0.25, 0.75) - znacznik*2-0.5 i wczytujemy mu bit
}
if(symbol < 256){ //jezeli to nie EOT, to zliczamy go i drukujemy na wyjscie
count[symbol]+=1;
countAll+=1;
//fputc(symbol,stdin);
}
} while(symbol != 256);
}
int main(int argc, char** argv){
//printf("%llu %llu %llu\n%llu %llu %llu\n", MAX/4, MAX/2, MAX/4*3, ONE, HALF, THREE);
if (argc < 4){
printf("Usage: ./main -c (compression) / -d (decompression) <in_file> <out_file>\n");
return 1;
}
FILE* in = fopen(argv[2], "rb");
FILE* out = fopen(argv[3], "wb");
if(!in || !out){
printf("Something wrong with files\n");
return 2;
}
for(int i=0; i<257; i++){
count[i]=1;
}
if(!strcmp(argv[1], "-c")){
compress(in, out);
}else{
decompress(in, out);
}
fclose(in);
fclose(out);
countAll-=257;
double entropy = 0;
for (int i=0; i<256; i++){
count[i]-=1;
if(count[i]>0){
double probability = (double) count[i] / (double) countAll;
entropy += probability*log2(probability); //wyliczenie entropii jak na liscie 1
}
}
if(entropy != 0)
entropy *= -1;
printf("Entopia = %f\n", entropy);
printf("Srednia dlugosc kodu: %f\n", (double)bytesCoded*8.0/(double)countAll); //srednia dlugosc kodu: liczba zakodowanych bitow przez liczbe znakow
printf("Stopien kompresji: %lu:%lu = %f:1 (%f%%)\n",countAll,bytesCoded,(double)countAll/(double)bytesCoded, (double)bytesCoded/(double)countAll*100.0); //stopien kompresji: waga przed kompresja / waga po kompresji
return 0;
} |
the_stack_data/28262492.c | #include <stdio.h>
int main() {
int i, j, v1[5] = {}, v2[5] = {};
printf("Vetor 1:\n");
for (i = 0; i < 5; i++) {
printf("Introduza %d numero: ", i + 1);
scanf("%d", &v1[i]);
}
printf("Vetor 2:\n");
for (i = 0; i < 5; i++) {
printf("Introduza %d numero: ", i + 1);
scanf("%d", &v2[i]);
}
printf("\n");
printf("Comuns:");
for (i = 0; i < 5; i++) {
for (j = 0; j < 5; j++) {
if (v1[i] == v2[j]) {
printf(" %d", v1[i]);
}
}
}
printf("\n");
return 0;
} |
the_stack_data/215767853.c | /*
* Copyright (c) 2007, 2008 University of Tsukuba
* Copyright (C) 2007, 2008
* National Institute of Information and Communications Technology
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the University of Tsukuba 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.
*/
#ifdef VPN
#ifdef VPN_VE
#include "config.h"
#include "cpu_mmu.h"
#include "crypt.h"
#include "current.h"
#include "initfunc.h"
#include "mm.h"
#include "printf.h"
#include "spinlock.h"
#include "string.h"
#include "time.h"
#include "vmmcall.h"
#include "vpn_ve.h"
#include "vpnsys.h"
struct pqueue_list {
LIST1_DEFINE (struct pqueue_list);
void *data;
unsigned int len;
};
struct pqueue {
LIST1_DEFINE_HEAD (struct pqueue_list, list);
int num_item;
};
static void *
pqueue_getnext (struct pqueue *q, unsigned int *len)
{
struct pqueue_list *l;
void *r = NULL;
l = LIST1_POP (q->list);
if (l) {
q->num_item--;
r = l->data;
if (len)
*len = l->len;
free (l);
}
return r;
}
static void *
pqueue_peeknext (struct pqueue *q)
{
struct pqueue_list *l;
void *r = NULL;
l = LIST1_POP (q->list);
if (l) {
r = l->data;
LIST1_PUSH (q->list, l);
}
return r;
}
static void
pqueue_insert (struct pqueue *q, void *data, unsigned int len)
{
struct pqueue_list *l;
l = alloc (sizeof *l);
l->data = data;
l->len = len;
LIST1_ADD (q->list, l);
q->num_item++;
}
static void *
pqueue_new (void)
{
struct pqueue *q;
q = alloc (sizeof *q);
LIST1_HEAD_INIT (q->list);
q->num_item = 0;
return q;
}
static void *
memdup (void *p, int len)
{
return memcpy (alloc (len), p, len);
}
#define SE_QUEUE struct pqueue
#define SeGetNext(q) pqueue_getnext ((q), NULL)
#define SeGetNext2(q, l) pqueue_getnext ((q), (l))
#define SePeekNext(q) pqueue_peeknext ((q))
#define SeInsertQueue(q, data) pqueue_insert ((q), (data), 0)
#define SeInsertQueue2(q, d, l) pqueue_insert ((q), (d), (l))
#define SeNewQueue() pqueue_new ()
#define SeClone(p, len) memdup ((p), (len))
#define SeCopy memcpy
#define SeCopyStr(s) ((char *)memdup ((s), strlen ((s)) + 1))
#define SeFormat snprintf
#define SeFree free
#define SeMalloc alloc
#define SeStrCpy(dst, len, src) snprintf ((dst), (len), "%s", (src))
#define SeStrLen strlen
#define SeStrSize(s) (strlen ((s)) + 1)
#define SeZeroMalloc(len) memset (alloc ((len)), 0, (len))
// NIC
struct VPN_NIC
{
VPN_CTX *VpnCtx; // コンテキスト
SE_NICINFO NicInfo; // NIC 情報
SE_SYS_CALLBACK_RECV_NIC *RecvCallback; // パケット受信時のコールバック
void *RecvCallbackParam; // コールバックパラメータ
SE_QUEUE *SendPacketQueue; // 送信パケットキュー
SE_QUEUE *RecvPacketQueue; // 受信パケットキュー
bool IsVirtual; // 仮想 NIC かどうか
spinlock_t Lock; // ロック
};
// VPN クライアントコンテキスト
struct VPN_CTX
{
SE_HANDLE VpnClientHandle; // VPN クライアントハンドル
VPN_NIC *PhysicalNic; // 物理 NIC
SE_HANDLE PhysicalNicHandle; // 物理 NIC ハンドル
VPN_NIC *VirtualNic; // 仮想 NIC
SE_HANDLE VirtualNicHandle; // 仮想 NIC ハンドル
spinlock_t LogQueueLock; // ログのキューのロック
SE_QUEUE *LogQueue; // ログのキュー
};
void crypt_sys_log(char *type, char *message);
void crypt_sys_get_physical_nic_info(SE_HANDLE nic_handle, SE_NICINFO *info);
void crypt_sys_send_physical_nic(SE_HANDLE nic_handle, UINT num_packets, void **packets, UINT *packet_sizes);
void crypt_sys_set_physical_nic_recv_callback(SE_HANDLE nic_handle, SE_SYS_CALLBACK_RECV_NIC *callback, void *param);
void crypt_sys_get_virtual_nic_info(SE_HANDLE nic_handle, SE_NICINFO *info);
void crypt_sys_send_virtual_nic(SE_HANDLE nic_handle, UINT num_packets, void **packets, UINT *packet_sizes);
void crypt_sys_set_virtual_nic_recv_callback(SE_HANDLE nic_handle, SE_SYS_CALLBACK_RECV_NIC *callback, void *param);
void crypt_nic_recv_packet(VPN_NIC *n, UINT num_packets, void **packets, UINT *packet_sizes);
VPN_NIC *crypt_init_physical_nic(VPN_CTX *ctx);
VPN_NIC *crypt_init_virtual_nic(VPN_CTX *ctx);
void crypt_flush_old_packet_from_queue(SE_QUEUE *q);
static VPN_CTX *vpn_ctx = NULL; // VPN クライアントコンテキスト
// ve (Virtual Ethernet)
static spinlock_t ve_lock;
// Virtual Ethernet (ve) メイン処理
void crypt_ve_main(UCHAR *in, UCHAR *out)
{
VE_CTL *cin, *cout;
VPN_NIC *nic = NULL;
// 引数チェック
if (in == NULL || out == NULL)
{
return;
}
cin = (VE_CTL *)in;
cout = (VE_CTL *)out;
memset(cout, 0, sizeof(VE_CTL));
if (cin->EthernetType == VE_TYPE_PHYSICAL)
{
// 物理的な LAN カード
nic = vpn_ctx->PhysicalNic;
}
else if (cin->EthernetType == VE_TYPE_VIRTUAL)
{
// 仮想的な LAN カード
nic = vpn_ctx->VirtualNic;
}
if (nic != NULL)
{
if (cin->Operation == VE_OP_GET_LOG)
{
// ログから 1 行取得
spinlock_lock (&vpn_ctx->LogQueueLock);
{
char *str = SeGetNext(vpn_ctx->LogQueue);
if (str != NULL)
{
cout->PacketSize = SeStrSize(str);
SeStrCpy((char *)cout->PacketData, sizeof(cout->PacketData), str);
SeFree(str);
}
cout->NumQueue = vpn_ctx->LogQueue->num_item;
cout->RetValue = 1;
}
spinlock_unlock (&vpn_ctx->LogQueueLock);
}
else if (cin->Operation == VE_OP_GET_NEXT_SEND_PACKET)
{
// 次に送信すべきパケットの取得 (vpn -> vmm -> guest)
spinlock_lock (&nic->Lock);
{
// 古いパケットがある場合は破棄
crypt_flush_old_packet_from_queue(nic->SendPacketQueue);
// パケットが 1 つ以上キューにあるかどうか
if (nic->SendPacketQueue->num_item >= 1)
{
// キューから次のパケットをとる
UINT packet_data_size;
void *packet_data = SeGetNext2(nic->SendPacketQueue, &packet_data_size);
UINT packet_size_real = packet_data_size - sizeof(UINT64);
void *packet_data_real = ((UCHAR *)packet_data) + sizeof(UINT64);
memcpy(cout->PacketData, packet_data_real, packet_size_real);
cout->PacketSize = packet_size_real;
cout->NumQueue = nic->SendPacketQueue->num_item;
// メモリ解放
SeFree(packet_data);
}
cout->RetValue = 1;
}
spinlock_unlock (&nic->Lock);
}
else if (cin->Operation == VE_OP_PUT_RECV_PACKET)
{
bool flush = false;
UINT num_packets = 0;
void **packets = NULL;
UINT *packet_sizes = NULL;
// 受信したパケットの書き込み (guest -> vmm -> vpn)
spinlock_lock (&nic->Lock);
{
// 受信パケットは、パフォーマンス向上のため
// すぐに vpn に渡さずにいったん受信キューにためる
void *packet_data;
UINT packet_size = cin->PacketSize;
if (packet_size >= 1)
{
packet_data = SeClone(cin->PacketData, packet_size);
SeInsertQueue2(nic->RecvPacketQueue, packet_data, packet_size);
}
if (cin->NumQueue == 0)
{
// もうこれ以上受信パケットが無い場合は
// flush する (vpn に一気に渡す)
flush = true;
}
cout->RetValue = 1;
if (flush)
{
UINT i;
void *p;
num_packets = nic->RecvPacketQueue->num_item;
packets = SeMalloc(sizeof(void *) * num_packets);
packet_sizes = SeMalloc(sizeof(UINT *) * num_packets);
i = 0;
while (true)
{
UINT size;
p = SeGetNext2(nic->RecvPacketQueue, &size);
if (p == NULL)
{
break;
}
packets[i] = p;
packet_sizes[i] = size;
i++;
}
}
}
spinlock_unlock (&nic->Lock);
if (flush)
{
UINT i;
crypt_nic_recv_packet(nic, num_packets, packets, packet_sizes);
for (i = 0;i < num_packets;i++)
{
SeFree(packets[i]);
}
SeFree(packets);
SeFree(packet_sizes);
}
}
}
}
// Virtual Ethernet (ve) ハンドラ
void crypt_ve_handler()
{
UINT i;
UCHAR data[VE_BUFSIZE];
UCHAR data2[VE_BUFSIZE];
intptr addr;
bool ok = true;
if (!config.vmm.driver.vpn.ve)
return;
spinlock_lock(&ve_lock);
current->vmctl.read_general_reg(GENERAL_REG_RBX, &addr);
for (i = 0;i < (VE_BUFSIZE / 4);i++)
{
if (read_linearaddr_l((u32)((ulong)(((UCHAR *)addr) + (i * 4))), (u32 *)(data + (i * 4))) != VMMERR_SUCCESS)
{
ok = false;
break;
}
}
if (ok == false)
{
current->vmctl.write_general_reg(GENERAL_REG_RAX, 0);
spinlock_unlock(&ve_lock);
return;
}
crypt_ve_main(data, data2);
for (i = 0;i < (VE_BUFSIZE / 4);i++)
{
if (write_linearaddr_l((u32)((ulong)(((UCHAR *)addr) + (i * 4))), *((UINT *)(&data2[i * 4]))) != VMMERR_SUCCESS)
{
ok = false;
break;
}
}
if (ok == false)
{
current->vmctl.write_general_reg(GENERAL_REG_RAX, 0);
spinlock_unlock(&ve_lock);
return;
}
current->vmctl.write_general_reg(GENERAL_REG_RAX, 1);
spinlock_unlock(&ve_lock);
}
// Virtual Ethernet (ve) の初期化
void crypt_ve_init()
{
printf("Initing Virtual Ethernet (VE) for VPN Client Module...\n");
spinlock_init(&ve_lock);
vmmcall_register("ve", crypt_ve_handler);
printf("Virtual Ethernet (VE): Ok.\n");
}
INITFUNC ("vmmcal9", crypt_ve_init);
// 物理 NIC の初期化
VPN_NIC *crypt_init_physical_nic(VPN_CTX *ctx)
{
VPN_NIC *n = SeZeroMalloc(sizeof(VPN_NIC));
/* SeStrToBinEx(n->NicInfo.MacAddress, sizeof(n->NicInfo.MacAddress),
"00:12:12:12:12:12"); */
n->NicInfo.MacAddress[0] = 0x00;
n->NicInfo.MacAddress[1] = 0x12;
n->NicInfo.MacAddress[2] = 0x12;
n->NicInfo.MacAddress[3] = 0x12;
n->NicInfo.MacAddress[4] = 0x12;
n->NicInfo.MacAddress[5] = 0x12;
n->NicInfo.MediaSpeed = 1000000000;
n->NicInfo.MediaType = SE_MEDIA_TYPE_ETHERNET;
n->NicInfo.Mtu = 1500;
n->RecvPacketQueue = SeNewQueue();
n->SendPacketQueue = SeNewQueue();
n->VpnCtx = ctx;
n->IsVirtual = false;
spinlock_init (&n->Lock);
return n;
}
// 仮想 NIC の作成
VPN_NIC *crypt_init_virtual_nic(VPN_CTX *ctx)
{
VPN_NIC *n = SeZeroMalloc(sizeof(VPN_NIC));
/* SeStrToBinEx(n->NicInfo.MacAddress, sizeof(n->NicInfo.MacAddress),
"00:AC:AC:AC:AC:AC"); */
n->NicInfo.MacAddress[0] = 0x00;
n->NicInfo.MacAddress[1] = 0xAC;
n->NicInfo.MacAddress[2] = 0xAC;
n->NicInfo.MacAddress[3] = 0xAC;
n->NicInfo.MacAddress[4] = 0xAC;
n->NicInfo.MacAddress[5] = 0xAC;
n->NicInfo.MediaSpeed = 1000000000;
n->NicInfo.MediaType = SE_MEDIA_TYPE_ETHERNET;
n->NicInfo.Mtu = 1500;
n->RecvPacketQueue = SeNewQueue();
n->SendPacketQueue = SeNewQueue();
n->VpnCtx = ctx;
n->IsVirtual = true;
spinlock_init (&n->Lock);
return n;
}
static struct nicfunc vefunc = {
.GetPhysicalNicInfo = crypt_sys_get_physical_nic_info,
.SendPhysicalNic = crypt_sys_send_physical_nic,
.SetPhysicalNicRecvCallback = crypt_sys_set_physical_nic_recv_callback,
.GetVirtualNicInfo = crypt_sys_get_virtual_nic_info,
.SendVirtualNic = crypt_sys_send_virtual_nic,
.SetVirtualNicRecvCallback = crypt_sys_set_virtual_nic_recv_callback,
};
// VPN クライアントの初期化
void crypt_init_vpn()
{
vpn_ctx = SeZeroMalloc(sizeof(VPN_CTX));
// ログ用キューの初期化
vpn_ctx->LogQueue = SeNewQueue();
spinlock_init (&vpn_ctx->LogQueueLock);
// 物理 NIC の作成
vpn_ctx->PhysicalNic = crypt_init_physical_nic(vpn_ctx);
vpn_ctx->PhysicalNicHandle = (SE_HANDLE)vpn_ctx->PhysicalNic;
// 仮想 NIC の作成
vpn_ctx->VirtualNic = crypt_init_virtual_nic(vpn_ctx);
vpn_ctx->VirtualNicHandle = (SE_HANDLE)vpn_ctx->VirtualNic;
// VPN Client の作成
//vpn_ctx->VpnClientHandle = VPN_IPsec_Client_Start(vpn_ctx->PhysicalNicHandle, vpn_ctx->VirtualNicHandle, "config.txt");
vpn_ctx->VpnClientHandle = vpn_new_nic (vpn_ctx->PhysicalNicHandle,
vpn_ctx->VirtualNicHandle,
&vefunc);
}
// 提供システムコール: ログの出力 (画面に表示)
void crypt_sys_log(char *type, char *message)
{
char *lf = "\n";
void crypt_add_log_queue(char *type, char *message);
if (message[strlen(message) - 1] == '\n')
{
lf = "";
}
if (type != NULL && SeStrLen(type) >= 1)
{
printf("%s: %s%s", type, message, lf);
}
else
{
printf("%s%s", message, lf);
}
crypt_add_log_queue(type, message);
}
// ログキューにログデータを追加
void crypt_add_log_queue(char *type, char *message)
{
char *tmp;
char tmp2[512];
// 引数チェック
if (type == NULL || message == NULL)
{
return;
}
if (vpn_ctx == NULL)
{
return;
}
tmp = SeCopyStr(message);
if (SeStrLen(tmp) >= 1)
{
if (tmp[SeStrLen(tmp) - 1] == '\n')
{
tmp[SeStrLen(tmp) - 1] = 0;
}
}
if (SeStrLen(tmp) >= 1)
{
if (tmp[SeStrLen(tmp) - 1] == '\r')
{
tmp[SeStrLen(tmp) - 1] = 0;
}
}
if (type != NULL && SeStrLen(type) >= 1)
{
SeFormat(tmp2, sizeof(tmp2), "%s: %s", type, tmp);
}
else
{
SeStrCpy(tmp2, sizeof(tmp2), tmp);
}
SeFree(tmp);
spinlock_lock (&vpn_ctx->LogQueueLock);
{
while (vpn_ctx->LogQueue->num_item > CRYPT_MAX_LOG_QUEUE_LINES)
{
char *p = SeGetNext(vpn_ctx->LogQueue);
SeFree(p);
}
SeInsertQueue(vpn_ctx->LogQueue, SeCopyStr(tmp2));
}
spinlock_unlock (&vpn_ctx->LogQueueLock);
}
// 提供システムコール: 物理 NIC の情報の取得
void crypt_sys_get_physical_nic_info(SE_HANDLE nic_handle, SE_NICINFO *info)
{
VPN_NIC *n = (VPN_NIC *)nic_handle;
// 引数チェック
if (n == NULL)
{
return;
}
SeCopy(info, &n->NicInfo, sizeof(SE_NICINFO));
}
// 送信パケットキューから古いパケットを削除する
void crypt_flush_old_packet_from_queue(SE_QUEUE *q)
{
UINT64 now = get_time ();
UINT num = 0;
while (true)
{
void *data = SePeekNext(q);
UINT64 *time_stamp;
if (data == NULL)
{
break;
}
time_stamp = (UINT64 *)data;
if (now <= ((*time_stamp) + CRYPT_SEND_PACKET_LIFETIME * 1000))
{
break;
}
data = SeGetNext(q);
SeFree(data);
num++;
}
}
// 提供システムコール: 物理 NIC を用いてパケットを送信
void crypt_sys_send_physical_nic(SE_HANDLE nic_handle, UINT num_packets, void **packets, UINT *packet_sizes)
{
VPN_NIC *n = (VPN_NIC *)nic_handle;
UINT i;
// 引数チェック
if (n == NULL || num_packets == 0 || packets == NULL || packet_sizes == NULL)
{
return;
}
spinlock_lock (&n->Lock);
{
// パケットをキューに格納する
for (i = 0;i < num_packets;i++)
{
void *packet = packets[i];
UINT size = packet_sizes[i];
UCHAR *packet_copy = SeMalloc(size + sizeof(UINT64));
SeCopy(packet_copy + sizeof(UINT64), packet, size);
*((UINT64 *)packet_copy) = get_time ();
SeInsertQueue2(n->SendPacketQueue, packet_copy, size + sizeof(UINT64));
}
// 古いパケットを送信キューから削除する
crypt_flush_old_packet_from_queue(n->SendPacketQueue);
}
spinlock_unlock (&n->Lock);
}
// 提供システムコール: 物理 NIC からパケットを受信した際のコールバックを設定
void crypt_sys_set_physical_nic_recv_callback(SE_HANDLE nic_handle, SE_SYS_CALLBACK_RECV_NIC *callback, void *param)
{
VPN_NIC *n = (VPN_NIC *)nic_handle;
// 引数チェック
if (n == NULL)
{
return;
}
n->RecvCallback = callback;
n->RecvCallbackParam = param;
}
// 提供システムコール: 仮想 NIC の情報の取得
void crypt_sys_get_virtual_nic_info(SE_HANDLE nic_handle, SE_NICINFO *info)
{
VPN_NIC *n = (VPN_NIC *)nic_handle;
SeCopy(info, &n->NicInfo, sizeof(SE_NICINFO));
}
// 提供システムコール: 仮想 NIC を用いてパケットを送信
void crypt_sys_send_virtual_nic(SE_HANDLE nic_handle, UINT num_packets, void **packets, UINT *packet_sizes)
{
VPN_NIC *n = (VPN_NIC *)nic_handle;
UINT i;
// 引数チェック
if (n == NULL || num_packets == 0 || packets == NULL || packet_sizes == NULL)
{
return;
}
spinlock_lock (&n->Lock);
{
// パケットをキューに格納する
for (i = 0;i < num_packets;i++)
{
void *packet = packets[i];
UINT size = packet_sizes[i];
UCHAR *packet_copy = SeMalloc(size + sizeof(UINT64));
SeCopy(packet_copy + sizeof(UINT64), packet, size);
*((UINT64 *)packet_copy) = get_time ();
SeInsertQueue2(n->SendPacketQueue, packet_copy, size + sizeof(UINT64));
}
// 古いパケットを送信キューから削除する
crypt_flush_old_packet_from_queue(n->SendPacketQueue);
}
spinlock_unlock (&n->Lock);
}
// 提供システムコール: 仮想 NIC からパケットを受信した際のコールバックを設定
void crypt_sys_set_virtual_nic_recv_callback(SE_HANDLE nic_handle, SE_SYS_CALLBACK_RECV_NIC *callback, void *param)
{
VPN_NIC *n = (VPN_NIC *)nic_handle;
// 引数チェック
if (n == NULL)
{
return;
}
n->RecvCallback = callback;
n->RecvCallbackParam = param;
}
// 物理 / 仮想 NIC でパケットを受信したことを通知しパケットデータを渡す
void crypt_nic_recv_packet(VPN_NIC *n, UINT num_packets, void **packets, UINT *packet_sizes)
{
// 引数チェック
if (n == NULL || num_packets == 0 || packets == NULL || packet_sizes == NULL)
{
return;
}
n->RecvCallback((SE_HANDLE)n, num_packets, packets, packet_sizes, n->RecvCallbackParam);
}
static void
vpn_ve_init (void)
{
if (!config.vmm.driver.vpn.ve)
return;
crypt_init_vpn ();
}
INITFUNC ("driver1", vpn_ve_init);
#endif /* VPN_VE */
#endif /* VPN */
|
the_stack_data/198915.c | #include <stdio.h>
/*统计行数*/
int main(){
int c, nl;
nl = 0;
printf("please input:\n");
while((c=getchar()) != EOF)
if (c == '\n')
++nl;
printf("%d \n", nl);
return 0;
}
|
the_stack_data/137157.c | // Name: Sumit Kumar
// Roll No: CED19I028
// Lab3 Question: 2 exec system call demonstration..
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main(){
pid_t pid;
pid=fork();
if(pid < 0){
printf(" Error in fork\n");
} else if (pid==0) {
char *args[] = {"/home/sumit/C/Documents/OS/Lab4", NULL};
execvp("ls", args);
} else{
char *args[] = {"/home/sumit/C/Documents/OS/Lab4", NULL};
execvp("pstree", args);
}
return 0;
} |
the_stack_data/110611.c | #include <stdio.h>
#include <math.h>
int main()
{
double x, a, G, F, Y;
printf("Введите x:");
scanf("%lf", &x);
printf("Введите a:");
scanf("%lf", &a);
G = (5*(-2*pow(a,2) + a*x + 3*pow(x,2))/(10*pow(a,2) + 11*a*x + 3*pow(x,2)));
printf("G=%f\n\n", G);
printf("Введите x:");
scanf("%lf", &x);
printf("Введите a:");
scanf("%lf", &a);
F = sin(10*pow(a,2) - 7*a*x + pow(x,2));
printf ("F=%f\n\n", F);
printf("Введите x:");
scanf("%lf", &x);
printf("Введите a:");
scanf("%lf", &a);
Y = atan(45*pow(a,2) + 79*a*x + 30*pow(x,2));
printf("Y=%f\n\n", Y);
return 0;
}
|
the_stack_data/103264675.c | #include <stdio.h>
#include <stdlib.h>
int tarkistaNumero(int *ptr, int numero, int size)
{
int i = 0;
for (i = 0; i < size; i++) {
if (ptr[i] == numero) return 1;
}
return (0);
}
void arvoNumerot(int *ptr, int size)
{
int i = 0;
int num = 0;
srand(40);
for (i = 0; i < size; i++) {
do {
num = rand() % 38;
} while (tarkistaNumero(ptr, num, size));
ptr[i] = num;
}
}
void tulostaNumerot(int *ptr, int size)
{
int i = 0;
for (i = 0; i < size; i++) {
printf("%d ", ptr[i]);
}
printf("\n");
}
|
the_stack_data/248579557.c | #define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
typedef struct TYPE_6__ TYPE_3__ ;
typedef struct TYPE_5__ TYPE_2__ ;
typedef struct TYPE_4__ TYPE_1__ ;
/* Type definitions */
typedef int u32 ;
typedef int u16 ;
struct b43legacy_phy {scalar_t__ type; int rev; int analog; int radio_rev; scalar_t__ gmode; int /*<<< orphan*/ channel; } ;
struct b43legacy_wldev {TYPE_3__* dev; struct b43legacy_phy phy; } ;
struct TYPE_6__ {TYPE_2__* bus; } ;
struct TYPE_4__ {int boardflags_lo; } ;
struct TYPE_5__ {TYPE_1__ sprom; } ;
/* Variables and functions */
int B43legacy_BFL_EXTLNA ;
int B43legacy_MMIO_CHANNEL_EXT ;
int B43legacy_MMIO_PHY_RADIO ;
scalar_t__ B43legacy_PHYTYPE_B ;
int B43legacy_PHY_G_CRS ;
int /*<<< orphan*/ LPD (int,int,int) ;
int b43legacy_get_812_value (struct b43legacy_wldev*,int /*<<< orphan*/ ) ;
int b43legacy_phy_read (struct b43legacy_wldev*,int) ;
int /*<<< orphan*/ b43legacy_phy_write (struct b43legacy_wldev*,int,int) ;
int b43legacy_radio_calibrationvalue (struct b43legacy_wldev*) ;
int b43legacy_radio_read16 (struct b43legacy_wldev*,int) ;
int /*<<< orphan*/ b43legacy_radio_selectchannel (struct b43legacy_wldev*,int /*<<< orphan*/ ,int) ;
int /*<<< orphan*/ b43legacy_radio_write16 (struct b43legacy_wldev*,int,int) ;
int b43legacy_read16 (struct b43legacy_wldev*,int) ;
int /*<<< orphan*/ b43legacy_write16 (struct b43legacy_wldev*,int,int) ;
int flip_4bit (int) ;
int /*<<< orphan*/ udelay (int) ;
u16 b43legacy_radio_init2050(struct b43legacy_wldev *dev)
{
struct b43legacy_phy *phy = &dev->phy;
u16 backup[21] = { 0 };
u16 ret;
u16 i;
u16 j;
u32 tmp1 = 0;
u32 tmp2 = 0;
backup[0] = b43legacy_radio_read16(dev, 0x0043);
backup[14] = b43legacy_radio_read16(dev, 0x0051);
backup[15] = b43legacy_radio_read16(dev, 0x0052);
backup[1] = b43legacy_phy_read(dev, 0x0015);
backup[16] = b43legacy_phy_read(dev, 0x005A);
backup[17] = b43legacy_phy_read(dev, 0x0059);
backup[18] = b43legacy_phy_read(dev, 0x0058);
if (phy->type == B43legacy_PHYTYPE_B) {
backup[2] = b43legacy_phy_read(dev, 0x0030);
backup[3] = b43legacy_read16(dev, 0x03EC);
b43legacy_phy_write(dev, 0x0030, 0x00FF);
b43legacy_write16(dev, 0x03EC, 0x3F3F);
} else {
if (phy->gmode) {
backup[4] = b43legacy_phy_read(dev, 0x0811);
backup[5] = b43legacy_phy_read(dev, 0x0812);
backup[6] = b43legacy_phy_read(dev, 0x0814);
backup[7] = b43legacy_phy_read(dev, 0x0815);
backup[8] = b43legacy_phy_read(dev,
B43legacy_PHY_G_CRS);
backup[9] = b43legacy_phy_read(dev, 0x0802);
b43legacy_phy_write(dev, 0x0814,
(b43legacy_phy_read(dev, 0x0814)
| 0x0003));
b43legacy_phy_write(dev, 0x0815,
(b43legacy_phy_read(dev, 0x0815)
& 0xFFFC));
b43legacy_phy_write(dev, B43legacy_PHY_G_CRS,
(b43legacy_phy_read(dev,
B43legacy_PHY_G_CRS) & 0x7FFF));
b43legacy_phy_write(dev, 0x0802,
(b43legacy_phy_read(dev, 0x0802)
& 0xFFFC));
if (phy->rev > 1) { /* loopback gain enabled */
backup[19] = b43legacy_phy_read(dev, 0x080F);
backup[20] = b43legacy_phy_read(dev, 0x0810);
if (phy->rev >= 3)
b43legacy_phy_write(dev, 0x080F,
0xC020);
else
b43legacy_phy_write(dev, 0x080F,
0x8020);
b43legacy_phy_write(dev, 0x0810, 0x0000);
}
b43legacy_phy_write(dev, 0x0812,
b43legacy_get_812_value(dev,
LPD(0, 1, 1)));
if (phy->rev < 7 ||
!(dev->dev->bus->sprom.boardflags_lo
& B43legacy_BFL_EXTLNA))
b43legacy_phy_write(dev, 0x0811, 0x01B3);
else
b43legacy_phy_write(dev, 0x0811, 0x09B3);
}
}
b43legacy_write16(dev, B43legacy_MMIO_PHY_RADIO,
(b43legacy_read16(dev, B43legacy_MMIO_PHY_RADIO)
| 0x8000));
backup[10] = b43legacy_phy_read(dev, 0x0035);
b43legacy_phy_write(dev, 0x0035,
(b43legacy_phy_read(dev, 0x0035) & 0xFF7F));
backup[11] = b43legacy_read16(dev, 0x03E6);
backup[12] = b43legacy_read16(dev, B43legacy_MMIO_CHANNEL_EXT);
/* Initialization */
if (phy->analog == 0)
b43legacy_write16(dev, 0x03E6, 0x0122);
else {
if (phy->analog >= 2)
b43legacy_phy_write(dev, 0x0003,
(b43legacy_phy_read(dev, 0x0003)
& 0xFFBF) | 0x0040);
b43legacy_write16(dev, B43legacy_MMIO_CHANNEL_EXT,
(b43legacy_read16(dev,
B43legacy_MMIO_CHANNEL_EXT) | 0x2000));
}
ret = b43legacy_radio_calibrationvalue(dev);
if (phy->type == B43legacy_PHYTYPE_B)
b43legacy_radio_write16(dev, 0x0078, 0x0026);
if (phy->gmode)
b43legacy_phy_write(dev, 0x0812,
b43legacy_get_812_value(dev,
LPD(0, 1, 1)));
b43legacy_phy_write(dev, 0x0015, 0xBFAF);
b43legacy_phy_write(dev, 0x002B, 0x1403);
if (phy->gmode)
b43legacy_phy_write(dev, 0x0812,
b43legacy_get_812_value(dev,
LPD(0, 0, 1)));
b43legacy_phy_write(dev, 0x0015, 0xBFA0);
b43legacy_radio_write16(dev, 0x0051,
(b43legacy_radio_read16(dev, 0x0051)
| 0x0004));
if (phy->radio_rev == 8)
b43legacy_radio_write16(dev, 0x0043, 0x001F);
else {
b43legacy_radio_write16(dev, 0x0052, 0x0000);
b43legacy_radio_write16(dev, 0x0043,
(b43legacy_radio_read16(dev, 0x0043)
& 0xFFF0) | 0x0009);
}
b43legacy_phy_write(dev, 0x0058, 0x0000);
for (i = 0; i < 16; i++) {
b43legacy_phy_write(dev, 0x005A, 0x0480);
b43legacy_phy_write(dev, 0x0059, 0xC810);
b43legacy_phy_write(dev, 0x0058, 0x000D);
if (phy->gmode)
b43legacy_phy_write(dev, 0x0812,
b43legacy_get_812_value(dev,
LPD(1, 0, 1)));
b43legacy_phy_write(dev, 0x0015, 0xAFB0);
udelay(10);
if (phy->gmode)
b43legacy_phy_write(dev, 0x0812,
b43legacy_get_812_value(dev,
LPD(1, 0, 1)));
b43legacy_phy_write(dev, 0x0015, 0xEFB0);
udelay(10);
if (phy->gmode)
b43legacy_phy_write(dev, 0x0812,
b43legacy_get_812_value(dev,
LPD(1, 0, 0)));
b43legacy_phy_write(dev, 0x0015, 0xFFF0);
udelay(20);
tmp1 += b43legacy_phy_read(dev, 0x002D);
b43legacy_phy_write(dev, 0x0058, 0x0000);
if (phy->gmode)
b43legacy_phy_write(dev, 0x0812,
b43legacy_get_812_value(dev,
LPD(1, 0, 1)));
b43legacy_phy_write(dev, 0x0015, 0xAFB0);
}
tmp1++;
tmp1 >>= 9;
udelay(10);
b43legacy_phy_write(dev, 0x0058, 0x0000);
for (i = 0; i < 16; i++) {
b43legacy_radio_write16(dev, 0x0078, (flip_4bit(i) << 1)
| 0x0020);
backup[13] = b43legacy_radio_read16(dev, 0x0078);
udelay(10);
for (j = 0; j < 16; j++) {
b43legacy_phy_write(dev, 0x005A, 0x0D80);
b43legacy_phy_write(dev, 0x0059, 0xC810);
b43legacy_phy_write(dev, 0x0058, 0x000D);
if (phy->gmode)
b43legacy_phy_write(dev, 0x0812,
b43legacy_get_812_value(dev,
LPD(1, 0, 1)));
b43legacy_phy_write(dev, 0x0015, 0xAFB0);
udelay(10);
if (phy->gmode)
b43legacy_phy_write(dev, 0x0812,
b43legacy_get_812_value(dev,
LPD(1, 0, 1)));
b43legacy_phy_write(dev, 0x0015, 0xEFB0);
udelay(10);
if (phy->gmode)
b43legacy_phy_write(dev, 0x0812,
b43legacy_get_812_value(dev,
LPD(1, 0, 0)));
b43legacy_phy_write(dev, 0x0015, 0xFFF0);
udelay(10);
tmp2 += b43legacy_phy_read(dev, 0x002D);
b43legacy_phy_write(dev, 0x0058, 0x0000);
if (phy->gmode)
b43legacy_phy_write(dev, 0x0812,
b43legacy_get_812_value(dev,
LPD(1, 0, 1)));
b43legacy_phy_write(dev, 0x0015, 0xAFB0);
}
tmp2++;
tmp2 >>= 8;
if (tmp1 < tmp2)
break;
}
/* Restore the registers */
b43legacy_phy_write(dev, 0x0015, backup[1]);
b43legacy_radio_write16(dev, 0x0051, backup[14]);
b43legacy_radio_write16(dev, 0x0052, backup[15]);
b43legacy_radio_write16(dev, 0x0043, backup[0]);
b43legacy_phy_write(dev, 0x005A, backup[16]);
b43legacy_phy_write(dev, 0x0059, backup[17]);
b43legacy_phy_write(dev, 0x0058, backup[18]);
b43legacy_write16(dev, 0x03E6, backup[11]);
if (phy->analog != 0)
b43legacy_write16(dev, B43legacy_MMIO_CHANNEL_EXT, backup[12]);
b43legacy_phy_write(dev, 0x0035, backup[10]);
b43legacy_radio_selectchannel(dev, phy->channel, 1);
if (phy->type == B43legacy_PHYTYPE_B) {
b43legacy_phy_write(dev, 0x0030, backup[2]);
b43legacy_write16(dev, 0x03EC, backup[3]);
} else {
if (phy->gmode) {
b43legacy_write16(dev, B43legacy_MMIO_PHY_RADIO,
(b43legacy_read16(dev,
B43legacy_MMIO_PHY_RADIO) & 0x7FFF));
b43legacy_phy_write(dev, 0x0811, backup[4]);
b43legacy_phy_write(dev, 0x0812, backup[5]);
b43legacy_phy_write(dev, 0x0814, backup[6]);
b43legacy_phy_write(dev, 0x0815, backup[7]);
b43legacy_phy_write(dev, B43legacy_PHY_G_CRS,
backup[8]);
b43legacy_phy_write(dev, 0x0802, backup[9]);
if (phy->rev > 1) {
b43legacy_phy_write(dev, 0x080F, backup[19]);
b43legacy_phy_write(dev, 0x0810, backup[20]);
}
}
}
if (i >= 15)
ret = backup[13];
return ret;
} |
the_stack_data/20449898.c | #include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
int main() {
uint64_t a = 0ULL, b = 0ULL;
scanf ("%lld %lld", &a, &b);
printf ("64-bit division is %lld\n", a / b);
printf ("64-bit shift is %lld\n", a >> b);
return EXIT_SUCCESS;
}
|
the_stack_data/176706952.c | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int *A, *B, *C;
int i, j;
//Input
int linhas, colunas;
scanf("%d", &linhas);
scanf("%d", &colunas);
//Alocando memória na CPU
A = (int *)malloc(sizeof(int)*linhas*colunas);
B = (int *)malloc(sizeof(int)*linhas*colunas);
C = (int *)malloc(sizeof(int)*linhas*colunas);
//Inicializar
for(i = 0; i < linhas; i++){
for(j = 0; j < colunas; j++){
A[i*colunas+j] = B[i*colunas+j] = i+j;
}
}
//Computacao que deverá ser movida para a GPU (que no momento é executada na CPU)
//Lembrar que é necessário usar mapeamento 2D (visto em aula)
for(i=0; i < linhas; i++){
for(j = 0; j < colunas; j++){
C[i*colunas+j] = A[i*colunas+j] + B[i*colunas+j];
}
}
long long int somador=0;
//Manter esta computação na CPU
for(i = 0; i < linhas; i++){
for(j = 0; j < colunas; j++){
somador+=C[i*colunas+j];
}
}
printf("%lli\n", somador);
free(A);
free(B);
free(C);
}
|
the_stack_data/682825.c | #include <string.h>
void inplace_reverse(char * str)
{
if (str)
{
char * end = str + strlen(str) - 1;
# define XOR_SWAP(a,b) do\
{\
a ^= b;\
b ^= a;\
a ^= b;\
} while (0)
while (str < end)
{
XOR_SWAP(*str, *end);
str++;
end--;
}
# undef XOR_SWAP
}
}
|
the_stack_data/48575171.c | #include <stdio.h>
struct info{
char name[50];
char id[10];
char address[50];
char phone[12];
};
int main() {
struct info student[5];
for (int i = 0; i < 5; i++) {
printf("\n\n\nFor Student %d:-", i+1);
printf("\nEnter name: ");
scanf("%s", &student[i].name);
printf("\nEnter ID: ");
scanf("%s", &student[i].id);
printf("\nEnter Address: ");
scanf("%s", &student[i].address);
printf("\nEnter Phone: ");
scanf("%s", &student[i].phone);
}
printf("\n\n---------Information----------\n");
for (int i = 0; i < 5; i++){
printf("\n\n\nFor Student %d:", i+1);
printf("\nName: %s", student[i].name);
printf("\nID: %s", student[i].id);
printf("\nAddress: %s", student[i].address);
printf("\nPhone No: %s", student[i].phone);
}
return 0;
}
|
the_stack_data/90765272.c | struct mutex;
struct kref;
typedef struct {
int counter;
} atomic_t;
int __VERIFIER_nondet_int(void);
extern void mutex_lock(struct mutex *lock);
extern void mutex_lock_nested(struct mutex *lock, unsigned int subclass);
extern int mutex_lock_interruptible(struct mutex *lock);
extern int mutex_lock_killable(struct mutex *lock);
extern int mutex_lock_interruptible_nested(struct mutex *lock, unsigned int subclass);
extern int mutex_lock_killable_nested(struct mutex *lock, unsigned int subclass);
static inline int mutex_is_locked(struct mutex *lock);
extern int mutex_trylock(struct mutex *lock);
extern void mutex_unlock(struct mutex *lock);
extern int atomic_dec_and_mutex_lock(atomic_t *cnt, struct mutex *lock);
static inline int kref_put_mutex(struct kref *kref,
void (*release)(struct kref *kref),
struct mutex *lock);
static void specific_func(struct kref *kref);
void ldv_check_final_state(void);
void main(void)
{
struct mutex *mutex_1, *mutex_2, *mutex_3, *mutex_4, *mutex_5;
struct kref *kref;
atomic_t *counter;
int res = mutex_lock_killable_nested(&mutex_1, __VERIFIER_nondet_int());
// missing mutex_unlock
ldv_check_final_state();
}
|
the_stack_data/84917.c | #include <stdio.h>
void dbl_reverse(double *arr, int n);
int main(void)
{
double source[5] = {1.5, 4.5, 3.2, 0.7, -4.6};
printf("Values stored in the array are %f %f %f %f %f.\n",
*(source + 0), *(source + 1), *(source + 2),
*(source + 3), *(source + 4));
dbl_reverse(source, 5);
printf("Now they are %f %f %f %f %f.\n",
*(source + 0), *(source + 1), *(source + 2),
*(source + 3), *(source + 4));
return 0;
}
void dbl_reverse(double *arr, int n)
{
double temp[n];
for (int i = 0; i < n; i++)
temp[n - i - 1] = arr[i];
for (int i = 0; i < n; i++)
arr[i] = temp[i];
} |
the_stack_data/72012980.c | // C program to Sort a Linked List of 0's,1's and 2's.
#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
int data;
struct Node* next;
}Node;
void sortList(Node* head)
{
int count[] = {0,0,0};
int i = 0;
Node* temp = head;
while(temp!= NULL)
{
count[temp->data]+= 1;
temp = temp->next;
}
temp = head;
while(temp!= NULL)
{
if(count[i]==0)
++i;
else
{
temp->data = i;
--count[i];
temp = temp->next;
}
}
}
void push(Node** head_ref,int newdata)
{
Node* newnode = (Node*)malloc(sizeof(Node));
newnode->data = newdata;
newnode->next = (*head_ref);
(*head_ref) = newnode;
}
void printList(Node* node)
{
while(node!= NULL)
{
printf("%d ",node->data);
node = node->next;
}
}
//Driver Program
int main()
{
Node* head = NULL;
push(&head,2);
push(&head,1);
push(&head,0);
push(&head,2);
push(&head,1);
push(&head,2);
push(&head,0);
printf("\n Linked List Before Sorting \n");
printList(head);
printf("\n Linked List After Sorting \n ");
sortList(head);
printList(head);
return 0;
}
//Time - Complexity - 0(n)
//Space - Complexity - 0(1)
|
the_stack_data/472379.c | // Copyright (c) <2012> <Leif Asbrink>
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify,
// merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
// OR OTHER DEALINGS IN THE SOFTWARE.
#include <X11/Xlib.h>
#include <X11/cursorfont.h>
#include <X11/Xutil.h>
int main(int argc, char *argv[])
{
int i;
i=argc;
i=argv[0][0];
XOpenDisplay(NULL);
}
|
the_stack_data/35391.c | int
main()
{
int x;
x = 0;
x = x ? 0 : 2;
if(x != 2)
return 1;
return x == 2 ? 0 : 1;
} |
the_stack_data/140766193.c | #if HAVE_MATH_H
#include <math.h>
#endif
int main() {
float neg = -1.0;
float pos = 1.0;
float res = copysignf(pos, neg);
return 0;
}
|
the_stack_data/1005880.c |
/* This is generated by the getStubs.tcl tool (see the tcl distribution)
out of the tdom.decls file */
#ifdef USE_TCL_STUBS
#include <dom.h>
#include <tdom.h>
/* !BEGIN!: Do not edit below this line. */
TdomStubs tdomStubs = {
TCL_STUB_MAGIC,
NULL,
TclExpatObjCmd, /* 0 */
CheckExpatParserObj, /* 1 */
CHandlerSetInstall, /* 2 */
CHandlerSetRemove, /* 3 */
CHandlerSetCreate, /* 4 */
CHandlerSetGet, /* 5 */
CHandlerSetGetUserData, /* 6 */
GetExpatInfo, /* 7 */
XML_GetCurrentLineNumber, /* 8 */
XML_GetCurrentColumnNumber, /* 9 */
XML_GetCurrentByteIndex, /* 10 */
XML_GetCurrentByteCount, /* 11 */
XML_SetBase, /* 12 */
XML_GetBase, /* 13 */
XML_GetSpecifiedAttributeCount, /* 14 */
XML_GetIdAttributeIndex, /* 15 */
tcldom_getNodeFromName, /* 16 */
tcldom_getDocumentFromName, /* 17 */
};
/* !END!: Do not edit above this line. */
#endif /* USE_TCL_STUBS */
|
the_stack_data/34019.c |
// BUILD: $CC foo.c -dynamiclib -o $BUILD_DIR/libfoo.dylib -install_name $RUN_DIR/libfoo.dylib
// BUILD: $CC present.c $BUILD_DIR/libfoo.dylib -o $BUILD_DIR/dylib-static-present.exe
// BUILD: $CC foo.c -dynamiclib -o $TEMP_DIR/libfoo2.dylib -install_name $RUN_DIR/libfoomissing.dylib
// BUILD: $CC missing.c $TEMP_DIR/libfoo2.dylib -o $BUILD_DIR/dylib-static-missing.exe
// RUN: ./dylib-static-present.exe
// RUN: NOCR_TEST_NAME="dylib-static-link missing" $REQUIRE_CRASH ./dylib-static-missing.exe
#include <stdio.h>
extern int foo;
int main()
{
printf("[BEGIN] dylib-static-link present\n");
if ( foo == 42 )
printf("[PASS] dylib-static-link present\n");
else
printf("[FAIL] dylib-static-link present, wrong value\n");
return 0;
}
|
the_stack_data/920501.c | #include <stdio.h>
#include <math.h>
int main (void)
{
double bruch;
printf("Bitte geben Sie einen Dezimalbruch zwischen -1 und 1 ein: ");
scanf("%lf", &bruch);
printf("Arcus Sinus von %.2f ist %.4f\n", bruch, asin(bruch));
return 0;
}
|
the_stack_data/332976.c | #include <stdio.h>
int main(){
int board[3][3]={0};
while(1){
int xx,xy;
do{
printf("Enter a row (0, 1, or 2) for player X:");
scanf("%d", &xy);
printf("Enter a column (0, 1, or 2) for player X:");
scanf("%d", &xx);
}while(board[xy][xx]!=0);
board[xy][xx]=1;
for(int i=0;i<3;i++){
puts("-------");
printf("|");
for(int j=0;j<3;j++){
if(board[i][j]==1)printf("X|");
else if(board[i][j]==2)printf("O|");
else printf(" |");
}
printf("\n");
}
puts("-------");
for(int i=0;i<3;i++){
if((board[i][0]==board[i][1])&&(board[i][1]==board[i][2])&&(board[i][0])){
if(board[i][0]==1)printf("X player won.\n");
else printf("O player won.\n");
return 0;
}
if((board[0][i]==board[1][i])&&(board[1][i]==board[2][i])&&(board[0][i])){
if(board[0][i]==1)printf("X player won.\n");
else printf("O player won.\n");
return 0;
}
}
if(((board[0][0])&&(board[0][0]==board[1][1])&&(board[1][1]==board[2][2]))
||((board[0][2])&&(board[0][2]==board[1][1])&&(board[1][1]==board[2][0]))){
if(board[1][1]==1)printf("X player won.\n");
else printf("O player won.\n");
return 0;
}
int flag=0;
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
if(board[i][j]==0)flag=1;
}
}
if(flag==0){
printf("draw.\n");
return 0;
}
int yx,yy;
do{
printf("Enter a row (0, 1, or 2) for player O:");
scanf("%d", &yy);
printf("Enter a column (0, 1, or 2) for player O:");
scanf("%d", &yx);
}while(board[yy][yx]!=0);
board[yy][yx]=2;
for(int i=0;i<3;i++){
puts("-------");
printf("|");
for(int j=0;j<3;j++){
if(board[i][j]==1)printf("X|");
else if(board[i][j]==2)printf("O|");
else printf(" |");
}
printf("\n");
}
puts("-------");
for(int i=0;i<3;i++){
if((board[i][0]==board[i][1])&&(board[i][1]==board[i][2])&&(board[i][0])){
if(board[i][0]==1)printf("X player won.\n");
else printf("O player won.\n");
return 0;
}
if((board[0][i]==board[1][i])&&(board[1][i]==board[2][i])&&(board[0][i])){
if(board[0][i]==1)printf("X player won.\n");
else printf("O player won.\n");
return 0;
}
}
if(((board[0][0])&&(board[0][0]==board[1][1])&&(board[1][1]==board[2][2]))
||((board[0][2])&&(board[0][2]==board[1][1])&&(board[1][1]==board[2][0]))){
if(board[1][1]==1)printf("X player won.\n");
else printf("O player won.\n");
return 0;
}
flag=0;
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
if(board[i][j]==0)flag=1;
}
}
if(flag==0){
printf("draw.\n");
return 0;
}
}
} |
the_stack_data/6387584.c | #include <stdio.h>
int
test()
{
long long x;
x = 0;
x = x + 1;
if (x != 1)
return 1;
return 0;
}
int main () {
int x;
x = test();
printf("%d\n", x);
return 0;
} |
the_stack_data/777281.c | #include <math.h>
double fmin(double x, double y)
{
if (isnan(x))
return y;
if (isnan(y))
return x;
// XXX EMSCRIPTEN: use wasm builtins for code size
#ifdef __wasm__
return __builtin_wasm_min_f64(x, y);
#else
/* handle signed zeros, see C99 Annex F.9.9.2 */
if (signbit(x) != signbit(y))
return signbit(x) ? x : y;
return x < y ? x : y;
#endif
}
|
the_stack_data/154829312.c | /*
* SPI testing utility (using spidev driver)
*
* Copyright (c) 2007 MontaVista Software, Inc.
* Copyright (c) 2007 Anton Vorontsov <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License.
*
* Cross-compile with cross-gcc -I/path/to/cross-kernel/include
*/
#include <stdint.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/ioctl.h>
#include <sys/stat.h>
#include <linux/types.h>
#include <linux/spi/spidev.h>
#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
static void pabort(const char *s)
{
perror(s);
abort();
}
static const char *device = "/dev/spidev0.0";
static uint32_t mode;
static uint8_t bits = 8;
static char *input_file;
static char *output_file;
static uint32_t speed = 1000000;
static uint16_t delay;
static int verbose;
uint8_t default_tx[] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0x40, 0x00, 0x00, 0x00, 0x00, 0x95,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xF0, 0x0D,
};
uint8_t default_rx[ARRAY_SIZE(default_tx)] = {0, };
char *input_tx;
static void hex_dump(const void *src, size_t length, size_t line_size,
char *prefix)
{
int i = 0;
const unsigned char *address = src;
const unsigned char *line = address;
unsigned char c;
printf("%s | ", prefix);
while (length-- > 0) {
printf("%02X ", *address++);
if (!(++i % line_size) || (length == 0 && i % line_size)) {
if (length == 0) {
while (i++ % line_size)
printf("__ ");
}
printf(" | "); /* right close */
while (line < address) {
c = *line++;
printf("%c", (c < 33 || c == 255) ? 0x2E : c);
}
printf("\n");
if (length > 0)
printf("%s | ", prefix);
}
}
}
/*
* Unescape - process hexadecimal escape character
* converts shell input "\x23" -> 0x23
*/
static int unescape(char *_dst, char *_src, size_t len)
{
int ret = 0;
int match;
char *src = _src;
char *dst = _dst;
unsigned int ch;
while (*src) {
if (*src == '\\' && *(src+1) == 'x') {
match = sscanf(src + 2, "%2x", &ch);
if (!match)
pabort("malformed input string");
src += 4;
*dst++ = (unsigned char)ch;
} else {
*dst++ = *src++;
}
ret++;
}
return ret;
}
static void transfer(int fd, uint8_t const *tx, uint8_t const *rx, size_t len)
{
int ret;
int out_fd;
struct spi_ioc_transfer tr = {
.tx_buf = (unsigned long)tx,
.rx_buf = (unsigned long)rx,
.len = len,
.delay_usecs = delay,
.speed_hz = speed,
.bits_per_word = bits,
};
if (mode & SPI_TX_QUAD)
tr.tx_nbits = 4;
else if (mode & SPI_TX_DUAL)
tr.tx_nbits = 2;
if (mode & SPI_RX_QUAD)
tr.rx_nbits = 4;
else if (mode & SPI_RX_DUAL)
tr.rx_nbits = 2;
if (!(mode & SPI_LOOP)) {
if (mode & (SPI_TX_QUAD | SPI_TX_DUAL))
tr.rx_buf = 0;
else if (mode & (SPI_RX_QUAD | SPI_RX_DUAL))
tr.tx_buf = 0;
}
ret = ioctl(fd, SPI_IOC_MESSAGE(1), &tr);
if (ret < 1)
pabort("can't send spi message");
if (verbose)
hex_dump(tx, len, 32, "TX");
if (output_file) {
out_fd = open(output_file, O_WRONLY | O_CREAT | O_TRUNC, 0666);
if (out_fd < 0)
pabort("could not open output file");
ret = write(out_fd, rx, len);
if (ret != len)
pabort("not all bytes written to output file");
close(out_fd);
}
if (verbose || !output_file)
hex_dump(rx, len, 32, "RX");
}
static void print_usage(const char *prog)
{
printf("Usage: %s [-DsbdlHOLC3]\n", prog);
puts(" -D --device device to use (default /dev/spidev0.0)\n"
" -s --speed max speed (Hz)\n"
" -d --delay delay (usec)\n"
" -b --bpw bits per word\n"
" -i --input input data from a file (e.g. \"test.bin\")\n"
" -o --output output data to a file (e.g. \"results.bin\")\n"
" -l --loop loopback\n"
" -H --cpha clock phase\n"
" -O --cpol clock polarity\n"
" -L --lsb least significant bit first\n"
" -C --cs-high chip select active high\n"
" -3 --3wire SI/SO signals shared\n"
" -v --verbose Verbose (show tx buffer)\n"
" -p Send data (e.g. \"1234\\xde\\xad\")\n"
" -N --no-cs no chip select\n"
" -R --ready slave pulls low to pause\n"
" -2 --dual dual transfer\n"
" -4 --quad quad transfer\n");
exit(1);
}
static void parse_opts(int argc, char *argv[])
{
while (1) {
static const struct option lopts[] = {
{ "device", 1, 0, 'D' },
{ "speed", 1, 0, 's' },
{ "delay", 1, 0, 'd' },
{ "bpw", 1, 0, 'b' },
{ "input", 1, 0, 'i' },
{ "output", 1, 0, 'o' },
{ "loop", 0, 0, 'l' },
{ "cpha", 0, 0, 'H' },
{ "cpol", 0, 0, 'O' },
{ "lsb", 0, 0, 'L' },
{ "cs-high", 0, 0, 'C' },
{ "3wire", 0, 0, '3' },
{ "no-cs", 0, 0, 'N' },
{ "ready", 0, 0, 'R' },
{ "dual", 0, 0, '2' },
{ "verbose", 0, 0, 'v' },
{ "quad", 0, 0, '4' },
{ NULL, 0, 0, 0 },
};
int c;
c = getopt_long(argc, argv, "D:s:d:b:i:o:lHOLC3NR24p:v",
lopts, NULL);
if (c == -1)
break;
switch (c) {
case 'D':
device = optarg;
break;
case 's':
speed = atoi(optarg);
break;
case 'd':
delay = atoi(optarg);
break;
case 'b':
bits = atoi(optarg);
break;
case 'i':
input_file = optarg;
break;
case 'o':
output_file = optarg;
break;
case 'l':
mode |= SPI_LOOP;
break;
case 'H':
mode |= SPI_CPHA;
break;
case 'O':
mode |= SPI_CPOL;
break;
case 'L':
mode |= SPI_LSB_FIRST;
break;
case 'C':
mode |= SPI_CS_HIGH;
break;
case '3':
mode |= SPI_3WIRE;
break;
case 'N':
mode |= SPI_NO_CS;
break;
case 'v':
verbose = 1;
break;
case 'R':
mode |= SPI_READY;
break;
case 'p':
input_tx = optarg;
break;
case '2':
mode |= SPI_TX_DUAL;
break;
case '4':
mode |= SPI_TX_QUAD;
break;
default:
print_usage(argv[0]);
break;
}
}
if (mode & SPI_LOOP) {
if (mode & SPI_TX_DUAL)
mode |= SPI_RX_DUAL;
if (mode & SPI_TX_QUAD)
mode |= SPI_RX_QUAD;
}
}
static void transfer_escaped_string(int fd, char *str)
{
size_t size = strlen(str);
uint8_t *tx;
uint8_t *rx;
tx = malloc(size);
if (!tx)
pabort("can't allocate tx buffer");
rx = malloc(size);
if (!rx)
pabort("can't allocate rx buffer");
size = unescape((char *)tx, str, size);
transfer(fd, tx, rx, size);
free(rx);
free(tx);
}
static void transfer_file(int fd, char *filename)
{
ssize_t bytes;
struct stat sb;
int tx_fd;
uint8_t *tx;
uint8_t *rx;
if (stat(filename, &sb) == -1)
pabort("can't stat input file");
tx_fd = open(filename, O_RDONLY);
if (tx_fd < 0)
pabort("can't open input file");
tx = malloc(sb.st_size);
if (!tx)
pabort("can't allocate tx buffer");
rx = malloc(sb.st_size);
if (!rx)
pabort("can't allocate rx buffer");
bytes = read(tx_fd, tx, sb.st_size);
if (bytes != sb.st_size)
pabort("failed to read input file");
transfer(fd, tx, rx, sb.st_size);
free(rx);
free(tx);
close(tx_fd);
}
int main(int argc, char *argv[])
{
int ret = 0;
int fd;
parse_opts(argc, argv);
fd = open(device, O_RDWR);
if (fd < 0)
pabort("can't open device");
/*
* spi mode
*/
mode = 4;
printf("spi mode write: %04x\n", mode);
ret = ioctl(fd, SPI_IOC_WR_MODE, &mode);
if (ret == -1)
pabort("can't set spi mode");
ret = ioctl(fd, SPI_IOC_RD_MODE, &mode);
if (ret == -1)
pabort("can't get spi mode");
printf("spi mode read: %04x\n", mode);
/*
* bits per word
*/
ret = ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &bits);
if (ret == -1)
pabort("can't set bits per word");
ret = ioctl(fd, SPI_IOC_RD_BITS_PER_WORD, &bits);
if (ret == -1)
pabort("can't get bits per word");
/*
* max speed hz
*/
ret = ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed);
if (ret == -1)
pabort("can't set max speed hz");
ret = ioctl(fd, SPI_IOC_RD_MAX_SPEED_HZ, &speed);
if (ret == -1)
pabort("can't get max speed hz");
printf("spi mode: 0x%x\n", mode);
printf("bits per word: %d\n", bits);
printf("max speed: %d Hz (%d KHz)\n", speed, speed/1000);
if (input_tx && input_file)
pabort("only one of -p and --input may be selected");
if (input_tx)
transfer_escaped_string(fd, input_tx);
else if (input_file)
transfer_file(fd, input_file);
else
transfer(fd, default_tx, default_rx, sizeof(default_tx));
close(fd);
return ret;
}
|
the_stack_data/10984.c | /* PR middle-end/70680 */
int v;
void
f1 (void)
{
int i = 0, j = 0;
#pragma omp task default(shared) if(0)
{
#pragma omp simd collapse(2)
for (i = 0; i < 10; i++)
for (j = 0; j < 10; j++)
;
v = i + j;
}
if (i != 10 || j != 10)
__builtin_abort ();
}
void
f2 (void)
{
int i = 0, j = 0;
#pragma omp task default(shared) if(0)
{
#pragma omp simd collapse(2)
for (i = 0; i < 10; i++)
for (j = 0; j < 10; j++)
;
}
if (i != 10 || j != 10)
__builtin_abort ();
}
void
f3 (void)
{
int i = 0, j = 0;
#pragma omp task default(shared) if(0)
{
#pragma omp simd collapse(2) lastprivate (i, j)
for (i = 0; i < 10; i++)
for (j = 0; j < 10; j++)
;
v = i + j;
}
if (i != 10 || j != 10)
__builtin_abort ();
}
void
f4 (void)
{
int i = 0, j = 0;
#pragma omp task default(shared) if(0)
{
#pragma omp simd collapse(2) lastprivate (i, j)
for (i = 0; i < 10; i++)
for (j = 0; j < 10; j++)
;
}
if (i != 10 || j != 10)
__builtin_abort ();
}
int
main ()
{
f1 ();
if (v++ != 20)
__builtin_abort ();
f2 ();
f3 ();
if (v++ != 20)
__builtin_abort ();
f4 ();
return 0;
}
|
the_stack_data/98680.c | // RUN: jlang-cc %s -fsyntax-only -verify
//typedef __attribute__(( ext_vector_type(4) )) float float4;
typedef float float4 __attribute__((vector_size(16)));
float4 foo = (float4){ 1.0, 2.0, 3.0, 4.0 };
float4 foo2 = (float4){ 1.0, 2.0, 3.0, 4.0 , 5.0 }; // expected-warning{{excess elements in vector initializer}}
float4 array[] = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0};
int array_sizecheck[(sizeof(array) / sizeof(float4)) == 3? 1 : -1];
float4 array2[2] = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0,
9.0 }; // expected-warning {{excess elements in array initializer}}
float4 array3[2] = { {1.0, 2.0, 3.0}, 5.0, 6.0, 7.0, 8.0,
9.0 }; // expected-warning {{excess elements in array initializer}}
// rdar://6881069
__attribute__((vector_size(16))) // expected-error {{unsupported type 'float (void)' for vector_size attribute, please use on typedef}}
float f1(void) {
}
|
the_stack_data/62639073.c | #include <stdio.h>
//declaration of global array(initialised by 1)
int multi(int arr[]){
int prod = 1;
//adding array elements
printf("Performing summation \n\n");
for (int i = 0; i < 10; i++)
{
prod*=arr[i];
}
return prod;
}
int main()
{
//Program starts here
int sum=0;
int arr[10];
//Taking input of an array using a for loop
for (int i = 0; i < 10; i++)
{
printf("Enter your element: ");
scanf("%d",&arr[i]);
}
printf("\n");
//calling function for multiplication
int product;
product = multi(arr);
//printing the sum of array
printf("The Product of the array given %d",product);
}
|
the_stack_data/211079490.c | /*-------------------------------------------------------------------------
NeoPixel library helper functions for Esp8266.
Written by Michael C. Miller.
I invest time and resources providing this open source code,
please support me by dontating (see https://github.com/Makuna/NeoPixelBus)
-------------------------------------------------------------------------
This file is part of the Makuna/NeoPixelBus library.
NeoPixelBus 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 3 of
the License, or (at your option) any later version.
NeoPixelBus 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 NeoPixel. If not, see
<http://www.gnu.org/licenses/>.
-------------------------------------------------------------------------*/
#ifdef ARDUINO_ARCH_ESP8266
#include <Arduino.h>
#include <eagle_soc.h>
void ICACHE_RAM_ATTR esp8266_uart1_send_pixels(uint8_t* pixels, uint8_t* end)
{
const uint8_t _uartData[4] = { 0b00110111, 0b00000111, 0b00110100, 0b00000100 };
const uint8_t _uartFifoTrigger = 124; // tx fifo should be 128 bytes. minus the four we need to send
do
{
uint8_t subpix = *pixels++;
uint8_t buf[4] = { _uartData[(subpix >> 6) & 3],
_uartData[(subpix >> 4) & 3],
_uartData[(subpix >> 2) & 3],
_uartData[subpix & 3] };
// now wait till this the FIFO buffer has room to send more
while (((U1S >> USTXC) & 0xff) > _uartFifoTrigger);
for (uint8_t i = 0; i < 4; i++)
{
// directly write the byte to transfer into the UART1 FIFO register
U1F = buf[i];
}
} while (pixels < end);
}
inline uint32_t _getCycleCount()
{
uint32_t ccount;
__asm__ __volatile__("rsr %0,ccount":"=a" (ccount));
return ccount;
}
#define CYCLES_800_T0H (F_CPU / 2500000) // 0.4us
#define CYCLES_800_T1H (F_CPU / 1250000) // 0.8us
#define CYCLES_800 (F_CPU / 800000) // 1.25us per bit
#define CYCLES_400_T0H (F_CPU / 2000000)
#define CYCLES_400_T1H (F_CPU / 833333)
#define CYCLES_400 (F_CPU / 400000)
void ICACHE_RAM_ATTR bitbang_send_pixels_800(uint8_t* pixels, uint8_t* end, uint8_t pin)
{
const uint32_t pinRegister = _BV(pin);
uint8_t mask;
uint8_t subpix;
uint32_t cyclesStart;
// trigger emediately
cyclesStart = _getCycleCount() - CYCLES_800;
do
{
subpix = *pixels++;
for (mask = 0x80; mask != 0; mask >>= 1)
{
// do the checks here while we are waiting on time to pass
uint32_t cyclesBit = ((subpix & mask)) ? CYCLES_800_T1H : CYCLES_800_T0H;
uint32_t cyclesNext = cyclesStart;
uint32_t delta;
// after we have done as much work as needed for this next bit
// now wait for the HIGH
do
{
// cache and use this count so we don't incur another
// instruction before we turn the bit high
cyclesStart = _getCycleCount();
} while ((cyclesStart - cyclesNext) < CYCLES_800);
// set high
GPIO_REG_WRITE(GPIO_OUT_W1TS_ADDRESS, pinRegister);
// wait for the LOW
do
{
cyclesNext = _getCycleCount();
} while ((cyclesNext - cyclesStart) < cyclesBit);
// set low
GPIO_REG_WRITE(GPIO_OUT_W1TC_ADDRESS, pinRegister);
}
} while (pixels < end);
}
void ICACHE_RAM_ATTR bitbang_send_pixels_400(uint8_t* pixels, uint8_t* end, uint8_t pin)
{
const uint32_t pinRegister = _BV(pin);
uint8_t mask;
uint8_t subpix;
uint32_t cyclesStart;
// trigger emediately
cyclesStart = _getCycleCount() - CYCLES_400;
do
{
subpix = *pixels++;
for (mask = 0x80; mask; mask >>= 1)
{
uint32_t cyclesBit = ((subpix & mask)) ? CYCLES_400_T1H : CYCLES_400_T0H;
uint32_t cyclesNext = cyclesStart;
// after we have done as much work as needed for this next bit
// now wait for the HIGH
do
{
// cache and use this count so we don't incur another
// instruction before we turn the bit high
cyclesStart = _getCycleCount();
} while ((cyclesStart - cyclesNext) < CYCLES_400);
// set high
GPIO_REG_WRITE(GPIO_OUT_W1TS_ADDRESS, pinRegister);
// wait for the LOW
do
{
cyclesNext = _getCycleCount();
} while ((cyclesNext - cyclesStart) < cyclesBit);
// set low
GPIO_REG_WRITE(GPIO_OUT_W1TC_ADDRESS, pinRegister);
}
} while (pixels < end);
}
#endif
|
the_stack_data/7587.c | /*
* @Author: Huang Yuhui
* @Date: 2019-03-27 14:29:56
* @Last Modified by: Huang Yuhui
* @Last Modified time: 2019-03-27 14:45:53
*/
/*
* 程序填空题-题目描述如下:
*
* 函数'fun'的功能是:输出'a'所指数组中前'n'个数据并要求每行输出'5'个数
*/
#include <stdio.h>
#include <stdlib.h>
void fun(int *a, int n)
{
int i;
for (i = 0; i < n; i++)
{
/**********found**********/
if (i % 5 == 0)
/**********found**********/
printf("\n");
/**********found**********/
printf("%d ", a[i]);
}
}
void main()
{
int a[100] = {0}, i, n = 22;
for (i = 0; i < n; i++)
a[i] = rand() % 21;
fun(a, n);
printf("\n");
system("pause");
}
/*The result be shown as followed:
20 8 13 19 17
16 12 0 19 20
14 5 13 6 7
8 13 14 18 18
9 9
Press any key to continue . . .
*/
|
the_stack_data/3263097.c | /*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2011 Nexenta Systems, Inc. All rights reserved.
*/
/*
* Copyright 2006 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
extern void __vsqrt(int, double *, int, double *, int);
#pragma weak vsqrt_ = __vsqrt_
/* just invoke the serial function */
void
__vsqrt_(int *n, double *x, int *stridex, double *y, int *stridey)
{
__vsqrt(*n, x, *stridex, y, *stridey);
}
|
the_stack_data/99508.c | /***
* This code is a part of EvoApproxLib library (ehw.fit.vutbr.cz/approxlib) distributed under The MIT License.
* When used, please cite the following article(s): V. Mrazek, R. Hrbacek, Z. Vasicek and L. Sekanina, "EvoApprox8b: Library of approximate adders and multipliers for circuit design and benchmarking of approximation methods". Design, Automation & Test in Europe Conference & Exhibition (DATE), 2017, Lausanne, 2017, pp. 258-261. doi: 10.23919/DATE.2017.7926993
* This file contains a circuit from evoapprox8b dataset. Note that a new version of library was already published.
***/
#include <stdint.h>
#include <stdlib.h>
/// Approximate function mul8_074
/// Library = EvoApprox8b
/// Circuit = mul8_074
/// Area (180) = 4808
/// Delay (180) = 3.600
/// Power (180) = 1927.50
/// Area (45) = 352
/// Delay (45) = 1.340
/// Power (45) = 166.90
/// Nodes = 88
/// HD = 322388
/// MAE = 276.75433
/// MSE = 129209.81543
/// MRE = 5.93 %
/// WCE = 1926
/// WCRE = 100 %
/// EP = 98.1 %
uint16_t mul8_074(uint8_t a, uint8_t b)
{
uint16_t c = 0;
uint8_t n2 = (a >> 1) & 0x1;
uint8_t n4 = (a >> 2) & 0x1;
uint8_t n6 = (a >> 3) & 0x1;
uint8_t n8 = (a >> 4) & 0x1;
uint8_t n10 = (a >> 5) & 0x1;
uint8_t n12 = (a >> 6) & 0x1;
uint8_t n14 = (a >> 7) & 0x1;
uint8_t n16 = (b >> 0) & 0x1;
uint8_t n18 = (b >> 1) & 0x1;
uint8_t n20 = (b >> 2) & 0x1;
uint8_t n22 = (b >> 3) & 0x1;
uint8_t n24 = (b >> 4) & 0x1;
uint8_t n26 = (b >> 5) & 0x1;
uint8_t n28 = (b >> 6) & 0x1;
uint8_t n30 = (b >> 7) & 0x1;
uint8_t n32;
uint8_t n33;
uint8_t n34;
uint8_t n35;
uint8_t n38;
uint8_t n41;
uint8_t n47;
uint8_t n51;
uint8_t n62;
uint8_t n63;
uint8_t n65;
uint8_t n89;
uint8_t n93;
uint8_t n99;
uint8_t n117;
uint8_t n145;
uint8_t n171;
uint8_t n173;
uint8_t n398;
uint8_t n399;
uint8_t n414;
uint8_t n415;
uint8_t n427;
uint8_t n430;
uint8_t n514;
uint8_t n532;
uint8_t n548;
uint8_t n598;
uint8_t n648;
uint8_t n664;
uint8_t n682;
uint8_t n683;
uint8_t n749;
uint8_t n764;
uint8_t n782;
uint8_t n798;
uint8_t n814;
uint8_t n898;
uint8_t n914;
uint8_t n932;
uint8_t n933;
uint8_t n948;
uint8_t n949;
uint8_t n1014;
uint8_t n1032;
uint8_t n1048;
uint8_t n1049;
uint8_t n1064;
uint8_t n1082;
uint8_t n1148;
uint8_t n1164;
uint8_t n1165;
uint8_t n1182;
uint8_t n1183;
uint8_t n1198;
uint8_t n1199;
uint8_t n1214;
uint8_t n1215;
uint8_t n1264;
uint8_t n1282;
uint8_t n1298;
uint8_t n1314;
uint8_t n1321;
uint8_t n1332;
uint8_t n1348;
uint8_t n1364;
uint8_t n1399;
uint8_t n1414;
uint8_t n1415;
uint8_t n1432;
uint8_t n1433;
uint8_t n1448;
uint8_t n1449;
uint8_t n1464;
uint8_t n1465;
uint8_t n1482;
uint8_t n1483;
uint8_t n1532;
uint8_t n1548;
uint8_t n1564;
uint8_t n1582;
uint8_t n1598;
uint8_t n1614;
uint8_t n1632;
uint8_t n1664;
uint8_t n1665;
uint8_t n1682;
uint8_t n1683;
uint8_t n1698;
uint8_t n1699;
uint8_t n1714;
uint8_t n1715;
uint8_t n1732;
uint8_t n1733;
uint8_t n1748;
uint8_t n1749;
uint8_t n1764;
uint8_t n1782;
uint8_t n1798;
uint8_t n1814;
uint8_t n1832;
uint8_t n1848;
uint8_t n1864;
uint8_t n1882;
uint8_t n1898;
uint8_t n1914;
uint8_t n1915;
uint8_t n1932;
uint8_t n1933;
uint8_t n1948;
uint8_t n1949;
uint8_t n1964;
uint8_t n1965;
uint8_t n1982;
uint8_t n1983;
uint8_t n1998;
uint8_t n1999;
uint8_t n2014;
uint8_t n2015;
n32 = n18 & n14;
n33 = n18 & n14;
n34 = ~(n16 & n32 & n18);
n35 = ~(n16 & n32 & n18);
n38 = ~(n6 | n34 | n14);
n41 = ~(n18 & n38);
n47 = ~n35;
n51 = n47 & n38;
n62 = ~(n2 & n12 & n30);
n63 = ~(n2 & n12 & n30);
n65 = ~(n62 | n12);
n89 = ~(n65 ^ n38);
n93 = n89 | n38;
n99 = n63;
n117 = n93;
n145 = n41;
n171 = ~(n99 | n12);
n173 = n145;
n398 = n117 & n32;
n399 = n117 & n32;
n414 = n51 & n16;
n415 = n51 & n16;
n427 = ~n35;
n430 = ~n171;
n514 = n10 & n20;
n532 = n12 & n20;
n548 = n14 & n20;
n598 = n399 & n430;
n648 = n398 | n514;
n664 = n414 | n532;
n682 = n415 ^ n548;
n683 = n415 & n548;
n749 = n6 & n22;
n764 = n8 & n22;
n782 = n10 & n22;
n798 = n12 & n22;
n814 = n14 & n22;
n898 = n648 | n764;
n914 = n664 | n782;
n932 = n682 ^ n798;
n933 = n682 & n798;
n948 = (n683 ^ n814) ^ n933;
n949 = (n683 & n814) | (n814 & n933) | (n683 & n933);
n1014 = n6 & n24;
n1032 = n8 & n24;
n1048 = n10 & n24;
n1049 = n10 & n24;
n1064 = n12 & n24;
n1082 = n14 & n24;
n1148 = n898 | n1014;
n1164 = n914 ^ n1032;
n1165 = n914 & n1032;
n1182 = (n932 ^ n1048) ^ n1165;
n1183 = (n932 & n1048) | (n1048 & n1165) | (n932 & n1165);
n1198 = (n948 ^ n1064) ^ n1183;
n1199 = (n948 & n1064) | (n1064 & n1183) | (n948 & n1183);
n1214 = (n949 ^ n1082) ^ n1199;
n1215 = (n949 & n1082) | (n1082 & n1199) | (n949 & n1199);
n1264 = n4 & n26;
n1282 = n6 & n26;
n1298 = n8 & n26;
n1314 = n10 & n26;
n1321 = n33;
n1332 = n12 & n26;
n1348 = n14 & n26;
n1364 = n173 & n598;
n1399 = n1148 | n1264;
n1414 = (n1164 ^ n1282) ^ n1399;
n1415 = (n1164 & n1282) | (n1282 & n1399) | (n1164 & n1399);
n1432 = (n1182 ^ n1298) ^ n1415;
n1433 = (n1182 & n1298) | (n1298 & n1415) | (n1182 & n1415);
n1448 = (n1198 ^ n1314) ^ n1433;
n1449 = (n1198 & n1314) | (n1314 & n1433) | (n1198 & n1433);
n1464 = (n1214 ^ n1332) ^ n1449;
n1465 = (n1214 & n1332) | (n1332 & n1449) | (n1214 & n1449);
n1482 = (n1215 ^ n1348) ^ n1465;
n1483 = (n1215 & n1348) | (n1348 & n1465) | (n1215 & n1465);
n1532 = n4 & n28;
n1548 = n6 & n28;
n1564 = n8 & n28;
n1582 = n10 & n28;
n1598 = n12 & n28;
n1614 = n14 & n28;
n1632 = n1049;
n1664 = n1414 ^ n1532;
n1665 = n1414 & n1532;
n1682 = (n1432 ^ n1548) ^ n1665;
n1683 = (n1432 & n1548) | (n1548 & n1665) | (n1432 & n1665);
n1698 = (n1448 ^ n1564) ^ n1683;
n1699 = (n1448 & n1564) | (n1564 & n1683) | (n1448 & n1683);
n1714 = (n1464 ^ n1582) ^ n1699;
n1715 = (n1464 & n1582) | (n1582 & n1699) | (n1464 & n1699);
n1732 = (n1482 ^ n1598) ^ n1715;
n1733 = (n1482 & n1598) | (n1598 & n1715) | (n1482 & n1715);
n1748 = (n1483 ^ n1614) ^ n1733;
n1749 = (n1483 & n1614) | (n1614 & n1733) | (n1483 & n1733);
n1764 = n2 & n30;
n1782 = n2 & n30;
n1798 = n4 & n30;
n1814 = n6 & n30;
n1832 = n8 & n30;
n1848 = n10 & n30;
n1864 = n12 & n30;
n1882 = n14 & n30;
n1898 = n427 ^ n1764;
n1914 = n1664 ^ n1782;
n1915 = n1664 & n1782;
n1932 = (n1682 ^ n1798) ^ n1915;
n1933 = (n1682 & n1798) | (n1798 & n1915) | (n1682 & n1915);
n1948 = (n1698 ^ n1814) ^ n1933;
n1949 = (n1698 & n1814) | (n1814 & n1933) | (n1698 & n1933);
n1964 = (n1714 ^ n1832) ^ n1949;
n1965 = (n1714 & n1832) | (n1832 & n1949) | (n1714 & n1949);
n1982 = (n1732 ^ n1848) ^ n1965;
n1983 = (n1732 & n1848) | (n1848 & n1965) | (n1732 & n1965);
n1998 = (n1748 ^ n1864) ^ n1983;
n1999 = (n1748 & n1864) | (n1864 & n1983) | (n1748 & n1983);
n2014 = (n1749 ^ n1882) ^ n1999;
n2015 = (n1749 & n1882) | (n1882 & n1999) | (n1749 & n1999);
c |= (n1321 & 0x1) << 0;
c |= (n598 & 0x1) << 1;
c |= (n1699 & 0x1) << 2;
c |= (n1632 & 0x1) << 3;
c |= (n749 & 0x1) << 4;
c |= (n1364 & 0x1) << 5;
c |= (n1632 & 0x1) << 6;
c |= (n1898 & 0x1) << 7;
c |= (n1914 & 0x1) << 8;
c |= (n1932 & 0x1) << 9;
c |= (n1948 & 0x1) << 10;
c |= (n1964 & 0x1) << 11;
c |= (n1982 & 0x1) << 12;
c |= (n1998 & 0x1) << 13;
c |= (n2014 & 0x1) << 14;
c |= (n2015 & 0x1) << 15;
return c;
}
|
the_stack_data/168893002.c | /*
* libc/stdio/fgetc.c
*/
#include <stdio.h>
int fgetc(FILE * f)
{
unsigned char res;
return ((__stdio_read(f, &res, 1) <= 0) ? EOF : res);
}
|
the_stack_data/111077683.c | // File: 3.2.c
// Author: TaoKY
#include <stdio.h>
#include <math.h>
int main(){
int money = 1000;
double y1 = 0.0414, y2 = 0.0468, y3 = 0.054, y5 = 0.0585;
double dyn = 0.0072;
printf("1. %lf\n", money * (1 + 5 * y5));
printf("2. %lf\n", money * (1 + 2 * y2) * (1 + 3 * y3));
printf("3. %lf\n", money * (1 + 3 * y3) * (1 + 2 * y2));
printf("4. %lf\n", money * pow((1 + y1), 5));
printf("5. %lf\n", money * pow((1 + dyn / 4), 4 * 5));
return 0;
}
|
the_stack_data/448820.c | #include <sys/auxv.h>
int
main(void)
{
int res;
unsigned long val;
res = elf_aux_info(AT_HWCAP, &val, sizeof(unsigned long));
(void)res;
return (val != 0);
}
|
the_stack_data/66102.c | // Find all admissible words of length n
#include <stdio.h>
#define N 100
#define RANGE 3 /* values 0 to RANGE-1 permissible */
int n,trial[N];
main(int argc,char* argv[])
{int i,level,nsuccesses,a1p,a1n,a2p,a2n,b1p,b1n,b2p,b2n,next_value,pal;
char adm_str[20];
FILE *adm;
if (argc != 2)
{fprintf(stderr,"Usage: brinkhuis n\n");
exit(1);}
sscanf(argv[1],"%d",&n);
if (n < 12)
{fprintf(stderr,"Error: n=%d is smaller than 12\n",n);
exit(1);}
if (n >= N)
{fprintf(stderr,"Error: n=%d exceeds N-1=%d\n",n,N-1);
exit(1);}
b1p=b1n=b2p=b2n=a1p=a1n=a2p=a2n=nsuccesses=0;
trial[0]=0;
trial[1]=1;
trial[2]=2;
trial[3]=0;
trial[4]=2;
trial[5]=1;
trial[n-6]=1;
trial[n-5]=2;
trial[n-4]=0;
trial[n-3]=2;
trial[n-2]=1;
trial[n-1]=0;
trial[6]=0;
level=6;
sprintf(adm_str,"a1%d.txt",n);
adm=fopen(adm_str,"w+");
fprintf(adm,"%d\n",n);
while (level >= 6)
{if (chk(level))
{if (++level < n-6) next_value=0;
else
{if (chk(n-6) && chk(n-5) && chk(n-4) && chk(n-3) && chk(n-2) && chk(n-1))
{if ((pal=chkn()) > 1)
{printf("Success [%3d]: ",++nsuccesses);
for (i=0; i<n; i++)
{printf("%d",trial[i]);
fprintf(adm,"%d",trial[i]);}
if (pal&1)
{b1p++;
printf(" (palindromic)");}
else b1n+=2;
fprintf(adm,"\n");
printf("\n");}
if (pal&1) a1p++;
else a1n+=2;}
next_value=trial[--level]+1;}
}
else next_value=trial[level]+1;
while (level>=6 && next_value>=RANGE) next_value=trial[--level]+1;
if (level >= 6) trial[level]=next_value;}
fprintf(adm,"9\n");
fclose(adm);
trial[0]=0;
trial[1]=1;
trial[2]=2;
trial[3]=1;
trial[4]=0;
trial[5]=2;
trial[n-6]=2;
trial[n-5]=0;
trial[n-4]=1;
trial[n-3]=2;
trial[n-2]=1;
trial[n-1]=0;
trial[6]=0;
level=6;
sprintf(adm_str,"a2%d.txt",n);
adm=fopen(adm_str,"w+");
fprintf(adm,"%d\n",n);
while (level >= 6)
{if (chk(level))
{if (++level < n-6) next_value=0;
else
{if (chk(n-6) && chk(n-5) && chk(n-4) && chk(n-3) && chk(n-2) && chk(n-1))
{if ((pal=chkn()) > 1)
{printf("Success [%3d]: ",++nsuccesses);
for (i=0; i<n; i++)
{printf("%d",trial[i]);
fprintf(adm,"%d",trial[i]);}
if (pal&1)
{b2p++;
printf(" (palindromic)");}
else b2n+=2;
fprintf(adm,"\n");
printf("\n");}
if (pal&1) a2p++;
else a2n+=2;}
next_value=trial[--level]+1;}
}
else next_value=trial[level]+1;
while (level>=6 && next_value>=RANGE) next_value=trial[--level]+1;
if (level >= 6) trial[level]=next_value;}
fprintf(adm,"9\n");
fclose(adm);
printf("Done: a1=%3d, a1p=%3d, a1n=%3d; b1=%3d, b1p=%3d, b1n=%3d\n",a1p+a1n,a1p,a1n/2,b1p+b1n,b1p,b1n/2);
printf(" a2=%3d, a2p=%3d, a2n=%3d; b2=%3d, b2p=%3d, b2n=%3d\n",a2p+a2n,a2p,a2n/2,b2p+b2n,b2p,b2n/2);}
// Return the i-th entry of trial[j0](r0)|trial[j1](r1)|trial[j2](r2)
// where j0,j1,j2=0,1,2; r0,r1,r2=0,1 (1 means reverse)
// j=16*j2+4*j1+j0; r=4*r2+2*r1+r0
int tr(int i,int j,int r)
{if (i < n)
{if (r&1) return (trial[n-1-i]+(j&3))%3;
return (trial[i]+(j&3))%3;}
if (i < 2*n)
{if (r&2) return (trial[2*n-1-i]+((j&12)>>2))%3;
return (trial[i-n]+((j&12)>>2))%3;}
if (r&4) return (trial[3*n-1-i]+((j&48)>>4))%3;
return (trial[i-2*n]+((j&48)>>4))%3;}
// Check that trial[0..lev] is squarefree, assuming trial[0..lev-1] is.
// Also if lev==n-7, check that trial is not preceded by its reversal
// (in which case it is redundant).
int chk(int lev)
{int i,j,k,l,ti,tj;
for (l=1; (j=(lev-2*l+1))>=0; l++)
{i=0;
while (i<l && trial[j+i]==trial[j+l+i]) i++;
if (i == l) return 0;}
if (lev == n-7)
{i=6;
while (i < (j=(n-1-i)))
{if ((ti=trial[i]) != (tj=trial[j])) return (ti<tj);
i++;}
}
return 1;}
// Assuming trial[0..n-1] is squarefree, check its various concatenations.
// Return 0 if trial is non-squarefree non-palindromic;
// 1 if trial is non-squarefree palindromic;
// 2 if trial is squarefree non-palindromic;
// 3 if trial is squarefree palindromic.
int chkn()
{int frst,lst,len,i,palindromic;
i=(n+1)/2;
while (i>5 && trial[n-1-i]==trial[i]) i--;
palindromic=(i==5); // 1 for palindromic, 0 otherwise
for (frst=0; frst<n; frst++) for (lst=n+((n+1+frst)&1); lst<2*n; lst+=2)
{len=(lst+1-frst)/2;
i=0;
while (i<len && tr(frst+i,4,0)==tr(frst+len+i,4,0)) i++; // 0 1
if (i == len) return palindromic;
i=0;
while (i<len && tr(frst+i,8,0)==tr(frst+len+i,8,0)) i++; // 0 2
if (i == len) return palindromic;
if (!palindromic)
{i=0;
while (i<len && tr(frst+i,4,2)==tr(frst+len+i,4,2)) i++; // 0 1r
if (i == len) return 0;
i=0;
while (i<len && tr(frst+i,4,1)==tr(frst+len+i,4,1)) i++; // 0r 1
if (i == len) return 0;}
}
for (frst=0; frst<n; frst++) for (lst=2*n+((1+frst)&1); lst<3*n; lst+=2)
{len=(lst+1-frst)/2;
i=0;
while (i<len && tr(frst+i,4,0)==tr(frst+len+i,4,0)) i++; // 0 1 0
if (i == len) return palindromic;
i=0;
while (i<len && tr(frst+i,8,0)==tr(frst+len+i,8,0)) i++; // 0 2 0
if (i == len) return palindromic;
i=0;
while (i<len && tr(frst+i,36,0)==tr(frst+len+i,36,0)) i++; // 0 1 2
if (i == len) return palindromic;
i=0;
while (i<len && tr(frst+i,24,0)==tr(frst+len+i,24,0)) i++; // 0 2 1
if (i == len) return palindromic;
if (!palindromic)
{i=0;
while (i<len && tr(frst+i,4,4)==tr(frst+len+i,4,4)) i++; // 0 1 0r
if (i == len) return 0;
i=0;
while (i<len && tr(frst+i,8,4)==tr(frst+len+i,8,4)) i++; // 0 2 0r
if (i == len) return 0;
i=0;
while (i<len && tr(frst+i,4,2)==tr(frst+len+i,4,2)) i++; // 0 1r 0
if (i == len) return 0;
i=0;
while (i<len && tr(frst+i,8,2)==tr(frst+len+i,8,2)) i++; // 0 2r 0
if (i == len) return 0;
i=0;
while (i<len && tr(frst+i,36,4)==tr(frst+len+i,36,4)) i++; // 0 1 2r
if (i == len) return 0;
i=0;
while (i<len && tr(frst+i,36,2)==tr(frst+len+i,36,2)) i++; // 0 1r 2
if (i == len) return 0;
i=0;
while (i<len && tr(frst+i,24,4)==tr(frst+len+i,24,4)) i++; // 0 2 1r
if (i == len) return 0;
i=0;
while (i<len && tr(frst+i,24,2)==tr(frst+len+i,24,2)) i++; // 0 2r 1
if (i == len) return 0;
i=0;
while (i<len && tr(frst+i,36,1)==tr(frst+len+i,36,1)) i++; // 0r 1 2
if (i == len) return 0;
i=0;
while (i<len && tr(frst+i,24,1)==tr(frst+len+i,24,1)) i++; // 0r 2 1
if (i == len) return 0;}
}
return 2+palindromic;}
|
the_stack_data/41644.c | /**
*
* File Name: libkern/string/strcmp.c
* Title : Kernel Library
* Project : PINE64 ROCK64 Bare-Metal
* Author : Copyright (C) 2021 Johannes Krottmayer <[email protected]>
* Created : 2021-01-25
* Modified :
* Revised :
* Version : 0.1.0.0
* License : ISC (see LICENSE.txt)
*
* NOTE: This code is currently below version 1.0, and therefore is considered
* to be lacking in some functionality or documentation, or may not be fully
* tested. Nonetheless, you can expect most functions to work.
*
*/
int strcmp(const char *s1, const char *s2)
{
int i = 0;
while (s1[i] != '\0') {
if (s1[i] != s2[i])
return 1;
i++;
}
return 0;
}
|
the_stack_data/187644363.c | /* APPLE LOCAL file 6218859 */
/* { dg-options "-O2 -Werror=uninitialized" } */
int main(int argc, char *argv[]) {
int a;
return a; /* { dg-error "is used uninitialized in this function" } */
}
|
the_stack_data/769045.c | /*El paso por referencia se hace utilizando apuntadores. Se envía la dirección de memoria de la variable, por lo tanto los cambios que haga la función si afectan el valor de la variable*/
#include <stdio.h>
void sumar_referencia(int *numero); /* prototipo de la función */
int main(void)
{
int numero = 57; /* definimos numero con valor de 57*/
sumar_referencia(&numero); /* enviamos numero a la función */
printf("\nValor de numero dentro de main() es: %d ", numero);
/* podemos notar que el valor de numero se modifica
* y que ahora dentro de main() también se ha modificado
* aunque la función no haya retornado ningún valor.
*/
return 0;
}
void sumar_referencia(int *numero)
{
*numero += 1; /* le sumamos 1 al numero */
printf("\nValor de numero dentro sumar_referencia() es: %d", *numero);
return;
}
|
the_stack_data/86444.c | #include <stdio.h>
#include <string.h>
#define SZ_RECORD 132
#define NO_CMD 0
#define ADD_CMD 1
#define DEL_CMD 2
#define FIND_CMD 3
#define QUIT_CMD 4
/* TDB -- A trivial database to demonstrate linked lists in C */
struct dbase_rec {
struct dbase_rec *next;
char *record;
};
typedef struct dbase_rec dbase;
void drop_record (char *rec);
int cmp_record (char *key, char *rec);
dbase *read_dbase (char *fname);
char *find_dbase (dbase *db, char *key);
int del_dbase (dbase **db, char *key);
int add_dbase (dbase **db, char *rec);
void write_dbase (dbase *db, char *fname);
void drop_dbase (dbase **db);
int parse_command (char *command, char *buffer);
int main (int argc, char **argv);
char *
new_record (char *buffer) {
char *rec = (char *) malloc (SZ_RECORD+1);
strcpy (rec, buffer);
return rec;
}
void
drop_record (char *rec) {
free (rec);
}
int
cmp_record (char *key, char *rec) {
for ( ;*key && *rec && *rec == *key; rec ++, key ++)
;
if ((*key == ' ' || *key == '\0') && (*rec == ' ' || *rec == '\0'))
return 0;
return *key - *rec;
}
dbase *
read_dbase (char *fname) {
char *nl = NULL;
dbase *db = NULL;
dbase *row = NULL;
dbase *ptr = NULL;
char buffer[SZ_RECORD+1];
FILE *fd = fopen (fname, "r");
if (fd == NULL)
return db;
while (fgets (buffer, SZ_RECORD, fd)) {
nl = strchr (buffer, '\n');
if (nl == NULL) {
printf ("Database record truncated:\n%s\n", buffer);
} else {
*nl = '\0';
}
row = (dbase *) malloc (sizeof (dbase));
row->next = NULL;
row->record = new_record (buffer);
if (db == NULL) {
db = row;
} else {
for (ptr = db; ptr->next != NULL; ptr = ptr->next)
;
ptr->next = row;
}
}
fclose (fd);
return db;
}
char *
find_dbase (dbase *db, char *key) {
dbase *ptr = NULL;
for (ptr = db; ptr != NULL; ptr = ptr->next) {
if (cmp_record (key, ptr->record) == 0)
return ptr->record;
}
return NULL;
}
int
del_dbase (dbase **db, char *key) {
dbase *ptr = NULL;
dbase *prevptr = NULL;
for (ptr = *db; ptr != NULL; ptr = ptr->next) {
if (cmp_record (key, ptr->record) == 0)
break;
prevptr = ptr;
}
if (ptr == NULL)
return 0;
if (prevptr != NULL) {
prevptr->next = ptr->next;
} else {
*db = ptr->next;
}
drop_record (ptr->record);
free (ptr);
return -1;
}
int
add_dbase (dbase **db, char *rec) {
int cmp;
int status;
dbase *ptr = NULL;
dbase *row = NULL;
dbase *prevptr = NULL;
dbase *nextptr = NULL;
row = (dbase *) malloc (sizeof (dbase));
row->next = NULL;
row->record = new_record (rec);
cmp = 1;
for (ptr = *db; ptr != NULL; ptr = ptr->next) {
cmp = cmp_record (rec, ptr->record);
if (cmp <= 0)
break;
prevptr = ptr;
}
if (cmp != 0) {
nextptr = ptr;
status = 1;
} else {
nextptr = ptr->next;
status = 0;
drop_record (ptr->record);
free (ptr);
}
row->next = nextptr;
if (prevptr != NULL) {
prevptr->next = row;
} else {
*db = row;
}
return status;
}
void
write_dbase (dbase *db, char *fname) {
dbase *ptr = NULL;
FILE *fd = fopen (fname, "w");
for (ptr = db; ptr != NULL; ptr = ptr->next)
fprintf (fd, "%s\n", ptr->record);
fclose (fd);
}
void
drop_dbase (dbase **db) {
dbase *ptr = NULL;
dbase *nextptr = NULL;
for (ptr = *db; ptr != NULL; ptr = nextptr) {
nextptr = ptr->next;
drop_record (ptr->record);
free (ptr);
}
*db = NULL;
}
int
parse_command (char *command, char *buffer) {
int ic;
int val;
char *nl;
char name[SZ_RECORD+1];
nl = strchr (command, '\n');
if (nl == NULL) {
printf ("Command truncated:\n%s\n", command);
return (NO_CMD);
} else {
*nl = '\0';
}
for (ic = 0; command[ic] != ' ' && command[ic] != '\0'; ic++)
name[ic] = command[ic];
name[ic] = '\0';
if (command[ic] == ' ')
ic = ic + 1;
strcpy (buffer, &command[ic]);
if (strcmp (name, "add") == 0) {
val = ADD_CMD;
} else if (strcmp (name, "del") == 0) {
val = DEL_CMD;
} else if (strcmp (name, "find") == 0) {
val = FIND_CMD;
} else if (strcmp (name, "quit") == 0) {
val = QUIT_CMD;
} else {
val = NO_CMD;
}
return val;
}
int
main (int argc, char **argv) {
char *fname = "phonelist.dat";
char command[SZ_RECORD+1];
char buffer[SZ_RECORD+1];
int more, val, num;
dbase *db = NULL;
char *rec = NULL;
if (argc > 1)
fname = argv[1];
db = read_dbase (fname);
for (more = 1; more; ) {
if (fgets (command, SZ_RECORD, stdin)) {
val = parse_command (command, buffer);
} else {
val = QUIT_CMD;
}
switch (val) {
case NO_CMD:
printf ("Unrecognized command:\n%s\n", command);
break;
case ADD_CMD:
num = add_dbase (&db, buffer);
if (num == 0) {
printf ("One row replaced\n");
} else {
printf ("One row added\n");
}
break;
case DEL_CMD:
num = del_dbase (&db, buffer);
if (num == 0) {
printf ("Row not found\n");
} else {
printf ("One row deleted\n");
}
break;
case FIND_CMD:
rec = find_dbase (db, buffer);
if (rec == NULL) {
printf ("Row not found\n");
} else {
printf ("%s\n", rec);
}
break;
case QUIT_CMD:
write_dbase (db, fname);
drop_dbase (&db);
more = 0;
break;
}
}
return 0;
}
|
the_stack_data/9513378.c | /*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#if defined(DEVICE_MODEL_ENABLED)
#include "iot_export_linkkit.h"
#include "sdk-impl_internal.h"
#include "iotx_system.h"
#include "iotx_utils.h"
#include "iotx_dm.h"
#define IMPL_LINKKIT_MALLOC(size) LITE_malloc(size, MEM_MAGIC, "impl.linkkit")
#define IMPL_LINKKIT_FREE(ptr) LITE_free(ptr)
#define IOTX_LINKKIT_KEY_ID "id"
#define IOTX_LINKKIT_KEY_CODE "code"
#define IOTX_LINKKIT_KEY_DEVID "devid"
#define IOTX_LINKKIT_KEY_SERVICEID "serviceid"
#define IOTX_LINKKIT_KEY_PROPERTYID "propertyid"
#define IOTX_LINKKIT_KEY_EVENTID "eventid"
#define IOTX_LINKKIT_KEY_PAYLOAD "payload"
#define IOTX_LINKKIT_KEY_CONFIG_ID "configId"
#define IOTX_LINKKIT_KEY_CONFIG_SIZE "configSize"
#define IOTX_LINKKIT_KEY_GET_TYPE "getType"
#define IOTX_LINKKIT_KEY_SIGN "sign"
#define IOTX_LINKKIT_KEY_SIGN_METHOD "signMethod"
#define IOTX_LINKKIT_KEY_URL "url"
#define IOTX_LINKKIT_KEY_VERSION "version"
#define IOTX_LINKKIT_KEY_UTC "utc"
#define IOTX_LINKKIT_KEY_RRPCID "rrpcid"
#define IOTX_LINKKIT_KEY_CTX "ctx"
#define IOTX_LINKKIT_KEY_TOPO "topo"
#define IOTX_LINKKIT_KEY_PRODUCT_KEY "productKey"
#define IOTX_LINKKIT_KEY_TIME "time"
#define IOTX_LINKKIT_KEY_DATA "data"
#define IOTX_LINKKIT_KEY_MESSAGE "message"
#define IOTX_LINKKIT_SYNC_DEFAULT_TIMEOUT_MS 10000
#define IOTX_LINKKIT_ASYNC_DEFAULT_TIMEOUT_MS 30000
typedef struct {
int msgid;
void *semaphore;
int code;
struct list_head linked_list;
} iotx_linkkit_upstream_sync_callback_node_t;
typedef struct {
void *mutex;
void *upstream_mutex;
int is_opened;
int is_connected;
int cloud_redirect;
struct list_head upstream_sync_callback_list;
} iotx_linkkit_ctx_t;
static iotx_linkkit_ctx_t g_iotx_linkkit_ctx = {0};
static int _awss_reported = 0;
static iotx_linkkit_ctx_t *_iotx_linkkit_get_ctx(void)
{
return &g_iotx_linkkit_ctx;
}
static void _iotx_linkkit_mutex_lock(void)
{
iotx_linkkit_ctx_t *ctx = _iotx_linkkit_get_ctx();
if (ctx->mutex) {
HAL_MutexLock(ctx->mutex);
}
}
static void _iotx_linkkit_mutex_unlock(void)
{
iotx_linkkit_ctx_t *ctx = _iotx_linkkit_get_ctx();
if (ctx->mutex) {
HAL_MutexUnlock(ctx->mutex);
}
}
static int _impl_copy(_IN_ void *input, _IN_ int input_len, _OU_ void **output, _IN_ int output_len)
{
if (input == NULL || output == NULL || *output != NULL) {
return DM_INVALID_PARAMETER;
}
*output = sdk_malloc(output_len);
if (*output == NULL) {
return DM_MEMORY_NOT_ENOUGH;
}
memset(*output, 0, output_len);
memcpy(*output, input, input_len);
return SUCCESS_RETURN;
}
#ifdef DEVICE_MODEL_GATEWAY
static void _iotx_linkkit_upstream_mutex_lock(void)
{
iotx_linkkit_ctx_t *ctx = _iotx_linkkit_get_ctx();
if (ctx->upstream_mutex) {
HAL_MutexLock(ctx->upstream_mutex);
}
}
static void _iotx_linkkit_upstream_mutex_unlock(void)
{
iotx_linkkit_ctx_t *ctx = _iotx_linkkit_get_ctx();
if (ctx->upstream_mutex) {
HAL_MutexUnlock(ctx->upstream_mutex);
}
}
static int _iotx_linkkit_upstream_sync_callback_list_insert(int msgid, void *semaphore,
iotx_linkkit_upstream_sync_callback_node_t **node)
{
iotx_linkkit_ctx_t *ctx = _iotx_linkkit_get_ctx();
iotx_linkkit_upstream_sync_callback_node_t *search_node = NULL;
list_for_each_entry(search_node, &ctx->upstream_sync_callback_list, linked_list,
iotx_linkkit_upstream_sync_callback_node_t) {
if (search_node->msgid == msgid) {
sdk_debug("Message Already Exist: %d", msgid);
return FAIL_RETURN;
}
}
search_node = IMPL_LINKKIT_MALLOC(sizeof(iotx_linkkit_upstream_sync_callback_node_t));
if (search_node == NULL) {
sdk_debug("malloc error");
return FAIL_RETURN;
}
memset(search_node, 0, sizeof(iotx_linkkit_upstream_sync_callback_node_t));
search_node->msgid = msgid;
search_node->semaphore = semaphore;
INIT_LIST_HEAD(&search_node->linked_list);
list_add(&search_node->linked_list, &ctx->upstream_sync_callback_list);
sdk_debug("New Message, msgid: %d", msgid);
*node = search_node;
return SUCCESS_RETURN;
}
static int _iotx_linkkit_upstream_sync_callback_list_remove(int msgid)
{
iotx_linkkit_ctx_t *ctx = _iotx_linkkit_get_ctx();
iotx_linkkit_upstream_sync_callback_node_t *search_node = NULL;
list_for_each_entry(search_node, &ctx->upstream_sync_callback_list, linked_list,
iotx_linkkit_upstream_sync_callback_node_t) {
if (search_node->msgid == msgid) {
sdk_debug("Message Found: %d, Delete It", msgid);
HAL_SemaphoreDestroy(search_node->semaphore);
list_del(&search_node->linked_list);
IMPL_LINKKIT_FREE(search_node);
return SUCCESS_RETURN;
}
}
return FAIL_RETURN;
}
static int _iotx_linkkit_upstream_sync_callback_list_search(int msgid,
iotx_linkkit_upstream_sync_callback_node_t **node)
{
iotx_linkkit_ctx_t *ctx = _iotx_linkkit_get_ctx();
iotx_linkkit_upstream_sync_callback_node_t *search_node = NULL;
if (node == NULL || *node != NULL) {
sdk_debug("invalid param");
return FAIL_RETURN;
}
list_for_each_entry(search_node, &ctx->upstream_sync_callback_list, linked_list,
iotx_linkkit_upstream_sync_callback_node_t) {
if (search_node->msgid == msgid) {
sdk_debug("Sync Message Found: %d", msgid);
*node = search_node;
return SUCCESS_RETURN;
}
}
return FAIL_RETURN;
}
static void _iotx_linkkit_upstream_sync_callback_list_destroy(void)
{
iotx_linkkit_ctx_t *ctx = _iotx_linkkit_get_ctx();
iotx_linkkit_upstream_sync_callback_node_t *search_node = NULL, *next_node = NULL;
list_for_each_entry_safe(search_node, next_node, &ctx->upstream_sync_callback_list, linked_list,
iotx_linkkit_upstream_sync_callback_node_t) {
list_del(&search_node->linked_list);
HAL_SemaphoreDestroy(search_node->semaphore);
IMPL_LINKKIT_FREE(search_node);
}
}
#ifdef DEVICE_MODEL_GATEWAY
static int subdev_cloud_response_code = 200;
#endif
static void _iotx_linkkit_upstream_callback_remove(int msgid, int code)
{
int res = 0;
iotx_linkkit_upstream_sync_callback_node_t *sync_node = NULL;
res = _iotx_linkkit_upstream_sync_callback_list_search(msgid, &sync_node);
if (res == SUCCESS_RETURN) {
sync_node->code = (code == IOTX_DM_ERR_CODE_SUCCESS) ? (SUCCESS_RETURN) : (FAIL_RETURN);
sdk_debug("Sync Message %d Result: %d", msgid, sync_node->code);
HAL_SemaphorePost(sync_node->semaphore);
}
}
#endif
#ifdef LOG_REPORT_TO_CLOUD
int report_sample = 0;
#endif
#ifdef ALCS_ENABLED
extern void dm_server_free_context(_IN_ void *ctx);
#endif
static void _iotx_linkkit_event_callback(iotx_dm_event_types_t type, char *payload)
{
int res = 0;
void *callback;
#ifdef LOG_REPORT_TO_CLOUD
lite_cjson_t msg_id;
#endif
lite_cjson_t lite, lite_item_id, lite_item_devid, lite_item_serviceid, lite_item_payload, lite_item_ctx;
lite_cjson_t lite_item_code, lite_item_eventid, lite_item_utc, lite_item_rrpcid, lite_item_topo;
lite_cjson_t lite_item_pk, lite_item_time;
lite_cjson_t lite_item_version, lite_item_configid, lite_item_configsize, lite_item_gettype, lite_item_sign,
lite_item_signmethod, lite_item_url, lite_item_data, lite_item_message;
sdk_info("Receive Message Type: %d", type);
if (payload) {
sdk_info("Receive Message: %s", payload);
res = dm_utils_json_parse(payload, strlen(payload), cJSON_Invalid, &lite);
if (res != SUCCESS_RETURN) {
return;
}
#ifdef LOG_REPORT_TO_CLOUD
dm_utils_json_object_item(&lite, "msgid", 5, cJSON_Invalid, &msg_id);
#endif
dm_utils_json_object_item(&lite, IOTX_LINKKIT_KEY_ID, strlen(IOTX_LINKKIT_KEY_ID), cJSON_Invalid, &lite_item_id);
dm_utils_json_object_item(&lite, IOTX_LINKKIT_KEY_DEVID, strlen(IOTX_LINKKIT_KEY_DEVID), cJSON_Invalid,
&lite_item_devid);
dm_utils_json_object_item(&lite, IOTX_LINKKIT_KEY_SERVICEID, strlen(IOTX_LINKKIT_KEY_SERVICEID), cJSON_Invalid,
&lite_item_serviceid);
dm_utils_json_object_item(&lite, IOTX_LINKKIT_KEY_PAYLOAD, strlen(IOTX_LINKKIT_KEY_PAYLOAD), cJSON_Invalid,
&lite_item_payload);
dm_utils_json_object_item(&lite, IOTX_LINKKIT_KEY_CTX, strlen(IOTX_LINKKIT_KEY_CTX), cJSON_Invalid, &lite_item_ctx);
dm_utils_json_object_item(&lite, IOTX_LINKKIT_KEY_CODE, strlen(IOTX_LINKKIT_KEY_CODE), cJSON_Invalid, &lite_item_code);
dm_utils_json_object_item(&lite, IOTX_LINKKIT_KEY_EVENTID, strlen(IOTX_LINKKIT_KEY_EVENTID), cJSON_Invalid,
&lite_item_eventid);
dm_utils_json_object_item(&lite, IOTX_LINKKIT_KEY_UTC, strlen(IOTX_LINKKIT_KEY_UTC), cJSON_Invalid, &lite_item_utc);
dm_utils_json_object_item(&lite, IOTX_LINKKIT_KEY_RRPCID, strlen(IOTX_LINKKIT_KEY_RRPCID), cJSON_Invalid,
&lite_item_rrpcid);
dm_utils_json_object_item(&lite, IOTX_LINKKIT_KEY_TOPO, strlen(IOTX_LINKKIT_KEY_TOPO), cJSON_Invalid,
&lite_item_topo);
dm_utils_json_object_item(&lite, IOTX_LINKKIT_KEY_PRODUCT_KEY, strlen(IOTX_LINKKIT_KEY_PRODUCT_KEY), cJSON_Invalid,
&lite_item_pk);
dm_utils_json_object_item(&lite, IOTX_LINKKIT_KEY_TIME, strlen(IOTX_LINKKIT_KEY_TIME), cJSON_Invalid,
&lite_item_time);
dm_utils_json_object_item(&lite, IOTX_LINKKIT_KEY_VERSION, strlen(IOTX_LINKKIT_KEY_VERSION), cJSON_Invalid,
&lite_item_version);
dm_utils_json_object_item(&lite, IOTX_LINKKIT_KEY_CONFIG_ID, strlen(IOTX_LINKKIT_KEY_CONFIG_ID), cJSON_Invalid,
&lite_item_configid);
dm_utils_json_object_item(&lite, IOTX_LINKKIT_KEY_CONFIG_SIZE, strlen(IOTX_LINKKIT_KEY_CONFIG_SIZE), cJSON_Invalid,
&lite_item_configsize);
dm_utils_json_object_item(&lite, IOTX_LINKKIT_KEY_GET_TYPE, strlen(IOTX_LINKKIT_KEY_GET_TYPE), cJSON_Invalid,
&lite_item_gettype);
dm_utils_json_object_item(&lite, IOTX_LINKKIT_KEY_SIGN, strlen(IOTX_LINKKIT_KEY_SIGN), cJSON_Invalid,
&lite_item_sign);
dm_utils_json_object_item(&lite, IOTX_LINKKIT_KEY_SIGN_METHOD, strlen(IOTX_LINKKIT_KEY_SIGN_METHOD), cJSON_Invalid,
&lite_item_signmethod);
dm_utils_json_object_item(&lite, IOTX_LINKKIT_KEY_URL, strlen(IOTX_LINKKIT_KEY_URL), cJSON_Invalid,
&lite_item_url);
dm_utils_json_object_item(&lite, IOTX_LINKKIT_KEY_DATA, strlen(IOTX_LINKKIT_KEY_DATA), cJSON_Invalid,
&lite_item_data);
dm_utils_json_object_item(&lite, IOTX_LINKKIT_KEY_MESSAGE, strlen(IOTX_LINKKIT_KEY_MESSAGE), cJSON_Invalid,
&lite_item_message);
}
switch (type) {
case IOTX_DM_EVENT_CLOUD_CONNECTED: {
#ifdef DEV_BIND_ENABLED
if (_awss_reported == 0)
{
awss_report_cloud();
_awss_reported = 1;
}
#endif
callback = iotx_event_callback(ITE_CONNECT_SUCC);
if (callback) {
((int (*)(void))callback)();
}
iotx_event_post(IOTX_CONN_CLOUD_SUC);
}
break;
case IOTX_DM_EVENT_CLOUD_DISCONNECT: {
callback = iotx_event_callback(ITE_DISCONNECTED);
if (callback) {
((int (*)(void))callback)();
}
iotx_event_post(IOTX_CONN_CLOUD_FAIL);
}
break;
case IOTX_DM_EVENT_INITIALIZED: {
if (payload == NULL || lite_item_devid.type != cJSON_Number) {
return;
}
sdk_debug("Current Devid: %d", lite_item_devid.value_int);
callback = iotx_event_callback(ITE_INITIALIZE_COMPLETED);
if (callback) {
((int (*)(const int))callback)(lite_item_devid.value_int);
}
}
break;
case IOTX_DM_EVENT_MODEL_DOWN_RAW: {
int raw_data_len = 0;
unsigned char *raw_data = NULL;
if (payload == NULL || lite_item_devid.type != cJSON_Number || lite_item_payload.type != cJSON_String) {
return;
}
sdk_debug("Current Devid: %d", lite_item_devid.value_int);
sdk_debug("Current Raw Data: %.*s", lite_item_payload.value_length, lite_item_payload.value);
raw_data_len = lite_item_payload.value_length / 2;
raw_data = IMPL_LINKKIT_MALLOC(raw_data_len);
if (raw_data == NULL) {
sdk_err("No Enough Memory");
return;
}
LITE_hexstr_convert(lite_item_payload.value, lite_item_payload.value_length, raw_data, raw_data_len);
HEXDUMP_DEBUG(raw_data, raw_data_len);
callback = iotx_event_callback(ITE_RAWDATA_ARRIVED);
if (callback) {
((int (*)(const int, const unsigned char *, const int))callback)(lite_item_devid.value_int, raw_data, raw_data_len);
}
IMPL_LINKKIT_FREE(raw_data);
}
break;
#ifdef LINK_VISUAL_ENABLE
case IOTX_DM_EVENT_MODEL_LINK_VISUAL: {
if (payload == NULL || lite_item_devid.type != cJSON_Number || lite_item_payload.type != cJSON_Object ||
lite_item_serviceid.type != cJSON_String) {
return;
}
sdk_debug("Current Id: %.*s", lite_item_id.value_length, lite_item_id.value);
sdk_debug("Current ServiceID: %.*s", lite_item_serviceid.value_length, lite_item_serviceid.value);
sdk_debug("Current Devid: %d", lite_item_devid.value_int);
sdk_debug("Current Raw Data: %.*s", lite_item_payload.value_length, lite_item_payload.value);
unsigned char *request = IMPL_LINKKIT_MALLOC(lite_item_payload.value_length + 1);
if (request == NULL) {
sdk_err("Not Enough Memory");
return;
}
memset(request, 0, lite_item_payload.value_length + 1);
memcpy(request, lite_item_payload.value, lite_item_payload.value_length);
callback = iotx_event_callback(ITE_LINK_VISUAL);
if (callback) {
((int (*)(const int, const char *, const int, const unsigned char *, const int))callback)(lite_item_devid.value_int, lite_item_serviceid.value, lite_item_serviceid.value_length,request, lite_item_payload.value_length);
}
IMPL_LINKKIT_FREE(request);
}
break;
#endif
case IOTX_DM_EVENT_MODEL_UP_RAW_REPLY: {
int raw_data_len = 0;
unsigned char *raw_data = NULL;
if (payload == NULL || lite_item_devid.type != cJSON_Number || lite_item_payload.type != cJSON_String) {
return;
}
sdk_debug("Current Devid: %d", lite_item_devid.value_int);
sdk_debug("Current Raw Data: %.*s", lite_item_payload.value_length, lite_item_payload.value);
raw_data_len = lite_item_payload.value_length / 2;
raw_data = IMPL_LINKKIT_MALLOC(raw_data_len);
if (raw_data == NULL) {
sdk_err("No Enough Memory");
return;
}
memset(raw_data, 0, raw_data_len);
LITE_hexstr_convert(lite_item_payload.value, lite_item_payload.value_length, raw_data, raw_data_len);
HEXDUMP_DEBUG(raw_data, raw_data_len);
callback = iotx_event_callback(ITE_RAWDATA_ARRIVED);
if (callback) {
((int (*)(const int, const unsigned char *, const int))callback)(lite_item_devid.value_int, raw_data, raw_data_len);
}
IMPL_LINKKIT_FREE(raw_data);
}
break;
#if !defined(DEVICE_MODEL_RAWDATA_SOLO)
case IOTX_DM_EVENT_THING_SERVICE_REQUEST: {
int response_len = 0;
char *request = NULL, *response = NULL;
uintptr_t property_get_ctx_num = 0;
void *property_get_ctx = NULL;
if (payload == NULL || lite_item_id.type != cJSON_String || lite_item_devid.type != cJSON_Number ||
lite_item_serviceid.type != cJSON_String || lite_item_payload.type != cJSON_Object) {
return;
}
sdk_err("Current Id: %.*s", lite_item_id.value_length, lite_item_id.value);
sdk_debug("Current Devid: %d", lite_item_devid.value_int);
sdk_debug("Current ServiceID: %.*s", lite_item_serviceid.value_length, lite_item_serviceid.value);
sdk_debug("Current Payload: %.*s", lite_item_payload.value_length, lite_item_payload.value);
sdk_debug("Current Ctx: %.*s", lite_item_ctx.value_length, lite_item_ctx.value);
LITE_hexstr_convert(lite_item_ctx.value, lite_item_ctx.value_length, (unsigned char *)&property_get_ctx_num,
sizeof(uintptr_t));
property_get_ctx = (void *)property_get_ctx_num;
// sdk_debug("property_get_ctx_num: %0x016llX", property_get_ctx_num);
// sdk_debug("property_get_ctx: %p", property_get_ctx);
request = IMPL_LINKKIT_MALLOC(lite_item_payload.value_length + 1);
if (request == NULL) {
sdk_err("Not Enough Memory");
return;
}
memset(request, 0, lite_item_payload.value_length + 1);
memcpy(request, lite_item_payload.value, lite_item_payload.value_length);
#ifndef LINK_VISUAL_ENABLE
callback = iotx_event_callback(ITE_SERVICE_REQUEST);
if (callback) {
res = ((int (*)(const int, const char *, const int, const char *, const int, char **,
int *))callback)(lite_item_devid.value_int, lite_item_serviceid.value,
lite_item_serviceid.value_length, request, lite_item_payload.value_length, &response, &response_len);
if (response != NULL && response_len > 0) {
/* service response exist */
iotx_dm_error_code_t code = (res == 0) ? (IOTX_DM_ERR_CODE_SUCCESS) : (IOTX_DM_ERR_CODE_REQUEST_ERROR);
iotx_dm_send_service_response(lite_item_devid.value_int, lite_item_id.value, lite_item_id.value_length, code,
lite_item_serviceid.value,
lite_item_serviceid.value_length,
response, response_len, property_get_ctx);
HAL_Free(response);
}
}
#else
callback = iotx_event_callback(ITE_SERVICE_REQUST);
if (callback) {
res = ((int (*)(const int, const char *, const int, const char *, const int, const char *, const int, char **,
int *))callback)(lite_item_devid.value_int, lite_item_id.value, lite_item_id.value_length, lite_item_serviceid.value,
lite_item_serviceid.value_length, request, lite_item_payload.value_length, &response, &response_len);
if (response != NULL && response_len > 0) {
iotx_dm_error_code_t code = (res == 0) ? (IOTX_DM_ERR_CODE_SUCCESS) : (IOTX_DM_ERR_CODE_REQUEST_ERROR);
iotx_dm_send_service_response(lite_item_devid.value_int, lite_item_id.value, lite_item_id.value_length, code,
lite_item_serviceid.value,
lite_item_serviceid.value_length,
response, response_len);
IMPL_LINKKIT_FREE(response);
}
}
#endif
#ifdef ALCS_ENABLED
if (property_get_ctx) {
dm_server_free_context(property_get_ctx);
}
#endif
IMPL_LINKKIT_FREE(request);
}
break;
case IOTX_DM_EVENT_THING_EVENT_NOTIFY: {
char is_need_notify_user = 1;
char *property_payload = NULL;
lite_cjson_t lite_identifier, lite_iden_val;
if (payload == NULL || lite_item_devid.type != cJSON_Number || lite_item_payload.type != cJSON_Object) {
return;
}
sdk_debug("Current Devid: %d", lite_item_devid.value_int);
sdk_debug("Current Payload: %.*s", lite_item_payload.value_length, lite_item_payload.value);
property_payload = IMPL_LINKKIT_MALLOC(lite_item_payload.value_length + 1);
if (property_payload == NULL) {
sdk_err("No Enough Memory");
return;
}
dm_utils_json_object_item(&lite_item_payload, "identifier", strlen("identifier"), cJSON_Invalid,
&lite_identifier);
dm_utils_json_object_item(&lite_item_payload, "value", strlen("value"), cJSON_Invalid,
&lite_iden_val);
#ifdef LOG_REPORT_TO_CLOUD
if (SUCCESS_RETURN == check_target_msg(msg_id.value, msg_id.value_length)) {
report_sample = 1;
send_permance_info(msg_id.value, msg_id.value_length, "3", 1);
}
#endif
memset(property_payload, 0, lite_item_payload.value_length + 1);
memcpy(property_payload, lite_item_payload.value, lite_item_payload.value_length);
#ifdef ALCS_GROUP_COMM_ENABLE
#ifdef DM_UNIFIED_SERVICE_POST
if ( NULL != strstr(property_payload, "_LivingLink.alcs.localgroup") ){
iotx_alcs_localgroup_rsp(property_payload, lite_item_payload.value, 2);
IMPL_LINKKIT_FREE(property_payload);
return;
}
#endif
#endif
#if defined(AWSS_BATCH_DEVAP_ENABLE) && defined(AWSS_SUPPORT_ZEROCONFIG) && !defined(AWSS_DISABLE_REGISTRAR)
// Find "awss.modeswitch" identifier and do awss mode switch or not.
//sdk_debug("identifier: %.*s", lite_identifier.value_length, lite_identifier.value);
if ( (lite_identifier.type == cJSON_String)
&& !strncmp(lite_identifier.value, "awss.modeswitch", strlen("awss.modeswitch"))
&& lite_iden_val.type == cJSON_Object ) {
lite_cjson_t lite_awss_mode, lite_mode_pk;
uint8_t tomode = 0xFF;
uint8_t pk_found = 0;
//sdk_debug("awss.modeswitch found, value(%.*s)", lite_iden_val.value_length, lite_iden_val.value);
dm_utils_json_object_item(&lite_iden_val, "mode", strlen("mode"), cJSON_Invalid,
&lite_awss_mode);
dm_utils_json_object_item(&lite_iden_val, "productKey", strlen("productKey"), cJSON_Invalid,
&lite_mode_pk);
// Parse switch mode and product Key from awss.modeswitch payload
if (lite_awss_mode.type == cJSON_String) {
if (!strncmp(lite_awss_mode.value, "0", strlen("0"))) {
// tomode: 0 - switch to zero config
tomode = 0;
sdk_debug("mode found(%d))", tomode);
} else {
sdk_err("awss.modeswitch mode not support");
// invalid mode switch, should be ignored
tomode = 0xFF;
}
}
if ( (lite_mode_pk.type == cJSON_String) && (lite_mode_pk.value_length > 0) ) {
pk_found = 1;
sdk_debug("mode pk found");
}
// Do awss mode switch action based on command parsed from cloud
if (tomode != 0xFF) {
extern void registrar_switchmode_start(char *p_productkey, int pk_len, uint8_t awss_mode);
registrar_switchmode_start(pk_found ? lite_mode_pk.value : NULL, lite_mode_pk.value_length, tomode);
}
}
#endif
#ifdef DEVICE_MODEL_GATEWAY //Handle subdev connect async
if (!strncmp(lite_identifier.value, SUBDEV_CONNECT_IDENTIFIER, strlen(SUBDEV_CONNECT_IDENTIFIER)))
{
int mesg_id = 0, res = SUCCESS_RETURN;
char *device_list = NULL;
lite_cjson_t lite_DeviceList;
lite_cjson_t lite_msg_id;
is_need_notify_user = 0;
sdk_info("recv subdev async mesg");
dm_utils_json_object_item(&lite_iden_val, "DeviceList", strlen("DeviceList"), cJSON_Array,
&lite_DeviceList);
dm_utils_json_object_item(&lite_iden_val, "requestId", strlen("requestId"), cJSON_Number,
&lite_msg_id);
if (!lite_cjson_is_array(&lite_DeviceList) || !lite_cjson_is_number(&lite_msg_id))
{
sdk_err("content error");
IMPL_LINKKIT_FREE(property_payload);
return;
}
device_list = IMPL_LINKKIT_MALLOC(lite_DeviceList.value_length + 1);
if (device_list == NULL)
{
sdk_err("No mem");
IMPL_LINKKIT_FREE(property_payload);
return;
}
mesg_id = lite_msg_id.value_int;
memset(device_list, 0, lite_DeviceList.value_length + 1);
memcpy(device_list, lite_DeviceList.value, lite_DeviceList.value_length);
res = iotx_dm_subdev_connect_reply(lite_item_id.value_int, device_list, lite_DeviceList.value_length);
IMPL_LINKKIT_FREE(device_list);
if (res != SUCCESS_RETURN)
{
subdev_cloud_response_code = 400; //just let subdev connect fail
}
else
{
subdev_cloud_response_code = 200;
}
_iotx_linkkit_upstream_mutex_lock();
_iotx_linkkit_upstream_callback_remove(mesg_id, subdev_cloud_response_code);
_iotx_linkkit_upstream_mutex_unlock();
}
#endif
if (!strncmp(lite_identifier.value, "_LivingLink.thing.reset.reply", strlen("_LivingLink.thing.reset.reply")))
{
sdk_info("got cloud reset done");
awss_handle_reset_cloud_reply();
}
if (is_need_notify_user == 1)
{
callback = iotx_event_callback(ITE_EVENT_NOTIFY);
if (callback)
{
((int (*)(const int, const char *, const int))callback)(lite_item_devid.value_int, property_payload,
lite_item_payload.value_length);
}
}
#ifdef LOG_REPORT_TO_CLOUD
if (1 == report_sample) {
send_permance_info(NULL, 0, "5", 2);
report_sample = 0;
}
#endif
IMPL_LINKKIT_FREE(property_payload);
}
break;
case IOTX_DM_EVENT_PROPERTY_SET: {
char *property_payload = NULL;
if (payload == NULL || lite_item_devid.type != cJSON_Number || lite_item_payload.type != cJSON_Object) {
return;
}
sdk_debug("Current Devid: %d", lite_item_devid.value_int);
sdk_debug("Current Payload: %.*s", lite_item_payload.value_length, lite_item_payload.value);
property_payload = IMPL_LINKKIT_MALLOC(lite_item_payload.value_length + 1);
if (property_payload == NULL) {
sdk_err("No Enough Memory");
return;
}
#ifdef LOG_REPORT_TO_CLOUD
if (SUCCESS_RETURN == check_target_msg(msg_id.value, msg_id.value_length)) {
report_sample = 1;
send_permance_info(msg_id.value, msg_id.value_length, "3", 1);
}
#endif
memset(property_payload, 0, lite_item_payload.value_length + 1);
memcpy(property_payload, lite_item_payload.value, lite_item_payload.value_length);
callback = iotx_event_callback(ITE_PROPERTY_SET);
if (callback) {
((int (*)(const int, const char *, const int))callback)(lite_item_devid.value_int, property_payload,
lite_item_payload.value_length);
}
#ifdef LOG_REPORT_TO_CLOUD
if (1 == report_sample) {
send_permance_info(NULL, 0, "5", 2);
report_sample = 0;
}
#endif
IMPL_LINKKIT_FREE(property_payload);
}
break;
case IOTX_DM_EVENT_PROPERTY_GET: {
int response_len = 0;
char *request = NULL, *response = NULL;
uintptr_t property_get_ctx_num = 0;
void *property_get_ctx = NULL;
if (payload == NULL || lite_item_id.type != cJSON_String || lite_item_devid.type != cJSON_Number ||
lite_item_payload.type != cJSON_Array || lite_item_ctx.type != cJSON_String) {
return;
}
sdk_debug("Current Id: %.*s", lite_item_id.value_length, lite_item_id.value);
sdk_debug("Current Devid: %d", lite_item_devid.value_int);
sdk_debug("Current Payload: %.*s", lite_item_payload.value_length, lite_item_payload.value);
sdk_debug("Current Ctx: %.*s", lite_item_ctx.value_length, lite_item_ctx.value);
LITE_hexstr_convert(lite_item_ctx.value, lite_item_ctx.value_length, (unsigned char *)&property_get_ctx_num,
sizeof(uintptr_t));
property_get_ctx = (void *)property_get_ctx_num;
sdk_debug("property_get_ctx_num: %0x016llX", property_get_ctx_num);
sdk_debug("property_get_ctx: %p", property_get_ctx);
request = IMPL_LINKKIT_MALLOC(lite_item_payload.value_length + 1);
if (request == NULL) {
sdk_err("No Enough Memory");
return;
}
memset(request, 0, lite_item_payload.value_length + 1);
memcpy(request, lite_item_payload.value, lite_item_payload.value_length);
callback = iotx_event_callback(ITE_PROPERTY_GET);
if (callback) {
res = ((int (*)(const int, const char *, const int, char **, int *))callback)(lite_item_devid.value_int, request,
lite_item_payload.value_length, &response, &response_len);
if (response != NULL && response_len > 0) {
/* property get response exist */
iotx_dm_error_code_t code = (res == 0) ? (IOTX_DM_ERR_CODE_SUCCESS) : (IOTX_DM_ERR_CODE_REQUEST_ERROR);
iotx_dm_send_property_get_response(lite_item_devid.value_int, lite_item_id.value, lite_item_id.value_length, code,
response, response_len, property_get_ctx);
HAL_Free(response);
}
}
IMPL_LINKKIT_FREE(request);
}
break;
case IOTX_DM_EVENT_EVENT_PROPERTY_POST_REPLY:
case IOTX_DM_EVENT_DEVICEINFO_UPDATE_REPLY:
case IOTX_DM_EVENT_DEVICEINFO_DELETE_REPLY: {
char *user_payload = NULL;
int user_payload_length = 0;
if (payload == NULL || lite_item_id.type != cJSON_Number || lite_item_code.type != cJSON_Number
|| lite_item_devid.type != cJSON_Number) {
return;
}
sdk_debug("Current Id: %d", lite_item_id.value_int);
sdk_debug("Current Code: %d", lite_item_code.value_int);
sdk_debug("Current Devid: %d", lite_item_devid.value_int);
if (lite_item_payload.type == cJSON_Object && lite_item_payload.value_length > 0) {
user_payload = IMPL_LINKKIT_MALLOC(lite_item_payload.value_length + 1);
if (user_payload == NULL) {
sdk_err("No Enough Memory");
return;
}
memset(user_payload, 0, lite_item_payload.value_length + 1);
memcpy(user_payload, lite_item_payload.value, lite_item_payload.value_length);
user_payload_length = lite_item_payload.value_length;
}
callback = iotx_event_callback(ITE_REPORT_REPLY);
if (callback) {
((int (*)(const int, const int, const int, const char *, const int))callback)(lite_item_devid.value_int,
lite_item_id.value_int, lite_item_code.value_int, user_payload,
user_payload_length);
}
if (user_payload) {
IMPL_LINKKIT_FREE(user_payload);
}
}
break;
case IOTX_DM_EVENT_EVENT_SPECIFIC_POST_REPLY: {
char *user_eventid = NULL;
char *user_payload = NULL;
if (payload == NULL || lite_item_id.type != cJSON_Number || lite_item_code.type != cJSON_Number ||
lite_item_devid.type != cJSON_Number || lite_item_eventid.type != cJSON_String
|| lite_item_payload.type != cJSON_String) {
return;
}
sdk_debug("Current Id: %d", lite_item_id.value_int);
sdk_debug("Current Code: %d", lite_item_code.value_int);
sdk_debug("Current Devid: %d", lite_item_devid.value_int);
sdk_debug("Current EventID: %.*s", lite_item_eventid.value_length, lite_item_eventid.value);
sdk_debug("Current Message: %.*s", lite_item_payload.value_length, lite_item_payload.value);
user_eventid = IMPL_LINKKIT_MALLOC(lite_item_eventid.value_length + 1);
if (user_eventid == NULL) {
sdk_err("Not Enough Memory");
return;
}
memset(user_eventid, 0, lite_item_eventid.value_length + 1);
memcpy(user_eventid, lite_item_eventid.value, lite_item_eventid.value_length);
user_payload = IMPL_LINKKIT_MALLOC(lite_item_payload.value_length + 1);
if (user_payload == NULL) {
sdk_err("Not Enough Memory");
IMPL_LINKKIT_FREE(user_eventid);
return;
}
memset(user_payload, 0, lite_item_payload.value_length + 1);
memcpy(user_payload, lite_item_payload.value, lite_item_payload.value_length);
callback = iotx_event_callback(ITE_TRIGGER_EVENT_REPLY);
if (callback) {
((int (*)(const int, const int, const int, const char *, const int, const char *,
const int))callback)(lite_item_devid.value_int,
lite_item_id.value_int, lite_item_code.value_int,
user_eventid, lite_item_eventid.value_length, user_payload, lite_item_payload.value_length);
}
IMPL_LINKKIT_FREE(user_eventid);
IMPL_LINKKIT_FREE(user_payload);
}
break;
#ifdef DM_UNIFIED_SERVICE_POST
case IOTX_DM_UNIFIED_SERVICE_POST_REPLY:
{
char *user_payload = NULL;
char is_need_callback = 1;
if (payload == NULL || lite_item_id.type != cJSON_Number || lite_item_code.type != cJSON_Number ||
lite_item_devid.type != cJSON_Number || lite_item_payload.type != cJSON_Object)
{
return;
}
sdk_debug("Current Id: %d", lite_item_id.value_int);
sdk_debug("Current Code: %d", lite_item_code.value_int);
sdk_debug("Current Devid: %d", lite_item_devid.value_int);
sdk_debug("Current Message: %.*s", lite_item_payload.value_length, lite_item_payload.value);
user_payload = IMPL_LINKKIT_MALLOC(lite_item_payload.value_length + 1);
if (user_payload == NULL)
{
sdk_err("No mem");
return;
}
memset(user_payload, 0, lite_item_payload.value_length + 1);
memcpy(user_payload, lite_item_payload.value, lite_item_payload.value_length);
if (lite_item_code.value_int == 200)
{
lite_cjson_t lite_identifier;
dm_utils_json_object_item(&lite_item_payload, "identifier", strlen("identifier"), cJSON_String,
&lite_identifier);
#ifdef DEVICE_MODEL_GATEWAY
if ((lite_identifier.type == cJSON_String) &&
!strncmp(lite_identifier.value, SUBDEV_CONNECT_IDENTIFIER, strlen(SUBDEV_CONNECT_IDENTIFIER)))
{
int biz_code = 0;
lite_cjson_t lite_bizCode;
lite_cjson_t lite_serviceResult;
lite_cjson_t lite_DeviceList;
dm_utils_json_object_item(&lite_item_payload, "serviceResult", strlen("serviceResult"), cJSON_Object,
&lite_serviceResult);
dm_utils_json_object_item(&lite_serviceResult, "bizCode", strlen("bizCode"), cJSON_Number, &lite_bizCode);
biz_code = lite_bizCode.value_int;
if (biz_code == SUBDEV_CONNECT_RESPONSE_CODE_CLOUD_NOT_READY)
{
sdk_info("cloud subdev not ready wait async download");
}
else if (biz_code == SUBDEV_CONNECT_RESPONSE_CODE_INVALI_REQUEST ||
biz_code == SUBDEV_CONNECT_RESPONSE_CODE_CLOUD_ERROR ||
biz_code == SUBDEV_CONNECT_RESPONSE_CODE_TOTAL_OVERLIMIT)
{
sdk_err("subdev connect error code:%d", biz_code);
subdev_cloud_response_code = biz_code;
_iotx_linkkit_upstream_mutex_lock();
_iotx_linkkit_upstream_callback_remove(lite_item_id.value_int, 200); //200 for return errcode to user
_iotx_linkkit_upstream_mutex_unlock();
}
else
{
sdk_err("unknow biz_code:%d", biz_code);
dm_utils_json_object_item(&lite_serviceResult, "DeviceList", strlen("DeviceList"), cJSON_Array,
&lite_DeviceList);
char *device_list = IMPL_LINKKIT_MALLOC(lite_DeviceList.value_length + 1);
if (device_list == NULL)
{
sdk_err("No mem");
IMPL_LINKKIT_FREE(user_payload);
return;
}
memset(device_list, 0, lite_DeviceList.value_length + 1);
memcpy(device_list, lite_DeviceList.value, lite_DeviceList.value_length);
iotx_dm_subdev_connect_reply(lite_item_id.value_int, device_list, lite_DeviceList.value_length);
IMPL_LINKKIT_FREE(device_list);
subdev_cloud_response_code = 200;
_iotx_linkkit_upstream_mutex_lock();
_iotx_linkkit_upstream_callback_remove(lite_item_id.value_int, lite_item_code.value_int);
_iotx_linkkit_upstream_mutex_unlock();
}
}
is_need_callback = 0;
#endif
}
#ifdef ALCS_GROUP_COMM_ENABLE
if (NULL != strstr(user_payload, "_LivingLink.alcs.localgroup"))
{
iotx_alcs_localgroup_rsp(user_payload, lite_item_payload.value, 1);
is_need_callback = 0;
}
#endif
if (is_need_callback)
{
callback = iotx_event_callback(ITE_UNIFIED_SERVICE_POST);
if (callback)
{
((int (*)(const int, const int, const int, const char *, const int))callback)(lite_item_devid.value_int,
lite_item_id.value_int, lite_item_code.value_int, user_payload, lite_item_payload.value_length);
}
}
IMPL_LINKKIT_FREE(user_payload);
}
break;
#endif
case IOTX_DM_EVENT_NTP_RESPONSE: {
char *utc_payload = NULL;
if (payload == NULL || lite_item_utc.type != cJSON_String) {
return;
}
sdk_debug("Current UTC: %.*s", lite_item_utc.value_length, lite_item_utc.value);
utc_payload = IMPL_LINKKIT_MALLOC(lite_item_utc.value_length + 1);
if (utc_payload == NULL) {
sdk_err("Not Enough Memory");
return;
}
memset(utc_payload, 0, lite_item_utc.value_length + 1);
memcpy(utc_payload, lite_item_utc.value, lite_item_utc.value_length);
callback = iotx_event_callback(ITE_TIMESTAMP_REPLY);
if (callback) {
((int (*)(const char *))callback)(utc_payload);
}
IMPL_LINKKIT_FREE(utc_payload);
}
break;
case IOTX_DM_EVENT_CLOUD_ERROR: {
char *err_data = NULL;
char *err_detail = NULL;
if (payload == NULL) {
return;
}
if (payload == NULL || lite_item_code.type != cJSON_Number) {
return;
}
err_data = IMPL_LINKKIT_MALLOC(lite_item_data.value_length + 1);
if (err_data == NULL) {
sdk_err("Not Enough Memory");
return;
}
memset(err_data, 0, lite_item_data.value_length + 1);
memcpy(err_data, lite_item_data.value, lite_item_data.value_length);
err_detail = IMPL_LINKKIT_MALLOC(lite_item_message.value_length + 1);
if (err_detail == NULL) {
sdk_err("Not Enough Memory");
IMPL_LINKKIT_FREE(err_data);
return;
}
memset(err_detail, 0, lite_item_message.value_length + 1);
memcpy(err_detail, lite_item_message.value, lite_item_message.value_length);
callback = iotx_event_callback(ITE_CLOUD_ERROR);
if (callback) {
((int (*)(int ,const char *,const char *))callback)(lite_item_code.value_int, err_data, err_detail);
}
IMPL_LINKKIT_FREE(err_data);
IMPL_LINKKIT_FREE(err_detail);
}
break;
case IOTX_DM_EVENT_RRPC_REQUEST: {
int rrpc_response_len = 0;
char *rrpc_request = NULL, *rrpc_response = NULL;
if (payload == NULL || lite_item_id.type != cJSON_String || lite_item_devid.type != cJSON_Number ||
lite_item_serviceid.type != cJSON_String || lite_item_rrpcid.type != cJSON_String
|| lite_item_payload.type != cJSON_Object) {
return;
}
sdk_debug("Current Id: %.*s", lite_item_id.value_length, lite_item_id.value);
sdk_debug("Current Devid: %d", lite_item_devid.value_int);
sdk_debug("Current ServiceID: %.*s", lite_item_serviceid.value_length, lite_item_serviceid.value);
sdk_debug("Current RRPC ID: %.*s", lite_item_rrpcid.value_length, lite_item_rrpcid.value);
sdk_debug("Current Payload: %.*s", lite_item_payload.value_length, lite_item_payload.value);
rrpc_request = IMPL_LINKKIT_MALLOC(lite_item_payload.value_length + 1);
if (rrpc_request == NULL) {
sdk_err("Not Enough Memory");
return;
}
memset(rrpc_request, 0, lite_item_payload.value_length + 1);
memcpy(rrpc_request, lite_item_payload.value, lite_item_payload.value_length);
#ifndef LINK_VISUAL_ENABLE
callback = iotx_event_callback(ITE_SERVICE_REQUEST);
if (callback) {
res = ((int (*)(const int, const char *, const int, const char *, const int, char **,
int *))callback)(lite_item_devid.value_int, lite_item_serviceid.value,
lite_item_serviceid.value_length,
rrpc_request, lite_item_payload.value_length, &rrpc_response, &rrpc_response_len);
if (rrpc_response != NULL && rrpc_response_len > 0) {
iotx_dm_error_code_t code = (res == 0) ? (IOTX_DM_ERR_CODE_SUCCESS) : (IOTX_DM_ERR_CODE_REQUEST_ERROR);
iotx_dm_send_rrpc_response(lite_item_devid.value_int, lite_item_id.value, lite_item_id.value_length, code,
lite_item_rrpcid.value,
lite_item_rrpcid.value_length,
rrpc_response, rrpc_response_len);
IMPL_LINKKIT_FREE(rrpc_response);
}
}
#else
callback = iotx_event_callback(ITE_SERVICE_REQUST);
if (callback) {
res = ((int (*)(const int, const char *, const int, const char *, const int, const char *, const int, char **,
int *))callback)(lite_item_devid.value_int,
lite_item_rrpcid.value, lite_item_rrpcid.value_length,
lite_item_serviceid.value,
lite_item_serviceid.value_length,
rrpc_request, lite_item_payload.value_length, &rrpc_response, &rrpc_response_len);
if (rrpc_response != NULL && rrpc_response_len > 0) {
iotx_dm_error_code_t code = (res == 0) ? (IOTX_DM_ERR_CODE_SUCCESS) : (IOTX_DM_ERR_CODE_REQUEST_ERROR);
iotx_dm_send_rrpc_response(lite_item_devid.value_int, lite_item_id.value, lite_item_id.value_length, code,
lite_item_rrpcid.value,
lite_item_rrpcid.value_length,
rrpc_response, rrpc_response_len);
IMPL_LINKKIT_FREE(rrpc_response);
}
}
#endif
IMPL_LINKKIT_FREE(rrpc_request);
}
break;
#endif
case IOTX_DM_EVENT_FOTA_NEW_FIRMWARE: {
char *version = NULL;
if (payload == NULL || lite_item_version.type != cJSON_String) {
return;
}
sdk_debug("Current Firmware Version: %.*s", lite_item_version.value_length, lite_item_version.value);
version = sdk_malloc(lite_item_version.value_length + 1);
if (version == NULL) {
return;
}
memset(version, 0, lite_item_version.value_length + 1);
memcpy(version, lite_item_version.value, lite_item_version.value_length);
callback = iotx_event_callback(ITE_FOTA);
if (callback) {
((int (*)(const int, const char *))callback)(0, version);
}
if (version) {
sdk_free(version);
}
}
break;
case IOTX_DM_EVENT_COTA_NEW_CONFIG: {
char *config_id = NULL, *get_type = NULL, *sign = NULL, *sign_method = NULL, *url = NULL;
if (payload == NULL || lite_item_configid.type != cJSON_String || lite_item_configsize.type != cJSON_Number ||
lite_item_gettype.type != cJSON_String || lite_item_sign.type != cJSON_String
|| lite_item_signmethod.type != cJSON_String ||
lite_item_url.type != cJSON_String) {
return;
}
sdk_debug("Current Config ID: %.*s", lite_item_configid.value_length, lite_item_configid.value);
sdk_debug("Current Config Size: %d", lite_item_configsize.value_int);
sdk_debug("Current Get Type: %.*s", lite_item_gettype.value_length, lite_item_gettype.value);
sdk_debug("Current Sign: %.*s", lite_item_sign.value_length, lite_item_sign.value);
sdk_debug("Current Sign Method: %.*s", lite_item_signmethod.value_length, lite_item_signmethod.value);
sdk_debug("Current URL: %.*s", lite_item_url.value_length, lite_item_url.value);
_impl_copy(lite_item_configid.value, lite_item_configid.value_length, (void **)&config_id,
lite_item_configid.value_length + 1);
_impl_copy(lite_item_gettype.value, lite_item_gettype.value_length, (void **)&get_type,
lite_item_gettype.value_length + 1);
_impl_copy(lite_item_sign.value, lite_item_sign.value_length, (void **)&sign, lite_item_sign.value_length + 1);
_impl_copy(lite_item_signmethod.value, lite_item_signmethod.value_length, (void **)&sign_method,
lite_item_signmethod.value_length + 1);
_impl_copy(lite_item_url.value, lite_item_url.value_length, (void **)&url, lite_item_url.value_length + 1);
if (config_id == NULL || get_type == NULL || sign == NULL || sign_method == NULL || url == NULL) {
if (config_id) {
sdk_free(config_id);
}
if (get_type) {
sdk_free(get_type);
}
if (sign) {
sdk_free(sign);
}
if (sign_method) {
sdk_free(sign_method);
}
if (url) {
sdk_free(url);
}
return;
}
callback = iotx_event_callback(ITE_COTA);
if (callback) {
((int (*)(const int, const char *, int, const char *, const char *, const char *, const char *))callback)(0, config_id,
lite_item_configsize.value_int, get_type, sign, sign_method, url);
}
if (config_id) {
sdk_free(config_id);
}
if (get_type) {
sdk_free(get_type);
}
if (sign) {
sdk_free(sign);
}
if (sign_method) {
sdk_free(sign_method);
}
if (url) {
sdk_free(url);
}
}
break;
#ifdef DEVICE_MODEL_GATEWAY
case IOTX_DM_EVENT_TOPO_GET_REPLY: {
char *topo_list = NULL;
if (payload == NULL || lite_item_id.type != cJSON_Number || lite_item_devid.type != cJSON_Number ||
lite_item_code.type != cJSON_Number || lite_item_topo.type != cJSON_Array) {
return;
}
sdk_debug("Current Id: %d", lite_item_id.value_int);
sdk_debug("Current Devid: %d", lite_item_devid.value_int);
sdk_debug("Current Code: %d", lite_item_code.value_int);
sdk_debug("Current Topo List: %.*s", lite_item_topo.value_length, lite_item_topo.value);
topo_list = IMPL_LINKKIT_MALLOC(lite_item_topo.value_length + 1);
if (topo_list == NULL) {
sdk_err("Not Enough Memory");
return;
}
memset(topo_list, 0, lite_item_topo.value_length + 1);
memcpy(topo_list, lite_item_topo.value, lite_item_topo.value_length);
callback = iotx_event_callback(ITE_TOPOLIST_REPLY);
if (callback) {
((int (*)(const int, const int, const int, const char *, const int))callback)(lite_item_devid.value_int,
lite_item_id.value_int,
lite_item_code.value_int, topo_list, lite_item_topo.value_length);
}
IMPL_LINKKIT_FREE(topo_list);
}
break;
case IOTX_DM_EVENT_TOPO_DELETE_REPLY:
case IOTX_DM_EVENT_SUBDEV_RESET_REPLY:
case IOTX_DM_EVENT_TOPO_ADD_REPLY:
case IOTX_DM_EVENT_SUBDEV_REGISTER_REPLY:
case IOTX_DM_EVENT_COMBINE_LOGIN_REPLY:
case IOTX_DM_EVENT_COMBINE_LOGOUT_REPLY:
case IOTX_DM_EVENT_COMBINE_BATCH_LOGIN_REPLY:
case IOTX_DM_EVENT_COMBINE_BATCH_LOGOUT_REPLY: {
int itm_event = -1;
if (payload == NULL || lite_item_id.type != cJSON_Number || lite_item_devid.type != cJSON_Number ||
lite_item_code.type != cJSON_Number)
{
return;
}
sdk_debug("Current Id: %d", lite_item_id.value_int);
sdk_debug("Current Code: %d", lite_item_code.value_int);
sdk_debug("Current Devid: %d", lite_item_devid.value_int);
_iotx_linkkit_upstream_mutex_lock();
_iotx_linkkit_upstream_callback_remove(lite_item_id.value_int, lite_item_code.value_int);
_iotx_linkkit_upstream_mutex_unlock();
switch (type)
{
case IOTX_DM_EVENT_TOPO_DELETE_REPLY:
{
itm_event = ITM_EVENT_TOPO_DELETE_REPLY;
}
break;
case IOTX_DM_EVENT_SUBDEV_RESET_REPLY:
{
itm_event = ITM_EVENT_SUBDEV_RESET_REPLY;
}
break;
case IOTX_DM_EVENT_TOPO_ADD_REPLY:
{
itm_event = ITM_EVENT_TOPO_ADD_REPLY;
}
break;
case IOTX_DM_EVENT_COMBINE_LOGIN_REPLY:
{
itm_event = ITM_EVENT_COMBINE_LOGIN_REPLY;
}
break;
case IOTX_DM_EVENT_COMBINE_LOGOUT_REPLY:
{
itm_event = ITM_EVENT_COMBINE_LOGOUT_REPLY;
}
break;
case IOTX_DM_EVENT_COMBINE_BATCH_LOGIN_REPLY:
{
itm_event = ITM_EVENT_COMBINE_BATCH_LOGIN_REPLY;
}
break;
case IOTX_DM_EVENT_COMBINE_BATCH_LOGOUT_REPLY:
{
itm_event = ITM_EVENT_COMBINE_BATCH_LOGOUT_REPLY;
}
break;
default:break;
}
if (-1 != itm_event)
{
char *user_payload = NULL;
int user_payload_len = 0;
if (lite_item_payload.value_length == 0)
{
user_payload_len = 2 + 1;
}
else
{
user_payload_len = lite_item_payload.value_length + 1;
}
user_payload = IMPL_LINKKIT_MALLOC(user_payload_len);
if (user_payload == NULL)
{
sdk_err("No mem");
return;
}
memset(user_payload, 0, user_payload_len);
if (lite_item_payload.value_length == 0)
{
HAL_Snprintf(user_payload, user_payload_len, "%s", "{}");
}
else
{
memcpy(user_payload, lite_item_payload.value, lite_item_payload.value_length);
}
callback = iotx_event_callback(ITE_SUBDEV_MISC_OPS);
if (callback)
{
((int (*)(const int, int, const int, const char *, const int))callback)(lite_item_devid.value_int,
itm_event, lite_item_code.value_int, user_payload, user_payload_len - 1);
}
IMPL_LINKKIT_FREE(user_payload);
}
}
break;
case IOTX_DM_EVENT_GATEWAY_PERMIT: {
char *product_key = "";
if (payload == NULL || lite_item_time.type != cJSON_Number) {
return;
}
sdk_debug("Current Time: %d", lite_item_time.value_int);
if (lite_item_pk.type == cJSON_String) {
sdk_debug("Current Product Key: %.*s", lite_item_pk.value_length, lite_item_pk.value);
product_key = IMPL_LINKKIT_MALLOC(lite_item_pk.value_length + 1);
if (product_key == NULL) {
sdk_err("Not Enough Memory");
return;
}
memset(product_key, 0, lite_item_pk.value_length + 1);
memcpy(product_key, lite_item_pk.value, lite_item_pk.value_length);
}
callback = iotx_event_callback(ITE_PERMIT_JOIN);
if (callback) {
((int (*)(const char *, int))callback)((const char *)product_key, (const int)lite_item_time.value_int);
}
if (lite_item_pk.type == cJSON_String) {
IMPL_LINKKIT_FREE(product_key);
}
}
break;
case IOTX_DM_EVENT_TOPO_CHANGE:
{
char *user_payload = NULL;
int user_payload_len = 0;
if (lite_item_payload.value_length == 0)
{
user_payload_len = 2 + 1;
}
else
{
user_payload_len = lite_item_payload.value_length + 1;
}
user_payload = IMPL_LINKKIT_MALLOC(user_payload_len);
if (user_payload == NULL)
{
sdk_err("No mem");
return;
}
memset(user_payload, 0, user_payload_len);
if (lite_item_payload.value_length == 0)
{
HAL_Snprintf(user_payload, user_payload_len, "%s", "{}");
}
else
{
memcpy(user_payload, lite_item_payload.value, lite_item_payload.value_length);
}
callback = iotx_event_callback(ITE_TOPO_CHANGE);
if (callback)
{
((int (*)(const int, const char *, const int))callback)(lite_item_devid.value_int, user_payload, user_payload_len - 1);
}
IMPL_LINKKIT_FREE(user_payload);
}
#endif
default: {
}
break;
}
}
static int _iotx_linkkit_master_open(iotx_linkkit_dev_meta_info_t *meta_info)
{
int res = 0;
iotx_linkkit_ctx_t *ctx = _iotx_linkkit_get_ctx();
if (ctx->is_opened) {
return FAIL_RETURN;
}
ctx->is_opened = 1;
HAL_SetProductKey(meta_info->product_key);
HAL_SetProductSecret(meta_info->product_secret);
HAL_SetDeviceName(meta_info->device_name);
HAL_SetDeviceSecret(meta_info->device_secret);
/* Create Mutex */
ctx->mutex = HAL_MutexCreate();
if (ctx->mutex == NULL) {
sdk_err("Not Enough Memory");
ctx->is_opened = 0;
return FAIL_RETURN;
}
#ifdef DEVICE_MODEL_GATEWAY
ctx->upstream_mutex = HAL_MutexCreate();
if (ctx->upstream_mutex == NULL) {
HAL_MutexDestroy(ctx->mutex);
sdk_err("Not Enough Memory");
ctx->is_opened = 0;
return FAIL_RETURN;
}
#endif
res = iotx_dm_open();
if (res != SUCCESS_RETURN) {
#ifdef DEVICE_MODEL_GATEWAY
HAL_MutexDestroy(ctx->upstream_mutex);
#endif
HAL_MutexDestroy(ctx->mutex);
ctx->is_opened = 0;
return FAIL_RETURN;
}
INIT_LIST_HEAD(&ctx->upstream_sync_callback_list);
return SUCCESS_RETURN;
}
#ifdef DEVICE_MODEL_GATEWAY
static int _iotx_linkkit_slave_open(iotx_linkkit_dev_meta_info_t *meta_info)
{
int res = 0, devid = 0;
iotx_linkkit_ctx_t *ctx = _iotx_linkkit_get_ctx();
if (!ctx->is_opened) {
return FAIL_RETURN;
}
res = iotx_dm_subdev_create(meta_info->product_key, meta_info->device_name, meta_info->device_secret, &devid);
if (res != SUCCESS_RETURN) {
return FAIL_RETURN;
}
return devid;
}
static int _iotx_linkkit_slave_close(int devid)
{
iotx_linkkit_ctx_t *ctx = _iotx_linkkit_get_ctx();
_iotx_linkkit_mutex_lock();
if (ctx->is_opened == 0) {
_iotx_linkkit_mutex_unlock();
return FAIL_RETURN;
}
/* Release Subdev Resources */
iotx_dm_subdev_destroy(devid);
_iotx_linkkit_mutex_unlock();
return SUCCESS_RETURN;
}
#endif
static int _iotx_linkkit_master_connect(void)
{
int res = 0;
iotx_linkkit_ctx_t *ctx = _iotx_linkkit_get_ctx();
iotx_dm_init_params_t dm_init_params;
if (ctx->is_connected) {
return FAIL_RETURN;
}
ctx->is_connected = 1;
memset(&dm_init_params, 0, sizeof(iotx_dm_init_params_t));
dm_init_params.event_callback = _iotx_linkkit_event_callback;
res = iotx_dm_subscribe(IOTX_DM_LOCAL_NODE_DEVID);
if (res != SUCCESS_RETURN)
{
sdk_err("DM Subscribe Failed");
ctx->is_connected = 0;
return FAIL_RETURN;
}
res = iotx_dm_connect(&dm_init_params);
if (res != SUCCESS_RETURN)
{
sdk_err("DM Start Failed");
ctx->is_connected = 0;
return FAIL_RETURN;
}
//Let user event handle at last
iotx_dm_event_types_t type = IOTX_DM_EVENT_INITIALIZED;
_iotx_linkkit_event_callback(type, "{\"devid\":0}");
return SUCCESS_RETURN;
}
#ifdef DEVICE_MODEL_GATEWAY
typedef int (*dm_subdev_connect_cb)(int devid, iotx_linkkit_dev_meta_info_t *subdev_list, int subdev_total);
static int _iotx_linkkit_subdev_connect(int devid, dm_subdev_connect_cb connect_cb, iotx_linkkit_dev_meta_info_t *subdev_list, int subdev_total)
{
int res = 0, msgid = 0, code = 0;
iotx_linkkit_ctx_t *ctx = _iotx_linkkit_get_ctx();
iotx_linkkit_upstream_sync_callback_node_t *node = NULL;
void *semaphore = NULL;
if (ctx->is_connected == 0)
{
sdk_err("master isn't start");
return FAIL_RETURN;
}
if (devid <= 0 || !connect_cb)
{
sdk_err("param err");
return FAIL_RETURN;
}
/* Subdev connect */
res = connect_cb(devid, subdev_list, subdev_total);
if (res < SUCCESS_RETURN)
{
return FAIL_RETURN;
}
if (res > SUCCESS_RETURN)
{
semaphore = HAL_SemaphoreCreate();
if (semaphore == NULL)
{
return FAIL_RETURN;
}
msgid = res;
_iotx_linkkit_upstream_mutex_lock();
res = _iotx_linkkit_upstream_sync_callback_list_insert(msgid, semaphore, &node);
if (res != SUCCESS_RETURN)
{
HAL_SemaphoreDestroy(semaphore);
_iotx_linkkit_upstream_mutex_unlock();
return FAIL_RETURN;
}
_iotx_linkkit_upstream_mutex_unlock();
res = HAL_SemaphoreWait(semaphore, IOTX_LINKKIT_ASYNC_DEFAULT_TIMEOUT_MS);
if (res < SUCCESS_RETURN)
{
_iotx_linkkit_upstream_mutex_lock();
_iotx_linkkit_upstream_sync_callback_list_remove(msgid);
_iotx_linkkit_upstream_mutex_unlock();
return FAIL_RETURN;
}
_iotx_linkkit_upstream_mutex_lock();
code = node->code;
_iotx_linkkit_upstream_sync_callback_list_remove(msgid);
if (code != SUCCESS_RETURN)
{
_iotx_linkkit_upstream_mutex_unlock();
return FAIL_RETURN;
}
_iotx_linkkit_upstream_mutex_unlock();
}
if (subdev_cloud_response_code == 200)
{
res = SUCCESS_RETURN;
}
else
{
switch (subdev_cloud_response_code)
{
case SUBDEV_CONNECT_RESPONSE_CODE_CLOUD_ERROR:
{
res = ERROR_SUBDEV_CONNECT_RESPONSE_CODE_CLOUD_ERR;
}
break;
case SUBDEV_CONNECT_RESPONSE_CODE_INVALI_REQUEST:
{
res = ERROR_SUBDEV_CONNECT_RESPONSE_CODE_INVALI_REQUEST;
}
break;
case SUBDEV_CONNECT_RESPONSE_CODE_TOTAL_OVERLIMIT:
{
res = ERROR_SUBDEV_CONNECT_RESPONSE_CODE_TOTAL_OVERLIMIT;
}
default:
res = FAIL_RETURN;
break;
}
}
return res;
}
static int _iotx_linkkit_slave_connect(int devid)
{
int res = 0, msgid = 0, code = 0;
iotx_linkkit_ctx_t *ctx = _iotx_linkkit_get_ctx();
iotx_linkkit_upstream_sync_callback_node_t *node = NULL;
void *semaphore = NULL;
if (ctx->is_connected == 0) {
sdk_err("master isn't start");
return FAIL_RETURN;
}
if (devid <= 0) {
sdk_err("devid invalid");
return FAIL_RETURN;
}
/* Subdev Register */
res = iotx_dm_subdev_register(devid);
if (res < SUCCESS_RETURN) {
return FAIL_RETURN;
}
if (res > SUCCESS_RETURN) {
semaphore = HAL_SemaphoreCreate();
if (semaphore == NULL) {
return FAIL_RETURN;
}
msgid = res;
_iotx_linkkit_upstream_mutex_lock();
res = _iotx_linkkit_upstream_sync_callback_list_insert(msgid, semaphore, &node);
if (res != SUCCESS_RETURN) {
HAL_SemaphoreDestroy(semaphore);
_iotx_linkkit_upstream_mutex_unlock();
return FAIL_RETURN;
}
_iotx_linkkit_upstream_mutex_unlock();
res = HAL_SemaphoreWait(semaphore, IOTX_LINKKIT_SYNC_DEFAULT_TIMEOUT_MS);
if (res < SUCCESS_RETURN) {
_iotx_linkkit_upstream_mutex_lock();
_iotx_linkkit_upstream_sync_callback_list_remove(msgid);
_iotx_linkkit_upstream_mutex_unlock();
return FAIL_RETURN;
}
_iotx_linkkit_upstream_mutex_lock();
code = node->code;
_iotx_linkkit_upstream_sync_callback_list_remove(msgid);
if (code != SUCCESS_RETURN) {
_iotx_linkkit_upstream_mutex_unlock();
return FAIL_RETURN;
}
_iotx_linkkit_upstream_mutex_unlock();
}
/* Subdev Add Topo */
res = iotx_dm_subdev_topo_add(devid);
if (res < SUCCESS_RETURN) {
_iotx_linkkit_mutex_unlock();
return FAIL_RETURN;
}
semaphore = HAL_SemaphoreCreate();
if (semaphore == NULL) {
_iotx_linkkit_mutex_unlock();
return FAIL_RETURN;
}
msgid = res;
_iotx_linkkit_upstream_mutex_lock();
res = _iotx_linkkit_upstream_sync_callback_list_insert(msgid, semaphore, &node);
if (res != SUCCESS_RETURN) {
HAL_SemaphoreDestroy(semaphore);
_iotx_linkkit_upstream_mutex_unlock();
return FAIL_RETURN;
}
_iotx_linkkit_upstream_mutex_unlock();
res = HAL_SemaphoreWait(semaphore, IOTX_LINKKIT_SYNC_DEFAULT_TIMEOUT_MS);
if (res < SUCCESS_RETURN) {
_iotx_linkkit_upstream_mutex_lock();
_iotx_linkkit_upstream_sync_callback_list_remove(msgid);
_iotx_linkkit_upstream_mutex_unlock();
return FAIL_RETURN;
}
_iotx_linkkit_upstream_mutex_lock();
code = node->code;
_iotx_linkkit_upstream_sync_callback_list_remove(msgid);
if (code != SUCCESS_RETURN) {
_iotx_linkkit_upstream_mutex_unlock();
return FAIL_RETURN;
}
_iotx_linkkit_upstream_mutex_unlock();
return SUCCESS_RETURN;
}
static int _iotx_linkkit_subdev_delete_topo(int devid)
{
int res = 0, msgid = 0, code = 0;
iotx_linkkit_ctx_t *ctx = _iotx_linkkit_get_ctx();
iotx_linkkit_upstream_sync_callback_node_t *node = NULL;
void *semaphore = NULL;
if (ctx->is_connected == 0) {
sdk_err("master isn't start");
return FAIL_RETURN;
}
if (devid <= 0) {
sdk_err("devid invalid");
return FAIL_RETURN;
}
/* Subdev Delete Topo */
res = iotx_dm_subdev_topo_del(devid);
if (res < SUCCESS_RETURN) {
return FAIL_RETURN;
}
msgid = res;
semaphore = HAL_SemaphoreCreate();
if (semaphore == NULL) {
return FAIL_RETURN;
}
_iotx_linkkit_upstream_mutex_lock();
res = _iotx_linkkit_upstream_sync_callback_list_insert(msgid, semaphore, &node);
if (res != SUCCESS_RETURN) {
HAL_SemaphoreDestroy(semaphore);
_iotx_linkkit_upstream_mutex_unlock();
return FAIL_RETURN;
}
_iotx_linkkit_upstream_mutex_unlock();
res = HAL_SemaphoreWait(semaphore, IOTX_LINKKIT_SYNC_DEFAULT_TIMEOUT_MS);
if (res < SUCCESS_RETURN) {
_iotx_linkkit_upstream_mutex_lock();
_iotx_linkkit_upstream_sync_callback_list_remove(msgid);
_iotx_linkkit_upstream_mutex_unlock();
return FAIL_RETURN;
}
_iotx_linkkit_upstream_mutex_lock();
code = node->code;
_iotx_linkkit_upstream_sync_callback_list_remove(msgid);
if (code != SUCCESS_RETURN) {
_iotx_linkkit_upstream_mutex_unlock();
return FAIL_RETURN;
}
_iotx_linkkit_upstream_mutex_unlock();
return SUCCESS_RETURN;
}
static int _iotx_linkkit_subdev_reset(int devid)
{
int res = 0, msgid = 0, code = 0;
iotx_linkkit_ctx_t *ctx = _iotx_linkkit_get_ctx();
iotx_linkkit_upstream_sync_callback_node_t *node = NULL;
void *semaphore = NULL;
if (ctx->is_connected == 0) {
sdk_err("master isn't start");
return FAIL_RETURN;
}
if (devid <= 0) {
sdk_err("devid invalid");
return FAIL_RETURN;
}
/* Subdev Delete Topo */
res = iotx_dm_subdev_reset(devid);
if (res < SUCCESS_RETURN) {
return FAIL_RETURN;
}
msgid = res;
semaphore = HAL_SemaphoreCreate();
if (semaphore == NULL) {
return FAIL_RETURN;
}
_iotx_linkkit_upstream_mutex_lock();
res = _iotx_linkkit_upstream_sync_callback_list_insert(msgid, semaphore, &node);
if (res != SUCCESS_RETURN) {
HAL_SemaphoreDestroy(semaphore);
_iotx_linkkit_upstream_mutex_unlock();
return FAIL_RETURN;
}
_iotx_linkkit_upstream_mutex_unlock();
res = HAL_SemaphoreWait(semaphore, IOTX_LINKKIT_SYNC_DEFAULT_TIMEOUT_MS);
if (res < SUCCESS_RETURN) {
_iotx_linkkit_upstream_mutex_lock();
_iotx_linkkit_upstream_sync_callback_list_remove(msgid);
_iotx_linkkit_upstream_mutex_unlock();
return FAIL_RETURN;
}
_iotx_linkkit_upstream_mutex_lock();
code = node->code;
_iotx_linkkit_upstream_sync_callback_list_remove(msgid);
if (code != SUCCESS_RETURN) {
_iotx_linkkit_upstream_mutex_unlock();
return FAIL_RETURN;
}
_iotx_linkkit_upstream_mutex_unlock();
return SUCCESS_RETURN;
}
#endif
static int _iotx_linkkit_master_close(void)
{
iotx_linkkit_ctx_t *ctx = _iotx_linkkit_get_ctx();
_iotx_linkkit_mutex_lock();
if (ctx->is_opened == 0) {
_iotx_linkkit_mutex_unlock();
return FAIL_RETURN;
}
ctx->is_opened = 0;
iotx_dm_close();
#ifdef DEVICE_MODEL_GATEWAY
_iotx_linkkit_upstream_sync_callback_list_destroy();
HAL_MutexDestroy(ctx->upstream_mutex);
#endif
_iotx_linkkit_mutex_unlock();
HAL_MutexDestroy(ctx->mutex);
memset(ctx, 0, sizeof(iotx_linkkit_ctx_t));
_awss_reported = 0;
return SUCCESS_RETURN;
}
//data moved from global data center to the region user used, MUST reinitialized sdk and all devices.
int user_handle_redirect()
{
iotx_linkkit_dev_meta_info_t meta_info;
int id = 0;
int res = 0;
//close master
memset(&meta_info, 0, sizeof(iotx_linkkit_dev_meta_info_t));
HAL_GetProductKey(meta_info.product_key);
HAL_GetProductSecret(meta_info.product_secret);
HAL_GetDeviceName(meta_info.device_name);
HAL_GetDeviceSecret(meta_info.device_secret);
IOT_Linkkit_Close(IOTX_DM_LOCAL_NODE_DEVID);
/* Create Master Device Resources */
do {
id = IOT_Linkkit_Open(IOTX_LINKKIT_DEV_TYPE_MASTER, &meta_info);
if (id < 0) {
sdk_err("IOT_Linkkit_Open Failed, retry after 5s...\n");
HAL_SleepMs(5000);
}
} while (id < 0);
/* Start Connect Aliyun Server */
do {
res = IOT_Linkkit_Connect(id);
if (res < 0) {
sdk_err("IOT_Linkkit_Connect Failed, retry after 5s...\n");
HAL_SleepMs(5000);
}
} while (res < 0);
return 0;
}
static int user_redirect_event_handler(void)
{
iotx_linkkit_ctx_t *ctx = _iotx_linkkit_get_ctx();
sdk_debug("Cloud Redirect");
ctx->cloud_redirect = 1;
return 0;
}
int IOT_Linkkit_Open(iotx_linkkit_dev_type_t dev_type, iotx_linkkit_dev_meta_info_t *meta_info)
{
int res = 0;
if (dev_type < 0 || dev_type >= IOTX_LINKKIT_DEV_TYPE_MAX || meta_info == NULL) {
sdk_err("Invalid Parameter");
return FAIL_RETURN;
}
switch (dev_type) {
case IOTX_LINKKIT_DEV_TYPE_MASTER: {
res = _iotx_linkkit_master_open(meta_info);
if (res == SUCCESS_RETURN) {
res = IOTX_DM_LOCAL_NODE_DEVID;
IOT_RegisterCallback(ITE_REDIRECT, user_redirect_event_handler);
}
}
break;
case IOTX_LINKKIT_DEV_TYPE_SLAVE: {
#ifdef DEVICE_MODEL_GATEWAY
res = _iotx_linkkit_slave_open(meta_info);
#else
res = FAIL_RETURN;
#endif
}
break;
default: {
sdk_err("Unknown Device Type");
res = FAIL_RETURN;
}
break;
}
return res;
}
int IOT_Linkkit_Connect(int devid)
{
int res = 0;
iotx_linkkit_ctx_t *ctx = _iotx_linkkit_get_ctx();
if (devid < 0) {
sdk_err("Invalid Parameter");
return FAIL_RETURN;
}
if (ctx->is_opened == 0) {
return FAIL_RETURN;
}
_iotx_linkkit_mutex_lock();
if (devid == IOTX_DM_LOCAL_NODE_DEVID) {
res = _iotx_linkkit_master_connect();
} else {
#ifdef DEVICE_MODEL_GATEWAY
res = _iotx_linkkit_subdev_connect(devid, iotx_dm_subdev_connect, NULL, 0);
#else
res = FAIL_RETURN;
#endif
}
_iotx_linkkit_mutex_unlock();
return res;
}
void IOT_Linkkit_Yield(int timeout_ms)
{
iotx_linkkit_ctx_t *ctx = _iotx_linkkit_get_ctx();
if (timeout_ms <= 0) {
sdk_err("Invalid Parameter");
return;
}
if (ctx->is_opened == 0 || ctx->is_connected == 0) {
HAL_SleepMs(timeout_ms);
return;
}
// NOTICE: Do Not remove the following codes!
if (ctx->cloud_redirect == 1){
ctx->is_connected = 0;
user_handle_redirect();
ctx->cloud_redirect = 0;
}
iotx_dm_yield(timeout_ms);
iotx_dm_dispatch();
#if (CONFIG_SDK_THREAD_COST == 1)
HAL_SleepMs(timeout_ms);
#endif
}
int IOT_Linkkit_Close(int devid)
{
int res = 0;
if (devid < 0) {
sdk_err("Invalid Parameter");
return FAIL_RETURN;
}
if (devid == IOTX_DM_LOCAL_NODE_DEVID) {
#ifdef DEV_BIND_ENABLED
extern void awss_bind_deinit(void);
awss_bind_deinit();
#endif
res = _iotx_linkkit_master_close();
} else {
#ifdef DEVICE_MODEL_GATEWAY
res = _iotx_linkkit_slave_close(devid);
#else
res = FAIL_RETURN;
#endif
}
return res;
}
#ifdef DEVICE_MODEL_GATEWAY
static int _iotx_linkkit_subdev_batch_login(iotx_linkkit_dev_meta_info_t *subdev_list, int subdev_total)
{
int res = 0, msgid = 0, code = 0;
int index = 0;
int subdev_id = -1;
iotx_linkkit_dev_meta_info_t *p_subdev = NULL;
iotx_linkkit_upstream_sync_callback_node_t *node = NULL;
void *semaphore = NULL;
if (subdev_list == NULL || subdev_total < 1)
{
sdk_err("param err");
return FAIL_RETURN;
}
res = iotx_dm_subdev_batch_login(subdev_list, subdev_total);
if (res < SUCCESS_RETURN) {
return FAIL_RETURN;
}
msgid = res;
semaphore = HAL_SemaphoreCreate();
if (semaphore == NULL) {
return FAIL_RETURN;
}
_iotx_linkkit_upstream_mutex_lock();
res = _iotx_linkkit_upstream_sync_callback_list_insert(msgid, semaphore, &node);
if (res != SUCCESS_RETURN) {
HAL_SemaphoreDestroy(semaphore);
_iotx_linkkit_upstream_mutex_unlock();
return FAIL_RETURN;
}
_iotx_linkkit_upstream_mutex_unlock();
res = HAL_SemaphoreWait(semaphore, IOTX_LINKKIT_SYNC_DEFAULT_TIMEOUT_MS);
if (res < SUCCESS_RETURN) {
_iotx_linkkit_upstream_mutex_lock();
_iotx_linkkit_upstream_sync_callback_list_remove(msgid);
_iotx_linkkit_upstream_mutex_unlock();
return FAIL_RETURN;
}
_iotx_linkkit_upstream_mutex_lock();
code = node->code;
_iotx_linkkit_upstream_sync_callback_list_remove(msgid);
if (code != SUCCESS_RETURN) {
_iotx_linkkit_upstream_mutex_unlock();
return FAIL_RETURN;
}
_iotx_linkkit_upstream_mutex_unlock();
for (index = 0; index < subdev_total; index++) {
p_subdev = subdev_list + index;
if (SUCCESS_RETURN == iotx_dm_subdev_query(p_subdev->product_key, p_subdev->device_name, &subdev_id) && subdev_id > 0)
{
res = iotx_dm_subscribe(subdev_id);
if (res != SUCCESS_RETURN) {
return FAIL_RETURN;
}
void *callback = iotx_event_callback(ITE_INITIALIZE_COMPLETED);
if (callback) {
((int (*)(const int))callback)(subdev_id);
}
}
}
return res;
}
static int _iotx_linkkit_subdev_batch_logout(iotx_linkkit_dev_meta_info_t *subdev_list, int subdev_total)
{
int res = 0, msgid = 0, code = 0;
iotx_linkkit_upstream_sync_callback_node_t *node = NULL;
void *semaphore = NULL;
if (subdev_list == NULL || subdev_total < 1)
{
sdk_err("param err");
return FAIL_RETURN;
}
res = iotx_dm_subdev_batch_logout(subdev_list, subdev_total);
if (res < SUCCESS_RETURN) {
return FAIL_RETURN;
}
msgid = res;
semaphore = HAL_SemaphoreCreate();
if (semaphore == NULL) {
return FAIL_RETURN;
}
_iotx_linkkit_upstream_mutex_lock();
res = _iotx_linkkit_upstream_sync_callback_list_insert(msgid, semaphore, &node);
if (res != SUCCESS_RETURN) {
HAL_SemaphoreDestroy(semaphore);
_iotx_linkkit_upstream_mutex_unlock();
return FAIL_RETURN;
}
_iotx_linkkit_upstream_mutex_unlock();
res = HAL_SemaphoreWait(semaphore, IOTX_LINKKIT_SYNC_DEFAULT_TIMEOUT_MS);
if (res < SUCCESS_RETURN) {
_iotx_linkkit_upstream_mutex_lock();
_iotx_linkkit_upstream_sync_callback_list_remove(msgid);
_iotx_linkkit_upstream_mutex_unlock();
return FAIL_RETURN;
}
_iotx_linkkit_upstream_mutex_lock();
code = node->code;
_iotx_linkkit_upstream_sync_callback_list_remove(msgid);
if (code != SUCCESS_RETURN) {
_iotx_linkkit_upstream_mutex_unlock();
return FAIL_RETURN;
}
_iotx_linkkit_upstream_mutex_unlock();
return res;
}
#endif
int IOT_Linkkit_Report_Ext(int devid, iotx_linkkit_msg_type_t msg_type, unsigned char *payload, int payload_len, int sendto)
{
int res = 0;
iotx_linkkit_ctx_t *ctx = _iotx_linkkit_get_ctx();
if (devid < 0 || msg_type < 0 || msg_type >= IOTX_LINKKIT_MSG_MAX) {
sdk_err("Invalid Parameter");
return FAIL_RETURN;
}
if (ctx->is_opened == 0 || ctx->is_connected == 0) {
return FAIL_RETURN;
}
_iotx_linkkit_mutex_lock();
switch (msg_type) {
#if !defined(DEVICE_MODEL_RAWDATA_SOLO)
case ITM_MSG_POST_PROPERTY: {
if (payload == NULL || payload_len <= 0) {
sdk_err("Invalid Parameter");
_iotx_linkkit_mutex_unlock();
return FAIL_RETURN;
}
res = iotx_dm_post_property_to(devid, (char *)payload, payload_len, sendto);
#ifdef LOG_REPORT_TO_CLOUD
if (1 == report_sample) {
send_permance_info(NULL, 0, "4", 1);
}
#endif
}
break;
#endif
default: {
sdk_err("Unknown Message Type");
res = FAIL_RETURN;
}
break;
}
_iotx_linkkit_mutex_unlock();
return res;
}
int IOT_Linkkit_Report(int devid, iotx_linkkit_msg_type_t msg_type, unsigned char *payload, int payload_len)
{
int res = 0;
iotx_linkkit_ctx_t *ctx = _iotx_linkkit_get_ctx();
if (devid < 0 || msg_type < 0 || msg_type >= IOTX_LINKKIT_MSG_MAX) {
sdk_err("Invalid Parameter");
return FAIL_RETURN;
}
if (ctx->is_opened == 0 || ctx->is_connected == 0) {
return FAIL_RETURN;
}
_iotx_linkkit_mutex_lock();
switch (msg_type) {
#if !defined(DEVICE_MODEL_RAWDATA_SOLO)
case ITM_MSG_POST_PROPERTY: {
if (payload == NULL || payload_len <= 0) {
sdk_err("Invalid Parameter");
_iotx_linkkit_mutex_unlock();
return FAIL_RETURN;
}
res = iotx_dm_post_property(devid, (char *)payload, payload_len);
#ifdef LOG_REPORT_TO_CLOUD
if (1 == report_sample) {
send_permance_info(NULL, 0, "4", 1);
}
#endif
}
break;
#ifdef DM_UNIFIED_SERVICE_POST
case ITM_MSG_UNIFIED_SERVICE_POST: {
if (payload == NULL || payload_len <= 0) {
sdk_err("param err");
_iotx_linkkit_mutex_unlock();
return FAIL_RETURN;
}
res = iotx_dm_unified_service_post(devid, (char *)payload, payload_len);
#ifdef LOG_REPORT_TO_CLOUD
if (1 == report_sample) {
send_permance_info(NULL, 0, "4", 1);
}
#endif
}break;
#endif
#ifdef DEVICE_MODEL_GATEWAY
case ITM_MSG_CONNECT_SUBDEV:
{
if (payload && payload_len > 0)
{
int subdev_id = -1;
int subdev_total = 0;
int subdev_valid_num = 0;
int index = 0;
iotx_linkkit_dev_meta_info_t *p_subdev_list = (iotx_linkkit_dev_meta_info_t*)payload;
iotx_linkkit_dev_meta_info_t *p_subdev_valid_list = NULL;
subdev_total = payload_len / sizeof(iotx_linkkit_dev_meta_info_t);
p_subdev_valid_list = IMPL_LINKKIT_MALLOC(payload_len);
if (p_subdev_valid_list == NULL)
{
sdk_err("no mem");
_iotx_linkkit_mutex_unlock();
return ERROR_NO_ENOUGH_MEM;
}
for(index = 0;index < subdev_total;index++)
{
iotx_linkkit_dev_meta_info_t *p_subdev = p_subdev_list + index;
subdev_id = _iotx_linkkit_slave_open(p_subdev);
if (subdev_id > 0) {
memcpy(p_subdev_valid_list + subdev_valid_num, p_subdev, sizeof(iotx_linkkit_dev_meta_info_t));
subdev_valid_num ++;
}
else
{
sdk_err("open dn(%s) fail", p_subdev->device_name);
}
}
res = _iotx_linkkit_subdev_connect(1, iotx_dm_multi_subdev_connect, p_subdev_valid_list, subdev_valid_num);
if (p_subdev_valid_list) IMPL_LINKKIT_FREE(p_subdev_valid_list);
#ifdef LOG_REPORT_TO_CLOUD
if (1 == report_sample) {
send_permance_info(NULL, 0, "4", 1);
}
#endif
}
}break;
#endif
case ITM_MSG_EVENT_NOTIFY_REPLY: {
if (payload == NULL || payload_len <= 0) {
sdk_err("Invalid Parameter");
_iotx_linkkit_mutex_unlock();
return FAIL_RETURN;
}
res = iotx_dm_event_notify_reply(devid, (char *)payload, payload_len);
#ifdef LOG_REPORT_TO_CLOUD
if (1 == report_sample) {
send_permance_info(NULL, 0, "4", 1);
}
#endif
}
break;
case ITM_MSG_DEVICEINFO_UPDATE: {
if (payload == NULL || payload_len <= 0) {
sdk_err("Invalid Parameter");
_iotx_linkkit_mutex_unlock();
return FAIL_RETURN;
}
res = iotx_dm_deviceinfo_update(devid, (char *)payload, payload_len);
}
break;
case ITM_MSG_DEVICEINFO_DELETE: {
if (payload == NULL || payload_len <= 0) {
sdk_err("Invalid Parameter");
_iotx_linkkit_mutex_unlock();
return FAIL_RETURN;
}
res = iotx_dm_deviceinfo_delete(devid, (char *)payload, payload_len);
}
break;
#endif
case ITM_MSG_POST_RAW_DATA: {
if (payload == NULL || payload_len <= 0) {
sdk_err("Invalid Parameter");
_iotx_linkkit_mutex_unlock();
return FAIL_RETURN;
}
res = iotx_dm_post_rawdata(devid, (char *)payload, payload_len);
}
break;
#ifdef DEVICE_MODEL_GATEWAY
case ITM_MSG_LOGIN:
{
iotx_linkkit_dev_meta_info_t subdev;
memset(&subdev, 0, sizeof(iotx_linkkit_dev_meta_info_t));
if (SUCCESS_RETURN != iotx_dm_get_subdev_triples_by_devid(devid, &subdev))
{
sdk_err("login no subdev:%d", devid);
_iotx_linkkit_mutex_unlock();
return FAIL_RETURN;
}
res = _iotx_linkkit_subdev_batch_login(&subdev, 1);
if (res != SUCCESS_RETURN)
{
_iotx_linkkit_mutex_unlock();
return FAIL_RETURN;
}
}
break;
case ITM_MSG_LOGOUT:
{
iotx_linkkit_dev_meta_info_t subdev;
memset(&subdev, 0, sizeof(iotx_linkkit_dev_meta_info_t));
if (SUCCESS_RETURN != iotx_dm_get_subdev_triples_by_devid(devid, &subdev))
{
sdk_err("logout no subdev:%d", devid);
_iotx_linkkit_mutex_unlock();
return FAIL_RETURN;
}
res = _iotx_linkkit_subdev_batch_logout(&subdev, 1);
if (res != SUCCESS_RETURN)
{
_iotx_linkkit_mutex_unlock();
return FAIL_RETURN;
}
}
break;
case ITM_MSG_BATCH_LOGIN:
{
if (payload && payload_len > 0)
{
int subdev_id = -1;
int subdev_total = 0;
int subdev_valid_num = 0;
int index = 0;
iotx_linkkit_dev_meta_info_t *p_subdev_list = (iotx_linkkit_dev_meta_info_t *)payload;
iotx_linkkit_dev_meta_info_t *p_subdev_valid_list = NULL;
subdev_total = payload_len / sizeof(iotx_linkkit_dev_meta_info_t);
p_subdev_valid_list = IMPL_LINKKIT_MALLOC(payload_len);
if (p_subdev_valid_list == NULL)
{
sdk_err("no mem");
_iotx_linkkit_mutex_unlock();
return ERROR_NO_ENOUGH_MEM;
}
for (index = 0; index < subdev_total; index++)
{
iotx_linkkit_dev_meta_info_t *p_subdev = p_subdev_list + index;
subdev_id = _iotx_linkkit_slave_open(p_subdev);
if (subdev_id > 0)
{
memcpy(p_subdev_valid_list + subdev_valid_num, p_subdev, sizeof(iotx_linkkit_dev_meta_info_t));
subdev_valid_num++;
}
else
{
sdk_err("batch login open dn(%s) fail", p_subdev->device_name);
}
}
res = _iotx_linkkit_subdev_batch_login(p_subdev_valid_list, subdev_valid_num);
if (p_subdev_valid_list)
IMPL_LINKKIT_FREE(p_subdev_valid_list);
#ifdef LOG_REPORT_TO_CLOUD
if (1 == report_sample)
{
send_permance_info(NULL, 0, "4", 1);
}
#endif
}
}
break;
case ITM_MSG_BATCH_LOGOUT:
{
if (payload && payload_len > 0)
{
int subdev_id = -1;
int subdev_total = 0;
int subdev_valid_num = 0;
int index = 0;
iotx_linkkit_dev_meta_info_t *p_subdev_list = (iotx_linkkit_dev_meta_info_t *)payload;
iotx_linkkit_dev_meta_info_t *p_subdev_valid_list = NULL;
subdev_total = payload_len / sizeof(iotx_linkkit_dev_meta_info_t);
p_subdev_valid_list = IMPL_LINKKIT_MALLOC(payload_len);
if (p_subdev_valid_list == NULL)
{
sdk_err("no mem");
_iotx_linkkit_mutex_unlock();
return ERROR_NO_ENOUGH_MEM;
}
for (index = 0; index < subdev_total; index++)
{
iotx_linkkit_dev_meta_info_t *p_subdev = p_subdev_list + index;
subdev_id = _iotx_linkkit_slave_open(p_subdev);
if (subdev_id > 0)
{
memcpy(p_subdev_valid_list + subdev_valid_num, p_subdev, sizeof(iotx_linkkit_dev_meta_info_t));
subdev_valid_num++;
}
else
{
sdk_err("batch logout open dn(%s) fail", p_subdev->device_name);
}
}
res = _iotx_linkkit_subdev_batch_logout(p_subdev_valid_list, subdev_valid_num);
if (p_subdev_valid_list)
IMPL_LINKKIT_FREE(p_subdev_valid_list);
#ifdef LOG_REPORT_TO_CLOUD
if (1 == report_sample)
{
send_permance_info(NULL, 0, "4", 1);
}
#endif
}
}
break;
case ITM_MSG_DELETE_TOPO: {
if (payload && payload_len == sizeof(iotx_linkkit_dev_meta_info_t)) {
int subdev_id = -1;
int ret = 0;
iotx_linkkit_dev_meta_info_t *p_subdev = (iotx_linkkit_dev_meta_info_t*)payload;
ret = iotx_dm_subdev_query(p_subdev->product_key, p_subdev->device_name, &subdev_id);
if (SUCCESS_RETURN == ret && subdev_id > 0) {
devid = subdev_id;
}
}
res = _iotx_linkkit_subdev_delete_topo(devid);
if (res != SUCCESS_RETURN) {
_iotx_linkkit_mutex_unlock();
return FAIL_RETURN;
}
}
break;
case ITM_MSG_SUBDEV_RESET:
{
if (payload && payload_len == sizeof(iotx_linkkit_dev_meta_info_t)) {
int subdev_id = -1;
int ret = 0;
iotx_linkkit_dev_meta_info_t *p_subdev = (iotx_linkkit_dev_meta_info_t*)payload;
ret = iotx_dm_subdev_query(p_subdev->product_key, p_subdev->device_name, &subdev_id);
if (SUCCESS_RETURN == ret && subdev_id > 0) {
devid = subdev_id;
}
}
res = _iotx_linkkit_subdev_reset(devid);
if (res != SUCCESS_RETURN) {
_iotx_linkkit_mutex_unlock();
return FAIL_RETURN;
}
}
break;
#endif
default: {
sdk_err("Unknown Message Type");
res = FAIL_RETURN;
}
break;
}
_iotx_linkkit_mutex_unlock();
return res;
}
int IOT_Linkkit_Query(int devid, iotx_linkkit_msg_type_t msg_type, unsigned char *payload, int payload_len)
{
int res = 0;
iotx_linkkit_ctx_t *ctx = _iotx_linkkit_get_ctx();
if (devid < 0 || msg_type < 0 || msg_type >= IOTX_LINKKIT_MSG_MAX) {
sdk_err("Invalid Parameter");
return FAIL_RETURN;
}
if (ctx->is_opened == 0 || ctx->is_connected == 0) {
return FAIL_RETURN;
}
_iotx_linkkit_mutex_lock();
switch (msg_type) {
#if !defined(DEVICE_MODEL_RAWDATA_SOLO)
case ITM_MSG_QUERY_TIMESTAMP: {
res = iotx_dm_qurey_ntp();
}
break;
#endif
case ITM_MSG_QUERY_TOPOLIST: {
#ifdef DEVICE_MODEL_GATEWAY
res = iotx_dm_query_topo_list();
#else
res = FAIL_RETURN;
#endif
}
break;
case ITM_MSG_QUERY_FOTA_DATA: {
res = iotx_dm_fota_perform_sync((char *)payload, payload_len);
}
break;
case ITM_MSG_QUERY_COTA_DATA: {
res = iotx_dm_cota_perform_sync((char *)payload, payload_len);
}
break;
case ITM_MSG_REQUEST_COTA: {
res = iotx_dm_cota_get_config("product", "file", "");
}
break;
case ITM_MSG_REQUEST_FOTA_IMAGE: {
res = iotx_dm_fota_request_image((const char *)payload, payload_len);
}
break;
#ifdef DEVICE_MODEL_GATEWAY
case ITM_MSG_QUERY_SUBDEV_ID:
{
if (payload && payload_len == sizeof(iotx_linkkit_dev_meta_info_t)) {
int subdev_id = -1;
int ret = 0;
iotx_linkkit_dev_meta_info_t *p_subdev = (iotx_linkkit_dev_meta_info_t*)payload;
ret = iotx_dm_subdev_query(p_subdev->product_key, p_subdev->device_name, &subdev_id);
if (SUCCESS_RETURN != ret) {
subdev_id = -1;
sdk_err("No subdev dn:%s", p_subdev->device_name);
}
_iotx_linkkit_mutex_unlock();
return subdev_id;
}
}
break;
#endif
default: {
sdk_err("Unknown Message Type");
res = FAIL_RETURN;
}
break;
}
_iotx_linkkit_mutex_unlock();
return res;
}
int IOT_Linkkit_TriggerEvent(int devid, char *eventid, int eventid_len, char *payload, int payload_len)
{
#if !defined(DEVICE_MODEL_RAWDATA_SOLO)
int res = 0;
iotx_linkkit_ctx_t *ctx = _iotx_linkkit_get_ctx();
if (devid < 0 || eventid == NULL || eventid_len <= 0 || payload == NULL || payload_len <= 0) {
sdk_err("Invalid Parameter");
return FAIL_RETURN;
}
if (ctx->is_opened == 0 || ctx->is_connected == 0) {
return FAIL_RETURN;
}
_iotx_linkkit_mutex_lock();
res = iotx_dm_post_event(devid, eventid, eventid_len, payload, payload_len);
_iotx_linkkit_mutex_unlock();
return res;
#else
return -1;
#endif
}
#ifdef DEVICE_MODEL_GATEWAY
#ifdef LINK_VISUAL_ENABLE
int iot_linkkit_subdev_query_id(char product_key[IOTX_PRODUCT_KEY_LEN + 1], char device_name[IOTX_DEVICE_NAME_LEN + 1])
{
int res = -1;
iotx_linkkit_ctx_t *ctx = _iotx_linkkit_get_ctx();
if (ctx->is_opened == 0) {
return res;
}
iotx_dm_subdev_query(product_key, device_name, &res);
return res;
}
#endif
#endif /* #ifdef DEVICE_MODEL_GATEWAY */
#endif
|
the_stack_data/175143711.c | /*
İki Sayının EBOB ve EKOK'unu Bulan Program
En Büyük Ortak Bölenini (Ebob) Bulma
(Her ikisini de tam bölen tam sayıların en büyüğüdür)
C program to find GCD (HCF) of two numbers using recursion
En Küçük Ortak Kat (EKOK)Bulma
C program to find LCM of two numbers using recursion
// Özyinelemeli Fonksiyon (Recursive Function)
*/
#include <stdio.h>
#include <locale.h>
int ebob(int sayi1, int sayi2)
{
if (sayi2 != 0)
{
return ebob(sayi2, sayi1 % sayi2);
}
else
{
return sayi1;
}
}
int ekok(int sayi1, int sayi2)
{
return (sayi1 * sayi2) / ebob(sayi1, sayi2);
}
int main()
{
setlocale(LC_ALL, "Turkish");
int sayi1, sayi2;
int EBOB, EKOK;
printf("İki Sayı Giriniz: \n");
scanf("%d %d", &sayi1, &sayi2);
if (sayi1 > sayi2)
{
EBOB = ebob(sayi1, sayi2);
EKOK = ekok(sayi1, sayi2);
}
else
EBOB = ebob(sayi2, sayi1);
EKOK = ekok(sayi2, sayi1);
printf("EBOB(%d,%d)= %d", sayi1, sayi2, EBOB);
printf("\nEKOK(%d,%d)= %d", sayi1, sayi2, EKOK);
return 0;
}
|
the_stack_data/766053.c | #include <stdio.h>
float fact(int);
int main() {
int n,r,C,P;
printf("Input values for n and r,where n is total number of things and r is the number of thigs taken at a time.\n: ");
scanf("%d %d",&n,&r);
P=fact(n)/fact(n-r);
C=P/fact(r);
printf("The permutation of %d things taken %d at a time is %d.\n",n,r,P);
printf("The combination of %d things taken %d at a time is %d.\n",n,r,C);
return 0;
}
float fact(int x) {
int i,b=1;
for (i=1;i<=x;i++)
b*=i;
return b;
}
|
the_stack_data/237643716.c | int function_4()
{
int a, b, c;
a = 0;
c = 98;
return a + c;
}
|
the_stack_data/89452.c | /**
* This file has no copyright assigned and is placed in the Public Domain.
* This file is part of the mingw-w64 runtime package.
* No warranty is given; refer to the file DISCLAIMER.PD within this package.
*/
#include <math.h>
float asinhf(float x)
{
if (isinf(x*x + 1)) {
if (x > 0)
return logf(2) + logf(x);
else
return -logf(2) - logf(-x);
}
return logf(x + sqrtf(x*x + 1));
}
|
the_stack_data/408532.c | #include<stdio.h>
#include<stdlib.h>
int main() {
char *animals[] = { "Bear","Dog","Monkey","Apple","Orange","Potato","Carrot","Yellow","Blue" };
char *yeh = animals[4];
while (*yeh != '\0') {
printf("%c", *(yeh++));
}
return 0;
} |
the_stack_data/61074414.c | // This file checks output given when processing C/ObjC files.
// When user selects invalid language standard
// print out supported values with short description.
// RUN: not %clang %s -std=foobar -c 2>&1 | FileCheck --match-full-lines %s
// RUN: not %clang -x objective-c %s -std=foobar -c 2>&1 | FileCheck --match-full-lines %s
// RUN: not %clang -x renderscript %s -std=foobar -c 2>&1 | FileCheck --match-full-lines %s
// CHECK: error: invalid value 'foobar' in '-std=foobar'
// CHECK-NEXT: note: use 'c89', 'c90', or 'iso9899:1990' for 'ISO C 1990' standard
// CHECK-NEXT: note: use 'iso9899:199409' for 'ISO C 1990 with amendment 1' standard
// CHECK-NEXT: note: use 'gnu89' or 'gnu90' for 'ISO C 1990 with GNU extensions' standard
// CHECK-NEXT: note: use 'c99' or 'iso9899:1999' for 'ISO C 1999' standard
// CHECK-NEXT: note: use 'gnu99' for 'ISO C 1999 with GNU extensions' standard
// CHECK-NEXT: note: use 'c11' or 'iso9899:2011' for 'ISO C 2011' standard
// CHECK-NEXT: note: use 'gnu11' for 'ISO C 2011 with GNU extensions' standard
// CHECK-NEXT: note: use 'c17', 'iso9899:2017', 'c18', or 'iso9899:2018' for 'ISO C 2017' standard
// CHECK-NEXT: note: use 'gnu17' or 'gnu18' for 'ISO C 2017 with GNU extensions' standard
// Make sure that no other output is present.
// CHECK-NOT: {{^.+$}}
|
the_stack_data/307239.c | /**
* Rudimentary C library implementation of `snprintf` and `vsnprintf`.
*
* `snprintf` takes a variable number of arguments and that isn't supported in
* Rust. So, instead, here is a really basic `snprintf` implementation, which
* is enough for Nordic Semiconductor's `libbsd` to link and run (at least for
* the parts we've tested so far).
*
* Copyright (c) 42 Technology, 2019.
* Licensed under the Blue Oak Model Licence 1.0.0
*/
/* ======================================================================== *
*
* System Includes
*
* ======================================================================== */
#include <string.h>
#include <stdbool.h>
#include <stdarg.h>
#include <stdint.h>
/* ======================================================================== *
*
* Private Function Declarations
*
* ======================================================================== */
static void write_output(
char out, char* restrict str, size_t max, size_t* written );
static char upcase(char c);
/* ======================================================================== *
*
* Macros
*
* ======================================================================== */
/**
* The longest number we can print is:
*
* -9223372036854775808
*/
#define MAXIMUM_NUMBER_LENGTH 21
/* ======================================================================== *
*
* External Function Declarations
*
* ======================================================================== */
/**
* This is provided by `itoa.rs`. It converts a signed number to a string in the
* specified radix.
*/
extern int32_t itoa(int64_t i, char* s, size_t s_len, uint8_t radix);
/**
* This is provided by `itoa.rs`. It converts an unsigned number to a string
* in the specified radix.
*/
extern int32_t utoa(uint64_t i, char* s, size_t s_len, uint8_t radix);
/* ======================================================================== *
*
* Public Function Definitions
*
* ======================================================================== */
/**
* vsnprintf - string formatting with a `va_list` into a fixed sized buffer.
*
* Supports:
*
* - d/i (decimal signed integer)
* - u (decimal unsigned integer)
* - x (hexadecimal unsigned integer)
* - c (char)
* - s (null-terminated string)
* - % (literal percent sign)
* - qualifiers: l, ll, z
*
* Does not support:
*
* - p (none)
* - p (pointer)
* - o (octal)
* - e (scientific notation with a lowercase e)
* - E (scientific notation with a capital E)
* - f (decimal floating point)
* - g (the shorter of %e and %f)
* - G (the shorter of %E and %f)
* - qualifiers: L, width, precision, -, +, space-pad, zero-pad, etc
*
* @param str the output buffer to write to
* @param size the size of the output buffer
* @param fmt the format string
* @param ap the variable number of arguments to render according to the
* format string
* @return the number of characters written to `str`
*/
int vsnprintf(
char* restrict str, size_t size, const char* restrict fmt, va_list ap )
{
size_t written = 0;
bool is_escape = false;
int is_long = 0;
bool is_size_t = false;
while ( *fmt )
{
if ( is_escape )
{
is_escape = false;
switch ( *fmt )
{
case 'z':
if ( is_long || is_size_t ) {
// not supported
return -1;
}
is_size_t = true;
is_escape = true;
break;
case 'l':
is_long++;
if ( is_long >= 3 ) {
// not supported
return -1;
}
is_escape = true;
break;
case 'u':
if ( is_size_t )
{
// Render %zu
char s[MAXIMUM_NUMBER_LENGTH] = { 0 };
size_t su = va_arg( ap, size_t );
utoa( su, s, sizeof(s), 10 );
for ( const char* p = s; *p != '\0'; p++ )
{
write_output( *p, str, size, &written );
}
}
else if ( is_long == 2 )
{
// Render %lu
char s[MAXIMUM_NUMBER_LENGTH] = { 0 };
unsigned long long ll = va_arg( ap, unsigned long long );
utoa( ll, s, sizeof(s), 10 );
for ( const char* p = s; *p != '\0'; p++ )
{
write_output( *p, str, size, &written );
}
}
else if ( is_long == 1 )
{
// Render %lu
char s[MAXIMUM_NUMBER_LENGTH] = { 0 };
unsigned long l = va_arg( ap, unsigned long );
utoa( l, s, sizeof(s), 10 );
for ( const char* p = s; *p != '\0'; p++ )
{
write_output( *p, str, size, &written );
}
}
else
{
// Render %u
unsigned int i = va_arg( ap, unsigned int );
char s[MAXIMUM_NUMBER_LENGTH] = { 0 };
utoa( i, s, sizeof(s), 10 );
for ( const char* p = s; *p != '\0'; p++ )
{
write_output( *p, str, size, &written );
}
}
break;
case 'x':
if ( is_size_t )
{
// Render %zu
char s[MAXIMUM_NUMBER_LENGTH] = { 0 };
size_t su = va_arg( ap, size_t );
utoa( su, s, sizeof(s), 16 );
for ( const char* p = s; *p != '\0'; p++ )
{
write_output( *p, str, size, &written );
}
}
else if ( is_long == 2 )
{
// Render %llu
char s[MAXIMUM_NUMBER_LENGTH] = { 0 };
unsigned long long ll = va_arg( ap, unsigned long long );
utoa( ll, s, sizeof(s), 16 );
for ( const char* p = s; *p != '\0'; p++ )
{
write_output( *p, str, size, &written );
}
}
else if ( is_long == 1 )
{
// Render %lu
char s[MAXIMUM_NUMBER_LENGTH] = { 0 };
unsigned long l = va_arg( ap, unsigned long );
utoa( l, s, sizeof(s), 16 );
for ( const char* p = s; *p != '\0'; p++ )
{
write_output( *p, str, size, &written );
}
}
else
{
// Render %u
unsigned int i = va_arg( ap, unsigned int );
char s[MAXIMUM_NUMBER_LENGTH] = { 0 };
utoa( i, s, sizeof(s), 16 );
for ( const char* p = s; *p != '\0'; p++ )
{
write_output( *p, str, size, &written );
}
}
break;
case 'X':
if ( is_size_t )
{
// Render %zu
char s[MAXIMUM_NUMBER_LENGTH] = { 0 };
size_t su = va_arg( ap, size_t );
utoa( su, s, sizeof(s), 16 );
for ( const char* p = s; *p != '\0'; p++ )
{
write_output( upcase(*p), str, size, &written );
}
}
else if ( is_long == 2 )
{
// Render %llu
char s[MAXIMUM_NUMBER_LENGTH] = { 0 };
unsigned long long ll = va_arg( ap, unsigned long long );
utoa( ll, s, sizeof(s), 16 );
for ( const char* p = s; *p != '\0'; p++ )
{
write_output( upcase(*p), str, size, &written );
}
}
else if ( is_long == 1 )
{
// Render %lu
char s[MAXIMUM_NUMBER_LENGTH] = { 0 };
unsigned long l = va_arg( ap, unsigned long );
utoa( l, s, sizeof(s), 16 );
for ( const char* p = s; *p != '\0'; p++ )
{
write_output( upcase(*p), str, size, &written );
}
}
else
{
// Render %u
unsigned int i = va_arg( ap, unsigned int );
char s[MAXIMUM_NUMBER_LENGTH] = { 0 };
utoa( i, s, sizeof(s), 16 );
for ( const char* p = s; *p != '\0'; p++ )
{
write_output( upcase(*p), str, size, &written );
}
}
break;
case 'i':
case 'd':
if ( is_long == 2 )
{
// Render %ld
char s[MAXIMUM_NUMBER_LENGTH] = { 0 };
signed long long ll = va_arg( ap, signed long long );
itoa( ll, s, sizeof(s), 10 );
for ( const char* p = s; *p != '\0'; p++ )
{
write_output( *p, str, size, &written );
}
}
else if ( is_long == 1 )
{
// Render %ld
char s[MAXIMUM_NUMBER_LENGTH] = { 0 };
signed long l = va_arg( ap, signed long );
itoa( l, s, sizeof(s), 10 );
for ( const char* p = s; *p != '\0'; p++ )
{
write_output( *p, str, size, &written );
}
}
else
{
// Render %d
signed int i = va_arg( ap, signed int );
char s[MAXIMUM_NUMBER_LENGTH] = { 0 };
itoa( i, s, sizeof(s), 10 );
for ( const char* p = s; *p != '\0'; p++ )
{
write_output( *p, str, size, &written );
}
}
break;
case 'c':
// Render %c
{
char c = (char) va_arg( ap, int );
write_output( c, str, size, &written );
}
break;
case 's':
// Render %s
{
const char *s = va_arg( ap, const char* );
for ( const char* p = s; *p != '\0'; p++ )
{
write_output( *p, str, size, &written );
}
}
break;
case '%':
write_output( '%', str, size, &written );
break;
default:
/* Ignore unknown format code */
break;
}
fmt++;
}
else
{
switch ( *fmt )
{
case '%':
is_escape = true;
is_long = 0;
is_size_t = false;
break;
default:
write_output( *fmt, str, size, &written );
break;
}
fmt++;
}
}
/* Add a terminating null (but don't count it) */
if ( written < size )
{
str[written] = '\0';
}
return (int) written;
}
/**
* snprintf - string formatting with `...` into a fixed sized buffer.
*
* Grabs the var-args as a `va_list` and calls `vsnprintf`.
*
* @param str the output buffer to write to
* @param size the size of the output buffer
* @param fmt the format string
* @param ... the variable number of arguments to render according to the
* format string
* @return the number of characters written to `str`
*/
int snprintf( char* restrict str, size_t size, const char* restrict fmt, ... )
{
va_list ap;
va_start( ap, fmt );
int result = vsnprintf( str, size, fmt, ap );
va_end( ap );
return result;
}
/* ======================================================================== *
*
* Private Function Definitions
*
* ======================================================================== */
/**
* write_output - Add a character to a bounded length buffer.
*
* If the character doesn't fit in the buffer, it is dropped, but the counter
* is still incremented.
*
* @param out the character to write
* @param str the buffer to write to
* @param written pass in the number of characters in the buffer; is increased
* by one regardless of whether we wrote to the buffer
* @param size the total size of `str`
*/
static void write_output(
char out, char* restrict str, size_t size, size_t* written )
{
// Check if it fits
if ( *written < size )
{
// Write the character
str[*written] = out;
*written = *written + 1;
}
else
{
*written = *written + 1;
}
}
/**
* Converts 'a'..'z' to 'A'..'Z', leaving all other characters unchanged.
*/
static char upcase(char c) {
if (( c >= 'a' ) && ( c <= 'z' ))
{
return (c - 'a') + 'A';
}
else
{
return c;
}
}
/* ======================================================================== *
*
* End of File
*
* ======================================================================== */
|
the_stack_data/786515.c | #include <stdio.h>
#include <stdlib.h>
void swapRows(int a, int b, int row, int col, double **AtAAtB);
void exchange(int i, int row, int col, double **AtAAtB)
{
int j;
j = i + 1;
if (AtAAtB[i][i] == 0)
{
while (j < row)
{
if (AtAAtB[j][i] != 0)
{
swapRows(i, j, row, col, AtAAtB);
return;
}
j++;
}
}
}
|
the_stack_data/175142499.c | #include <stdio.h>
#include <ctype.h>
#include <string.h>
/* #define DEBUG */
FILE *efopen (char *file, char *mode);
char *progname;
main(argc, argv)
int argc;
char *argv[];
{
FILE *f1, *f2, *efopen();
int i, len;
progname = argv[0];
if (argc != 2) {
fprintf(stderr, "Usage: dump file1 \n");
exit(1);
}
f1 = efopen(argv[1], "r");
dump(f1);
exit(1);
}
FILE *efopen(file, mode) /* fopen file, die if can't */
char *file, *mode;
{
FILE *fp, *fopen();
if ((fp = fopen(file, mode)) != NULL)
return fp;
fprintf(stderr, "%s: Can't open file %s mode %s\n",
progname, file, mode);
exit(1);
}
int dump (f1)
FILE *f1;
{
char inbuf[BUFSIZ], outbuf[BUFSIZ], *o;
int i, size, count = 0;
while (fgets(inbuf, sizeof inbuf, f1) != NULL) {
printf ("\n Record %d \n %s \n", ++count, inbuf);
size = strlen(inbuf);
for (i = 0; i < size; i++)
printf (" inbuf[%d] = %c %d \n", i, inbuf[i], inbuf[i]);
}
}
|
the_stack_data/67326407.c | // SPDX-License-Identifier: Apache-2.0
// Copyright 2019 Eotvos Lorand University, Budapest, Hungary
#if T4P4S_INIT_CRYPTO
#include "dpdkx_crypto.h"
#include "aliases.h"
#include <stdlib.h>
#include <rte_dev.h>
#include <error.h>
#include <util_debug.h>
#include <unistd.h>
#include <iso646.h>
extern struct lcore_conf lcore_conf[RTE_MAX_LCORE];
const char* crypto_task_type_names[] = {
"ENCRYPT",
"DECRYPT",
"MD5_HMAC",
};
struct rte_mempool *session_pool, *session_priv_pool;
int cdev_id;
struct rte_cryptodev_sym_session *session_encrypt;
struct rte_cryptodev_sym_session *session_decrypt;
struct rte_cryptodev_sym_session *session_hmac;
uint8_t iv[16];
struct rte_mempool *crypto_task_pool;
crypto_task_s *crypto_tasks[RTE_MAX_LCORE][CRYPTO_BURST_SIZE];
struct rte_mempool *rte_crypto_op_pool;
struct rte_crypto_op* enqueued_rte_crypto_ops[RTE_MAX_LCORE][CRYPTO_BURST_SIZE];
struct rte_crypto_op* dequeued_rte_crypto_ops[RTE_MAX_LCORE][CRYPTO_BURST_SIZE];
// -----------------------------------------------------------------------------
// Helper functions
void reset_pd(packet_descriptor_t *pd)
{
pd->parsed_size = 0;
if(pd->wrapper == 0){
pd->payload_size = 0;
}else{
pd->payload_size = rte_pktmbuf_pkt_len(pd->wrapper) - pd->parsed_size;
}
pd->deparse_hdrinst_count = 0;
pd->is_deparse_reordering = false;
}
void debug_crypto_task(crypto_task_s *op) {
#ifdef T4P4S_DEBUG
dbg_mbuf(op->data, " " T4LIT(<<<<,outgoing) " Sending packet to " T4LIT(crypto device,outgoing) " for " T4LIT(%s,extern) " operation", crypto_task_type_names[op->type])
uint8_t* buf = rte_pktmbuf_mtod(op->data, uint8_t*);
dbg_bytes(buf, sizeof(uint32_t), " :: Size info (" T4LIT(%luB) "): ", sizeof(uint32_t));
dbg_bytes(buf + op->offset, op->plain_length_to_encrypt, " :: Data (" T4LIT(%dB) ") : ", op->plain_length_to_encrypt);
debug(" :: plain_length_to_encrypt: %d\n",op->plain_length_to_encrypt);
debug(" :: offset: %d\n",op->offset);
debug(" :: padding_length: %d\n",op->padding_length);
#endif
}
// -----------------------------------------------------------------------------
// Crypto operations
int prepare_symmetric_ecnryption_op(crypto_task_s *task, struct rte_crypto_op *crypto_op) {
crypto_op->sym->m_src = task->data;
crypto_op->sym->cipher.data.offset = task->offset;
crypto_op->sym->cipher.data.length = task->plain_length_to_encrypt;
uint8_t *iv_ptr = rte_crypto_op_ctod_offset(crypto_op, uint8_t *, IV_OFFSET);
memcpy(iv_ptr, iv, AES_CBC_IV_LENGTH);
switch(task->type)
{
case CRYPTO_TASK_ENCRYPT:
rte_crypto_op_attach_sym_session(crypto_op, session_encrypt);
break;
case CRYPTO_TASK_DECRYPT:
rte_crypto_op_attach_sym_session(crypto_op, session_decrypt);
break;
default:
return 1;
}
return 0;
}
void process_symmetric_encryption_result(crypto_task_type_e task_type, packet_descriptor_t *pd) {
unsigned int lcore_id = rte_lcore_id();
struct rte_mbuf *mbuf = dequeued_rte_crypto_ops[lcore_id][0]->sym->m_src;
uint32_t packet_size = *(rte_pktmbuf_mtod(mbuf, uint32_t*));
// Remove the saved packet size from the begining
rte_pktmbuf_adj(mbuf, sizeof(int));
pd->wrapper = mbuf;
pd->data = rte_pktmbuf_mtod(pd->wrapper, uint8_t*);
pd->wrapper->pkt_len = packet_size;
dbg_bytes(pd->data, packet_size,
" " T4LIT( >> >> , incoming) " Result of " T4LIT(%s, extern) " crypto operation (" T4LIT(%dB) "): ",
crypto_task_type_names[task_type], rte_pktmbuf_pkt_len(pd->wrapper));
}
void prepare_hmac_op(crypto_task_s *task, struct rte_crypto_op *crypto_op) {
crypto_op->sym->auth.digest.data = (uint8_t *)rte_pktmbuf_append(task->data, MD5_DIGEST_LEN);
crypto_op->sym->auth.data.offset = task->offset;
crypto_op->sym->auth.data.length = task->plain_length_to_encrypt;
rte_crypto_op_attach_sym_session(crypto_op, session_hmac);
crypto_op->sym->m_src = task->data;
}
void process_hmac_result(crypto_task_type_e task_type, packet_descriptor_t *pd,
crypto_task_s *crypto_task) {
unsigned int lcore_id = rte_lcore_id();
uint8_t* wrapper_pointer = rte_pktmbuf_mtod(pd->wrapper, uint8_t*);
uint32_t target_relative = crypto_task->offset +
crypto_task->plain_length_to_encrypt;
uint8_t* target = wrapper_pointer + target_relative;
if (dequeued_rte_crypto_ops[lcore_id][0]->sym->m_dst) {
uint8_t *auth_tag = rte_pktmbuf_mtod_offset(dequeued_rte_crypto_ops[lcore_id][0]->sym->m_dst, uint8_t *,
crypto_task->padding_length);
memmove(target,auth_tag,MD5_DIGEST_LEN);
rte_pktmbuf_trim(pd->wrapper,crypto_task->padding_length);
}else {
uint8_t from_relative = crypto_task->offset +
crypto_task->plain_length_to_encrypt +
crypto_task->padding_length;
uint8_t* from_position = wrapper_pointer + from_relative;
memmove(target,from_position,MD5_DIGEST_LEN);
rte_pktmbuf_trim(pd->wrapper,crypto_task->padding_length);
}
rte_pktmbuf_adj(pd->wrapper, sizeof(int));
dbg_bytes(rte_pktmbuf_mtod(pd->wrapper, uint8_t*), rte_pktmbuf_pkt_len(pd->wrapper),
" " T4LIT( >> >> , incoming) " Result of " T4LIT(%s, extern) " crypto operation (" T4LIT(%dB) "): ",
crypto_task_type_names[task_type], rte_pktmbuf_pkt_len(pd->wrapper));
}
int process_crypto_op_result(crypto_task_type_e task_type, packet_descriptor_t *pd,
crypto_task_s *crypto_task) {
unsigned int lcore_id = rte_lcore_id();
int ret = 0;
switch(task_type){
case CRYPTO_TASK_MD5_HMAC:
process_hmac_result(task_type, pd, crypto_task);
break;
case CRYPTO_TASK_ENCRYPT:
case CRYPTO_TASK_DECRYPT:
process_symmetric_encryption_result(task_type, pd);
break;
default:
ret = 1;
break;
}
return ret;
}
void crypto_task_to_rte_crypto_op(crypto_task_s *task, struct rte_crypto_op *crypto_op)
{
if(task->type == CRYPTO_TASK_MD5_HMAC){
prepare_hmac_op(task, crypto_op);
}else {
prepare_symmetric_ecnryption_op(task, crypto_op);
}
}
// -----------------------------------------------------------------------------
// General functions
crypto_task_s* create_crypto_task(crypto_task_s **task_out, packet_descriptor_t* pd, crypto_task_type_e task_type, int offset, void* extraInformationForAsyncHandling){
int ret = rte_mempool_get(crypto_task_pool, (void**)task_out);
if(ret < 0){
rte_exit(EXIT_FAILURE, "Mempool get failed!\n");
//TODO: it should be a packet drop, not total fail
}
crypto_task_s *task = *task_out;
task->type = task_type;
task->data = pd->wrapper;
task->offset = offset;
task->original_plain_length = task->data->pkt_len;
task->plain_length_to_encrypt = task->data->pkt_len - task->offset;
#if ASYNC_MODE == ASYNC_MODE_CONTEXT
if(extraInformationForAsyncHandling != NULL){
void* context = extraInformationForAsyncHandling;
rte_pktmbuf_prepend(task->data, sizeof(void*));
*(rte_pktmbuf_mtod(task->data, void**)) = context;
task->offset += sizeof(void*);
}
#elif ASYNC_MODE == ASYNC_MODE_PD
packet_descriptor_t *store_pd = extraInformationForAsyncHandling;
*store_pd = *pd;
rte_pktmbuf_prepend(task->data, sizeof(packet_descriptor_t*));
*(rte_pktmbuf_mtod(task->data, packet_descriptor_t**)) = store_pd;
task->offset += sizeof(void**);
#endif
rte_pktmbuf_prepend(task->data, sizeof(uint32_t));
*(rte_pktmbuf_mtod(task->data, uint32_t*)) = task->original_plain_length;
task->offset += sizeof(uint32_t);
task->padding_length = (16 - task->plain_length_to_encrypt % 16) % 16;
if(task->padding_length){
void* padding_memory = rte_pktmbuf_append(task->data, task->padding_length);
memset(padding_memory, 0, task->padding_length);
}
return task;
}
int enqueue_crypto_ops(uint16_t number_of_ops){
unsigned int lcore_id = rte_lcore_id();
#ifdef START_CRYPTO_NODE
return rte_ring_enqueue_burst(lcore_conf[lcore_id].fake_crypto_rx, enqueued_rte_crypto_ops[lcore_id], number_of_ops, NULL);
#else
return rte_cryptodev_enqueue_burst(cdev_id, lcore_id, enqueued_rte_crypto_ops[lcore_id], number_of_ops);
#endif
}
void dequeue_crypto_ops_blocking(uint16_t number_of_ops){
unsigned int lcore_id = rte_lcore_id();
#ifdef START_CRYPTO_NODE
while(rte_ring_dequeue_burst(lcore_conf[lcore_id].fake_crypto_tx, (void**)dequeued_rte_crypto_ops[lcore_id], number_of_ops, NULL) == 0);
#else
while(rte_cryptodev_dequeue_burst(cdev_id, lcore_id, dequeued_rte_crypto_ops[lcore_id], number_of_ops) == 0);
#endif
}
void execute_task_blocking(crypto_task_type_e task_type, packet_descriptor_t *pd, unsigned int lcore_id,
crypto_task_s* crypto_task) {
debug_crypto_task(crypto_task);
if (rte_crypto_op_bulk_alloc(rte_crypto_op_pool, RTE_CRYPTO_OP_TYPE_SYMMETRIC, &enqueued_rte_crypto_ops[lcore_id][0], 1) == 0){
rte_exit(EXIT_FAILURE, "Not enough crypto operations available\n");
}
crypto_task_to_rte_crypto_op(crypto_task, enqueued_rte_crypto_ops[lcore_id][0]);
rte_mempool_put_bulk(crypto_task_pool, (void**) &crypto_task, 1);
if(enqueue_crypto_ops(1) == 0){
debug(" " T4LIT(!!!!,error) " " T4LIT(Enqueue ops in blocking sync task_type failed... skipping encryption,error) "\n");
return;
}
dequeue_crypto_ops_blocking(1);
if(process_crypto_op_result(task_type, pd, crypto_task) > 0){
debug(" " T4LIT(!!!!,error) " " T4LIT((*task_type) not found ... skipping,error) "\n");
}
rte_mempool_put_bulk(rte_crypto_op_pool, (void **)dequeued_rte_crypto_ops[lcore_id], 1);
reset_pd(pd);
}
void do_crypto_operation(crypto_task_type_e task_type, int offset, SHORT_STDPARAMS){
// deparse_packet(SHORT_STDPARAMS_IN);
// pd->is_deparse_reordering = false;
unsigned int lcore_id = rte_lcore_id();
crypto_task_s* crypto_task = create_crypto_task(&crypto_tasks[lcore_id][0], pd, task_type, offset, NULL);
execute_task_blocking(task_type, pd, lcore_id, crypto_task);
}
#endif
|
the_stack_data/69114.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <CL/cl.h>
unsigned char *read_buffer(char *file_name, size_t *size_ptr)
{
FILE *f;
unsigned char *buf;
size_t size;
/* Open file */
f = fopen(file_name, "rb");
if (!f)
return NULL;
/* Obtain file size */
fseek(f, 0, SEEK_END);
size = ftell(f);
fseek(f, 0, SEEK_SET);
/* Allocate and read buffer */
buf = malloc(size + 1);
fread(buf, 1, size, f);
buf[size] = '\0';
/* Return size of buffer */
if (size_ptr)
*size_ptr = size;
/* Return buffer */
return buf;
}
void write_buffer(char *file_name, const char *buffer, size_t buffer_size)
{
FILE *f;
/* Open file */
f = fopen(file_name, "w+");
/* Write buffer */
if(buffer)
fwrite(buffer, 1, buffer_size, f);
/* Close file */
fclose(f);
}
int main(int argc, char const *argv[])
{
/* Get platform */
cl_platform_id platform;
cl_uint num_platforms;
cl_int ret = clGetPlatformIDs(1, &platform, &num_platforms);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetPlatformIDs' failed\n");
exit(1);
}
printf("Number of platforms: %d\n", num_platforms);
printf("platform=%p\n", platform);
/* Get platform name */
char platform_name[100];
ret = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(platform_name), platform_name, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetPlatformInfo' failed\n");
exit(1);
}
printf("platform.name='%s'\n\n", platform_name);
/* Get device */
cl_device_id device;
cl_uint num_devices;
ret = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, &num_devices);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetDeviceIDs' failed\n");
exit(1);
}
printf("Number of devices: %d\n", num_devices);
printf("device=%p\n", device);
/* Get device name */
char device_name[100];
ret = clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(device_name),
device_name, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clGetDeviceInfo' failed\n");
exit(1);
}
printf("device.name='%s'\n", device_name);
printf("\n");
/* Create a Context Object */
cl_context context;
context = clCreateContext(NULL, 1, &device, NULL, NULL, &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clCreateContext' failed\n");
exit(1);
}
printf("context=%p\n", context);
/* Create a Command Queue Object*/
cl_command_queue command_queue;
command_queue = clCreateCommandQueue(context, device, 0, &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clCreateCommandQueue' failed\n");
exit(1);
}
printf("command_queue=%p\n", command_queue);
printf("\n");
/* Program source */
unsigned char *source_code;
size_t source_length;
/* Read program from 'pre_decrement_float16.cl' */
source_code = read_buffer("pre_decrement_float16.cl", &source_length);
/* Create a program */
cl_program program;
program = clCreateProgramWithSource(context, 1, (const char **)&source_code, &source_length, &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clCreateProgramWithSource' failed\n");
exit(1);
}
printf("program=%p\n", program);
/* Build program */
ret = clBuildProgram(program, 1, &device, NULL, NULL, NULL);
if (ret != CL_SUCCESS )
{
size_t size;
char *log;
/* Get log size */
clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,0, NULL, &size);
/* Allocate log and print */
log = malloc(size);
clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,size, log, NULL);
printf("error: call to 'clBuildProgram' failed:\n%s\n", log);
/* Free log and exit */
free(log);
exit(1);
}
printf("program built\n");
printf("\n");
/* Create a Kernel Object */
cl_kernel kernel;
kernel = clCreateKernel(program, "pre_decrement_float16", &ret);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clCreateKernel' failed\n");
exit(1);
}
/* Create and allocate host buffers */
size_t num_elem = 10;
/* Create and init host side src buffer 0 */
cl_float16 *src_0_host_buffer;
src_0_host_buffer = malloc(num_elem * sizeof(cl_float16));
for (int i = 0; i < num_elem; i++)
src_0_host_buffer[i] = (cl_float16){{2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0}};
/* Create and init device side src buffer 0 */
cl_mem src_0_device_buffer;
src_0_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_float16), NULL, &ret);
if (ret != CL_SUCCESS)
{
printf("error: could not create source buffer\n");
exit(1);
}
ret = clEnqueueWriteBuffer(command_queue, src_0_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_float16), src_0_host_buffer, 0, NULL, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clEnqueueWriteBuffer' failed\n");
exit(1);
}
/* Create host dst buffer */
cl_float16 *dst_host_buffer;
dst_host_buffer = malloc(num_elem * sizeof(cl_float16));
memset((void *)dst_host_buffer, 1, num_elem * sizeof(cl_float16));
/* Create device dst buffer */
cl_mem dst_device_buffer;
dst_device_buffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY, num_elem *sizeof(cl_float16), NULL, &ret);
if (ret != CL_SUCCESS)
{
printf("error: could not create dst buffer\n");
exit(1);
}
/* Set kernel arguments */
ret = CL_SUCCESS;
ret |= clSetKernelArg(kernel, 0, sizeof(cl_mem), &src_0_device_buffer);
ret |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &dst_device_buffer);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clSetKernelArg' failed\n");
exit(1);
}
/* Launch the kernel */
size_t global_work_size = num_elem;
size_t local_work_size = num_elem;
ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clEnqueueNDRangeKernel' failed\n");
exit(1);
}
/* Wait for it to finish */
clFinish(command_queue);
/* Read results from GPU */
ret = clEnqueueReadBuffer(command_queue, dst_device_buffer, CL_TRUE,0, num_elem * sizeof(cl_float16), dst_host_buffer, 0, NULL, NULL);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clEnqueueReadBuffer' failed\n");
exit(1);
}
/* Dump dst buffer to file */
char dump_file[100];
sprintf((char *)&dump_file, "%s.result", argv[0]);
write_buffer(dump_file, (const char *)dst_host_buffer, num_elem * sizeof(cl_float16));
printf("Result dumped to %s\n", dump_file);
/* Free host dst buffer */
free(dst_host_buffer);
/* Free device dst buffer */
ret = clReleaseMemObject(dst_device_buffer);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseMemObject' failed\n");
exit(1);
}
/* Free host side src buffer 0 */
free(src_0_host_buffer);
/* Free device side src buffer 0 */
ret = clReleaseMemObject(src_0_device_buffer);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseMemObject' failed\n");
exit(1);
}
/* Release kernel */
ret = clReleaseKernel(kernel);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseKernel' failed\n");
exit(1);
}
/* Release program */
ret = clReleaseProgram(program);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseProgram' failed\n");
exit(1);
}
/* Release command queue */
ret = clReleaseCommandQueue(command_queue);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseCommandQueue' failed\n");
exit(1);
}
/* Release context */
ret = clReleaseContext(context);
if (ret != CL_SUCCESS)
{
printf("error: call to 'clReleaseContext' failed\n");
exit(1);
}
return 0;
} |
the_stack_data/111078695.c | /*
* Copyright (C) 2007 Nokia Corporation.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Author: Adrian Hunter
*/
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <errno.h>
struct child_info {
struct child_info *next;
pid_t pid;
int terminated;
int killed;
int gone;
};
struct child_info *children = 0;
static void kill_children(void)
{
struct child_info *child;
child = children;
while (child) {
if (!child->gone) {
if (!child->terminated) {
child->terminated = 1;
kill(child->pid, SIGTERM);
} /*else if (!child->killed) {
child->killed = 1;
kill(child->pid, SIGKILL);
}*/
}
child = child->next;
}
}
static void add_child(pid_t child_pid)
{
struct child_info *child;
size_t sz;
sz = sizeof(struct child_info);
child = (struct child_info *) malloc(sz);
memset(child, 0, sz);
child->pid = child_pid;
child->next = children;
children = child;
}
static void mark_child_gone(pid_t child_pid)
{
struct child_info *child;
child = children;
while (child) {
if (child->pid == child_pid) {
child->gone = 1;
break;
}
child = child->next;
}
}
static int have_children(void)
{
struct child_info *child;
child = children;
while (child) {
if (!child->gone)
return 1;
child = child->next;
}
return 0;
}
static int parse_command_line(char *cmdline, int *pargc, char ***pargv)
{
char **tmp;
char *p, *v, *q;
size_t sz;
int argc = 0;
int state = 0;
char *argv[1024];
if (!cmdline)
return 1;
q = v = (char *) malloc(strlen(cmdline) + 1024);
if (!v)
return 1;
p = cmdline;
for (;;) {
char c = *p++;
if (!c) {
*v++ = 0;
break;
}
switch (state) {
case 0: /* Between args */
if (isspace(c))
break;
argv[argc++] = v;
if (c == '"') {
state = 2;
break;
} else if (c == '\'') {
state = 3;
break;
}
state = 1;
/* fall-through */
case 1: /* Not quoted */
if (c == '\\') {
if (*p)
*v++ = *p;
} else if (isspace(c)) {
*v++ = 0;
state = 0;
} else
*v++ = c;
break;
case 2: /* Double quoted */
if (c == '\\' && *p == '"') {
*v++ = '"';
++p;
} else if (c == '"') {
*v++ = 0;
state = 0;
} else
*v++ = c;
break;
case 3: /* Single quoted */
if (c == '\'') {
*v++ = 0;
state = 0;
} else
*v++ = c;
break;
}
}
argv[argc] = 0;
sz = sizeof(char *) * (argc + 1);
tmp = (char **) malloc(sz);
if (!tmp) {
free(q);
return 1;
}
if (argc == 0)
free(q);
memcpy(tmp, argv, sz);
*pargc = argc;
*pargv = tmp;
return 0;
}
static void signal_handler(int signum)
{
(void)signum;
kill_children();
}
int result = 0;
int alarm_gone_off = 0;
static void alarm_handler(int signum)
{
(void)signum;
if (!result)
alarm_gone_off = 1;
kill_children();
}
int main(int argc, char *argv[], char **env)
{
int p;
pid_t child_pid;
int status;
int duration = 0;
p = 1;
if (argc > 1) {
if (strncmp(argv[p], "--help", 6) == 0 ||
strncmp(argv[p], "-h", 2) == 0) {
printf( "Usage is: "
"fstest_monitor options programs...\n"
" Options are:\n"
" -h, --help "
"This help message\n"
" -d, --duration arg "
"Stop after arg seconds\n"
"\n"
"Run programs and wait for them."
" If duration is specified,\n"
"kill all programs"
" after that number of seconds have elapsed.\n"
"Example: "
"fstest_monitor \"/bin/ls -l\" /bin/date\n"
);
return 1;
}
if (strncmp(argv[p], "--duration", 10) == 0 ||
strncmp(argv[p], "-d", 2) == 0) {
char *s;
if (p+1 < argc && !isdigit(argv[p][strlen(argv[p])-1]))
++p;
s = argv[p];
while (*s && !isdigit(*s))
++s;
duration = atoi(s);
++p;
}
}
signal(SIGTERM, signal_handler);
signal(SIGINT, signal_handler);
for (; p < argc; ++p) {
child_pid = fork();
if (child_pid) {
/* Parent */
if (child_pid == (pid_t) -1) {
kill_children();
result = 1;
break;
}
add_child(child_pid);
} else {
/* Child */
int cargc;
char **cargv;
if (parse_command_line(argv[p], &cargc, &cargv))
return 1;
execve(cargv[0], cargv, env);
return 1;
}
}
if (!result && duration > 0) {
signal(SIGALRM, alarm_handler);
alarm(duration);
}
while (have_children()) {
status = 0;
child_pid = wait(&status);
if (child_pid == (pid_t) -1) {
if (errno == EINTR)
continue;
kill_children();
return 1;
}
mark_child_gone(child_pid);
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
result = 1;
kill_children();
}
}
if (alarm_gone_off)
return 0;
return result;
}
|
the_stack_data/167331409.c | /*
* myint.c - Another handy routine for testing your tiny shell
*
* usage: myint <n>
* Sleeps for <n> seconds and sends SIGINT to itself.
*
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
int main(int argc, char **argv)
{
int i, secs;
pid_t pid;
if (argc != 2) {
fprintf(stderr, "Usage: %s <n>\n", argv[0]);
exit(0);
}
secs = atoi(argv[1]);
for (i=0; i < secs; i++)
sleep(1);
pid = getpid();
if (kill(pid, SIGINT) < 0)
fprintf(stderr, "kill (int) error");
exit(0);
}
|
the_stack_data/23575956.c | /*
** is_digit.c for in /home/thebau-j/rendu/blowshitup/ServerZappy/server/utils
**
** Made by
** Login <[email protected]>
**
** Started on Sun Jul 13 16:07:31 2014
** Last update Sun Jul 13 16:07:33 2014
*/
#include <stdbool.h>
bool is_digit(char *str)
{
int i;
i = -1;
if ((!str) || str[0] == '\0')
return (false);
while (str[++i])
if (str[i] < '0' || str[i] > '9')
return (false);
return (true);
}
|
the_stack_data/8591.c |
/***************************************************************************
*
* Programmers and Purdue Email Addresses:
* 1. [email protected]
* 2. [email protected]
* 3. [email protected] (delete line if no third partner)
*
* Lab #:
*
* Academic Integrity Statement:
*
* We have not used source code obtained from any other unauthorized source,
* either modified or unmodified. Neither have we provided access to our code
* to another. The effort we are submitting is our own original work.
*
* Day, Time, Location of Lab:
*
* Program Description:
*
***************************************************************************/
#include <stdio.h>
#include <math.h>
// Global Declarations
void inputValue(int*, int*);
int calcMonth(int, int);
int calcDate_in_month(int, int, int, int*);
int calcLastDec31(int);
int calcDay_of_week(int, int);
int calcOrdinal_numeral(int);
void outputResult(int, int, int, int, int);
int main()
{
// Local declarations
int year_given;
int day_given;
int month_calculated;
int date_in_month;
int days_before_calculated_month;
int day_of_week_of_last_Dec31;
int day_of_week_of_given_day;
int numeral_of_given_day;
// Statements
inputValue(&year_given, &day_given);
month_calculated = calcMonth(year_given, day_given);
date_in_month = calcDate_in_month(month_calculated, day_given, year_given, &days_before_calculated_month);
day_of_week_of_last_Dec31 = calcLastDec31(year_given);
day_of_week_of_given_day = calcDay_of_week(day_of_week_of_last_Dec31, day_given);
numeral_of_given_day = calcOrdinal_numeral(date_in_month);
outputResult(month_calculated, date_in_month, year_given, numeral_of_given_day, day_of_week_of_given_day);
return(0);
}
/***************************************************************************
*
* Function Information
*
* Name of Function:
*
* Function Return Type:
*
* Parameters (list data type, name, and comment one per line):
* 1.
* 2.
* 3.
*
* Function Description:
*
***************************************************************************/
void inputValue(int* add_y_given, int* add_d_given)
{
// Local Declarations
int leapyear;
// Statements
printf("Enter the year -> ");
scanf("%d", add_y_given);
leapyear = (!(*add_y_given % 4) && (*add_y_given % 100)) || !(*add_y_given % 400);
printf("Enter day number of year (1-%d) -> ", 365 + leapyear);
scanf("%d", add_d_given);
}
/***************************************************************************
*
* Function Information
*
* Name of Function:
*
* Function Return Type:
*
* Parameters (list data type, name, and comment one per line):
* 1.
* 2.
* 3.
*
* Function Description:
*
***************************************************************************/
int calcMonth(int y_given, int d_given)
{
// Local Declarations
int leapyear;
int calculated_month;
// Statements
leapyear = (!(y_given % 4) && (y_given % 100)) || !(y_given % 400);
/***********************************************************************
This selection helps to calculate the month based on given day
************************************************************************/
if (d_given > 334 + leapyear)
{
calculated_month = 12;
}
else if (334 + leapyear >= d_given && d_given > 304 + leapyear)
{
calculated_month = 11;
}
else if (304 + leapyear >= d_given && d_given > 273 + leapyear)
{
calculated_month = 10;
}
else if (273 + leapyear >= d_given && d_given > 243 + leapyear)
{
calculated_month = 9;
}
else if (243 + leapyear >= d_given && d_given > 212 + leapyear)
{
calculated_month = 8;
}
else if (212 + leapyear >= d_given && d_given > 181 + leapyear)
{
calculated_month = 7;
}
else if (181 + leapyear >= d_given && d_given > 151 + leapyear)
{
calculated_month = 6;
}
else if (151 + leapyear >= d_given && d_given > 120 + leapyear)
{
calculated_month = 5;
}
else if (120 + leapyear >= d_given && d_given > 90 + leapyear)
{
calculated_month = 4;
}
else if (90 + leapyear >= d_given && d_given > 59 + leapyear)
{
calculated_month = 3;
}
else if (59 + leapyear >= d_given && d_given > 31)
{
calculated_month = 2;
}
else
{
calculated_month = 1;
}
return(calculated_month);
}
/***************************************************************************
*
* Function Information
*
* Name of Function:
*
* Function Return Type:
*
* Parameters (list data type, name, and comment one per line):
* 1.
* 2.
* 3.
*
* Function Description:
*
***************************************************************************/
int calcDate_in_month(int calc_month, int d_given, int y_given, int* d_before_month)
{
// Local Declarations
int leap;
int days_before_month = 0;
int date;
// Statements
leap = (!(y_given % 4) && (y_given % 100)) || !(y_given % 400);
/***********************************************************************
This switch helps to calculate the days before the input month
************************************************************************/
switch(calc_month - 1)
{
case 11: days_before_month += 30;
case 10: days_before_month += 31;
case 9: days_before_month += 30;
case 8: days_before_month += 31;
case 7: days_before_month += 31;
case 6: days_before_month += 30;
case 5: days_before_month += 31;
case 4: days_before_month += 30;
case 3: days_before_month += 31;
case 2: days_before_month += 28 + leap;
case 1: days_before_month += 31;
}
*d_before_month = days_before_month;
date = d_given - days_before_month;
return(date);
}
/***************************************************************************
*
* Function Information
*
* Name of Function: calcLastDec31
*
* Function Return Type: int
*
* Parameters (list data type, name, and comment one per line):
* 1. int, year_input // the value of given year
*
* Function Description: calculate the day of week of last year's December 31th
*
***************************************************************************/
int calcLastDec31(int y_given)
{
// Local Declarations
int d_lastDec31; // the day of week of last year's December 31th
// Statements
d_lastDec31 = (( y_given - 1) * 365 + (y_given - 1) / 4 - (y_given - 1) / 100 + (y_given - 1) / 400) % 7;
return( d_lastDec31);
}
/***************************************************************************
*
* Function Information
*
* Name of Function:
*
* Function Return Type:
*
* Parameters (list data type, name, and comment one per line):
* 1.
* 2.
* 3.
*
* Function Description:
*
***************************************************************************/
int calcDay_of_week(int d_lastDec31, int d_given)
{
// Local Declarations
int day_of_week;
// Statements
day_of_week = d_given % 7 + d_lastDec31;
return(day_of_week);
}
/***************************************************************************
*
* Function Information
*
* Name of Function:
*
* Function Return Type:
*
* Parameters (list data type, name, and comment one per line):
* 1.
* 2.
* 3.
*
* Function Description:
*
***************************************************************************/
int calcOrdinal_numeral(int d_in_month)
{
// Local Declarations
int num;
// Statements
num = (d_in_month - 1) / 7 + 1;
return(num);
}
/***************************************************************************
*
* Function Information
*
* Name of Function:
*
* Function Return Type:
*
* Parameters (list data type, name, and comment one per line):
* 1.
* 2.
* 3.
*
* Function Description:
*
***************************************************************************/
void outputResult(int calc_month, int d_in_month, int y_given, int num, int day_of_week)
{
// Statements
printf("\nDate: ");
switch(calc_month)
{
case 12: printf("December");
break;
case 11: printf("November");
break;
case 10: printf("October");
break;
case 9: printf("September");
break;
case 8: printf("August");
break;
case 7: printf("July");
break;
case 6: printf("June");
break;
case 5: printf("May");
break;
case 4: printf("April");
break;
case 3: printf("March");
break;
case 2: printf("February");
break;
case 1: printf("January");
break;
}
printf(" %d, %d\n", d_in_month, y_given);
printf("Occurrence: ");
switch(num)
{
case 5: printf("5th ");
break;
case 4: printf("4th ");
break;
case 3: printf("3rd ");
break;
case 2: printf("2nd ");
break;
case 1: printf("1st ");
break;
}
switch(day_of_week)
{
case 0: printf("Sunday\n");
break;
case 6: printf("Saturday\n");
break;
case 5: printf("Friday\n");
break;
case 4: printf("Thursday\n");
break;
case 3: printf("Wednesday\n");
break;
case 2: printf("Tuesday\n");
break;
case 1: printf("Monday\n");
break;
}
}
|
the_stack_data/170453373.c | #include <stdbool.h>
#define T(t) (t*)0;
#define C(n) switch(n){case n:;}
static void f()
{
T(bool)
C(true)
C(false)
C(__bool_true_false_are_defined)
}
|
the_stack_data/50496.c | #ifdef EMBED
static unsigned int _seed;
void srandom(unsigned int seed)
{
_seed = seed;
}
long random(void)
{
_seed += 13;
return((_seed * (_seed + 1)) | (_seed << (_seed % 30)));
}
#endif /* EMBED */
|
the_stack_data/150142876.c | #include<stdio.h>
#include<string.h>
#define maxn 10000
char num[maxn];
void add(){
char temp[maxn];
int i=0,j,k=0;
int c=0,sum;
for(j=strlen(num)-1;j>=0;){
sum=num[i]+num[j]+c-96;
c=sum/10;
sum=sum%10;
temp[k++]=sum+'0';
j--;
i++;
}
if(c==1){
temp[k++]='1';
}
for(i=0,j=k-1;j>=0;){
num[i]=temp[j];
i++;
j--;
}
num[k]=0;
return;
}
int check(){
int i=0,j;
j=strlen(num)-1;
while(i<j){
if(num[i]!=num[j]){
return 0;
}
i++;
j--;
}
return 1;
}
int main(){
int n,i=0;
scanf("%s %d",&num,&n);
while(i<n){
if(check()){
break;
}else{
i++;
add();
}
}
printf("%s\n%d\n",num,i);
}
|
the_stack_data/167330781.c | // Exercise 6 from chapter 9
// This program is a rewrite of program 9.4. The dateUpdate function uses compound literals.
#include<stdio.h>
#include<stdbool.h>
struct date
{
int month;
int day;
int year;
};
// Function to calculate tomorrow's date
struct date dateUpdate( struct date today )
{
struct date tomorrow;
int numberOfDays( struct date d );
if( today.day != numberOfDays( today ) )
{
tomorrow = ( struct date ){ today.month, today.day + 1, today.year };
}
else if( today.month == 12 ) // end of the year
{
tomorrow = ( struct date ){ 1, 1, today.year + 1 };
}
else // end of month
{
tomorrow = ( struct date ){ today.month + 1, 1, today.year };
}
return tomorrow;
}
// Function to find the number of days in a month
int numberOfDays( struct date d )
{
int days;
bool isLeapYear( struct date d );
const int daysPerMonth[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if( isLeapYear( d ) && d.month == 2 )
days = 29;
else
days = daysPerMonth[d.month - 1];
return days;
}
// Function to determine if it's a leap year
bool isLeapYear( struct date d )
{
bool leapYearFlag;
if( ( d.year % 4 == 0 && d.year % 100 != 0 ) || d.year % 400 == 0 )
leapYearFlag = true; // It's a leap year
else
leapYearFlag = false; // Not a leap year
return leapYearFlag;
}
int main( void )
{
struct date dateUpdate( struct date today );
struct date thisDay, nextDay;
printf( "Enter today's date (mm dd yyyy): " );
scanf( "%i%i%i", &thisDay.month, &thisDay.day, &thisDay.year );
nextDay = dateUpdate( thisDay );
printf( "Tomorrow's date is %i/%i/%.2i.\n", nextDay.month, nextDay.day, nextDay.year % 100 );
return 0;
}
|
the_stack_data/212642871.c | #include <stdio.h>
#include <stdlib.h>
int main()
{
/* Да се напише програма, която прочита от клавиатурата две числа и извежда сумата
на четните числа и произведението на нечетните, които се намират между тези две числа. */
unsigned int firstNumber, secondNumber;
unsigned int evenNumbersSum = 0;
unsigned int oddNumbersProduct = 1;
int i;
printf("Enter the first number: ");
scanf("%d", &firstNumber);
printf("Enter the second number: ");
scanf("%d", &secondNumber);
for (i = firstNumber + 1; i < secondNumber; i++) {
if (i % 2 == 0) {
evenNumbersSum += i;
} else {
oddNumbersProduct *= i;
}
}
printf("The sum is: %d\n", evenNumbersSum);
printf("The product is: %d\n", oddNumbersProduct);
return 0;
}
|
the_stack_data/76058.c | #include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
int ret;
printf("I'm Parent\n");
ret = fork();
printf("Return Value : %d\n", ret);
} |
the_stack_data/9619.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define findpos 0
#define removepos 0
#define removevals 0
#define addsorted 1
struct Node
{
int val;
struct Node *next;
};
void listAdd(struct Node **list, int val);
void listAddSort(struct Node **list, int val);
void listPrint(struct Node *pn);
int listLenght(struct Node *list);
int listPosition(struct Node *list, int val);
void listRemoveAt(struct Node **list, int val);
int removeAll(struct Node **list, int val);
int main(){
struct Node *list = NULL;
char input[25] = "";
while (strcmp(input, "stop") != 0)
{
printf("Inserisci un numero per inserirlo nella lista, o \"stop\" per terminare: ");
scanf("%s", &input);
if (strcmp(input, "stop") != 0)
{
# if addsorted
listAddSort(&list, atoi(input));
# else
listAdd(&list, atoi(input));
#endif
}
}
printf("Lungezza: %d\n", listLenght(list));
# if findpos
int pos;
printf("Inserisci un numero da cercare nella lista: ");
scanf("%d", &pos);
pos = listPosition(list, pos);
if (pos != -1)
{
printf("valore trovato alla posizione %d\n", pos + 1);
} else
{
printf("valore non presente nella lista\n");
}
#endif
#if removepos
int rem;
printf("Inserisci la posizione da rimuovere: ");
scanf("%d", &rem);
listRemoveAt(&list, rem - 1);
printf("Lista con il valore rimosso:\n");
listPrint(list);
#endif
#if removevals
int val;
printf("Inserisci il valore da rimuovere: ");
scanf("%d", &val);
int rem = removeAll(&list, val);
printf("Rimossi: %d\n", rem);
#endif
printf("Lista:\n");
listPrint(list);
}
void listAdd(struct Node **list, int val) {
struct Node *p = *list;
// If the list is not empty the pointer goes on until the last one
// Else alloc
if (*list)
{
while (p -> next)
{
p = p -> next;
}
p -> next = malloc(sizeof(struct Node));
p = p -> next;
} else {
*list = malloc(sizeof(struct Node));
p = *list;
}
p -> val = val;
p -> next = NULL;
}
void listAddSort(struct Node **list, int val) {
struct Node *act = *list;
struct Node **prev = list;
while (act && act -> val < val)
{
prev = &act -> next;
act = act -> next;
}
struct Node *newnode = malloc(sizeof(struct Node));
newnode -> val = val;
newnode -> next = act;
*prev = newnode;
}
int listLenght(struct Node *list) {
int l = 0;
if (list)
{
l++;
while (list -> next)
{
l++;
list = list -> next;
}
}
return l;
}
int listPosition(struct Node *list, int val) {
int p = 0;
if (list)
{
while (list -> next && list -> val != val)
{
p++;
list = list -> next;
}
if (list -> next == NULL && list -> val != val)
{
p = -1;
}
} else {
p = -1;
}
return p;
}
void listRemoveAt(struct Node **list, int val) {
struct Node *p = *list;
if (p)
{
for (int i = 1; i < val && p; i++)
{
p = p -> next;
}
if (p)
{
struct Node *p2 = p -> next;
if (p2)
{
if (val == 0)
{
*list = p -> next;
free(p);
} else {
p -> next = p2 -> next;
free(p2);
}
} else {
p -> next = p2;
}
}
}
}
void listPrint(struct Node *pn) {
while (pn){
printf("%d ",pn->val);
pn = pn -> next;
}
printf("\n");
}
int removeAll(struct Node **list, int val) {
int count = 0;
if (*list)
{
struct Node *prec = NULL;
struct Node *p = *list;
while (p)
{
if ( p -> val == val) {
if (prec)
{
prec -> next = p -> next;
free(p);
p = prec -> next;
} else {
*list = p -> next;
free(p);
p = *list;
}
count++;
} else {
prec = p;
p = p -> next;
}
}
}
return count;
} |
the_stack_data/97696.c | int d[2] = {72, 1};
void MAIN()
{
d[0] &= 64;
assert(d[0] == 64, "d[0] must be 64");
assert(d[1] == 1, "d[1] must be 1");
}
|
the_stack_data/6388592.c | /* David Kirkby 21st August 2010
Licenced under the GPL version 2 or at your option any later version.
Set the FPU's precision control to 53 bits (double precision) instead of
the default 64-bits (extended precision). I've commented it fairly
liberally, with the hope it's helpful if anyone needs to edit it.
Note, the extended precision uses 80 bits in total,
of which 64 are for the mantissa.
Double precsion uses 64 bits in total, but ony 53 are
for the mantissa.
The precision is set by bits 8 and 9 of the Control Word in the floating
point processor. The Control word has 16 bits.
Data taken from The 80387 Programmer's reference Manual, Intel,
1987.
00 = 24-bits (single precision)
01 = reserved (or at least it was at the time the 387 was released)
10 = 53-bits (double precision)
11 = 64-bits (extended precision).
FLDCW is an x86 instruction to "Load the Control Word"
FNSTCW is an x88 instruction to "Store FPU Control Word"
It does so without checking for pending unmasked floating-point
exceptions. (A similar FSTCW checks for them first).
*/
/*
* Rrefreshed and revisited for Debian on behalf of the Debian Science Team
* by Jerome Benoit <[email protected]>, 2014-10-07.
*/
#if defined(ISOC99_FENV)
#include <fenv.h>
#elif defined(FPUCONTROLH)
#include <fpu_control.h>
#define ADHOC__FPU_OR_MASK_EXTENDED (((fpu_control_t)(0x1) << 8) | ((fpu_control_t)(0x1) << 9))
#define ADHOC__FPU_AND_MASK_DOUBLE (~((fpu_control_t)(0x1) << 8))
#elif defined(x86)
#define _SET_FPU_CONTROL_WORD(x) asm volatile ("fldcw %0": :"m" (x));
#define _READ_FPU_CONTROL_WORD(x) asm volatile ("fnstcw %0":"=m" (x));
#else
#endif
void fpu_53bits()
{
#if defined(ISOC99_FENV)
fesetprec(FE_DBLPREC);
#elif defined(FPUCONTROLH)
fpu_control_t fpu_control=_FPU_DEFAULT;
_FPU_GETCW(fpu_control);
fpu_control|=ADHOC__FPU_OR_MASK_EXTENDED;
fpu_control&=ADHOC__FPU_AND_MASK_DOUBLE;
_FPU_SETCW(fpu_control);
#elif defined(x86)
/* The control word is 16 bits, numbered 0 to 15 */
volatile unsigned short control_word;
_READ_FPU_CONTROL_WORD(control_word); /* Read the FPU control word */
control_word=control_word & 0xfeff; /* Set bit 8 = 0 */
control_word=control_word | 0x200; /* Set bit 9 = 1 */
_SET_FPU_CONTROL_WORD(control_word); /* Force double-precision, 53-bit mantissa */
#endif
}
|
the_stack_data/908251.c | #include <linux/types.h>
#include <linux/input.h>
#include <linux/hidraw.h>
#include <stdint.h>
#include <stdbool.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
int main(int argc, char *argv[])
{
int fd;
int i, j, k, n, res, desc_size = 0;
uint8_t buf[256];
struct hidraw_report_descriptor rpt_desc;
struct hidraw_devinfo info;
char *device = "/dev/hidraw0";
if (argc > 1) {
device = argv[1];
}
fd = open(device, O_RDWR|O_NONBLOCK);
if (fd < 0) {
perror("Unable to open device");
return 1;
}
memset(&rpt_desc, 0x0, sizeof(rpt_desc));
memset(&info, 0x0, sizeof(info));
memset(buf, 0x0, sizeof(buf));
// Get Raw Name
res = ioctl(fd, HIDIOCGRAWNAME(256), buf);
if (res < 0) {
perror("HIDIOCGRAWNAME");
} else {
printf("Connected to %s.\n", buf);
}
int allMeters = false;
int meterNumber = 0;
int meterLevel = 0;
if (argc > 2) {
if (!strcmp (argv[2], "all")) {
allMeters = true;
} else {
meterNumber = atoi (argv[2]);
if ((meterNumber < 0) || (meterNumber > 3)) {
printf ("bad meter number.\n");
return -1;
}
}
} else {
printf ("usage: four-meters <1-4|all> <0-255>\n");
return -1;
}
if (argc > 3) {
meterLevel = atoi (argv[3]);
if ((meterLevel < 0) || (meterLevel > 255)) {
printf ("bad meter number.\n");
return -1;
}
} else {
printf ("usage: four-meters <1-4|all> <0-255>\n");
return -1;
}
if (allMeters) {
printf ("Setting all meters to %d...\n", meterLevel);
buf[0] = 0x01; // report id
buf[1] = meterLevel; // meter 1 level (1A)
buf[2] = meterLevel; // meter 2 level (1B)
buf[3] = meterLevel; // meter 3 level (2A)
buf[4] = meterLevel; // meter 4 level (2B)
res = write(fd, buf, 5);
if (res < 0) {
printf("Error: %d\n", errno);
perror("write");
} else {
printf("write() wrote %d bytes\n", res);
}
} else {
printf ("Setting meter %d to %d...\n", meterNumber, meterLevel);
buf[0] = 0x02; // report id
buf[1] = meterNumber; // meter number
buf[2] = meterLevel; // meter level
res = write(fd, buf, 3);
if (res < 0) {
printf("Error: %d\n", errno);
perror("write");
} else {
printf("write() wrote %d bytes\n", res);
}
}
close(fd);
return 0;
}
|
the_stack_data/132953287.c | // Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
int issue8811Initialized = 0;
void issue8811Init() {
}
|
the_stack_data/575092.c | #include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/syscall.h>
#define gettid() syscall(SYS_gettid)
/* this function is run by the second thread */
void *thread_main(void *parg)
{
int i = random() % 13;
int ctid = gettid();
printf("Thread %i wait %d second\n", ctid, i);
sleep (i);
printf("After thread_main\n");
/* the function must return something - NULL will do */
return ctid;
}
int main()
{
#define NUM_THREAD 16
/* this variable is our reference to the second thread */
pthread_t tid[NUM_THREAD];
int i, ret;
int ctid;
/* create a second thread which executes inc_x(&x) */
printf("Before pthread_create >>>>START\n");
for (i = 0; i < NUM_THREAD; i++) {
pthread_create(&tid[i], NULL, &thread_main, NULL);
}
printf("After pthread_create >>>>END\n");
printf("Before pthread_join >>>>START\n");
for (i = 0; i < NUM_THREAD; i++) {
pthread_join(tid[i], &ctid);
printf("Iter %d: pthread_join for thread %d finished\n", i, ctid);
}
printf("After pthread_join >>>>END\n");
return 0;
}
|
the_stack_data/115170.c |
extern void *malloc (unsigned long __size) __attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__malloc__)) ;
extern void free (void *__ptr) __attribute__ ((__nothrow__ , __leaf__));
extern int strcmp (const char *__s1, const char *__s2)
__attribute__ ((__nothrow__ , __leaf__)) __attribute__ ((__pure__)) __attribute__ ((__nonnull__ (1, 2)));
static const char *linked = (void*)0;
int sysfs_link_sibling(const char *s_name)
{
if (linked != (void*)0)
return (!strcmp(s_name,linked)) ? -17 : -12;
linked = s_name;
return 0;
}
void sysfs_unlink_sibling(const char *s_name)
{
if (linked != (void*)0 && !strcmp(s_name,linked))
linked = (void*)0;
}
int sysfs_create_dir(const char *name)
{
return sysfs_link_sibling(name);
}
int kobject_add(const char *name)
{
return sysfs_create_dir(name);
}
int *kobject_create_and_add(const char *name)
{
int *kobj =(int*) malloc(sizeof(int));
if (!kobj)
return (void*)0;
int retval = kobject_add(name);
if (retval)
{
free(kobj);
kobj = (void*)0;
}
return kobj;
}
int *class_compat_register(const char *name)
{
int *kobj;
kobj = kobject_create_and_add(name);
if (!kobj)
return (void*)0;
return kobj;
}
void class_compat_unregister(const char *name)
{
free(name);
}
static int *switch_class;
int create_extcon_class(void)
{
switch_class = class_compat_register("switch");
if (!switch_class)
return -12;
return 0;
}
int extcon_class_init(void)
{
return create_extcon_class();
}
void extcon_class_exit(void)
{
return;
}
int main(void)
{
extcon_class_init();
extcon_class_exit();
extcon_class_init();
return 0;
}
|
the_stack_data/132636.c | #ifdef ZFP_WITH_CUDA
#include "../cuda_zfp/cuZFP.h"
static void
_t2(decompress_cuda, Scalar, 1)(zfp_stream* stream, zfp_field* field)
{
if(zfp_stream_compression_mode(stream) == zfp_mode_fixed_rate)
{
cuda_decompress(stream, field);
}
}
/* compress 1d strided array */
static void
_t2(decompress_strided_cuda, Scalar, 1)(zfp_stream* stream, zfp_field* field)
{
if(zfp_stream_compression_mode(stream) == zfp_mode_fixed_rate)
{
cuda_decompress(stream, field);
}
}
/* compress 2d strided array */
static void
_t2(decompress_strided_cuda, Scalar, 2)(zfp_stream* stream, zfp_field* field)
{
if(zfp_stream_compression_mode(stream) == zfp_mode_fixed_rate)
{
cuda_decompress(stream, field);
}
}
/* compress 3d strided array */
static void
_t2(decompress_strided_cuda, Scalar, 3)(zfp_stream* stream, zfp_field* field)
{
if(zfp_stream_compression_mode(stream) == zfp_mode_fixed_rate)
{
cuda_decompress(stream, field);
}
}
#endif
|
the_stack_data/150140525.c | #include <stdio.h>
int main(int argc, char *argv[]) {
printf("hello,world!!\n");
printf("To C, or not to C: that is the question.\n");
return 0;
} |
the_stack_data/24143.c | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
double y, z, x, raizy, pontenciay, potenciax;
printf("Digite o valor de Z: ");
scanf("%lf", &z);
printf("Digite o valor de Y: ");
scanf("%lf", &y);
raizy = sqrt(y);
pontenciay = pow(y, 22);
potenciax = pow(z, 33);
x = raizy*(pontenciay+potenciax);
printf("O valor de X eh: %.2lf", x);
return 0;
} |
the_stack_data/916095.c | /***
* This code is a part of EvoApproxLib library (ehw.fit.vutbr.cz/approxlib) distributed under The MIT License.
* When used, please cite the following article(s): V. Mrazek, R. Hrbacek, Z. Vasicek and L. Sekanina, "EvoApprox8b: Library of approximate adders and multipliers for circuit design and benchmarking of approximation methods". Design, Automation & Test in Europe Conference & Exhibition (DATE), 2017, Lausanne, 2017, pp. 258-261. doi: 10.23919/DATE.2017.7926993
* This file contains a circuit from evoapprox8b dataset. Note that a new version of library was already published.
***/
#include <stdint.h>
#include <stdlib.h>
/// Approximate function mul8_012
/// Library = EvoApprox8b
/// Circuit = mul8_012
/// Area (180) = 12408
/// Delay (180) = 3.190
/// Power (180) = 5804.80
/// Area (45) = 881
/// Delay (45) = 1.240
/// Power (45) = 484.10
/// Nodes = 234
/// HD = 0
/// MAE = 0.00000
/// MSE = 0.00000
/// MRE = 0.00 %
/// WCE = 0
/// WCRE = 0 %
/// EP = 0.0 %
uint16_t mul8_012(uint8_t a, uint8_t b)
{
uint16_t c = 0;
uint8_t n0 = (a >> 0) & 0x1;
uint8_t n2 = (a >> 1) & 0x1;
uint8_t n4 = (a >> 2) & 0x1;
uint8_t n6 = (a >> 3) & 0x1;
uint8_t n8 = (a >> 4) & 0x1;
uint8_t n10 = (a >> 5) & 0x1;
uint8_t n12 = (a >> 6) & 0x1;
uint8_t n14 = (a >> 7) & 0x1;
uint8_t n16 = (b >> 0) & 0x1;
uint8_t n18 = (b >> 1) & 0x1;
uint8_t n20 = (b >> 2) & 0x1;
uint8_t n22 = (b >> 3) & 0x1;
uint8_t n24 = (b >> 4) & 0x1;
uint8_t n26 = (b >> 5) & 0x1;
uint8_t n28 = (b >> 6) & 0x1;
uint8_t n30 = (b >> 7) & 0x1;
uint8_t n32;
uint8_t n38;
uint8_t n44;
uint8_t n50;
uint8_t n56;
uint8_t n62;
uint8_t n68;
uint8_t n74;
uint8_t n82;
uint8_t n88;
uint8_t n94;
uint8_t n100;
uint8_t n106;
uint8_t n112;
uint8_t n118;
uint8_t n126;
uint8_t n132;
uint8_t n138;
uint8_t n144;
uint8_t n150;
uint8_t n156;
uint8_t n162;
uint8_t n168;
uint8_t n176;
uint8_t n182;
uint8_t n188;
uint8_t n194;
uint8_t n200;
uint8_t n206;
uint8_t n212;
uint8_t n220;
uint8_t n226;
uint8_t n232;
uint8_t n238;
uint8_t n244;
uint8_t n250;
uint8_t n256;
uint8_t n262;
uint8_t n270;
uint8_t n276;
uint8_t n282;
uint8_t n288;
uint8_t n294;
uint8_t n300;
uint8_t n306;
uint8_t n314;
uint8_t n320;
uint8_t n326;
uint8_t n332;
uint8_t n338;
uint8_t n344;
uint8_t n350;
uint8_t n358;
uint8_t n364;
uint8_t n370;
uint8_t n376;
uint8_t n382;
uint8_t n388;
uint8_t n394;
uint8_t n400;
uint8_t n408;
uint8_t n414;
uint8_t n420;
uint8_t n426;
uint8_t n432;
uint8_t n433;
uint8_t n438;
uint8_t n439;
uint8_t n444;
uint8_t n445;
uint8_t n452;
uint8_t n453;
uint8_t n458;
uint8_t n459;
uint8_t n464;
uint8_t n465;
uint8_t n470;
uint8_t n471;
uint8_t n476;
uint8_t n482;
uint8_t n488;
uint8_t n489;
uint8_t n494;
uint8_t n495;
uint8_t n502;
uint8_t n503;
uint8_t n508;
uint8_t n509;
uint8_t n514;
uint8_t n515;
uint8_t n520;
uint8_t n521;
uint8_t n526;
uint8_t n527;
uint8_t n532;
uint8_t n538;
uint8_t n546;
uint8_t n547;
uint8_t n552;
uint8_t n553;
uint8_t n558;
uint8_t n559;
uint8_t n564;
uint8_t n565;
uint8_t n570;
uint8_t n571;
uint8_t n576;
uint8_t n577;
uint8_t n582;
uint8_t n583;
uint8_t n588;
uint8_t n589;
uint8_t n596;
uint8_t n597;
uint8_t n602;
uint8_t n603;
uint8_t n608;
uint8_t n609;
uint8_t n614;
uint8_t n615;
uint8_t n620;
uint8_t n621;
uint8_t n626;
uint8_t n627;
uint8_t n632;
uint8_t n633;
uint8_t n640;
uint8_t n641;
uint8_t n646;
uint8_t n652;
uint8_t n653;
uint8_t n658;
uint8_t n659;
uint8_t n664;
uint8_t n665;
uint8_t n670;
uint8_t n671;
uint8_t n676;
uint8_t n677;
uint8_t n684;
uint8_t n685;
uint8_t n690;
uint8_t n691;
uint8_t n696;
uint8_t n697;
uint8_t n702;
uint8_t n708;
uint8_t n714;
uint8_t n720;
uint8_t n726;
uint8_t n727;
uint8_t n734;
uint8_t n735;
uint8_t n740;
uint8_t n741;
uint8_t n746;
uint8_t n747;
uint8_t n752;
uint8_t n753;
uint8_t n758;
uint8_t n759;
uint8_t n764;
uint8_t n765;
uint8_t n770;
uint8_t n771;
uint8_t n778;
uint8_t n779;
uint8_t n784;
uint8_t n785;
uint8_t n796;
uint8_t n802;
uint8_t n803;
uint8_t n808;
uint8_t n809;
uint8_t n814;
uint8_t n815;
uint8_t n820;
uint8_t n821;
uint8_t n828;
uint8_t n829;
uint8_t n834;
uint8_t n835;
uint8_t n840;
uint8_t n841;
uint8_t n846;
uint8_t n847;
uint8_t n852;
uint8_t n853;
uint8_t n858;
uint8_t n859;
uint8_t n916;
uint8_t n922;
uint8_t n946;
uint8_t n952;
uint8_t n958;
uint8_t n966;
uint8_t n996;
uint8_t n1002;
uint8_t n1016;
uint8_t n1022;
uint8_t n1034;
uint8_t n1060;
uint8_t n1066;
uint8_t n1072;
uint8_t n1078;
uint8_t n1084;
uint8_t n1090;
uint8_t n1096;
uint8_t n1104;
uint8_t n1105;
uint8_t n1140;
uint8_t n1146;
uint8_t n1154;
uint8_t n1160;
uint8_t n1161;
uint8_t n1166;
uint8_t n1178;
uint8_t n1184;
uint8_t n1190;
uint8_t n1204;
uint8_t n1205;
uint8_t n1242;
uint8_t n1248;
uint8_t n1254;
uint8_t n1260;
uint8_t n1266;
uint8_t n1272;
uint8_t n1278;
uint8_t n1284;
uint8_t n1292;
uint8_t n1298;
uint8_t n1304;
uint8_t n1310;
uint8_t n1354;
uint8_t n1355;
uint8_t n1360;
uint8_t n1366;
uint8_t n1372;
uint8_t n1378;
uint8_t n1386;
uint8_t n1392;
uint8_t n1398;
uint8_t n1404;
uint8_t n1410;
uint8_t n1416;
uint8_t n1422;
uint8_t n1430;
uint8_t n1436;
uint8_t n1454;
uint8_t n1492;
uint8_t n1498;
uint8_t n1504;
uint8_t n1505;
uint8_t n1510;
uint8_t n1516;
uint8_t n1524;
uint8_t n1530;
uint8_t n1536;
uint8_t n1542;
uint8_t n1548;
uint8_t n1554;
uint8_t n1561;
uint8_t n1568;
uint8_t n1574;
uint8_t n1580;
uint8_t n1586;
uint8_t n1592;
uint8_t n1598;
uint8_t n1662;
uint8_t n1668;
uint8_t n1674;
uint8_t n1680;
uint8_t n1681;
uint8_t n1686;
uint8_t n1692;
uint8_t n1698;
uint8_t n1704;
uint8_t n1712;
uint8_t n1718;
uint8_t n1724;
uint8_t n1730;
uint8_t n1736;
uint8_t n1742;
uint8_t n1748;
uint8_t n1756;
uint8_t n1762;
uint8_t n1768;
uint8_t n1774;
uint8_t n1968;
uint8_t n1974;
uint8_t n1980;
uint8_t n1988;
uint8_t n1994;
uint8_t n2000;
uint8_t n2006;
uint8_t n2012;
uint8_t n2018;
uint8_t n2024;
n32 = n0 & n16;
n38 = n2 & n16;
n44 = n4 & n16;
n50 = n6 & n16;
n56 = n8 & n16;
n62 = n10 & n16;
n68 = n12 & n16;
n74 = n14 & n16;
n82 = n0 & n18;
n88 = n2 & n18;
n94 = n4 & n18;
n100 = n6 & n18;
n106 = n8 & n18;
n112 = n10 & n18;
n118 = n12 & n18;
n126 = n14 & n18;
n132 = n0 & n20;
n138 = n2 & n20;
n144 = n4 & n20;
n150 = n6 & n20;
n156 = n8 & n20;
n162 = n10 & n20;
n168 = n12 & n20;
n176 = n14 & n20;
n182 = n0 & n22;
n188 = n2 & n22;
n194 = n4 & n22;
n200 = n6 & n22;
n206 = n8 & n22;
n212 = n10 & n22;
n220 = n12 & n22;
n226 = n14 & n22;
n232 = n0 & n24;
n238 = n2 & n24;
n244 = n4 & n24;
n250 = n6 & n24;
n256 = n8 & n24;
n262 = n10 & n24;
n270 = n12 & n24;
n276 = n14 & n24;
n282 = n0 & n26;
n288 = n2 & n26;
n294 = n4 & n26;
n300 = n6 & n26;
n306 = n8 & n26;
n314 = n10 & n26;
n320 = n12 & n26;
n326 = n14 & n26;
n332 = n0 & n28;
n338 = n2 & n28;
n344 = n4 & n28;
n350 = n6 & n28;
n358 = n8 & n28;
n364 = n10 & n28;
n370 = n12 & n28;
n376 = n14 & n28;
n382 = n0 & n30;
n388 = n2 & n30;
n394 = n4 & n30;
n400 = n6 & n30;
n408 = n8 & n30;
n414 = n10 & n30;
n420 = n12 & n30;
n426 = n14 & n30;
n432 = n38 ^ n82;
n433 = n38 & n82;
n438 = (n44 ^ n88) ^ n132;
n439 = (n44 & n88) | (n88 & n132) | (n44 & n132);
n444 = (n50 ^ n94) ^ n138;
n445 = (n50 & n94) | (n94 & n138) | (n50 & n138);
n452 = (n56 ^ n100) ^ n144;
n453 = (n56 & n100) | (n100 & n144) | (n56 & n144);
n458 = (n62 ^ n106) ^ n150;
n459 = (n62 & n106) | (n106 & n150) | (n62 & n150);
n464 = (n68 ^ n112) ^ n156;
n465 = (n68 & n112) | (n112 & n156) | (n68 & n156);
n470 = (n74 ^ n118) ^ n162;
n471 = (n74 & n118) | (n118 & n162) | (n74 & n162);
n476 = n126 & n168;
n482 = n126 ^ n168;
n488 = n188 ^ n232;
n489 = n188 & n232;
n494 = (n194 ^ n238) ^ n282;
n495 = (n194 & n238) | (n238 & n282) | (n194 & n282);
n502 = (n200 ^ n244) ^ n288;
n503 = (n200 & n244) | (n244 & n288) | (n200 & n288);
n508 = (n206 ^ n250) ^ n294;
n509 = (n206 & n250) | (n250 & n294) | (n206 & n294);
n514 = (n212 ^ n256) ^ n300;
n515 = (n212 & n256) | (n256 & n300) | (n212 & n300);
n520 = (n220 ^ n262) ^ n306;
n521 = (n220 & n262) | (n262 & n306) | (n220 & n306);
n526 = (n226 ^ n270) ^ n314;
n527 = (n226 & n270) | (n270 & n314) | (n226 & n314);
n532 = n276 & n320;
n538 = n276 ^ n320;
n546 = n438 ^ n433;
n547 = n438 & n433;
n552 = (n444 ^ n439) ^ n182;
n553 = (n444 & n439) | (n439 & n182) | (n444 & n182);
n558 = (n452 ^ n445) ^ n488;
n559 = (n452 & n445) | (n445 & n488) | (n452 & n488);
n564 = (n458 ^ n453) ^ n494;
n565 = (n458 & n453) | (n453 & n494) | (n458 & n494);
n570 = (n464 ^ n459) ^ n502;
n571 = (n464 & n459) | (n459 & n502) | (n464 & n502);
n576 = (n470 ^ n465) ^ n508;
n577 = (n470 & n465) | (n465 & n508) | (n470 & n508);
n582 = (n482 ^ n471) ^ n514;
n583 = (n482 & n471) | (n471 & n514) | (n482 & n514);
n588 = (n176 ^ n476) ^ n520;
n589 = (n176 & n476) | (n476 & n520) | (n176 & n520);
n596 = n495 ^ n332;
n597 = n495 & n332;
n602 = (n503 ^ n338) ^ n382;
n603 = (n503 & n338) | (n338 & n382) | (n503 & n382);
n608 = (n509 ^ n344) ^ n388;
n609 = (n509 & n344) | (n344 & n388) | (n509 & n388);
n614 = (n515 ^ n350) ^ n394;
n615 = (n515 & n350) | (n350 & n394) | (n515 & n394);
n620 = (n521 ^ n358) ^ n400;
n621 = (n521 & n358) | (n358 & n400) | (n521 & n400);
n626 = (n527 ^ n364) ^ n408;
n627 = (n527 & n364) | (n364 & n408) | (n527 & n408);
n632 = (n532 ^ n370) ^ n414;
n633 = (n532 & n370) | (n370 & n414) | (n532 & n414);
n640 = n376 & n420;
n641 = n376 & n420;
n646 = n376 ^ n420;
n652 = n552 ^ n547;
n653 = n552 & n547;
n658 = n558 ^ n553;
n659 = n558 & n553;
n664 = (n564 ^ n559) ^ n489;
n665 = (n564 & n559) | (n559 & n489) | (n564 & n489);
n670 = (n570 ^ n565) ^ n596;
n671 = (n570 & n565) | (n565 & n596) | (n570 & n596);
n676 = (n576 ^ n571) ^ n602;
n677 = (n576 & n571) | (n571 & n602) | (n576 & n602);
n684 = (n582 ^ n577) ^ n608;
n685 = (n582 & n577) | (n577 & n608) | (n582 & n608);
n690 = (n588 ^ n583) ^ n614;
n691 = (n588 & n583) | (n583 & n614) | (n588 & n614);
n696 = (n526 ^ n589) ^ n620;
n697 = (n526 & n589) | (n589 & n620) | (n526 & n620);
n702 = n538 & n626;
n708 = n538 ^ n626;
n714 = n326 & n632;
n720 = n326 ^ n632;
n726 = n658 ^ n653;
n727 = n658 & n653;
n734 = n664 ^ n659;
n735 = n664 & n659;
n740 = n670 ^ n665;
n741 = n670 & n665;
n746 = (n676 ^ n671) ^ n597;
n747 = (n676 & n671) | (n671 & n597) | (n676 & n597);
n752 = (n684 ^ n677) ^ n603;
n753 = (n684 & n677) | (n677 & n603) | (n684 & n603);
n758 = (n690 ^ n685) ^ n609;
n759 = (n690 & n685) | (n685 & n609) | (n690 & n609);
n764 = (n696 ^ n691) ^ n615;
n765 = (n696 & n691) | (n691 & n615) | (n696 & n615);
n770 = (n708 ^ n697) ^ n621;
n771 = (n708 & n697) | (n697 & n621) | (n708 & n621);
n778 = (n720 ^ n702) ^ n627;
n779 = (n720 & n702) | (n702 & n627) | (n720 & n627);
n784 = (n646 ^ n714) ^ n633;
n785 = (n646 & n714) | (n714 & n633) | (n646 & n633);
n796 = n426 ^ n640;
n802 = n734 ^ n727;
n803 = n734 & n727;
n808 = n740 ^ n735;
n809 = n740 & n735;
n814 = n746 ^ n741;
n815 = n746 & n741;
n820 = n752 ^ n747;
n821 = n752 & n747;
n828 = n758 ^ n753;
n829 = n758 & n753;
n834 = n764 ^ n759;
n835 = n764 & n759;
n840 = n770 ^ n765;
n841 = n770 & n765;
n846 = n778 ^ n771;
n847 = n778 & n771;
n852 = n784 ^ n779;
n853 = n784 & n779;
n858 = n796 ^ n785;
n859 = n796 & n785;
n916 = n808 & n803;
n922 = n809 ^ n916;
n946 = n814 & n916;
n952 = n814 & n809;
n958 = n815 | n952;
n966 = n958 | n946;
n996 = n820 & n966;
n1002 = n820 & n815;
n1016 = n996;
n1022 = n821 | n1016;
n1034 = n828 & n1016;
n1060 = n1034 & n922;
n1066 = n828 & n1002;
n1072 = n828 & n821;
n1078 = n829 | n1072;
n1084 = n1066 | n1060;
n1090 = n1078 | n1084;
n1096 = n1090;
n1104 = n834 & n828;
n1105 = n834 & n828;
n1140 = n1105 & n1022;
n1146 = n1104 & n1002;
n1154 = n834 & n1072;
n1160 = n834 & n829;
n1161 = n834 & n829;
n1166 = n835 | n1160;
n1178 = n1140;
n1184 = n1166;
n1190 = n1184 | n1178;
n1204 = n840 & n834;
n1205 = n840 & n834;
n1242 = n1204 & n1140;
n1248 = n1161 & n1146;
n1254 = n1204 & n1154;
n1260 = n1205 & n1160;
n1266 = n840 & n835;
n1272 = n841 | n1266;
n1278 = n1260;
n1284 = n1248 | n1242;
n1292 = n1272 | n1278;
n1298 = n1284;
n1304 = n1292 | n1298;
n1310 = n846 & n840;
n1354 = n846 & n1204;
n1355 = n846 & n1204;
n1360 = n1354 & n1060;
n1366 = n1355 & n1146;
n1372 = n846 & n1254;
n1378 = n1310 & n1260;
n1386 = n846 & n1266;
n1392 = n846 & n841;
n1398 = n847 | n1392;
n1404 = n1386 | n1378;
n1410 = n1372 | n1366;
n1416 = n1360;
n1422 = n1398 | n1404;
n1430 = n1410 | n1416;
n1436 = n1422 | n1430;
n1454 = n852 & n846;
n1492 = n1454 & n1354;
n1498 = n1492 & n1060;
n1504 = n852 & n1310;
n1505 = n852 & n1310;
n1510 = n1504 & n1146;
n1516 = n1454 & n1254;
n1524 = n1505 & n1378;
n1530 = n1454 & n1266;
n1536 = n852 & n1392;
n1542 = n852 & n847;
n1548 = n853 | n1542;
n1554 = n1536 | n1530;
n1561 = n1524 | n1516;
n1568 = n1510 | n1498;
n1574 = n1548 | n1554;
n1580 = n1561 | n1568;
n1586 = n1574 | n1580;
n1592 = n1586;
n1598 = n858 & n852;
n1662 = n2 & n1498;
n1668 = n1598 & n1366;
n1674 = n1668;
n1680 = n858 & n1454;
n1681 = n858 & n1454;
n1686 = n1680 & n1254;
n1692 = n1681 & n1378;
n1698 = n1681 & n1530;
n1704 = n1681 & n1392;
n1712 = n858 & n1542;
n1718 = n858 & n853;
n1724 = n859 | n1718;
n1730 = n1712 | n1704;
n1736 = n1698 | n1692;
n1742 = n1686 | n1674;
n1748 = n1662;
n1756 = n1724 | n1730;
n1762 = n1736 | n1742;
n1768 = n1756 | n1762;
n1774 = n1768 | n1748;
n1968 = n808 ^ n803;
n1974 = n814 ^ n922;
n1980 = n820 ^ n966;
n1988 = n828 ^ n1022;
n1994 = n834 ^ n1096;
n2000 = n840 ^ n1190;
n2006 = n846 ^ n1304;
n2012 = n852 ^ n1436;
n2018 = n858 ^ n1592;
n2024 = n641 | n1774;
c |= (n32 & 0x1) << 0;
c |= (n432 & 0x1) << 1;
c |= (n546 & 0x1) << 2;
c |= (n652 & 0x1) << 3;
c |= (n726 & 0x1) << 4;
c |= (n802 & 0x1) << 5;
c |= (n1968 & 0x1) << 6;
c |= (n1974 & 0x1) << 7;
c |= (n1980 & 0x1) << 8;
c |= (n1988 & 0x1) << 9;
c |= (n1994 & 0x1) << 10;
c |= (n2000 & 0x1) << 11;
c |= (n2006 & 0x1) << 12;
c |= (n2012 & 0x1) << 13;
c |= (n2018 & 0x1) << 14;
c |= (n2024 & 0x1) << 15;
return c;
}
|
the_stack_data/178265366.c | // Copyright (c) 2015 Nuxi, https://nuxi.nl/
//
// SPDX-License-Identifier: BSD-2-Clause
#include <locale.h>
#include <regex.h>
#include <string.h>
int regcomp_l(regex_t *restrict preg, const char *restrict pattern, int cflags,
locale_t locale) {
return regncomp_l(preg, pattern, strlen(pattern), cflags, locale);
}
|
the_stack_data/67324954.c | // RUN: %clang_cc1 -fsyntax-only -verify -Wtautological-bitwise-compare %s
#define mydefine 2
enum {
ZERO,
ONE,
};
void f(int x) {
if ((8 & x) == 3) {} // expected-warning {{bitwise comparison always evaluates to false}}
if ((x & 8) == 4) {} // expected-warning {{bitwise comparison always evaluates to false}}
if ((x & 8) != 4) {} // expected-warning {{bitwise comparison always evaluates to true}}
if ((2 & x) != 4) {} // expected-warning {{bitwise comparison always evaluates to true}}
if ((x | 4) == 3) {} // expected-warning {{bitwise comparison always evaluates to false}}
if ((x | 3) != 4) {} // expected-warning {{bitwise comparison always evaluates to true}}
if ((5 | x) != 3) {} // expected-warning {{bitwise comparison always evaluates to true}}
if ((x & 0x15) == 0x13) {} // expected-warning {{bitwise comparison always evaluates to false}}
if ((0x23 | x) == 0x155){} // expected-warning {{bitwise comparison always evaluates to false}}
if (!!((8 & x) == 3)) {} // expected-warning {{bitwise comparison always evaluates to false}}
int y = ((8 & x) == 3) ? 1 : 2; // expected-warning {{bitwise comparison always evaluates to false}}
if ((x & 8) == 8) {}
if ((x & 8) != 8) {}
if ((x | 4) == 4) {}
if ((x | 4) != 4) {}
if ((x & 9) == 8) {}
if ((x & 9) != 8) {}
if ((x | 4) == 5) {}
if ((x | 4) != 5) {}
if ((x & mydefine) == 8) {}
if ((x | mydefine) == 4) {}
}
void g(int x) {
if (x | 5) {} // expected-warning {{bitwise or with non-zero value always evaluates to true}}
if (5 | x) {} // expected-warning {{bitwise or with non-zero value always evaluates to true}}
if (!((x | 5))) {} // expected-warning {{bitwise or with non-zero value always evaluates to true}}
if (x | -1) {} // expected-warning {{bitwise or with non-zero value always evaluates to true}}
if (x | ONE) {} // expected-warning {{bitwise or with non-zero value always evaluates to true}}
if (x | ZERO) {}
}
|
the_stack_data/173577888.c | #include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
void sorting(int *a, int l, int r)
{
int max;
int check = 0;
while ((2 * l <= r) && (!check))
{
if (2 * l == r)
max = 2 * l;
else
if (a[2 * l] > a[2 * l + 1])
max = 2 * l;
else
max = 2 * l + 1;
if (a[l] < a[max])
{
int q = a[l];
a[l] = a[max];
a[max] = q;
l = max;
}
else
check = 1;
}
}
void Pyramid(int *a, int n)
{
int i;
for (i = n/2 - 1; i >= 0; i--)
sorting(a, i, n);
for (i = n - 1; i >= 1; i--)
{
int q = a[0];
a[0] = a[i];
a[i] = q;
sorting(a, 0, i - 1);
}
}
int main()
{
int *a;
int n,i;
scanf("%d", &n);
a = (int*)malloc(n * sizeof(int));
for(i = 0; i<n; i++)
scanf("%d", &a[i]);
Pyramid(a, n);
for(i=0; i<n; i++)
printf("%d ",a[i]);
free(a);
printf("\n");
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.