file
stringlengths
18
26
data
stringlengths
3
1.04M
the_stack_data/231393705.c
#include <math.h> /* |cos(x) - c(x)| < 2**-34.1 (~[-5.37e-11, 5.295e-11]). */ static const double C0 = -0x1ffffffd0c5e81.0p-54, /* -0.499999997251031003120 */ C1 = 0x155553e1053a42.0p-57, /* 0.0416666233237390631894 */ C2 = -0x16c087e80f1e27.0p-62, /* -0.00138867637746099294692 */ C3 = 0x199342e0ee5069.0p-68; /* 0.0000243904487962774090654 */ float __cosdf(double x) { double_t r, w, z; /* Try to optimize for parallel evaluation as in __tandf.c. */ z = x*x; w = z*z; r = C2+z*C3; return ((1.0+z*C0) + w*C1) + (w*z)*r; }
the_stack_data/165767843.c
#include <unistd.h> void ft_putchar(char c) { write(1, &c, 1); } void ft_putnbr(int nb) { if (nb == -2147483648) { ft_putchar('-'); ft_putchar('2'); nb = 147483648; } if (nb < 0) { ft_putchar('-'); nb = -nb; } if (nb < 10) { ft_putchar(nb + 48); return ; } else { ft_putnbr(nb / 10); } ft_putnbr(nb % 10); }
the_stack_data/363001.c
/* * Argon2 source code package * * Written by Daniel Dinu and Dmitry Khovratovich, 2015 * * This work is licensed under a Creative Commons CC0 1.0 License/Waiver. * * You should have received a copy of the CC0 Public Domain Dedication along * with * this software. If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include <stdint.h> #include <stdlib.h> #include <string.h> #if (defined(HAVE_EMMINTRIN_H) && defined(HAVE_TMMINTRIN_H)) || \ (defined(_MSC_VER) && (defined(_M_X64) || defined(_M_AMD64) || defined(_M_IX86))) #pragma GCC target("sse2") #pragma GCC target("ssse3") #ifdef _MSC_VER # include <intrin.h> /* for _mm_set_epi64x */ #endif #include <emmintrin.h> #include <tmmintrin.h> #include "argon2.h" #include "argon2-core.h" #include "argon2-impl.h" #include "blamka-round-ssse3.h" static void fill_block(__m128i *state, const uint8_t *ref_block, uint8_t *next_block) { __m128i block_XY[ARGON2_OWORDS_IN_BLOCK]; uint32_t i; for (i = 0; i < ARGON2_OWORDS_IN_BLOCK; i++) { block_XY[i] = state[i] = _mm_xor_si128( state[i], _mm_loadu_si128((__m128i const *)(&ref_block[16 * i]))); } for (i = 0; i < 8; ++i) { BLAKE2_ROUND(state[8 * i + 0], state[8 * i + 1], state[8 * i + 2], state[8 * i + 3], state[8 * i + 4], state[8 * i + 5], state[8 * i + 6], state[8 * i + 7]); } for (i = 0; i < 8; ++i) { BLAKE2_ROUND(state[8 * 0 + i], state[8 * 1 + i], state[8 * 2 + i], state[8 * 3 + i], state[8 * 4 + i], state[8 * 5 + i], state[8 * 6 + i], state[8 * 7 + i]); } for (i = 0; i < ARGON2_OWORDS_IN_BLOCK; i++) { state[i] = _mm_xor_si128(state[i], block_XY[i]); _mm_storeu_si128((__m128i *)(&next_block[16 * i]), state[i]); } } static void fill_block_with_xor(__m128i *state, const uint8_t *ref_block, uint8_t *next_block) { __m128i block_XY[ARGON2_OWORDS_IN_BLOCK]; uint32_t i; for (i = 0; i < ARGON2_OWORDS_IN_BLOCK; i++) { state[i] = _mm_xor_si128(state[i], _mm_loadu_si128((__m128i const *)(&ref_block[16 * i]))); block_XY[i] = _mm_xor_si128(state[i], _mm_loadu_si128((__m128i const *)(&next_block[16 * i]))); } for (i = 0; i < 8; ++i) { BLAKE2_ROUND(state[8 * i + 0], state[8 * i + 1], state[8 * i + 2], state[8 * i + 3], state[8 * i + 4], state[8 * i + 5], state[8 * i + 6], state[8 * i + 7]); } for (i = 0; i < 8; ++i) { BLAKE2_ROUND(state[8 * 0 + i], state[8 * 1 + i], state[8 * 2 + i], state[8 * 3 + i], state[8 * 4 + i], state[8 * 5 + i], state[8 * 6 + i], state[8 * 7 + i]); } for (i = 0; i < ARGON2_OWORDS_IN_BLOCK; i++) { state[i] = _mm_xor_si128(state[i], block_XY[i]); _mm_storeu_si128((__m128i *)(&next_block[16 * i]), state[i]); } } static void generate_addresses(const argon2_instance_t *instance, const argon2_position_t *position, uint64_t *pseudo_rands) { block address_block, input_block, tmp_block; uint32_t i; init_block_value(&address_block, 0); init_block_value(&input_block, 0); if (instance != NULL && position != NULL) { input_block.v[0] = position->pass; input_block.v[1] = position->lane; input_block.v[2] = position->slice; input_block.v[3] = instance->memory_blocks; input_block.v[4] = instance->passes; input_block.v[5] = instance->type; for (i = 0; i < instance->segment_length; ++i) { if (i % ARGON2_ADDRESSES_IN_BLOCK == 0) { /* Temporary zero-initialized blocks */ __m128i zero_block[ARGON2_OWORDS_IN_BLOCK]; __m128i zero2_block[ARGON2_OWORDS_IN_BLOCK]; memset(zero_block, 0, sizeof(zero_block)); memset(zero2_block, 0, sizeof(zero2_block)); init_block_value(&address_block, 0); init_block_value(&tmp_block, 0); /* Increasing index counter */ input_block.v[6]++; /* First iteration of G */ fill_block_with_xor(zero_block, (uint8_t *)&input_block.v, (uint8_t *)&tmp_block.v); /* Second iteration of G */ fill_block_with_xor(zero2_block, (uint8_t *)&tmp_block.v, (uint8_t *)&address_block.v); } pseudo_rands[i] = address_block.v[i % ARGON2_ADDRESSES_IN_BLOCK]; } } } int fill_segment_ssse3(const argon2_instance_t *instance, argon2_position_t position) { block *ref_block = NULL, *curr_block = NULL; uint64_t pseudo_rand, ref_index, ref_lane; uint32_t prev_offset, curr_offset; uint32_t starting_index, i; __m128i state[64]; const int data_independent_addressing = 1; /* instance->type == Argon2_i */ /* Pseudo-random values that determine the reference block position */ uint64_t *pseudo_rands = NULL; if (instance == NULL) { return ARGON2_OK; } pseudo_rands = (uint64_t *)malloc(sizeof(uint64_t) * instance->segment_length); if (pseudo_rands == NULL) { return ARGON2_MEMORY_ALLOCATION_ERROR; } if (data_independent_addressing) { generate_addresses(instance, &position, pseudo_rands); } starting_index = 0; if ((0 == position.pass) && (0 == position.slice)) { starting_index = 2; /* we have already generated the first two blocks */ } /* Offset of the current block */ curr_offset = position.lane * instance->lane_length + position.slice * instance->segment_length + starting_index; if (0 == curr_offset % instance->lane_length) { /* Last block in this lane */ prev_offset = curr_offset + instance->lane_length - 1; } else { /* Previous block */ prev_offset = curr_offset - 1; } memcpy(state, ((instance->region->memory + prev_offset)->v), ARGON2_BLOCK_SIZE); for (i = starting_index; i < instance->segment_length; ++i, ++curr_offset, ++prev_offset) { /*1.1 Rotating prev_offset if needed */ if (curr_offset % instance->lane_length == 1) { prev_offset = curr_offset - 1; } /* 1.2 Computing the index of the reference block */ /* 1.2.1 Taking pseudo-random value from the previous block */ if (data_independent_addressing) { #pragma warning(push) #pragma warning(disable: 6385) pseudo_rand = pseudo_rands[i]; #pragma warning(pop) } else { pseudo_rand = instance->region->memory[prev_offset].v[0]; } /* 1.2.2 Computing the lane of the reference block */ ref_lane = ((pseudo_rand >> 32)) % instance->lanes; if ((position.pass == 0) && (position.slice == 0)) { /* Can not reference other lanes yet */ ref_lane = position.lane; } /* 1.2.3 Computing the number of possible reference block within the * lane. */ position.index = i; ref_index = index_alpha(instance, &position, pseudo_rand & 0xFFFFFFFF, ref_lane == position.lane); /* 2 Creating a new block */ ref_block = instance->region->memory + instance->lane_length * ref_lane + ref_index; curr_block = instance->region->memory + curr_offset; if (position.pass != 0) { fill_block_with_xor(state, (uint8_t *)ref_block->v, (uint8_t *)curr_block->v); } else { fill_block(state, (uint8_t *)ref_block->v, (uint8_t *)curr_block->v); } } free(pseudo_rands); return ARGON2_OK; } #endif
the_stack_data/123253.c
// BUILD_ONLY: MacOSX // BUILD_MIN_OS: 10.5 // BUILD: $CC bar.c -dynamiclib -install_name $RUN_DIR/libbar.dylib -o $BUILD_DIR/libbar.dylib -nostdlib -ldylib1.o // BUILD: $CC foo.c -dynamiclib $BUILD_DIR/libbar.dylib -sub_library libbar -install_name $RUN_DIR/libfoo.dylib -o $BUILD_DIR/libfoo.dylib -nostdlib -ldylib1.o // BUILD: $CC main.c -o $BUILD_DIR/dylib-re-export.exe $BUILD_DIR/libfoo.dylib -L$BUILD_DIR -nostdlib -lSystem -lcrt1.10.5.o // RUN: ./dylib-re-export.exe #include <stdio.h> extern int bar(); int main() { printf("[BEGIN] dylib-re-export-old-format\n"); if ( bar() == 42 ) printf("[PASS] dylib-re-export-old-format\n"); else printf("[FAIL] dylib-re-export-old-format, wrong value\n"); return 0; }
the_stack_data/192329373.c
/*++ Copyright (c) 1991 Microsoft Corporation Module Name: vrdlcdbg.c Abstract: Contains functions for dumping CCBs, parameter tables; diagnostic and debugging functions for DOS DLC (CCB1) Contents: DbgOut DbgOutStr DumpCcb DumpDosDlcBufferPool DumpDosDlcBufferChain MapCcbRetcode (DefaultParameterTableDump) (DumpParameterTableHeader) (DumpBufferFreeParms) (DumpBufferGetParms) (DumpDirCloseAdapterParms) (DumpDirDefineMifEnvironmentParms) (DumpDirInitializeParms) (DumpDirModifyOpenParmsParms) (DumpDirOpenAdapterParms) (DumpDirReadLog) (DumpDirRestoreOpenParmsParms) (DumpDirSetFunctionalAddressParms) (DumpDirSetGroupAddressParms) (DumpDirSetUserAppendageParms) (DumpDirStatusParms) (DumpDirTimerCancelParms) (DumpDirTimerCancelGroupParms) (DumpDirTimerSetParms) (DumpDlcCloseSapParms) (DumpDlcCloseStationParms) (DumpDlcConnectStationParms) (DumpDlcFlowControlParms) (MapFlowControl) (DumpDlcModifyParms) (DumpDlcOpenSapParms) (MapOptionsPriority) (DumpDlcOpenStationParms) (DumpDlcReallocateParms) (DumpDlcResetParms) (DumpDlcStatisticsParms) (DumpPdtTraceOffParms) (DumpPdtTraceOnParms) (DumpReadParms) (MapReadEvent) (MapDlcStatus) (DumpReadCancelParms) (DumpReceiveParms) (DumpReceiveCancelParms) (DumpReceiveModifyParms) (DumpTransmitDirFrameParms) (DumpTransmitIFrameParms) (DumpTransmitTestCmdParms) (DumpTransmitUiFrameParms) (DumpTransmitXidCmdParms) (DumpTransmitXidRespFinalParms) (DumpTransmitXidRespNotFinalParms) (DumpTransmitParms) (DumpTransmitQueue) DumpReceiveDataBuffer (MapMessageType) DumpData IsCcbErrorCodeAllowable IsCcbErrorCodeValid IsCcbCommandValid MapCcbCommandToName DumpDosAdapter (MapAdapterType) Author: Richard L Firth (rfirth) 30-Apr-1992 Revision History: --*/ #if DBG #include <stdio.h> #include <stdarg.h> #include <string.h> #include <nt.h> #include <ntrtl.h> // ASSERT, DbgPrint #include <nturtl.h> #include <windows.h> #include <softpc.h> // x86 virtual machine definitions #include <vrdlctab.h> #include <vdmredir.h> #include <smbgtpt.h> #include <dlcapi.h> // Official DLC API definition #include <ntdddlc.h> // IOCTL commands #include <dlcio.h> // Internal IOCTL API interface structures #include "vrdlc.h" #include "vrdebug.h" #include "vrdlcdbg.h" // // defines // // // standard parameters to each table dump routine // #define DUMP_TABLE_PARMS \ IN PVOID Parameters, \ IN BOOL IsDos, \ IN BOOL IsInput, \ IN WORD Segment, \ IN WORD Offset // // DumpData options // #define DD_NO_ADDRESS 0x00000001 // don't display address of data #define DD_LINE_BEFORE 0x00000002 // linefeed before first dumped line #define DD_LINE_AFTER 0x00000004 // linefeed after last dumped line #define DD_INDENT_ALL 0x00000008 // indent all lines #define DD_NO_ASCII 0x00000010 // don't dump ASCII respresentation #define DD_UPPER_CASE 0x00000020 // upper-case hex dump (F4 instead of f4) // // misc. // #define DEFAULT_FIELD_WIDTH 13 // amount of description before a number // // local prototypes // VOID DbgOutStr( IN LPSTR Str ); PRIVATE VOID DefaultParameterTableDump( DUMP_TABLE_PARMS ); PRIVATE VOID DumpParameterTableHeader( IN LPSTR CommandName, IN PVOID Table, IN BOOL IsDos, IN WORD Segment, IN WORD Offset ); PRIVATE VOID DumpBufferFreeParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpBufferGetParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpDirCloseAdapterParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpDirDefineMifEnvironmentParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpDirInitializeParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpDirModifyOpenParmsParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpDirOpenAdapterParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpDirReadLog( DUMP_TABLE_PARMS ); PRIVATE VOID DumpDirRestoreOpenParmsParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpDirSetFunctionalAddressParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpDirSetGroupAddressParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpDirSetUserAppendageParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpDirStatusParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpDirTimerCancelParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpDirTimerCancelGroupParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpDirTimerSetParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpDlcCloseSapParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpDlcCloseStationParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpDlcConnectStationParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpDlcFlowControlParms( DUMP_TABLE_PARMS ); PRIVATE LPSTR MapFlowControl( BYTE FlowControl ); PRIVATE VOID DumpDlcModifyParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpDlcOpenSapParms( DUMP_TABLE_PARMS ); PRIVATE LPSTR MapOptionsPriority( UCHAR OptionsPriority ); PRIVATE VOID DumpDlcOpenStationParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpDlcReallocateParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpDlcResetParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpDlcStatisticsParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpPdtTraceOffParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpPdtTraceOnParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpReadParms( DUMP_TABLE_PARMS ); PRIVATE LPSTR MapReadEvent( UCHAR Event ); PRIVATE LPSTR MapDlcStatus( WORD Status ); PRIVATE VOID DumpReadCancelParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpReceiveParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpReceiveCancelParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpReceiveModifyParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpTransmitDirFrameParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpTransmitIFrameParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpTransmitTestCmdParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpTransmitUiFrameParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpTransmitXidCmdParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpTransmitXidRespFinalParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpTransmitXidRespNotFinalParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpTransmitParms( DUMP_TABLE_PARMS ); PRIVATE VOID DumpTransmitQueue( IN DOS_ADDRESS dpQueue ); PRIVATE LPSTR MapMessageType( UCHAR MessageType ); VOID DumpData( IN LPSTR Title, IN PBYTE Address, IN DWORD Length, IN DWORD Options, IN DWORD Indent, IN BOOL IsDos, IN WORD Segment, IN WORD Offset ); PRIVATE LPSTR MapAdapterType( IN ADAPTER_TYPE AdapterType ); // // explanations of error codes returned in CCB_RETCODE fields. Explanations // taken more-or-less verbatim from IBM Local Area Network Technical Reference // table B-1 ppB-2 to B-5. Includes all errors, even not relevant to CCB1 // static LPSTR CcbRetcodeExplanations[] = { "Success", "Invalid command code", "Duplicate command, one already outstanding", "Adapter open, should be closed", "Adapter closed, should be open", "Required parameter missing", "Invalid/incompatible option", "Command cancelled - unrecoverable failure", "Unauthorized access priority", "Adapter not initialized, should be", "Command cancelled by user request", "Command cancelled, adapter closed while command in progress", "Command completed Ok, adapter not open", "Invalid error code 0x0D", "Invalid error code 0x0E", "Invalid error code 0x0F", "Adapter open, NetBIOS not operational", "Error in DIR.TIMER.SET or DIR.TIMER.CANCEL", "Available work area exceeded", "Invalid LOG.ID", "Invalid shared RAM segment or size", "Lost log data, buffer too small, log reset", "Requested buffer size exceeds pool length", "Command invalid, NetBIOS operational", "Invalid SAP buffer length", "Inadequate buffers available for request", "USER_LENGTH value too large for buffer length", "The CCB_PARM_TAB pointer is invalid", "A pointer in the CCB parameter table is invalid", "Invalid CCB_ADAPTER value", "Invalid functional address", "Invalid error code 0x1F", "Lost data on receive, no buffers available", "Lost data on receive, inadequate buffer space", "Error on frame transmission, check TRANSMIT_FS data", "Error on frame transmit or strip process", "Unauthorized MAC frame", "Maximum number of commands exceeded", "Unrecognized command correlator", "Link not transmitting I frames, state changed from link opened", "Invalid transmit frame length", "Invalid error code 0x29", "Invalid error code 0x2a", "Invalid error code 0x2b", "Invalid error code 0x2c", "Invalid error code 0x2d", "Invalid error code 0x2e", "Invalid error code 0x2f", "Inadequate receive buffers for adapter to open", "Invalid error code 0x31", "Invalid NODE_ADDRESS", "Invalid adapter receive buffer length defined", "Invalid adapter transmit buffer length defined", "Invalid error code 0x35", "Invalid error code 0x36", "Invalid error code 0x37", "Invalid error code 0x38", "Invalid error code 0x39", "Invalid error code 0x3a", "Invalid error code 0x3b", "Invalid error code 0x3c", "Invalid error code 0x3d", "Invalid error code 0x3e", "Invalid error code 0x3f", "Invalid STATION_ID", "Protocol error, link in invalid state for command", "Parameter exceeded maximum allowed", "Invalid SAP value or value already in use", "Invalid routing information field", "Requested group membership in non-existent group SAP", "Resources not available", "Sap cannot close unless all link stations are closed", "Group SAP cannot close, individual SAPs not closed", "Group SAP has reached maximum membership", "Sequence error, incompatible command in progress", "Station closed without remote acknowledgement", "Sequence error, cannot close, DLC commands outstanding", "Unsuccessful link station connection attempted", "Member SAP not found in group SAP list", "Invalid remote address, may not be a group address", "Invalid pointer in CCB_POINTER field", "Invalid error code 0x51", "Invalid application program ID", "Invalid application program key code", "Invalid system key code", "Buffer is smaller than buffer size given in DLC.OPEN.SAP", "Adapter's system process is not installed", "Inadequate stations available", "Invalid CCB_PARAMETER_1 parameter", "Inadequate queue elements to satisfy request", "Initialization failure, cannot open adapter", "Error detected in chained READ command", "Direct stations not assigned to application program", "Dd interface not installed", "Requested adapter is not installed", "Chained CCBs must all be for same adapter", "Adapter initializing, command not accepted", "Number of allowed application programs has been exceeded", "Command cancelled by system action", "Direct stations not available", "Invalid DDNAME parameter", "Inadequate GDT selectors to satisfy request", "Invalid error code 0x66", "Command cancelled, CCB resources purged", "Application program ID not valid for interface", "Segment associated with request cannot be locked" }; #define NUMBER_OF_ERROR_MESSAGES ARRAY_ELEMENTS(CcbRetcodeExplanations) #define LAST_DLC_ERROR_CODE LAST_ELEMENT(CcbRetcodeExplanations) VOID DbgOut( IN LPSTR Format, IN ... ) /*++ Routine Description: Sends formatted debug output to desired output device. If DEBUG_TO_FILE was specified in VR environment flags, output goes to VRDEBUG.LOG in current directory, else to standard debug output via DbgPrint Arguments: Format - printf-style format string ... - variable args Return Value: None. --*/ { va_list list; char buffer[2048]; va_start(list, Format); vsprintf(buffer, Format, list); va_end(list); if (hVrDebugLog) { fputs(buffer, hVrDebugLog); } else { DbgPrint(buffer); } } VOID DbgOutStr( IN LPSTR Str ) /*++ Routine Description: Sends formatted debug output to desired output device. If DEBUG_TO_FILE was specified in VR environment flags, output goes to VRDEBUG.LOG in current directory, else to standard debug output via DbgPrint Arguments: Str - string to print Return Value: None. --*/ { if (hVrDebugLog) { fputs(Str, hVrDebugLog); } else { DbgPrint(Str); } } VOID DumpCcb( IN PVOID Ccb, IN BOOL DumpAll, IN BOOL CcbIsInput, IN BOOL IsDos, IN WORD Segment OPTIONAL, IN WORD Offset OPTIONAL ) /*++ Routine Description: Dumps (to debug terminal) a CCB and any associated parameter table. Also displays the symbolic CCB command and an error code description if the CCB is being returned to the caller. Dumps in either DOS format (segmented 16-bit pointers) or NT format (flat 32-bit pointers) Arguments: Ccb - flat 32-bit pointer to CCB1 or CCB2 to dump DumpAll - if TRUE, dumps parameter tables and buffers, else just CCB CcbIsInput - if TRUE, CCB is from user: don't display error code explanation IsDos - if TRUE, CCB is DOS format Segment - if IsDos is TRUE, segment of CCB in VDM Offset - if IsDos is TRUE, offset of CCB in VDM Return Value: None. --*/ { PVOID parmtab = NULL; LPSTR cmdname = "UNKNOWN CCB!"; PLLC_CCB NtCcb = (PLLC_CCB)Ccb; PLLC_DOS_CCB DosCcb = (PLLC_DOS_CCB)Ccb; BOOL haveParms = FALSE; VOID (*DumpParms)(PVOID, BOOL, BOOL, WORD, WORD) = DefaultParameterTableDump; PVOID parameterTable = NULL; WORD seg; WORD off; BOOL parmsInCcb = FALSE; switch (((PLLC_CCB)Ccb)->uchDlcCommand) { case LLC_BUFFER_FREE: cmdname = "BUFFER.FREE"; haveParms = TRUE; DumpParms = DumpBufferFreeParms; break; case LLC_BUFFER_GET: cmdname = "BUFFER.GET"; haveParms = TRUE; DumpParms = DumpBufferGetParms; break; case LLC_DIR_CLOSE_ADAPTER: cmdname = "DIR.CLOSE.ADAPTER"; haveParms = TRUE; DumpParms = DumpDirCloseAdapterParms; parmsInCcb = TRUE; break; case LLC_DIR_CLOSE_DIRECT: cmdname = "DIR.CLOSE.DIRECT"; break; case 0x2b: // // not supported ! (yet?) // cmdname = "DIR.DEFINE.MIF.ENVIRONMENT"; haveParms = TRUE; break; case LLC_DIR_INITIALIZE: cmdname = "DIR.INITIALIZE"; haveParms = TRUE; DumpParms = DumpDirInitializeParms; break; case LLC_DIR_INTERRUPT: cmdname = "DIR.INTERRUPT"; break; case LLC_DIR_MODIFY_OPEN_PARMS: cmdname = "DIR.MODIFY.OPEN.PARMS"; haveParms = TRUE; break; case LLC_DIR_OPEN_ADAPTER: cmdname = "DIR.OPEN.ADAPTER"; haveParms = TRUE; DumpParms = DumpDirOpenAdapterParms; break; case LLC_DIR_OPEN_DIRECT: // // not supported from DOS! // cmdname = "DIR.OPEN.DIRECT"; haveParms = TRUE; break; case LLC_DIR_READ_LOG: cmdname = "DIR.READ.LOG"; haveParms = TRUE; break; case LLC_DIR_RESTORE_OPEN_PARMS: cmdname = "DIR.RESTORE.OPEN.PARMS"; break; case LLC_DIR_SET_FUNCTIONAL_ADDRESS: cmdname = "DIR.SET.FUNCTIONAL.ADDRESS"; haveParms = TRUE; DumpParms = DumpDirSetFunctionalAddressParms; parmsInCcb = TRUE; break; case LLC_DIR_SET_GROUP_ADDRESS: cmdname = "DIR.SET.GROUP.ADDRESS"; haveParms = TRUE; DumpParms = DumpDirSetGroupAddressParms; parmsInCcb = TRUE; break; case LLC_DIR_SET_USER_APPENDAGE: cmdname = "DIR.SET.USER.APPENDAGE"; haveParms = TRUE; DumpParms = DumpDirSetUserAppendageParms; break; case LLC_DIR_STATUS: cmdname = "DIR.STATUS"; haveParms = TRUE; DumpParms = DumpDirStatusParms; break; case LLC_DIR_TIMER_CANCEL: cmdname = "DIR.TIMER.CANCEL"; haveParms = TRUE; DumpParms = DumpDirTimerCancelParms; parmsInCcb = TRUE; break; case LLC_DIR_TIMER_CANCEL_GROUP: cmdname = "DIR.TIMER.CANCEL.GROUP"; haveParms = TRUE; DumpParms = DumpDirTimerCancelGroupParms; parmsInCcb = TRUE; break; case LLC_DIR_TIMER_SET: cmdname = "DIR.TIMER.SET"; haveParms = TRUE; DumpParms = DumpDirTimerSetParms; parmsInCcb = TRUE; break; case LLC_DLC_CLOSE_SAP: cmdname = "DLC.CLOSE.SAP"; haveParms = TRUE; DumpParms = DumpDlcCloseSapParms; parmsInCcb = TRUE; break; case LLC_DLC_CLOSE_STATION: cmdname = "DLC.CLOSE.STATION"; haveParms = TRUE; DumpParms = DumpDlcCloseStationParms; parmsInCcb = TRUE; break; case LLC_DLC_CONNECT_STATION: cmdname = "DLC.CONNECT.STATION"; haveParms = TRUE; DumpParms = DumpDlcConnectStationParms; break; case LLC_DLC_FLOW_CONTROL: cmdname = "DLC.FLOW.CONTROL"; haveParms = TRUE; DumpParms = DumpDlcFlowControlParms; parmsInCcb = TRUE; break; case LLC_DLC_MODIFY: cmdname = "DLC.MODIFY"; haveParms = TRUE; break; case LLC_DLC_OPEN_SAP: cmdname = "DLC.OPEN.SAP"; haveParms = TRUE; DumpParms = DumpDlcOpenSapParms; break; case LLC_DLC_OPEN_STATION: cmdname = "DLC.OPEN.STATION"; haveParms = TRUE; DumpParms = DumpDlcOpenStationParms; break; case LLC_DLC_REALLOCATE_STATIONS: cmdname = "DLC.REALLOCATE"; haveParms = TRUE; break; case LLC_DLC_RESET: cmdname = "DLC.RESET"; haveParms = TRUE; DumpParms = DumpDlcResetParms; parmsInCcb = TRUE; break; case LLC_DLC_SET_THRESHOLD: cmdname = "DLC.SET.THRESHOLD"; haveParms = TRUE; break; case LLC_DLC_STATISTICS: cmdname = "DLC.STATISTICS"; haveParms = TRUE; break; case 0x25: // // not supported ! // cmdname = "PDT.TRACE.OFF"; break; case 0x24: // // not supported ! // cmdname = "PDT.TRACE.ON"; break; case LLC_READ: cmdname = "READ"; haveParms = TRUE; DumpParms = DumpReadParms; break; case LLC_READ_CANCEL: cmdname = "READ.CANCEL"; break; case LLC_RECEIVE: cmdname = "RECEIVE"; haveParms = TRUE; DumpParms = DumpReceiveParms; break; case LLC_RECEIVE_CANCEL: cmdname = "RECEIVE.CANCEL"; haveParms = TRUE; DumpParms = DumpReceiveCancelParms; parmsInCcb = TRUE; break; case LLC_RECEIVE_MODIFY: cmdname = "RECEIVE.MODIFY"; haveParms = TRUE; DumpParms = DumpReceiveModifyParms; break; case LLC_TRANSMIT_DIR_FRAME: cmdname = "TRANSMIT.DIR.FRAME"; haveParms = TRUE; DumpParms = DumpTransmitDirFrameParms; break; case LLC_TRANSMIT_I_FRAME: cmdname = "TRANSMIT.I.FRAME"; haveParms = TRUE; DumpParms = DumpTransmitIFrameParms; break; case LLC_TRANSMIT_TEST_CMD: cmdname = "TRANSMIT.TEST.CMD"; haveParms = TRUE; DumpParms = DumpTransmitTestCmdParms; break; case LLC_TRANSMIT_UI_FRAME: cmdname = "TRANSMIT.UI.FRAME"; haveParms = TRUE; DumpParms = DumpTransmitUiFrameParms; break; case LLC_TRANSMIT_XID_CMD: cmdname = "TRANSMIT.XID.CMD"; haveParms = TRUE; DumpParms = DumpTransmitXidCmdParms; break; case LLC_TRANSMIT_XID_RESP_FINAL: cmdname = "TRANSMIT.XID.RESP.FINAL"; haveParms = TRUE; DumpParms = DumpTransmitXidRespFinalParms; break; case LLC_TRANSMIT_XID_RESP_NOT_FINAL: cmdname = "TRANSMIT.XID.RESP.NOT.FINAL"; haveParms = TRUE; DumpParms = DumpTransmitXidRespNotFinalParms; break; } if (IsDos) { seg = GET_SELECTOR(&DosCcb->u.pParms); off = GET_OFFSET(&DosCcb->u.pParms); parmtab = POINTER_FROM_WORDS(seg, off); } else { parmtab = NtCcb->u.pParameterTable; } if (IsDos) { PLLC_DOS_CCB DosCcb = (PLLC_DOS_CCB)Ccb; DBGPRINT( "\n" "------------------------------------------------------------------------------" "\n" ); IF_DEBUG(TIME) { SYSTEMTIME timestruct; GetLocalTime(&timestruct); DBGPRINT( "%02d:%02d:%02d.%03d\n", timestruct.wHour, timestruct.wMinute, timestruct.wSecond, timestruct.wMilliseconds ); } DBGPRINT( "%s DOS CCB @%04x:%04x:\n" "adapter %02x\n" "command %02x [%s]\n" "retcode %02x [%s]\n" "reserved %02x\n" "next %04x:%04x\n" "ANR %04x:%04x\n", CcbIsInput ? "INPUT" : "OUTPUT", Segment, Offset, DosCcb->uchAdapterNumber, DosCcb->uchDlcCommand, cmdname, DosCcb->uchDlcStatus, CcbIsInput ? "" : MapCcbRetcode(DosCcb->uchDlcStatus), DosCcb->uchReserved1, GET_SEGMENT(&DosCcb->pNext), GET_OFFSET(&DosCcb->pNext), GET_SEGMENT(&DosCcb->ulCompletionFlag), GET_OFFSET(&DosCcb->ulCompletionFlag) ); if (haveParms) { if (!parmsInCcb) { DBGPRINT( "parms %04x:%04x\n", GET_SEGMENT(&DosCcb->u.pParms), GET_OFFSET(&DosCcb->u.pParms) ); parameterTable = POINTER_FROM_WORDS(GET_SEGMENT(&DosCcb->u.pParms), GET_OFFSET(&DosCcb->u.pParms) ); } else { parameterTable = (PVOID)READ_DWORD(&DosCcb->u.ulParameter); } } } else { PLLC_CCB NtCcb = (PLLC_CCB)Ccb; DBGPRINT( "\n" "------------------------------------------------------------------------------" "\n" ); IF_DEBUG(TIME) { SYSTEMTIME timestruct; GetLocalTime(&timestruct); DBGPRINT( "%02d:%02d:%02d.%03d\n", timestruct.wHour, timestruct.wMinute, timestruct.wSecond, timestruct.wMilliseconds ); } DBGPRINT( "%s NT CCB @ %#8x\n" "adapter %02x\n" "command %02x [%s]\n" "retcode %02x [%s]\n" "reserved %02x\n" "next %08x\n" "ANR %08x\n", CcbIsInput ? "INPUT" : "OUTPUT", Ccb, NtCcb->uchAdapterNumber, NtCcb->uchDlcCommand, cmdname, NtCcb->uchDlcStatus, CcbIsInput ? "" : MapCcbRetcode(NtCcb->uchDlcStatus), NtCcb->uchReserved1, NtCcb->pNext, NtCcb->ulCompletionFlag ); if (haveParms) { if (!parmsInCcb) { DBGPRINT( "parms %08x\n", NtCcb->u.pParameterTable ); } parameterTable = NtCcb->u.pParameterTable; } DBGPRINT( "hEvent %08x\n" "reserved %02x\n" "readflag %02x\n" "reserved %04x\n", NtCcb->hCompletionEvent, NtCcb->uchReserved2, NtCcb->uchReadFlag, NtCcb->usReserved3 ); } if ((parameterTable && DumpAll) || parmsInCcb) { DumpParms(parameterTable, IsDos, CcbIsInput, seg, off); } } VOID DumpDosDlcBufferPool( IN PDOS_DLC_BUFFER_POOL PoolDescriptor ) /*++ Routine Description: Dumps a DOS DLC buffer pool so we can see that it looks ok Arguments: PoolDescriptor - pointer to DOS_DLC_BUFFER_POOL structure Return Value: None. --*/ { int count = PoolDescriptor->BufferCount; DBGPRINT( "DOS DLC Buffer Pool @%04x:%04x, BufferSize=%d, BufferCount=%d\n", HIWORD(PoolDescriptor->dpBuffer), LOWORD(PoolDescriptor->dpBuffer), PoolDescriptor->BufferSize, PoolDescriptor->BufferCount ); DumpDosDlcBufferChain(PoolDescriptor->dpBuffer, PoolDescriptor->BufferCount); } VOID DumpDosDlcBufferChain( IN DOS_ADDRESS DosAddress, IN DWORD BufferCount ) /*++ Routine Description: Dumps a chain of DOS buffers Arguments: DosAddress - address of buffer in VDM memory in DOS_ADDRESS format (16:16) BufferCount - number of buffers to dump Return Value: None. --*/ { WORD seg = HIWORD(DosAddress); WORD off = LOWORD(DosAddress); LPVOID pointer = DOS_PTR_TO_FLAT(DosAddress); int i; for (i = 1; BufferCount; --BufferCount, ++i) { DBGPRINT("Buffer % 3d: %04x:%04x, Next Buffer @%04x:%04x\n", i, seg, off, (DWORD)GET_SELECTOR(&((PLLC_DOS_BUFFER)pointer)->pNext), (DWORD)GET_OFFSET(&((PLLC_DOS_BUFFER)pointer)->pNext) ); seg = GET_SELECTOR(&((PLLC_DOS_BUFFER)pointer)->pNext); off = GET_OFFSET(&((PLLC_DOS_BUFFER)pointer)->pNext); IF_DEBUG(DUMP_FREE_BUF) { PLLC_DOS_BUFFER pBuf = (PLLC_DOS_BUFFER)pointer; DBGPRINT( "next buffer %04x:%04x\n" "frame length %04x\n" "data length %04x\n" "user offset %04x\n" "user length %04x\n" "station id %04x\n" "options %02x\n" "message type %02x\n" "buffers left %04x\n" "rcv FS %02x\n" "adapter num %02x\n" "\n", GET_SEGMENT(&pBuf->Contiguous.pNextBuffer), GET_OFFSET(&pBuf->Contiguous.pNextBuffer), READ_WORD(&pBuf->Contiguous.cbFrame), READ_WORD(&pBuf->Contiguous.cbBuffer), READ_WORD(&pBuf->Contiguous.offUserData), READ_WORD(&pBuf->Contiguous.cbUserData), READ_WORD(&pBuf->Contiguous.usStationId), pBuf->Contiguous.uchOptions, pBuf->Contiguous.uchMsgType, READ_WORD(&pBuf->Contiguous.cBuffersLeft), pBuf->Contiguous.uchRcvFS, pBuf->Contiguous.uchAdapterNumber ); } pointer = READ_FAR_POINTER(&((PLLC_DOS_BUFFER)pointer)->pNext); } } LPSTR MapCcbRetcode( IN BYTE Retcode ) /*++ Routine Description: Returns string describing error code Arguments: Retcode - CCB_RETCODE Return Value: LPSTR --*/ { static char errbuf[128]; if (Retcode == LLC_STATUS_PENDING) { return "Command in progress"; } else if (Retcode > NUMBER_OF_ERROR_MESSAGES) { sprintf(errbuf, "*** Invalid error code 0x%2x ***", Retcode); return errbuf; } return CcbRetcodeExplanations[Retcode]; } PRIVATE VOID DefaultParameterTableDump( DUMP_TABLE_PARMS ) /*++ Routine Description: Displays default message for CCBs which have parameter tables that don't have a dump routine yet Arguments: Parameters - pointer to parameter table IsDos - if TRUE parameters in DOS (16:16) format Segment - if IsDos is TRUE, segment of CCB in VDM Offset - if IsDos is TRUE, offset of CCB in VDM Return Value: None. --*/ { DBGPRINT("Parameter table dump not implemented for this CCB\n"); } PRIVATE VOID DumpParameterTableHeader( IN LPSTR CommandName, IN PVOID Table, IN BOOL IsDos, IN WORD Segment, IN WORD Offset ) /*++ Routine Description: Displays header for parameter table dump. Displays address in DOS or NT format (32-bit flat or 16:16) Arguments: CommandName - name of command which owns parameter table Table - flat 32-bit address of parameter table IsDos - if TRUE, use Segment:Offset in display Segment - if IsDos is TRUE, segment of parameter table in VDM Offset - if IsDos is TRUE, offset of parameter table in VDM Return Value: None. --*/ { DBGPRINT( IsDos ? "\n%s parameter table @%04x:%04x\n" : "\n%s parameter table @%08x\n", CommandName, IsDos ? (DWORD)Segment : (DWORD)Table, IsDos ? (DWORD)Offset : 0 ); } PRIVATE VOID DumpBufferFreeParms( DUMP_TABLE_PARMS ) { PLLC_BUFFER_FREE_PARMS parms = (PLLC_BUFFER_FREE_PARMS)Parameters; DumpParameterTableHeader("BUFFER.FREE", Parameters, IsDos, Segment, Offset); DBGPRINT( "station id %04x\n" "buffers left %04x\n" "reserved %02x %02x %02x %02x\n", READ_WORD(&parms->usReserved1), READ_WORD(&parms->cBuffersLeft), ((PBYTE)&(parms->ulReserved))[0], ((PBYTE)&(parms->ulReserved))[1], ((PBYTE)&(parms->ulReserved))[2], ((PBYTE)&(parms->ulReserved))[3] ); if (IsDos) { DBGPRINT( "first buffer %04x:%04x\n", GET_SELECTOR(&parms->pFirstBuffer), GET_OFFSET(&parms->pFirstBuffer) ); } else { DBGPRINT( "first buffer %08x\n", parms->pFirstBuffer); } } PRIVATE VOID DumpBufferGetParms( DUMP_TABLE_PARMS ) { // // Antti's definition different from that in manual, so use IBM def. // typedef struct { WORD StationId; WORD BufferLeft; BYTE BufferGet; BYTE Reserved[3]; DWORD FirstBuffer; } CCB1_BUFFER_GET_PARMS, *PCCB1_BUFFER_GET_PARMS; PCCB1_BUFFER_GET_PARMS parms = (PCCB1_BUFFER_GET_PARMS)Parameters; DumpParameterTableHeader("BUFFER.GET", Parameters, IsDos, Segment, Offset); DBGPRINT( "station id %04x\n" "buffers left %04x\n" "buffers get %02x\n" "reserved %02x %02x %02x\n", READ_WORD(&parms->StationId), READ_WORD(&parms->BufferLeft), parms->BufferGet, parms->Reserved[0], parms->Reserved[1], parms->Reserved[2] ); if (IsDos) { DBGPRINT( "first buffer %04x:%04x\n", GET_SELECTOR(&parms->FirstBuffer), GET_OFFSET(&parms->FirstBuffer) ); } else { DBGPRINT( "first buffer %08x\n", parms->FirstBuffer); } } PRIVATE VOID DumpDirCloseAdapterParms( DUMP_TABLE_PARMS ) { UNREFERENCED_PARAMETER(IsDos); UNREFERENCED_PARAMETER(Segment); UNREFERENCED_PARAMETER(Offset); DBGPRINT( "lock code %04x\n", LOWORD(Parameters)); } PRIVATE VOID DumpDirDefineMifEnvironmentParms( DUMP_TABLE_PARMS ) { } PRIVATE VOID DumpDirInitializeParms( DUMP_TABLE_PARMS ) { // // once again, invent a structure to reflect the DOS CCB parameter table // as defined in the IBM LAN tech ref // typedef struct { WORD BringUps; WORD SharedRam; BYTE Reserved[4]; DWORD AdapterCheckAppendage; DWORD NetworkStatusChangeAppendage; DWORD IoErrorAppendage; } CCB1_DIR_INITIALIZE_PARMS, *PCCB1_DIR_INITIALIZE_PARMS; PCCB1_DIR_INITIALIZE_PARMS parms = (PCCB1_DIR_INITIALIZE_PARMS)Parameters; DumpParameterTableHeader("DIR.INITIALIZE", Parameters, IsDos, Segment, Offset); DBGPRINT( "bring ups %04x\n" "shared RAM %04x\n" "reserved %02x %02x %02x %02x\n" "adap. check %04x:%04x\n" "n/w status %04x:%04x\n" "pc error %04x:%04x\n", READ_WORD(&parms->BringUps), READ_WORD(&parms->SharedRam), parms->Reserved[0], parms->Reserved[1], parms->Reserved[2], parms->Reserved[3], GET_SEGMENT(&parms->AdapterCheckAppendage), GET_OFFSET(&parms->AdapterCheckAppendage), GET_SEGMENT(&parms->NetworkStatusChangeAppendage), GET_OFFSET(&parms->NetworkStatusChangeAppendage), GET_SEGMENT(&parms->IoErrorAppendage), GET_OFFSET(&parms->IoErrorAppendage) ); } PRIVATE VOID DumpDirModifyOpenParmsParms( DUMP_TABLE_PARMS ) { } PRIVATE VOID DumpDirOpenAdapterParms( DUMP_TABLE_PARMS ) { PLLC_DOS_DIR_OPEN_ADAPTER_PARMS dosParms = (PLLC_DOS_DIR_OPEN_ADAPTER_PARMS)Parameters; PLLC_DIR_OPEN_ADAPTER_PARMS ntParms = (PLLC_DIR_OPEN_ADAPTER_PARMS)Parameters; DumpParameterTableHeader("DIR.OPEN.ADAPTER", Parameters, IsDos, Segment, Offset); if (IsDos) { PADAPTER_PARMS pAdapterParms = READ_FAR_POINTER(&dosParms->pAdapterParms); PDIRECT_PARMS pDirectParms = READ_FAR_POINTER(&dosParms->pDirectParms); PDLC_PARMS pDlcParms = READ_FAR_POINTER(&dosParms->pDlcParms); PNCB_PARMS pNcbParms = READ_FAR_POINTER(&dosParms->pNcbParms); ULPBYTE pProductId; DWORD i; DBGPRINT( "adapter parms %04x:%04x\n" "direct parms %04x:%04x\n" "DLC parms %04x:%04x\n" "NCB parms %04x:%04x\n", GET_SEGMENT(&dosParms->pAdapterParms), GET_OFFSET(&dosParms->pAdapterParms), GET_SEGMENT(&dosParms->pDirectParms), GET_OFFSET(&dosParms->pDirectParms), GET_SEGMENT(&dosParms->pDlcParms), GET_OFFSET(&dosParms->pDlcParms), GET_SEGMENT(&dosParms->pNcbParms), GET_OFFSET(&dosParms->pNcbParms) ); if (pAdapterParms) { DBGPRINT( "\n" "ADAPTER_PARMS @%04x:%04x\n" "open error %04x\n" "open options %04x\n" "node address %02x-%02x-%02x-%02x-%02x-%02x\n" "group address %08x\n" "func. address %08x\n" "# rcv buffers %04x\n" "rcv buf len %04x\n" "DHB len %04x\n" "# DHBs %02x\n" "Reserved %02x\n" "Open Lock %04x\n" "Product ID %04x:%04x\n", GET_SEGMENT(&dosParms->pAdapterParms), GET_OFFSET(&dosParms->pAdapterParms), READ_WORD(&pAdapterParms->OpenErrorCode), READ_WORD(&pAdapterParms->OpenOptions), READ_BYTE(&pAdapterParms->NodeAddress[0]), READ_BYTE(&pAdapterParms->NodeAddress[1]), READ_BYTE(&pAdapterParms->NodeAddress[2]), READ_BYTE(&pAdapterParms->NodeAddress[3]), READ_BYTE(&pAdapterParms->NodeAddress[4]), READ_BYTE(&pAdapterParms->NodeAddress[5]), READ_DWORD(&pAdapterParms->GroupAddress), READ_DWORD(&pAdapterParms->FunctionalAddress), READ_WORD(&pAdapterParms->NumberReceiveBuffers), READ_WORD(&pAdapterParms->ReceiveBufferLength), READ_WORD(&pAdapterParms->DataHoldBufferLength), READ_BYTE(&pAdapterParms->NumberDataHoldBuffers), READ_BYTE(&pAdapterParms->Reserved), READ_WORD(&pAdapterParms->OpenLock), GET_SEGMENT(&pAdapterParms->ProductId), GET_OFFSET(&pAdapterParms->ProductId) ); pProductId = READ_FAR_POINTER(&pAdapterParms->ProductId); if (pProductId) { DBGPRINT("\nPRODUCT ID:\n"); for (i=0; i<18; ++i) { DBGPRINT("%02x ", *pProductId++); } DBGPRINT("\n"); } } if (pDirectParms) { DBGPRINT( "\n" "DIRECT_PARMS @%04x:%04x\n" "dir buf size %04x\n" "dir pool blx %04x\n" "dir buf pool %04x:%04x\n" "adap chk exit %04x:%04x\n" "nw stat exit %04x:%04x\n" "pc error exit %04x:%04x\n" "adap wrk area %04x:%04x\n" "adap wrk req. %04x\n" "adap wrk act %04x\n", GET_SEGMENT(&dosParms->pDirectParms), GET_OFFSET(&dosParms->pDirectParms), READ_WORD(&pDirectParms->DirectBufferSize), READ_WORD(&pDirectParms->DirectPoolBlocks), GET_SEGMENT(&pDirectParms->DirectBufferPool), GET_OFFSET(&pDirectParms->DirectBufferPool), GET_SEGMENT(&pDirectParms->AdapterCheckExit), GET_OFFSET(&pDirectParms->AdapterCheckExit), GET_SEGMENT(&pDirectParms->NetworkStatusExit), GET_OFFSET(&pDirectParms->NetworkStatusExit), GET_SEGMENT(&pDirectParms->PcErrorExit), GET_OFFSET(&pDirectParms->PcErrorExit), GET_SEGMENT(&pDirectParms->AdapterWorkArea), GET_OFFSET(&pDirectParms->AdapterWorkArea), READ_WORD(&pDirectParms->AdapterWorkAreaRequested), READ_WORD(&pDirectParms->AdapterWorkAreaActual) ); } if (pDlcParms) { DBGPRINT( "\n" "DLC_PARMS @%04x:%04x\n" "max SAPs %02x\n" "max links %02x\n" "max grp SAPs %02x\n" "max grp memb %02x\n" "T1 tick 1 %02x\n" "T2 tick 1 %02x\n" "Ti tick 1 %02x\n" "T1 tick 2 %02x\n" "T2 tick 2 %02x\n" "Ti tick 2 %02x\n", GET_SEGMENT(&dosParms->pDlcParms), GET_OFFSET(&dosParms->pDlcParms), READ_BYTE(&pDlcParms->MaxSaps), READ_BYTE(&pDlcParms->MaxStations), READ_BYTE(&pDlcParms->MaxGroupSaps), READ_BYTE(&pDlcParms->MaxGroupMembers), READ_BYTE(&pDlcParms->T1Tick1), READ_BYTE(&pDlcParms->T2Tick1), READ_BYTE(&pDlcParms->TiTick1), READ_BYTE(&pDlcParms->T1Tick2), READ_BYTE(&pDlcParms->T2Tick2), READ_BYTE(&pDlcParms->TiTick2) ); } if (pNcbParms) { DBGPRINT( "\n" "NCB_PARMS @%04x:%04x???\n", GET_SEGMENT(&dosParms->pNcbParms), GET_OFFSET(&dosParms->pNcbParms) ); } } else { PLLC_ADAPTER_OPEN_PARMS pAdapterParms = ntParms->pAdapterParms; PLLC_EXTENDED_ADAPTER_PARMS pExtendedParms = ntParms->pExtendedParms; PLLC_DLC_PARMS pDlcParms = ntParms->pDlcParms; PVOID pNcbParms = ntParms->pReserved1; DBGPRINT( "adapter parms %08x\n" "direct parms %08x\n" "DLC parms %08x\n" "NCB parms %08x\n", pAdapterParms, pExtendedParms, pDlcParms, pNcbParms ); if (pAdapterParms) { DBGPRINT( "\n" "ADAPTER_PARMS @%08x\n" "open error %04x\n" "open options %04x\n" "node address %02x-%02x-%02x-%02x-%02x-%02x\n" "group address %08x\n" "func. address %08x\n" "reserved 1 %04x\n" "reserved 2 %04x\n" "max frame len %04x\n" "reserved 3[0] %04x\n" "reserved 3[1] %04x\n" "reserved 3[2] %04x\n" "reserved 3[3] %04x\n" "bring ups %04x\n" "init warnings %04x\n" "reserved 4[0] %04x\n" "reserved 4[1] %04x\n" "reserved 4[2] %04x\n", pAdapterParms, pAdapterParms->usOpenErrorCode, pAdapterParms->usOpenOptions, pAdapterParms->auchNodeAddress[0], pAdapterParms->auchNodeAddress[1], pAdapterParms->auchNodeAddress[2], pAdapterParms->auchNodeAddress[3], pAdapterParms->auchNodeAddress[4], pAdapterParms->auchNodeAddress[5], *(UNALIGNED DWORD *)&pAdapterParms->auchGroupAddress, *(UNALIGNED DWORD *)&pAdapterParms->auchFunctionalAddress, pAdapterParms->usReserved1, pAdapterParms->usReserved2, pAdapterParms->usMaxFrameSize, pAdapterParms->usReserved3[0], pAdapterParms->usReserved3[1], pAdapterParms->usReserved3[2], pAdapterParms->usReserved3[3], pAdapterParms->usBringUps, pAdapterParms->InitWarnings, pAdapterParms->usReserved4[0], pAdapterParms->usReserved4[1], pAdapterParms->usReserved4[2] ); } if (pExtendedParms) { DBGPRINT( "\n" "EXTENDED PARMS @%08x\n" "hBufferPool %08x\n" "pSecurityDesc %08x\n" "Ethernet Type %08x\n", pExtendedParms, pExtendedParms->hBufferPool, pExtendedParms->pSecurityDescriptor, pExtendedParms->LlcEthernetType ); } if (pDlcParms) { DBGPRINT( "\n" "DLC_PARMS @%04x:%04x\n" "max SAPs %02x\n" "max links %02x\n" "max grp SAPs %02x\n" "max grp memb %02x\n" "T1 tick 1 %02x\n" "T2 tick 1 %02x\n" "Ti tick 1 %02x\n" "T1 tick 2 %02x\n" "T2 tick 2 %02x\n" "Ti tick 2 %02x\n", pDlcParms, pDlcParms->uchDlcMaxSaps, pDlcParms->uchDlcMaxStations, pDlcParms->uchDlcMaxGroupSaps, pDlcParms->uchDlcMaxGroupMembers, pDlcParms->uchT1_TickOne, pDlcParms->uchT2_TickOne, pDlcParms->uchTi_TickOne, pDlcParms->uchT1_TickTwo, pDlcParms->uchT2_TickTwo, pDlcParms->uchTi_TickTwo ); } if (pNcbParms) { DBGPRINT( "\n" "NCB_PARMS @%08x???\n", pNcbParms ); } } } PRIVATE VOID DumpDirReadLog( DUMP_TABLE_PARMS ) { DumpParameterTableHeader("DIR.READ.LOG", Parameters, IsDos, Segment, Offset); } PRIVATE VOID DumpDirRestoreOpenParmsParms( DUMP_TABLE_PARMS ) { } PRIVATE VOID DumpDirSetFunctionalAddressParms( DUMP_TABLE_PARMS ) { DBGPRINT( "funct addr %08lx\n", Parameters); } PRIVATE VOID DumpDirSetGroupAddressParms( DUMP_TABLE_PARMS ) { DBGPRINT( "group addr %08lx\n", Parameters); } PRIVATE VOID DumpDirSetUserAppendageParms( DUMP_TABLE_PARMS ) { PLLC_DIR_SET_USER_APPENDAGE_PARMS parms = (PLLC_DIR_SET_USER_APPENDAGE_PARMS)Parameters; DumpParameterTableHeader("DIR.SET.USER.APPENDAGE", Parameters, IsDos, Segment, Offset); if (IsDos) { DBGPRINT( "adapt check %04x:%04x\n" "n/w status %04x:%04x\n" "w/s error %04x:%04x\n", GET_SEGMENT(&parms->dpAdapterCheckExit), GET_OFFSET(&parms->dpAdapterCheckExit), GET_SEGMENT(&parms->dpNetworkStatusExit), GET_OFFSET(&parms->dpNetworkStatusExit), GET_SEGMENT(&parms->dpPcErrorExit), GET_OFFSET(&parms->dpPcErrorExit) ); } } PRIVATE VOID DumpDirStatusParms( DUMP_TABLE_PARMS ) { PDOS_DIR_STATUS_PARMS dosParms = (PDOS_DIR_STATUS_PARMS)Parameters; DumpParameterTableHeader("DIR.STATUS", Parameters, IsDos, Segment, Offset); if (IsDos) { DBGPRINT( "perm addr %02x-%02x-%02x-%02x-%02x-%02x\n" "local addr %02x-%02x-%02x-%02x-%02x-%02x\n" "group addr %08lx\n" "func addr %08lx\n" "max SAPs %02x\n" "open SAPs %02x\n" "max links %02x\n" "open links %02x\n" "avail links %02x\n" "adapt config %02x\n" "ucode level %02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x\n" "adap parms %04x:%04x\n" "adap MAC %04x:%04x\n" "timer tick %04x:%04x\n" "last NW stat %04x\n" "ext. status %04x:%04x\n", dosParms->auchPermanentAddress[0], dosParms->auchPermanentAddress[1], dosParms->auchPermanentAddress[2], dosParms->auchPermanentAddress[3], dosParms->auchPermanentAddress[4], dosParms->auchPermanentAddress[5], dosParms->auchNodeAddress[0], dosParms->auchNodeAddress[1], dosParms->auchNodeAddress[2], dosParms->auchNodeAddress[3], dosParms->auchNodeAddress[4], dosParms->auchNodeAddress[5], READ_DWORD(&dosParms->auchGroupAddress), READ_DWORD(&dosParms->auchFunctAddr), dosParms->uchMaxSap, dosParms->uchOpenSaps, dosParms->uchMaxStations, dosParms->uchOpenStation, dosParms->uchAvailStations, dosParms->uchAdapterConfig, dosParms->auchMicroCodeLevel[0], dosParms->auchMicroCodeLevel[1], dosParms->auchMicroCodeLevel[2], dosParms->auchMicroCodeLevel[3], dosParms->auchMicroCodeLevel[4], dosParms->auchMicroCodeLevel[5], dosParms->auchMicroCodeLevel[6], dosParms->auchMicroCodeLevel[7], dosParms->auchMicroCodeLevel[8], dosParms->auchMicroCodeLevel[9], GET_SEGMENT(&dosParms->dpAdapterParmsAddr), GET_OFFSET(&dosParms->dpAdapterParmsAddr), GET_SEGMENT(&dosParms->dpAdapterMacAddr), GET_OFFSET(&dosParms->dpAdapterMacAddr), GET_SEGMENT(&dosParms->dpTimerTick), GET_OFFSET(&dosParms->dpTimerTick), READ_WORD(&dosParms->usLastNetworkStatus), GET_SEGMENT(&dosParms->dpExtendedParms), GET_OFFSET(&dosParms->dpExtendedParms) ); } else { DBGPRINT("no dump for this table yet\n"); } } PRIVATE VOID DumpDirTimerCancelParms( DUMP_TABLE_PARMS ) { if (IsDos) { DBGPRINT( "cancel timer %04x:%04x\n", HIWORD(Parameters), LOWORD(Parameters) ); } } PRIVATE VOID DumpDirTimerCancelGroupParms( DUMP_TABLE_PARMS ) { if (IsDos) { DBGPRINT( "cancel timer %04x:%04x\n", HIWORD(Parameters), LOWORD(Parameters) ); } } PRIVATE VOID DumpDirTimerSetParms( DUMP_TABLE_PARMS ) { if (IsDos) { DBGPRINT( "timer value %04x\n", LOWORD(Parameters) ); } } PRIVATE VOID DumpDlcCloseSapParms( DUMP_TABLE_PARMS ) { if (IsDos) { DBGPRINT( "STATION_ID %04x\n" "reserved %04x\n", LOWORD(Parameters), HIWORD(Parameters) ); } } PRIVATE VOID DumpDlcCloseStationParms( DUMP_TABLE_PARMS ) { if (IsDos) { DBGPRINT( "STATION_ID %04x\n" "reserved %02x %02x\n", LOWORD(Parameters), LOBYTE(HIWORD(Parameters)), HIBYTE(HIWORD(Parameters)) ); } } PRIVATE VOID DumpDlcConnectStationParms( DUMP_TABLE_PARMS ) { LLC_DLC_CONNECT_PARMS UNALIGNED * parms = (PLLC_DLC_CONNECT_PARMS)Parameters; ULPBYTE routing = NULL; int i; DumpParameterTableHeader("DLC.CONNECT.STATION", Parameters, IsDos, Segment, Offset); DBGPRINT( "station id %04x\n" "reserved %02x %02x\n", READ_WORD(&parms->usStationId), ((ULPBYTE)(&parms->usReserved))[0], ((ULPBYTE)(&parms->usReserved))[1] ); if (IsDos) { DBGPRINT( "routing addr %04x:%04x\n", GET_SEGMENT(&parms->pRoutingInfo), GET_OFFSET(&parms->pRoutingInfo) ); routing = READ_FAR_POINTER(&parms->pRoutingInfo); } else { DBGPRINT( "routing addr %08x\n", parms->pRoutingInfo ); routing = parms->pRoutingInfo; } if (routing) { DBGPRINT("ROUTING INFO: "); for (i=0; i<18; ++i) { DBGPRINT("%02x ", routing[i]); } DBGPRINT("\n"); } } PRIVATE VOID DumpDlcFlowControlParms( DUMP_TABLE_PARMS ) { DBGPRINT( "STATION_ID %04x\n" "flow control %02x [%s]\n" "reserved %02x\n", LOWORD(Parameters), LOBYTE(HIWORD(Parameters)), MapFlowControl(LOBYTE(HIWORD(Parameters))), HIBYTE(HIWORD(Parameters)) ); } PRIVATE LPSTR MapFlowControl(BYTE FlowControl) { if (FlowControl & 0x80) { if (FlowControl & 0x40) { return "reset local_busy(buffer)"; } else { return "reset local_busy(user)"; } } else { return "set local_busy(user)"; } } PRIVATE VOID DumpDlcModifyParms( DUMP_TABLE_PARMS ) { } PRIVATE VOID DumpDlcOpenSapParms( DUMP_TABLE_PARMS ) { PLLC_DLC_OPEN_SAP_PARMS parms = (PLLC_DLC_OPEN_SAP_PARMS)Parameters; DumpParameterTableHeader("DLC.OPEN.SAP", Parameters, IsDos, Segment, Offset); DBGPRINT( "station id %04x\n" "user stat %04x\n" "T1 %02x\n" "T2 %02x\n" "Ti %02x\n" "max out %02x\n" "max in %02x\n" "max out inc %02x\n" "max retry %02x\n" "max members %02x\n" "max I field %04x\n" "SAP value %02x\n" "options %02x [%s]\n" "link count %02x\n" "reserved %02x %02x\n" "group count %02x\n", READ_WORD(&parms->usStationId), READ_WORD(&parms->usUserStatValue), parms->uchT1, parms->uchT2, parms->uchTi, parms->uchMaxOut, parms->uchMaxIn, parms->uchMaxOutIncr, parms->uchMaxRetryCnt, parms->uchMaxMembers, READ_WORD(&parms->usMaxI_Field), parms->uchSapValue, parms->uchOptionsPriority, MapOptionsPriority(parms->uchOptionsPriority), parms->uchcStationCount, parms->uchReserved2[0], parms->uchReserved2[1], parms->cGroupCount ); if (IsDos) { DBGPRINT( "group list %04x:%04x\n" "dlc stat app %04x:%04x\n", GET_SEGMENT(&parms->pGroupList), GET_OFFSET(&parms->pGroupList), GET_SEGMENT(&parms->DlcStatusFlags), GET_OFFSET(&parms->DlcStatusFlags) ); // // some code here to dump group list // } else { DBGPRINT( "group list %08x\n" "dlc status %08x\n", parms->pGroupList, parms->DlcStatusFlags ); } DBGPRINT( "buffer size %04x\n" "pool length %04x\n", READ_WORD(&parms->uchReserved3[0]), READ_WORD(&parms->uchReserved3[2]) ); if (IsDos) { DBGPRINT( "buffer pool %04x:%04x\n", READ_WORD(&parms->uchReserved3[6]), READ_WORD(&parms->uchReserved3[4]) ); } else { DBGPRINT( "buffer pool %08x\n", *(LPDWORD)&parms->uchReserved3[4] ); } } PRIVATE LPSTR MapOptionsPriority(UCHAR OptionsPriority) { static char buf[80]; char* bufptr = buf; bufptr += sprintf(buf, "Access Priority=%d", (OptionsPriority & 0xe0) >> 5); if (OptionsPriority & 8) { bufptr += sprintf(bufptr, " XID handled by APP"); } else { bufptr += sprintf(bufptr, " XID handled by DLC"); } if (OptionsPriority & 4) { bufptr += sprintf(bufptr, " Individual SAP"); } if (OptionsPriority & 2) { bufptr += sprintf(bufptr, " Group SAP"); } if (OptionsPriority & 1) { bufptr += sprintf(bufptr, " Group Member SAP"); } return buf; } PRIVATE VOID DumpDlcOpenStationParms( DUMP_TABLE_PARMS ) { PLLC_DLC_OPEN_STATION_PARMS parms = (PLLC_DLC_OPEN_STATION_PARMS)Parameters; ULPBYTE dest = NULL; int i; DumpParameterTableHeader("DLC.OPEN.STATION", Parameters, IsDos, Segment, Offset); DBGPRINT( "sap station %04x\n" "link station %04x\n" "T1 %02x\n" "T2 %02x\n" "Ti %02x\n" "max out %02x\n" "max in %02x\n" "max out inc %02x\n" "max retry %02x\n" "remote SAP %02x\n" "max I field %04x\n" "access pri %02x\n", READ_WORD(&parms->usSapStationId), READ_WORD(&parms->usLinkStationId), parms->uchT1, parms->uchT2, parms->uchTi, parms->uchMaxOut, parms->uchMaxIn, parms->uchMaxOutIncr, parms->uchMaxRetryCnt, parms->uchRemoteSap, READ_WORD(&parms->usMaxI_Field), parms->uchAccessPriority ); if (IsDos) { DBGPRINT( "destination %04x:%04x\n", GET_SEGMENT(&parms->pRemoteNodeAddress), GET_OFFSET(&parms->pRemoteNodeAddress) ); dest = READ_FAR_POINTER(&parms->pRemoteNodeAddress); } else { DBGPRINT( "destination %08x\n", parms->pRemoteNodeAddress ); dest = parms->pRemoteNodeAddress; } if (dest) { DBGPRINT("DESTINATION ADDRESS: "); for (i=0; i<6; ++i) { DBGPRINT("%02x ", dest[i]); } DBGPRINT("\n"); } } PRIVATE VOID DumpDlcReallocateParms( DUMP_TABLE_PARMS ) { } PRIVATE VOID DumpDlcResetParms( DUMP_TABLE_PARMS ) { DBGPRINT( "STATION_ID %04x\n" "reserved %02x %02x\n", LOWORD(Parameters), LOBYTE(HIWORD(Parameters)), HIBYTE(HIWORD(Parameters)) ); } PRIVATE VOID DumpDlcStatisticsParms( DUMP_TABLE_PARMS ) { } PRIVATE VOID DumpPdtTraceOffParms( DUMP_TABLE_PARMS ) { } PRIVATE VOID DumpPdtTraceOnParms( DUMP_TABLE_PARMS ) { } PRIVATE VOID DumpReadParms( DUMP_TABLE_PARMS ) { PLLC_READ_PARMS parms = (PLLC_READ_PARMS)Parameters; DumpParameterTableHeader("READ", Parameters, IsDos, Segment, Offset); // // this parameter table not for DOS // DBGPRINT( "station id %04x\n" "option ind. %02x\n" "event set %02x\n" "event %02x [%s]\n" "crit. subset %02x\n" "notify flag %08x\n", parms->usStationId, parms->uchOptionIndicator, parms->uchEventSet, parms->uchEvent, MapReadEvent(parms->uchEvent), parms->uchCriticalSubset, parms->ulNotificationFlag ); // // rest of table interpreted differently depending on whether status change // if (parms->uchEvent & 0x38) { DBGPRINT( "station id %04x\n" "status code %04x [%s]\n" "FRMR data %02x %02x %02x %02x %02x\n" "access pri. %02x\n" "remote addr %02x-%02x-%02x-%02x-%02x-%02x\n" "remote SAP %02x\n" "reserved %02x\n" "user stat %04x\n", parms->Type.Status.usStationId, parms->Type.Status.usDlcStatusCode, MapDlcStatus(parms->Type.Status.usDlcStatusCode), parms->Type.Status.uchFrmrData[0], parms->Type.Status.uchFrmrData[1], parms->Type.Status.uchFrmrData[2], parms->Type.Status.uchFrmrData[3], parms->Type.Status.uchFrmrData[4], parms->Type.Status.uchAccessPritority, parms->Type.Status.uchRemoteNodeAddress[0], parms->Type.Status.uchRemoteNodeAddress[1], parms->Type.Status.uchRemoteNodeAddress[2], parms->Type.Status.uchRemoteNodeAddress[3], parms->Type.Status.uchRemoteNodeAddress[4], parms->Type.Status.uchRemoteNodeAddress[5], parms->Type.Status.uchRemoteSap, parms->Type.Status.uchReserved, parms->Type.Status.usUserStatusValue ); } else { DBGPRINT( "CCB count %04x\n" "CCB list %08x\n" "buffer count %04x\n" "buffer list %08x\n" "frame count %04x\n" "frame list %08x\n" "error code %04x\n" "error data %04x %04x %04x\n", parms->Type.Event.usCcbCount, parms->Type.Event.pCcbCompletionList, parms->Type.Event.usBufferCount, parms->Type.Event.pFirstBuffer, parms->Type.Event.usReceivedFrameCount, parms->Type.Event.pReceivedFrame, parms->Type.Event.usEventErrorCode, parms->Type.Event.usEventErrorData[0], parms->Type.Event.usEventErrorData[1], parms->Type.Event.usEventErrorData[2] ); // // address of CCB is in DOS memory // if (parms->Type.Event.usCcbCount) { DumpCcb(DOS_PTR_TO_FLAT(parms->Type.Event.pCcbCompletionList), TRUE, // DumpAll FALSE, // CcbIsInput TRUE, // IsDos HIWORD(parms->Type.Event.pCcbCompletionList), LOWORD(parms->Type.Event.pCcbCompletionList) ); } if (parms->Type.Event.usReceivedFrameCount) { DumpReceiveDataBuffer(parms->Type.Event.pReceivedFrame, FALSE, 0, 0); } } } PRIVATE LPSTR MapReadEvent(UCHAR Event) { switch (Event) { case 0x80: return "Reserved Event!"; case 0x40: return "System Action (non-critical)"; case 0x20: return "Network Status (non-critical)"; case 0x10: return "Critical Exception"; case 0x8: return "DLC Status Change"; case 0x4: return "Receive Data"; case 0x2: return "Transmit Completion"; case 0x1: return "Command Completion"; } return "Unknown Read Event"; } PRIVATE LPSTR MapDlcStatus(WORD Status) { if (Status & 0x8000) { return "Link lost"; } else if (Status & 0x4000) { return "DM/DISC Received -or- DISC ack'd"; } else if (Status & 0x2000) { return "FRMR Received"; } else if (Status & 0x1000) { return "FRMR Sent"; } else if (Status & 0x0800) { return "SABME Received for open link station"; } else if (Status & 0x0400) { return "SABME Received - link station opened"; } else if (Status & 0x0200) { return "REMOTE Busy Entered"; } else if (Status & 0x0100) { return "REMOTE Busy Left"; } else if (Status & 0x0080) { return "Ti EXPIRED"; } else if (Status & 0x0040) { return "DLC counter overflow - issue DLC.STATISTICS"; } else if (Status & 0x0020) { return "Access Priority lowered"; } else if (Status & 0x001e) { return "*** ERROR - INVALID STATUS ***"; } else if (Status & 0x0001) { return "Entered LOCAL Busy"; } else { return "Unknown DLC Status"; } } PRIVATE VOID DumpReadCancelParms( DUMP_TABLE_PARMS ) { } PRIVATE VOID DumpReceiveParms( DUMP_TABLE_PARMS ) { // // the format of the recieve parameter table is different depending on // whether this is a DOS command (CCB1) or NT (CCB2) // PLLC_RECEIVE_PARMS ntParms = (PLLC_RECEIVE_PARMS)Parameters; PLLC_DOS_RECEIVE_PARMS dosParms = (PLLC_DOS_RECEIVE_PARMS)Parameters; PLLC_DOS_RECEIVE_PARMS_EX dosExParms = (PLLC_DOS_RECEIVE_PARMS_EX)Parameters; PVOID Buffer; DumpParameterTableHeader("RECEIVE", Parameters, IsDos, Segment, Offset); // // some common bits: use any structure pointer // DBGPRINT( "station id %04x\n" "user length %04x\n", READ_WORD(&ntParms->usStationId), READ_WORD(&ntParms->usUserLength) ); // // dump segmented pointers for DOS, flat for NT // if (IsDos) { DBGPRINT( "receive exit %04x:%04x\n" "first buffer %04x:%04x\n", GET_SEGMENT(&dosParms->ulReceiveExit), GET_OFFSET(&dosParms->ulReceiveExit), GET_SEGMENT(&dosParms->pFirstBuffer), GET_OFFSET(&dosParms->pFirstBuffer) ); Buffer = READ_FAR_POINTER(&dosParms->pFirstBuffer); // // use Segment & Offset to address received data buffer // Segment = GET_SEGMENT(&dosParms->pFirstBuffer); Offset = GET_OFFSET(&dosParms->pFirstBuffer); } else { DBGPRINT( "receive flag %08x\n" "first buffer %08x\n", ntParms->ulReceiveFlag, ntParms->pFirstBuffer ); Buffer = ntParms->pFirstBuffer; } // // more common bits // DBGPRINT( "options %02x\n", ntParms->uchOptions ); if (!IsDos) { DBGPRINT( "reserved1 %02x %02x %02x\n" "read options %02x\n" "reserved2 %02x %02x %02x\n" "original CCB %08x\n" "orig. exit %08x\n", ntParms->auchReserved1[0], ntParms->auchReserved1[1], ntParms->auchReserved1[2], ntParms->uchRcvReadOption, ((PLLC_DOS_RECEIVE_PARMS_EX)ntParms)->auchReserved2[0], ((PLLC_DOS_RECEIVE_PARMS_EX)ntParms)->auchReserved2[1], ((PLLC_DOS_RECEIVE_PARMS_EX)ntParms)->auchReserved2[2], ((PLLC_DOS_RECEIVE_PARMS_EX)ntParms)->dpOriginalCcbAddress, ((PLLC_DOS_RECEIVE_PARMS_EX)ntParms)->dpCompletionFlag ); /* } else { // // we have no way of knowing from the general purpose parameters if this // is the original DOS CCB1 RECEIVE parameter table, or the extended // RECEIVE parameter table that we create. Dump the extended bits for // DOS anyhow // DBGPRINT( "\nExtended RECEIVE parameters for table @%08x\n" "reserved1 %02x %02x %02x\n" "read options %02x\n" "reserved2 %02x %02x %02x\n" "original CCB %04x:%04x\n" "orig. exit %04x:%04x\n", Parameters, dosExParms->auchReserved1[0], dosExParms->auchReserved1[1], dosExParms->auchReserved1[2], dosExParms->uchRcvReadOption, dosExParms->auchReserved2[0], dosExParms->auchReserved2[1], dosExParms->auchReserved2[2], GET_SEGMENT(&dosExParms->dpOriginalCcbAddress), GET_OFFSET(&dosExParms->dpOriginalCcbAddress), GET_SEGMENT(&dosExParms->dpCompletionFlag), GET_OFFSET(&dosExParms->dpCompletionFlag) ); */ } // // only dump the buffer(s) if this is an output CCB dump // if (Buffer && !IsInput) { DumpReceiveDataBuffer(Buffer, IsDos, Segment, Offset); } } PRIVATE VOID DumpReceiveCancelParms( DUMP_TABLE_PARMS ) { DBGPRINT("STATION_ID %04x\n", LOWORD(Parameters)); } PRIVATE VOID DumpReceiveModifyParms( DUMP_TABLE_PARMS ) { PLLC_DOS_RECEIVE_MODIFY_PARMS parms = (PLLC_DOS_RECEIVE_MODIFY_PARMS)Parameters; PVOID Buffer; DumpParameterTableHeader("RECEIVE.MODIFY", Parameters, IsDos, Segment, Offset); DBGPRINT( "station id %04x\n" "user length %04x\n" "receive exit %04x:%04x\n" "first buffer %04x:%04x\n" "subroutine %04x:%04x\n", READ_WORD(&parms->StationId), READ_WORD(&parms->UserLength), GET_SEGMENT(&parms->ReceivedDataExit), GET_OFFSET(&parms->ReceivedDataExit), GET_SEGMENT(&parms->FirstBuffer), GET_OFFSET(&parms->FirstBuffer), GET_SEGMENT(&parms->Subroutine), GET_OFFSET(&parms->Subroutine) ); Buffer = READ_FAR_POINTER(&parms->FirstBuffer); if (Buffer) { DumpReceiveDataBuffer(Buffer, IsDos, Segment, Offset); } } PRIVATE VOID DumpTransmitDirFrameParms( DUMP_TABLE_PARMS ) { DumpParameterTableHeader("TRANSMIT.DIR.FRAME", Parameters, IsDos, Segment, Offset); DumpTransmitParms(Parameters, IsDos, IsInput, Segment, Offset); } PRIVATE VOID DumpTransmitIFrameParms( DUMP_TABLE_PARMS ) { DumpParameterTableHeader("TRANSMIT.I.FRAME", Parameters, IsDos, Segment, Offset); DumpTransmitParms(Parameters, IsDos, IsInput, Segment, Offset); } PRIVATE VOID DumpTransmitTestCmdParms( DUMP_TABLE_PARMS ) { DumpParameterTableHeader("TRANSMIT.TEST.CMD", Parameters, IsDos, Segment, Offset); DumpTransmitParms(Parameters, IsDos, IsInput, Segment, Offset); } PRIVATE VOID DumpTransmitUiFrameParms( DUMP_TABLE_PARMS ) { DumpParameterTableHeader("TRANSMIT.UI.FRAME", Parameters, IsDos, Segment, Offset); DumpTransmitParms(Parameters, IsDos, IsInput, Segment, Offset); } PRIVATE VOID DumpTransmitXidCmdParms( DUMP_TABLE_PARMS ) { DumpParameterTableHeader("TRANSMIT.XID.CMD", Parameters, IsDos, Segment, Offset); DumpTransmitParms(Parameters, IsDos, IsInput, Segment, Offset); } PRIVATE VOID DumpTransmitXidRespFinalParms( DUMP_TABLE_PARMS ) { DumpParameterTableHeader("TRANSMIT.XID.RESP.FINAL", Parameters, IsDos, Segment, Offset); DumpTransmitParms(Parameters, IsDos, IsInput, Segment, Offset); } PRIVATE VOID DumpTransmitXidRespNotFinalParms( DUMP_TABLE_PARMS ) { DumpParameterTableHeader("TRANSMIT.XID.RESP.NOT.FINAL", Parameters, IsDos, Segment, Offset); DumpTransmitParms(Parameters, IsDos, IsInput, Segment, Offset); } PRIVATE VOID DumpTransmitParms( DUMP_TABLE_PARMS ) { PLLC_TRANSMIT_PARMS ntParms = (PLLC_TRANSMIT_PARMS)Parameters; PLLC_DOS_TRANSMIT_PARMS dosParms = (PLLC_DOS_TRANSMIT_PARMS)Parameters; DBGPRINT( "station id %04x\n" "frame status %02x\n" "remote SAP %02x\n", READ_WORD(&dosParms->usStationId), dosParms->uchTransmitFs, dosParms->uchRemoteSap ); if (IsDos) { DBGPRINT( "xmit q1 %04x:%04x\n" "xmit q2 %04x:%04x\n" "buf. len. 1 %04x\n" "buf. len. 2 %04x\n" "buffer 1 %04x:%04x\n" "buffer 2 %04x:%04x\n", GET_SEGMENT(&dosParms->pXmitQueue1), GET_OFFSET(&dosParms->pXmitQueue1), GET_SEGMENT(&dosParms->pXmitQueue2), GET_OFFSET(&dosParms->pXmitQueue2), READ_WORD(&dosParms->cbBuffer1), READ_WORD(&dosParms->cbBuffer2), GET_SEGMENT(&dosParms->pBuffer1), GET_OFFSET(&dosParms->pBuffer1), GET_SEGMENT(&dosParms->pBuffer2), GET_OFFSET(&dosParms->pBuffer2) ); IF_DEBUG(DLC_TX_DATA) { if (READ_DWORD(&dosParms->pXmitQueue1)) { DBGPRINT("\nXMIT_QUEUE_ONE:\n"); DumpTransmitQueue(READ_DWORD(&dosParms->pXmitQueue1)); } if (READ_DWORD(&dosParms->pXmitQueue2)) { DBGPRINT("\nXMIT_QUEUE_TWO:\n"); DumpTransmitQueue(READ_DWORD(&dosParms->pXmitQueue2)); } if (dosParms->cbBuffer1) { DBGPRINT("\nBUFFER1:\n"); DumpData(NULL, NULL, dosParms->cbBuffer1, DD_UPPER_CASE, 0, TRUE, GET_SEGMENT(&dosParms->pBuffer1), GET_OFFSET(&dosParms->pBuffer1) ); } if (dosParms->cbBuffer2) { DBGPRINT("\nBUFFER2:\n"); DumpData(NULL, NULL, dosParms->cbBuffer2, DD_UPPER_CASE, 0, TRUE, GET_SEGMENT(&dosParms->pBuffer2), GET_OFFSET(&dosParms->pBuffer2) ); } } } else { DBGPRINT( "xmit q1 %08x\n" "xmit q2 %08x\n" "buf. len. 1 %02x\n" "buf. len. 2 %02x\n" "buffer 1 %08x\n" "buffer 2 %08x\n" "xmt read opt %02x\n", ntParms->pXmitQueue1, ntParms->pXmitQueue2, ntParms->cbBuffer1, ntParms->cbBuffer2, ntParms->pBuffer1, ntParms->pBuffer2, ntParms->uchXmitReadOption ); } } PRIVATE VOID DumpTransmitQueue( IN DOS_ADDRESS dpQueue ) { PLLC_XMIT_BUFFER pTxBuffer; WORD userLength; WORD dataLength; while (dpQueue) { pTxBuffer = (PLLC_XMIT_BUFFER)DOS_PTR_TO_FLAT(dpQueue); dataLength = READ_WORD(&pTxBuffer->cbBuffer); userLength = READ_WORD(&pTxBuffer->cbUserData); DBGPRINT( "\n" "Transmit Buffer @%04x:%04x\n" "next buffer %04x:%04x\n" "reserved %02x %02x\n" "data length %04x\n" "user data %04x\n" "user length %04x\n", HIWORD(dpQueue), LOWORD(dpQueue), GET_SEGMENT(&pTxBuffer->pNext), GET_OFFSET(&pTxBuffer->pNext), ((LPBYTE)(&pTxBuffer->usReserved1))[0], ((LPBYTE)(&pTxBuffer->usReserved1))[1], dataLength, READ_WORD(&pTxBuffer->usReserved2), userLength ); DumpData("user space", (PBYTE)(&pTxBuffer->auchData), userLength, DD_NO_ADDRESS | DD_UPPER_CASE | DD_INDENT_ALL, DEFAULT_FIELD_WIDTH, FALSE, // not displaying seg:off, so no need for these 3 0, 0 ); DumpData("xmit data", (PBYTE)(&pTxBuffer->auchData) + userLength, dataLength, DD_NO_ADDRESS | DD_UPPER_CASE | DD_INDENT_ALL, DEFAULT_FIELD_WIDTH, FALSE, // not displaying seg:off, so no need for these 3 0, 0 ); dpQueue = READ_DWORD(&pTxBuffer->pNext); } } VOID DumpReceiveDataBuffer( IN PVOID Buffer, IN BOOL IsDos, IN WORD Segment, IN WORD Offset ) { if (IsDos) { PLLC_DOS_BUFFER pBuf = (PLLC_DOS_BUFFER)Buffer; BOOL contiguous = pBuf->Contiguous.uchOptions & 0xc0; WORD userLength = READ_WORD(&pBuf->Next.cbUserData); WORD dataLength = READ_WORD(&pBuf->Next.cbBuffer); WORD userOffset = READ_WORD(&pBuf->Next.offUserData); // // Buffer 1: [not] contiguous MAC/DATA // DBGPRINT( "\n" "%sContiguous MAC/DATA frame @%04x:%04x\n" "next buffer %04x:%04x\n" "frame length %04x\n" "data length %04x\n" "user offset %04x\n" "user length %04x\n" "station id %04x\n" "options %02x\n" "message type %02x [%s]\n" "buffers left %04x\n" "rcv FS %02x\n" "adapter num %02x\n", contiguous ? "" : "Not", Segment, Offset, GET_SEGMENT(&pBuf->Contiguous.pNextBuffer), GET_OFFSET(&pBuf->Contiguous.pNextBuffer), READ_WORD(&pBuf->Contiguous.cbFrame), READ_WORD(&pBuf->Contiguous.cbBuffer), READ_WORD(&pBuf->Contiguous.offUserData), READ_WORD(&pBuf->Contiguous.cbUserData), READ_WORD(&pBuf->Contiguous.usStationId), pBuf->Contiguous.uchOptions, pBuf->Contiguous.uchMsgType, MapMessageType(pBuf->Contiguous.uchMsgType), READ_WORD(&pBuf->Contiguous.cBuffersLeft), pBuf->Contiguous.uchRcvFS, pBuf->Contiguous.uchAdapterNumber ); if (!contiguous) { DWORD cbLanHeader = (DWORD)pBuf->NotContiguous.cbLanHeader; DWORD cbDlcHeader = (DWORD)pBuf->NotContiguous.cbDlcHeader; DBGPRINT( "LAN hdr len %02x\n" "DLC hdr len %02x\n", cbLanHeader, cbDlcHeader ); DumpData("LAN header", NULL, (DWORD)cbLanHeader, DD_NO_ADDRESS | DD_NO_ASCII | DD_UPPER_CASE | DD_INDENT_ALL, DEFAULT_FIELD_WIDTH, TRUE, Segment, (WORD)(Offset + (WORD)&((PLLC_DOS_BUFFER)0)->NotContiguous.auchLanHeader) ); DumpData("DLC header", NULL, cbDlcHeader, DD_NO_ADDRESS | DD_NO_ASCII | DD_UPPER_CASE | DD_INDENT_ALL, DEFAULT_FIELD_WIDTH, TRUE, Segment, (WORD)(Offset + (WORD)&((PLLC_DOS_BUFFER)0)->NotContiguous.auchDlcHeader) ); IF_DEBUG(DLC_RX_DATA) { if (userLength) { DumpData("user space", NULL, userLength, DD_NO_ADDRESS | DD_UPPER_CASE | DD_INDENT_ALL, DEFAULT_FIELD_WIDTH, TRUE, Segment, //Offset + userOffset userOffset ); } else { DBGPRINT( "user space\n" ); } if (dataLength) { DumpData("rcvd data", NULL, dataLength, DD_NO_ADDRESS | DD_UPPER_CASE | DD_INDENT_ALL, DEFAULT_FIELD_WIDTH, TRUE, Segment, //Offset + userOffset + userLength (WORD)(userOffset + userLength) ); } else { DBGPRINT( "rcvd data\n" ); } } } else { // // data length is size of frame in contiguous buffer? // dataLength = READ_WORD(&pBuf->Contiguous.cbBuffer); IF_DEBUG(DLC_RX_DATA) { if (userLength) { DumpData("user space", NULL, userLength, DD_NO_ADDRESS | DD_UPPER_CASE | DD_INDENT_ALL, DEFAULT_FIELD_WIDTH, TRUE, Segment, //Offset + userOffset userOffset ); } else { DBGPRINT( "user space\n" ); } if (dataLength) { DumpData("rcvd data", NULL, dataLength, DD_NO_ADDRESS | DD_UPPER_CASE | DD_INDENT_ALL, DEFAULT_FIELD_WIDTH, TRUE, Segment, //Offset + userOffset + userLength (WORD)(userOffset + userLength) ); } else { DBGPRINT( "rcvd data\n" ); } } } // // dump second & subsequent buffers // Segment = GET_SEGMENT(&pBuf->pNext); Offset = GET_OFFSET(&pBuf->pNext); for ( pBuf = (PLLC_DOS_BUFFER)READ_FAR_POINTER(&pBuf->pNext); pBuf; pBuf = (PLLC_DOS_BUFFER)READ_FAR_POINTER(&pBuf->pNext) ) { userLength = READ_WORD(&pBuf->Next.cbUserData); dataLength = READ_WORD(&pBuf->Next.cbBuffer); DBGPRINT( "\n" "Buffer 2/Subsequent @%04x:%04x\n" "next buffer %04x:%04x\n" "frame length %04x\n" "data length %04x\n" "user offset %04x\n" "user length %04x\n", Segment, Offset, GET_SEGMENT(&pBuf->pNext), GET_OFFSET(&pBuf->pNext), READ_WORD(&pBuf->Next.cbFrame), dataLength, READ_WORD(&pBuf->Next.offUserData), userLength ); IF_DEBUG(DLC_RX_DATA) { if (userLength) { DumpData("user space", NULL, userLength, DD_NO_ADDRESS | DD_UPPER_CASE | DD_INDENT_ALL, DEFAULT_FIELD_WIDTH, TRUE, Segment, //Offset + READ_WORD(&pBuf->Next.offUserData) READ_WORD(&pBuf->Next.offUserData) ); } else { DBGPRINT( "user space\n" ); } // // there must be received data // DumpData("rcvd data", NULL, dataLength, DD_NO_ADDRESS | DD_UPPER_CASE | DD_INDENT_ALL, DEFAULT_FIELD_WIDTH, TRUE, Segment, //Offset + READ_WORD(&pBuf->Next.offUserData) + userLength (WORD)(READ_WORD(&pBuf->Next.offUserData) + userLength) ); } Segment = GET_SEGMENT(&pBuf->pNext); Offset = GET_OFFSET(&pBuf->pNext); } } else { PLLC_BUFFER pBuf = (PLLC_BUFFER)Buffer; BOOL contiguous = pBuf->Contiguous.uchOptions & 0xc0; WORD userLength = pBuf->Next.cbUserData; WORD dataLength = pBuf->Next.cbBuffer; WORD userOffset = pBuf->Next.offUserData; // // Buffer 1: [not] contiguous MAC/DATA // DBGPRINT( "\n" "%sContiguous MAC/DATA frame @%08x\n" "next buffer %08x\n" "frame length %04x\n" "data length %04x\n" "user offset %04x\n" "user length %04x\n" "station id %04x\n" "options %02x\n" "message type %02x [%s]\n" "buffers left %04x\n" "rcv FS %02x\n" "adapter num %02x\n", contiguous ? "" : "Not", pBuf, pBuf->Contiguous.pNextBuffer, pBuf->Contiguous.cbFrame, pBuf->Contiguous.cbBuffer, pBuf->Contiguous.offUserData, pBuf->Contiguous.cbUserData, pBuf->Contiguous.usStationId, pBuf->Contiguous.uchOptions, pBuf->Contiguous.uchMsgType, MapMessageType(pBuf->Contiguous.uchMsgType), pBuf->Contiguous.cBuffersLeft, pBuf->Contiguous.uchRcvFS, pBuf->Contiguous.uchAdapterNumber ); if (!contiguous) { DWORD cbLanHeader = (DWORD)pBuf->NotContiguous.cbLanHeader; DWORD cbDlcHeader = (DWORD)pBuf->NotContiguous.cbDlcHeader; DBGPRINT( "next frame %08x\n" "LAN hdr len %02x\n" "DLC hdr len %02x\n", pBuf->NotContiguous.pNextFrame, cbLanHeader, cbDlcHeader ); DumpData("LAN header", pBuf->NotContiguous.auchLanHeader, cbLanHeader, DD_NO_ADDRESS | DD_NO_ASCII | DD_UPPER_CASE | DD_INDENT_ALL, DEFAULT_FIELD_WIDTH, FALSE, 0, 0 ); DumpData("DLC header", pBuf->NotContiguous.auchDlcHeader, cbDlcHeader, DD_NO_ADDRESS | DD_NO_ASCII | DD_UPPER_CASE | DD_INDENT_ALL, DEFAULT_FIELD_WIDTH, FALSE, 0, 0 ); IF_DEBUG(DLC_RX_DATA) { if (userLength) { DumpData("user space ", (PBYTE)pBuf + userOffset, userLength, DD_NO_ADDRESS | DD_UPPER_CASE | DD_INDENT_ALL, DEFAULT_FIELD_WIDTH, FALSE, 0, 0 ); } else { DBGPRINT( "user space\n" ); } if (dataLength) { DumpData("rcvd data", (PBYTE)pBuf + userOffset + userLength, dataLength, DD_NO_ADDRESS | DD_UPPER_CASE | DD_INDENT_ALL, DEFAULT_FIELD_WIDTH, FALSE, 0, 0 ); } else { DBGPRINT( "rcvd data\n" ); } } } else { // // data length is size of frame in contiguous buffer? // dataLength = pBuf->Contiguous.cbFrame; DBGPRINT( "next frame %08x\n", pBuf->NotContiguous.pNextFrame ); IF_DEBUG(DLC_RX_DATA) { if (userLength) { DumpData("user space", (PBYTE)pBuf + userOffset, userLength, DD_NO_ADDRESS | DD_UPPER_CASE | DD_INDENT_ALL, DEFAULT_FIELD_WIDTH, FALSE, 0, 0 ); } else { DBGPRINT( "user space\n" ); } if (dataLength) { DumpData("rcvd data", (PBYTE)pBuf + userOffset + userLength, dataLength, DD_NO_ADDRESS | DD_UPPER_CASE | DD_INDENT_ALL, DEFAULT_FIELD_WIDTH, FALSE, 0, 0 ); } else { DBGPRINT( "rcvd data\n" ); } } } // // dump second & subsequent buffers // for (pBuf = pBuf->pNext; pBuf; pBuf = pBuf->pNext) { userLength = pBuf->Next.cbUserData; dataLength = pBuf->Next.cbBuffer; DBGPRINT( "\n" "Buffer 2/Subsequent @%08x\n" "next buffer %08x\n" "frame length %04x\n" "data length %04x\n" "user offset %04x\n" "user length %04x\n", pBuf, pBuf->pNext, pBuf->Next.cbFrame, dataLength, pBuf->Next.offUserData, userLength ); IF_DEBUG(DLC_RX_DATA) { if (userLength) { DumpData("user space", (PBYTE)&pBuf + pBuf->Next.offUserData, userLength, DD_NO_ADDRESS | DD_UPPER_CASE | DD_INDENT_ALL, DEFAULT_FIELD_WIDTH, FALSE, 0, 0 ); } else { DBGPRINT( "user space\n" ); } // // there must be received data // DumpData("rcvd data", (PBYTE)pBuf + pBuf->Next.offUserData + userLength, dataLength, DD_NO_ADDRESS | DD_UPPER_CASE | DD_INDENT_ALL, DEFAULT_FIELD_WIDTH, FALSE, 0, 0 ); } } } } PRIVATE LPSTR MapMessageType(UCHAR MessageType) { switch (MessageType) { case 0x02: return "MAC Frame (Direct Station on Token Ring only)"; case 0x04: return "I-Frame"; case 0x06: return "UI-Frame"; case 0x08: return "XID Command (POLL)"; case 0x0a: return "XID Command (not POLL)"; case 0x0c: return "XID Response (FINAL)"; case 0x0e: return "XID Response (not FINAL)"; case 0x10: return "TEST Response (FINAL)"; case 0x12: return "TEST Response (not FINAL)"; case 0x14: return "OTHER - non-MAC frame (Direct Station only)"; default: return "*** BAD FRAME TYPE ***"; } } VOID DumpData( IN LPSTR Title, IN PBYTE Address, IN DWORD Length, IN DWORD Options, IN DWORD Indent, IN BOOL IsDos, IN WORD Segment, IN WORD Offset ) { char dumpBuf[128]; char* bufptr; int i, n, iterations; char* hexptr; if (IsDos) { Address = LPBYTE_FROM_WORDS(Segment, Offset); } // // the usual dump style: 16 columns of hex bytes, followed by 16 columns // of corresponding ASCII characters, or '.' where the character is < 0x20 // (space) or > 0x7f (del?) // if (Options & DD_LINE_BEFORE) { DbgOutStr("\n"); } iterations = 0; while (Length) { bufptr = dumpBuf; if (Title && !iterations) { strcpy(bufptr, Title); bufptr = strchr(bufptr, 0); } if (Indent && ((Options & DD_INDENT_ALL) || iterations)) { int indentLen = (!iterations && Title) ? ((int)Indent - (int)strlen(Title) < 0) ? 1 : Indent - strlen(Title) : Indent; RtlFillMemory(bufptr, indentLen, ' '); bufptr += indentLen; } if (!(Options & DD_NO_ADDRESS)) { if (IsDos) { bufptr += sprintf(bufptr, "%04x:%04x ", Segment, Offset); } else { bufptr += sprintf(bufptr, "%08x: ", Address); } } n = (Length < 16) ? Length : 16; hexptr = bufptr; for (i = 0; i < n; ++i) { bufptr += sprintf(bufptr, "%02x", Address[i]); *bufptr++ = (i == 7) ? '-' : ' '; } if (Options & DD_UPPER_CASE) { _strupr(hexptr); } if (!(Options & DD_NO_ASCII)) { if (n < 16) { for (i = 0; i < 16-n; ++i) { bufptr += sprintf(bufptr, " "); } } bufptr += sprintf(bufptr, " "); for (i = 0; i < n; ++i) { *bufptr++ = (Address[i] < 0x20 || Address[i] > 0x7f) ? '.' : Address[i]; } } *bufptr++ = '\n'; *bufptr = 0; DbgOutStr(dumpBuf); Length -= n; Address += n; ++iterations; // // take care of segment wrap for DOS addresses // if (IsDos) { DWORD x = (DWORD)Offset + n; Offset = (WORD)x; if (HIWORD(x)) { Segment += 0x1000; } } } if (Options & DD_LINE_AFTER) { DbgOutStr("\n"); } } // // CCB1 error checking // #define BITS_PER_BYTE 8 #define CCB1_ERROR_SPREAD ((MAX_CCB1_ERROR + BITS_PER_BYTE) & ~(BITS_PER_BYTE-1)) // // Ccb1ErrorTable - for each command described in IBM Lan Tech. Ref. (including // those not applicable to CCB1), we keep a list of the permissable error codes // which are taken from the "Return Codes for CCB1 Commands" table on pp B-5 // and B-6 // The error list is an 80-bit bitmap in which an ON bit indicates that the // error number corresponding to the bit's position is allowable for the CCB1 // command corresponding to the list's index in the table // typedef struct { BOOL ValidForCcb1; BYTE ErrorList[CCB1_ERROR_SPREAD/BITS_PER_BYTE]; char* CommandName; } CCB1_ERROR_TABLE; #define MAX_INCLUSIVE_CCB1_COMMAND LLC_MAX_DLC_COMMAND CCB1_ERROR_TABLE Ccb1ErrorTable[MAX_INCLUSIVE_CCB1_COMMAND + 1] = { // DIR.INTERRUPT (0x00) { TRUE, {0x83, 0x02, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "DIR.INTERRUPT" }, // DIR.MODIFY.OPEN.PARMS (0x01) { TRUE, {0x97, 0x02, 0x40, 0x39, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "DIR.MODIFY.OPEN.PARMS" }, // DIR.RESTORE.OPEN.PARMS (0x02) { TRUE, {0xd3, 0x02, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "DIR.RESTORE.OPEN.PARMS" }, // DIR.OPEN.ADAPTER (0x03) { TRUE, {0xaf, 0x02, 0x45, 0x79, 0x00, 0x00, 0x1d, 0x00, 0x00, 0x00}, "DIR.OPEN.ADAPTER" }, // DIR.CLOSE.ADAPTER (0x04) { TRUE, {0xb3, 0x02, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "DIR.CLOSE.ADAPTER" }, // non-existent command (0x05) { FALSE, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "NON-EXISTENT COMMAND (0x05)" }, // DIR.SET.GROUP.ADDRESS (0x06) { TRUE, {0x93, 0x0a, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "DIR.SET.GROUP.ADDRESS" }, // DIR.SET.FUNCTIONAL.ADDRESS (0x07) { TRUE, {0x93, 0x0a, 0x00, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "DIR.SET.FUNCTIONAL.ADDRESS" }, // DIR.READ.LOG (0x08) { TRUE, {0x93, 0x0a, 0x28, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "DIR.READ.LOG" }, // non-existent command (0x09) { FALSE, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "NON-EXISTENT COMMAND (0x09)" }, // TRANSMIT.DIR.FRAME (0x0a) { TRUE, {0x93, 0x0f, 0x00, 0x28, 0xbc, 0x01, 0x00, 0x00, 0x13, 0x04}, "TRANSMIT.DIR.FRAME" }, // TRANSMIT.I.FRAME (0x0b) { TRUE, {0x93, 0x0f, 0x00, 0x28, 0xbc, 0x01, 0x00, 0x00, 0x13, 0x04}, "TRANSMIT.I.FRAME" }, // non-existent command (0x0c) { FALSE, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "NON-EXISTENT COMMAND (0x0c)" }, // TRANSMIT.UI.FRAME (0x0d) { TRUE, {0x93, 0x0f, 0x00, 0x28, 0xbc, 0x01, 0x00, 0x00, 0x13, 0x04}, "TRANSMIT.UI.FRAME" }, // TRANSMIT.XID.CMD (0x0e) { TRUE, {0x93, 0x0f, 0x00, 0x28, 0xbc, 0x01, 0x00, 0x00, 0x13, 0x04}, "TRANSMIT.XID.CMD" }, // TRANSMIT.XID.RESP.FINAL (0x0f) { TRUE, {0x93, 0x0f, 0x00, 0x28, 0xbc, 0x01, 0x00, 0x00, 0x13, 0x04}, "TRANSMIT.XID.RESP.FINAL" }, // TRANSMIT.XID.RESP.NOT.FINAL (0x10) { TRUE, {0x93, 0x0f, 0x00, 0x28, 0xbc, 0x01, 0x00, 0x00, 0x13, 0x04}, "TRANSMIT.XID.RESP.NOT.FINAL" }, // TRANSMIT.TEST.CMD (0x11) { TRUE, {0x93, 0x0f, 0x00, 0x28, 0xbc, 0x01, 0x00, 0x00, 0x13, 0x04}, "TRANSMIT.TEST.CMD" }, // non-existent command (0x12) { FALSE, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "NON-EXISTENT COMMAND (0x12)" }, // non-existent command (0x13) { FALSE, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "NON-EXISTENT COMMAND (0x13)" }, // DLC.RESET (0x14) { TRUE, {0x93, 0x0a, 0x00, 0x28, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00}, "DLC.RESET" }, // DLC.OPEN.SAP (0x15) { TRUE, {0xd3, 0x0b, 0x40, 0x39, 0x00, 0x00, 0x00, 0x00, 0x6c, 0x02}, "DLC.OPEN.SAP" }, // DLC.CLOSE.SAP (0x16) { TRUE, {0x93, 0x0a, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x81, 0x11}, "DLC.CLOSE.SAP" }, // DLC.REALLOCATE (0x17) { TRUE, {0x93, 0x01, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00}, "DLC.REALLOCATE" }, // non-existent command (0x18) { FALSE, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "NON-EXISTENT COMMAND (0x18)" }, // DLC.OPEN.STATION (0x19) { TRUE, {0xb3, 0x0b, 0x00, 0x38, 0x00, 0x00, 0x00, 0x00, 0x4d, 0x80}, "DLC.OPEN.STATION" }, // DLC.CLOSE.STATION (0x1a) { TRUE, {0x93, 0x0a, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x81, 0x18}, "DLC.CLOSE.STATION" }, // DLC.CONNECT.STATION (0x1b) { TRUE, {0x97, 0x0a, 0x00, 0x38, 0x00, 0x00, 0x00, 0x00, 0x13, 0x24}, "DLC.CONNECT.STATION" }, // DLC.MODIFY (0x1c) { TRUE, {0x93, 0x0b, 0x00, 0x28, 0x00, 0x00, 0x00, 0x00, 0x25, 0x42}, "DLC.MODIFY" }, // DLC.FLOW.CONTROL (0x1d) { TRUE, {0x93, 0x0a, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00}, "DLC.FLOW.CONTROL" }, // DLC.STATISTICS (0x1e) { TRUE, {0x93, 0x0a, 0x20, 0x28, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00}, "DLC.STATISTICS" }, // non-existent command (0x1f) { FALSE, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "NON-EXISTENT COMMAND (0x1f)" }, // DIR.INITIALIZE (0x20) { TRUE, {0x87, 0x00, 0x10, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "DIR.INITIALIZE" }, // DIR.STATUS (0x21) { TRUE, {0x03, 0x12, 0x00, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "DIR.STATUS" }, // DIR.TIMER.SET (0x22) { TRUE, {0x83, 0x0e, 0x02, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "DIR.TIMER.SET" }, // DIR.TIMER.CANCEL (0x23) { TRUE, {0x03, 0x02, 0x02, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "DIR.TIMER.CANCEL" }, // PDT.TRACE.ON (0x24) { TRUE, {0x45, 0x04, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "PDT.TRACE.ON" }, // PDT.TRACE.OFF (0x25) { TRUE, {0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "PDT.TRACE.OFF" }, // BUFFER.GET (0x26) { TRUE, {0x13, 0x02, 0x00, 0x2a, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00}, "BUFFER.GET" }, // BUFFER.FREE (0x27) { TRUE, {0x13, 0x02, 0x00, 0x38, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00}, "BUFFER.FREE" }, // RECEIVE (0x28) { TRUE, {0x97, 0x0e, 0x00, 0x3c, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00}, "RECEIVE" }, // RECEIVE.CANCEL (0x29) { TRUE, {0x13, 0x02, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00}, "RECEIVE.CANCEL" }, // RECEIVE.MODIFY (0x2a) { TRUE, {0x97, 0x0e, 0x00, 0x3c, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00}, "RECEIVE.MODIFY" }, // DIR.DEFINE.MIF.ENVIRONMENT (0x2b) { TRUE, {0x03, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "DIR.DEFINE.MIF.ENVIRONMENT" }, // DIR.TIMER.CANCEL.GROUP (0x2c) { TRUE, {0x03, 0x02, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "DIR.TIMER.CANCEL.GROUP" }, // DIR.SET.USER.APPENDAGE (0x2d) { TRUE, {0x93, 0x02, 0x00, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "DIR.SET.USER.APPENDAGE" }, // non-existent command (0x2e) { FALSE, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "NON-EXISTENT COMMAND (0x2e)" }, // non-existent command (0x2f) { FALSE, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "NON-EXISTENT COMMAND (0x2f)" }, // non-existent command (0x30) { FALSE, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "NON-EXISTENT COMMAND (0x30)" }, // READ (0x31) { FALSE, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "READ" }, // READ.CANCEL (0x32) { FALSE, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "READ.CANCEL" }, // DLC.SET.THRESHOLD (0x33) { FALSE, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "DLC.SET.THRESHOLD" }, // DIR.CLOSE.DIRECT (0x34) { FALSE, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "DIR.CLOSE.DIRECT" }, // DIR.OPEN.DIRECT (0x35) { FALSE, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "DIR.OPEN.DIRECT" }, // PURGE.RESOURCES (0x36) { FALSE, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "PURGE.RESOURCES" }, // LLC_MAX_DLC_COMMAND (0x37) ? { FALSE, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "NON-EXISTENT-COMMAND (0x37)" } }; BOOL IsCcbErrorCodeAllowable( IN BYTE CcbCommand, IN BYTE CcbErrorCode ) /*++ Routine Description: Check whether an error code is allowable for a particular CCB(1) command code. Perform range check on the error code before using as index into allowable error table Arguments: CcbCommand - Command code CcbErrorCode - Return code Return Value: BOOL TRUE - CcbErrorCode is valid for CcbCommand FALSE - CcbErrorCode should not be returned for CcbCommand OR CcbErrorCode is invalid (out of range) --*/ { if (CcbErrorCode == CCB_COMMAND_IN_PROGRESS) { return TRUE; } if (CcbErrorCode > MAX_CCB1_ERROR) return FALSE; return Ccb1ErrorTable[CcbCommand].ErrorList[CcbErrorCode/8] & (1 << (CcbErrorCode % 8)); } BOOL IsCcbErrorCodeValid( IN BYTE CcbErrorCode ) /*++ Routine Description: Check if a return code from a CCB(1) is an allowable return code, irrespective of command type Arguments: CcbErrorCode - return code to check Return Value: BOOL TRUE - CcbErrorCode is in range FALSE - CcbErrorCode is not in range --*/ { return (CcbErrorCode == CCB_COMMAND_IN_PROGRESS) // 0xff // 0x00 - 0x0c || ((CcbErrorCode >= CCB_SUCCESS) && (CcbErrorCode <= CCB_SUCCESS_ADAPTER_NOT_OPEN)) // 0x10 - 0x1e || ((CcbErrorCode >= CCB_NETBIOS_FAILURE) && (CcbErrorCode <= CCB_INVALID_FUNCTION_ADDRESS)) // 0x20 - 0x28 || ((CcbErrorCode >= CCB_DATA_LOST_NO_BUFFERS) && (CcbErrorCode <= CCB_INVALID_FRAME_LENGTH)) // 0x30 || (CcbErrorCode == CCB_NOT_ENOUGH_BUFFERS_OPEN) // 0x32 - 0x34 || ((CcbErrorCode >= CCB_INVALID_NODE_ADDRESS) && (CcbErrorCode <= CCB_INVALID_TRANSMIT_LENGTH)) // 0x40 - 0x4f || ((CcbErrorCode >= CCB_INVALID_STATION_ID) && (CcbErrorCode <= CCB_INVALID_REMOTE_ADDRESS)) ; } BOOL IsCcbCommandValid( IN BYTE CcbCommand ) /*++ Routine Description: Check if CCB command code is one of the allowable codes for a DOS CCB (CCB1) Arguments: CcbCommand - command code to check Return Value: BOOL TRUE - CcbCommand is recognized FALSE - CcbCommand is not recognized --*/ { return ((CcbCommand >= LLC_DIR_INTERRUPT) && (CcbCommand <= LLC_DIR_CLOSE_ADAPTER)) || ((CcbCommand >= LLC_DIR_SET_GROUP_ADDRESS) && (CcbCommand <= LLC_DIR_SET_FUNCTIONAL_ADDRESS)) || ((CcbCommand >= LLC_TRANSMIT_DIR_FRAME) && (CcbCommand <= LLC_TRANSMIT_I_FRAME)) || ((CcbCommand >= LLC_TRANSMIT_UI_FRAME) && (CcbCommand <= LLC_TRANSMIT_TEST_CMD)) || ((CcbCommand >= LLC_DLC_RESET) && (CcbCommand <= LLC_DLC_REALLOCATE_STATIONS)) || ((CcbCommand >= LLC_DLC_OPEN_STATION) && (CcbCommand <= LLC_DLC_STATISTICS)) || ((CcbCommand >= LLC_DIR_INITIALIZE) && (CcbCommand <= LLC_DIR_SET_USER_APPENDAGE)) ; } LPSTR MapCcbCommandToName( IN BYTE CcbCommand ) /*++ Routine Description: Return the name of a CCB command, given its value Arguments: CcbCommand - command code to map Return Value: char* pointer to ASCIZ name of command (in IBM format X.Y.Z) --*/ { return Ccb1ErrorTable[CcbCommand].CommandName; } VOID DumpDosAdapter( IN DOS_ADAPTER* pDosAdapter ) { DBGPRINT( "DOS_ADAPTER @ %08x\n" "AdapterType. . . . . . . . . %s\n" "IsOpen . . . . . . . . . . . %d\n" "DirectStationOpen. . . . . . %d\n" "DirectReceive. . . . . . . . %d\n" "WaitingRestore . . . . . . . %d\n" "BufferFree . . . . . . . . . %d\n" "BufferPool . . . . . . . . . %08x\n" "CurrentExceptionHandlers . . %08x %08x %08x\n" "PreviousExceptionHandlers. . %08x %08x %08x\n" "DlcStatusChangeAppendage . . \n" "LastNetworkStatusChange. . . %04x\n" "UserStatusValue. . . . . . . \n" "AdapterParms:\n" " OpenErrorCode . . . . . . %04x\n" " OpenOptions . . . . . . . %04x\n" " NodeAddress . . . . . . . %02x-%02x-%02x-%02x-%02x-%02x\n" " GroupAddress. . . . . . . %08x\n" " FunctionalAddress . . . . %08x\n" " NumberReceiveBuffers. . . %04x\n" " ReceiveBufferLength . . . %04x\n" " DataHoldBufferLength. . . %04x\n" " NumberDataHoldBuffers . . %02x\n" " Reserved. . . . . . . . . %02x\n" " OpenLock. . . . . . . . . %04x\n" " ProductId . . . . . . . . %08x\n" "DlcSpecified . . . . . . . . %d\n" "DlcParms:\n" " MaxSaps . . . . . . . . . %02x\n" " MaxStations . . . . . . . %02x\n" " MaxGroupSaps. . . . . . . %02x\n" " MaxGroupMembers . . . . . %02x\n" " T1Tick1 . . . . . . . . . %02x\n" " T2Tick1 . . . . . . . . . %02x\n" " TiTick1 . . . . . . . . . %02x\n" " T1Tick2 . . . . . . . . . %02x\n" " T2Tick2 . . . . . . . . . %02x\n" " TiTick2 . . . . . . . . . %02x\n" "AdapterCloseCcb. . . . . . . \n" "DirectCloseCcb . . . . . . . \n" "ReadCcb. . . . . . . . . . . \n" "EventQueueCritSec. . . . . . \n" "EventQueueHead . . . . . . . \n" "EventQueueTail . . . . . . . \n" "QueueElements. . . . . . . . \n" "LocalBusyCritSec . . . . . . \n" "DeferredReceives . . . . . . \n" "FirstIndex . . . . . . . . . \n" "LastIndex. . . . . . . . . . \n" "LocalBusyInfo. . . . . . . . \n", MapAdapterType(pDosAdapter->AdapterType), pDosAdapter->IsOpen, pDosAdapter->DirectStationOpen, pDosAdapter->DirectReceive, pDosAdapter->WaitingRestore, pDosAdapter->BufferFree, pDosAdapter->BufferPool, pDosAdapter->CurrentExceptionHandlers[0], pDosAdapter->CurrentExceptionHandlers[1], pDosAdapter->CurrentExceptionHandlers[2], pDosAdapter->PreviousExceptionHandlers[0], pDosAdapter->PreviousExceptionHandlers[1], pDosAdapter->PreviousExceptionHandlers[2], pDosAdapter->LastNetworkStatusChange, pDosAdapter->AdapterParms.OpenErrorCode, pDosAdapter->AdapterParms.OpenOptions, pDosAdapter->AdapterParms.NodeAddress[0], pDosAdapter->AdapterParms.NodeAddress[1], pDosAdapter->AdapterParms.NodeAddress[2], pDosAdapter->AdapterParms.NodeAddress[3], pDosAdapter->AdapterParms.NodeAddress[4], pDosAdapter->AdapterParms.NodeAddress[5], pDosAdapter->AdapterParms.GroupAddress, pDosAdapter->AdapterParms.FunctionalAddress, pDosAdapter->AdapterParms.NumberReceiveBuffers, pDosAdapter->AdapterParms.ReceiveBufferLength, pDosAdapter->AdapterParms.DataHoldBufferLength, pDosAdapter->AdapterParms.NumberDataHoldBuffers, pDosAdapter->AdapterParms.Reserved, pDosAdapter->AdapterParms.OpenLock, pDosAdapter->AdapterParms.ProductId, pDosAdapter->DlcSpecified, pDosAdapter->DlcParms.MaxSaps, pDosAdapter->DlcParms.MaxStations, pDosAdapter->DlcParms.MaxGroupSaps, pDosAdapter->DlcParms.MaxGroupMembers, pDosAdapter->DlcParms.T1Tick1, pDosAdapter->DlcParms.T2Tick1, pDosAdapter->DlcParms.TiTick1, pDosAdapter->DlcParms.T1Tick2, pDosAdapter->DlcParms.T2Tick2, pDosAdapter->DlcParms.TiTick2 ); } PRIVATE LPSTR MapAdapterType( IN ADAPTER_TYPE AdapterType ) { switch (AdapterType) { case TokenRing: return "Token Ring"; case Ethernet: return "Ethernet"; case PcNetwork: return "PC Network"; case UnknownAdapter: return "Unknown Adapter"; } return "*** REALLY UNKNOWN ADAPTER! ***"; } #endif
the_stack_data/104515.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <errno.h> #include <fcntl.h> #include <unistd.h> #include <sys/ioctl.h> #include <sys/stat.h> #include <linux/ioctl.h> #include <linux/types.h> #include <linux/i2c-dev.h> #define I2C_DEVICE "/dev/i2c-1" #define TMP006_ADDR (0x41) #define TMP006_PTR_MANID (0xFE) #define TMP006_PTR_DEVID (0xFF) #define TMP006_PTR_CFG (0x02) #define TMP006_PTR_TEMP (0x01) int fd; int ret; uint8_t buff[4]; uint16_t temp_reading; uint8_t looper; static float convert_reading_to_temp(uint16_t reading) { // As per datasheet: // 1 LSB = 0.03125 deg C (1/32) // Process: Right shift 16-bit value by 2 and then /32 float act_temp; reading = reading >> 2; act_temp = (float)((float)reading / 32); return act_temp; } int main(void) { fd = open(I2C_DEVICE, O_RDWR); if(fd < 0) { printf("Could not open the I2C device...\r\n"); exit(EXIT_FAILURE); } if(ioctl(fd,I2C_SLAVE,TMP006_ADDR) < 0) { printf("Could not set I2C device address...\r\n"); exit(EXIT_FAILURE); } ///////////////////// buff[0] = TMP006_PTR_MANID; if(write(fd,buff,1) != 1) { printf("Could not write the pointer register...\r\n"); exit(EXIT_FAILURE); } if(read(fd,buff,2) != 2) { printf("Could not read the MAN ID...\r\n"); exit(EXIT_FAILURE); } else { printf("The MAN ID is: %02x%02x...\r\n",buff[0],buff[1]); } ///////////////////// buff[0] = TMP006_PTR_DEVID; if(write(fd,buff,1) != 1) { printf("Could not write the pointer register...\r\n"); exit(EXIT_FAILURE); } if(read(fd,buff,2) != 2) { printf("Could not read the DEV ID...\r\n"); exit(EXIT_FAILURE); } else { printf("The DEV ID is: %02x%02x...\r\n",buff[0],buff[1]); } ///////////////////// buff[0] = TMP006_PTR_CFG; if(write(fd,buff,1) != 1) { printf("Could not write the pointer register...\r\n"); exit(EXIT_FAILURE); } if(read(fd,buff,2) != 2) { printf("Could not read the Config Register...\r\n"); exit(EXIT_FAILURE); } else { printf("The Config is: %02x%02x...\r\n",buff[0],buff[1]); } ///////////////////// buff[0] = TMP006_PTR_CFG; buff[1] = 0x70; buff[2] = 0x80; if(write(fd,buff,3) != 3) { printf("Could not write the pointer register...\r\n"); exit(EXIT_FAILURE); } sleep(1); ///////////////////// buff[0] = TMP006_PTR_CFG; if(write(fd,buff,1) != 1) { printf("Could not write the pointer register...\r\n"); exit(EXIT_FAILURE); } if(read(fd,buff,2) != 2) { printf("Could not read the modified Config Register...\r\n"); exit(EXIT_FAILURE); } else { printf("The modified Config is: %02x%02x...\r\n",buff[0],buff[1]); } ///////////////////// for(looper=0; looper<20; ++looper) { usleep(1000000); buff[0] = TMP006_PTR_TEMP; if(write(fd,buff,1) != 1) { printf("Could not write the pointer register...\r\n"); exit(EXIT_FAILURE); } if(read(fd,buff,2) != 2) { printf("Could not read the TEMPERATURE...\r\n"); exit(EXIT_FAILURE); } else { temp_reading = buff[0]; temp_reading <<= 8; temp_reading |= buff[1]; printf("The TEMPERATURE is: %.2f...\r\n",convert_reading_to_temp(temp_reading)); } } close(fd); exit(EXIT_SUCCESS); }
the_stack_data/383547.c
#include<stdio.h> main() { int x[10],i,j,y[10]; printf("Enter the 10 elements:\n"); for(i=0;i<10;i++) { scanf("%d",&x[i]); y[i]=x[i]; } printf("The elements in y array are:\n"); for(i=0;i<10;i++) { printf("%d",y[i]); } }
the_stack_data/5.c
/* * Copyright 2014 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /* * Stub routine for `fstatvfs' for porting support. */ #include <errno.h> struct statvfs; int fstatvfs(int fd, struct statvfs *buf) { errno = ENOSYS; return -1; }
the_stack_data/144807.c
/* * C Program to Append the Content of File at the end of Another */ #include <stdio.h> #include <stdlib.h> main() { FILE *fsring1, *fsring2, *ftemp; char ch, file1[20], file2[20], file3[20]; printf("Enter name of first file "); gets(file1); printf("Enter name of second file "); gets(file2); printf("Enter name to store merged file "); gets(file3); fsring1 = fopen(file1, "r"); fsring2 = fopen(file2, "r"); if (fsring1 == NULL || fsring2 == NULL) { perror("Error has occured"); printf("Press any key to exit...\n"); exit(EXIT_FAILURE); } ftemp = fopen(file3, "w"); if (ftemp == NULL) { perror("Error has occures"); printf("Press any key to exit...\n"); exit(EXIT_FAILURE); } while ((ch = fgetc(fsring1)) != EOF) fputc(ch, ftemp); while ((ch = fgetc(fsring2) ) != EOF) fputc(ch, ftemp); printf("Two files merged %s successfully.\n", file3); fclose(fsring1); fclose(fsring2); fclose(ftemp); return 0; }
the_stack_data/462494.c
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <stdint.h> #include <time.h> #include <signal.h> #include <unistd.h> #include <sys/time.h> struct mm_entry { unsigned int status; size_t size; struct mm_entry *next; struct mm_entry *prev; }; #define STATUS_ALLOCATED 0xFFFFFFFF #define STATUS_FREE 0xAAAAAAAA #define PAGE_SIZE 4096 #define MIN_ALLOC 16 #define MAGIC 0xAABBCCDD void *heap_start = NULL; static struct mm_entry *head = NULL; static bool sig_int = false; static bool is_power_of_two(unsigned int x); static unsigned int highest_bit(unsigned int x); static unsigned int add_offset(void *ptr, unsigned int offset); static unsigned int sub_offset(void *ptr, unsigned int offset); static struct mm_entry *break_chunk(struct mm_entry *node, size_t desired_size); static struct mm_entry *find_best_fit(size_t size, bool *best_fit); static void dump_entries(void); static int gen_rand(int min, int max); void heap_init(); void alloc_test(void); void *kmalloc(size_t size); void kfree(void *ptr); typedef void sigfunc(int); sigfunc *signal(int, sigfunc*); struct timeval t1; void sig_hand(int signo) { if (signo == SIGINT) { printf("\nreceived sigint\n"); sig_int = true; } else if (signo == SIGTSTP) { struct timeval t2; double val; gettimeofday(&t2, NULL); val = t2.tv_sec - t1.tv_sec; printf("time elapsed: %f\n", val); dump_entries(); } } int main(char *argv[], int argc) { int ret = 0; unsigned char *actual_ptr = NULL; if ((actual_ptr = malloc(PAGE_SIZE * 2)) != NULL) { heap_start = (void *)(add_offset(actual_ptr, PAGE_SIZE - 1) & ~0xFFF); heap_init(); printf("address of actual pointer: 0x%x\n", (unsigned int)actual_ptr); printf("address of heap_start: 0x%x\n", (unsigned int)heap_start); printf("sizeof's: %u, %u\n", sizeof(void *), sizeof(unsigned int)); printf("max address: 0x%x\n", (unsigned int)add_offset(actual_ptr, PAGE_SIZE * 2 - 1)); //dump_entries(); struct timeval t2; double time = 0.0; gettimeofday(&t1, NULL); alloc_test(); gettimeofday(&t2, NULL); time = (t2.tv_sec - t1.tv_sec); printf("time elapsed: %f\n", time); dump_entries(); free(actual_ptr); } else { printf("failed to allocate %i bytes!\n", PAGE_SIZE * 2); } return ret; } static int gen_rand(int min, int max) { return (min + (rand() % (max - min) + 1)); } void alloc_test(void) { void **ptr_table = (void *)kmalloc(75 * sizeof(void *)); srand(time(NULL)); if (signal(SIGINT, sig_hand) == SIG_ERR) { printf("SIG_ERR\n"); return; } if (signal(SIGTSTP, sig_hand) == SIG_ERR) { printf("SIG_ERR\n"); return; } if (ptr_table == NULL) { printf("ptr_table is null!\n"); } else { while (!sig_int) { int index = gen_rand(0, 74); int rand = gen_rand(0, 9); if (rand >= 5) { if (ptr_table[index] == NULL) { ptr_table[index] = kmalloc(gen_rand(10, 110)); if (ptr_table[index] == NULL) { ptr_table[index] = NULL; } } } else { if (ptr_table[index] != NULL) { kfree(ptr_table[index]); ptr_table[index] = NULL; } } /* struct timespec ts = { .tv_sec = 0, .tv_nsec = (999999999 + 1) / 4 }; struct timespec blah; nanosleep(&ts, &blah); //sleep(1); */ } kfree(ptr_table); } } void *kmalloc(size_t size) { void *ret = NULL; if (size > 0) { struct mm_entry *node = NULL; bool best_fit = false; if (size < MIN_ALLOC) { size = MIN_ALLOC; } else if (!is_power_of_two(size)) { size = highest_bit(size) << 1; } node = find_best_fit(size, &best_fit); if (node != NULL) { if (!best_fit) { struct mm_entry *nnode = break_chunk(node, size); if (nnode == NULL) { printf("no block large enough\n"); exit(-1); /* fix me */ } else { node = nnode; } } node->status = STATUS_ALLOCATED; ret = (void *)add_offset(node, sizeof(struct mm_entry)); } else { //printf("need to allocate more memory! requested size: %i\n", size); //exit(-1); } } return ret; } void kfree(void *ptr) { struct mm_entry *node = NULL; if (ptr != NULL) { node = (struct mm_entry *)sub_offset(ptr, sizeof(struct mm_entry)); if (node->status == STATUS_ALLOCATED) { struct mm_entry *next = node->next; struct mm_entry *prev = node->prev; node->status = STATUS_FREE; /* look right */ if (next != NULL && next->status == STATUS_FREE) { // eat next node->next = next->next; if (node->next != NULL) { node->next->prev = node; } node->size += (next->size + sizeof(struct mm_entry)); } /* look left */ if (prev != NULL && prev->status == STATUS_FREE) { // eat node prev->next = node->next; if (prev->next != NULL) { prev->next->prev = prev; } prev->size += (node->size + sizeof(struct mm_entry)); } } } else { printf("kfree() - ptr null\n"); } } static void dump_entries(void) { struct mm_entry *node = head; size_t total = 0; size_t total_free = 0; int i = 0; while (node != NULL) { printf("["); if (node == head) { printf("H:"); } else { printf("N:"); } if (node->status == STATUS_ALLOCATED) { printf("A:"); } else { printf("F:"); total_free += node->size; } printf("0x%x:%i]", (unsigned int)node, node->size); total += node->size; if (node->next != NULL) { printf("->"); } node = node->next; i++; } printf("[TOTAL: %i],[TOTAL_FREE: %i] [TOTAL NODES: %i, capacity: %i]\n", total + (i * sizeof(struct mm_entry)), total_free, i, i * sizeof(struct mm_entry)); printf("\n"); } struct mm_entry *break_chunk(struct mm_entry *node, size_t desired_size) { struct mm_entry *ret = NULL; size_t actual_size = desired_size + sizeof(struct mm_entry); if (node->status == STATUS_FREE) { if (node->size > actual_size) { struct mm_entry *new_node = NULL; node->size -= actual_size; new_node = (struct mm_entry *)add_offset(node, node->size + sizeof(struct mm_entry)); new_node->size = desired_size; new_node->next = node->next; new_node->prev = node; if (new_node->next != NULL) { new_node->next->prev = new_node; } node->next = new_node; ret = new_node; } } return ret; } void heap_init(void) { /* assume we've requested/been given a page to play with */ struct mm_entry *node = (struct mm_entry *)heap_start; node->next = NULL; node->prev = NULL; node->size = PAGE_SIZE - sizeof(struct mm_entry); node->status = STATUS_FREE; head = node; } static struct mm_entry *find_best_fit(size_t size, bool *best_fit) { struct mm_entry *ret = NULL; struct mm_entry *sch_node = head; struct mm_entry *next_best = NULL; bool bf = false; while (sch_node != NULL) { if (sch_node->status == STATUS_FREE) { if (sch_node->size == size) { ret = sch_node; bf = true; break; } else if (next_best != NULL) { if (sch_node->size < next_best->size && sch_node->size > (size + sizeof(struct mm_entry))) { next_best = sch_node; } } else if (sch_node->size > (size + sizeof(struct mm_entry))) { next_best = sch_node; } } sch_node = sch_node->next; } if (!bf) { ret = next_best; } *best_fit = bf; return ret; } static unsigned int add_offset(void *ptr, unsigned int offset) { return ((unsigned int)ptr + offset); } static unsigned int sub_offset(void *ptr, unsigned int offset) { return ((unsigned int)ptr - offset); } static bool is_power_of_two(unsigned int x) { return ((x != 0) && !(x & (x - 1))); } static unsigned int highest_bit(unsigned int x) { x |= (x >> 1); x |= (x >> 2); x |= (x >> 4); x |= (x >> 8); x |= (x >> 16); return x - (x >> 1); } static int first_set_bit(unsigned int x) { return __builtin_ffs(x) - 1; }
the_stack_data/181394370.c
#include <ncurses.h> int main(void) { char text1[] = "Oh give me a clone!\n"; char text2[] = "Yes a clone of my own!"; initscr(); addstr(text1); /* add the first string */ addstr(text2); /* add the second string */ move(2,0); /* cursor to row 3, column 1 */ addstr("With the Y chromosome changed to the X."); refresh(); /* display the result */ getch(); endwin(); return 0; }
the_stack_data/265062.c
// UTMSPACE_2018-2019-sem2_SCSJ1013_Programming_Techniques_I // SX180357CSJS04 // Randy Tan Shaoxian // ALgorithm for the program: even_or_odd_integers_divide_multiply // 1. Begin. // 2. Read in the value of an integer, store it in number. // 3. Do an integer divsion on number, divide it by 2 and store it in test_number. // 4. Multiply test_number by 2 as an integer and assign it back to test_number. // 5. If test_number == number, go to the next step, otherwise go to step 8. // 6. Write number " is even." to the output. // 7. Go to step 9. // 8. Write number " is odd." to the output. // 9. End. // Input & Output 1 // // Input // Enter an integer: 55 // // Output // 55 is odd. // Input & Output 2 // // Input // Enter an integer: 8 // // Output // 8 is even. // Input & Output 3 // // Input // Enter an integer: 1158 // // Output // 1158 is even. #include <stdio.h> int main (void) { int number, test_number; printf("Enter an integer: "); scanf("%d", &number); test_number = number / 2; test_number *= 2; if (test_number == number) { printf("%d is even.\n", number); } else { printf("%d is odd.\n", number); } return 0; }
the_stack_data/165768855.c
#include <stdio.h> #include <malloc.h> #include <string.h> static char *read_header(char *name) { long size; char *header; FILE *f=fopen(name,"r"); if (!f) { perror(name); return strdup(""); } fseek(f,0,SEEK_END); size=ftell(f); fseek(f,0,SEEK_SET); header=malloc(size+1L); fread(header,size,1,f); header[size]=0; fclose(f); return header; } int main(int argc,char **argv) { static char s[4096]; int size; char **headers; int header_count; int n; char *header_name; headers=NULL; for (header_count=0;header_count<argc-1;header_count++) { headers=realloc(headers,(header_count+1)*sizeof(char*)); headers[header_count]=read_header(argv[header_count+1]); } while ("false") { fgets(s,sizeof(s),stdin); if (feof(stdin)) break; size=strlen(s); if (s[size-1]=='\n') s[size-1]=0; header_name=""; for (n=0;n<header_count;n++) { if (strstr(headers[n],s)) { header_name=argv[n+1]; break; } } fprintf(stdout,"%s\n",header_name); fflush(stdout); } while (header_count) free(headers[--header_count]); return 0; }
the_stack_data/86076574.c
#include<stdio.h> int main() { int m,n,i; scanf("%d %d",&m,&n); int fz=m,fm=1; for(i=1;i<n;i++) { fz=fz*(m-i); } for(i=1;i<=n;i++) { fm=fm*i; } int jg=fz/fm; printf("%d",jg); }
the_stack_data/89199156.c
/* Capstone Disassembly Engine */ /* TMS320C64x Backend by Fotis Loukos <[email protected]> 2016 */ #ifdef CAPSTONE_HAS_TMS320C64X #ifdef _MSC_VER // Disable security warnings for strcpy #ifndef _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS #endif // Banned API Usage : strcpy is a Banned API as listed in dontuse.h for // security purposes. #pragma warning(disable:28719) #endif #include <ctype.h> #include <string.h> #include "TMS320C64xInstPrinter.h" #include "../../MCInst.h" #include "../../utils.h" #include "../../SStream.h" #include "../../MCRegisterInfo.h" #include "../../MathExtras.h" #include "TMS320C64xMapping.h" #include "capstone/tms320c64x.h" static char *getRegisterName(unsigned RegNo); static void printOperand(MCInst *MI, unsigned OpNo, SStream *O); static void printMemOperand(MCInst *MI, unsigned OpNo, SStream *O); static void printMemOperand2(MCInst *MI, unsigned OpNo, SStream *O); static void printRegPair(MCInst *MI, unsigned OpNo, SStream *O); void TMS320C64x_post_printer(csh ud, cs_insn *insn, char *insn_asm, MCInst *mci) { SStream ss; char *p, *p2, tmp[8]; unsigned int unit = 0; int i; cs_tms320c64x *tms320c64x; if (mci->csh->detail) { tms320c64x = &mci->flat_insn->detail->tms320c64x; for (i = 0; i < insn->detail->groups_count; i++) { switch(insn->detail->groups[i]) { case TMS320C64X_GRP_FUNIT_D: unit = TMS320C64X_FUNIT_D; break; case TMS320C64X_GRP_FUNIT_L: unit = TMS320C64X_FUNIT_L; break; case TMS320C64X_GRP_FUNIT_M: unit = TMS320C64X_FUNIT_M; break; case TMS320C64X_GRP_FUNIT_S: unit = TMS320C64X_FUNIT_S; break; case TMS320C64X_GRP_FUNIT_NO: unit = TMS320C64X_FUNIT_NO; break; } if (unit != 0) break; } tms320c64x->funit.unit = unit; SStream_Init(&ss); if (tms320c64x->condition.reg != TMS320C64X_REG_INVALID) SStream_concat(&ss, "[%c%s]|", (tms320c64x->condition.zero == 1) ? '!' : '|', cs_reg_name(ud, tms320c64x->condition.reg)); p = strchr(insn_asm, '\t'); if (p != NULL) *p++ = '\0'; SStream_concat0(&ss, insn_asm); if ((p != NULL) && (((p2 = strchr(p, '[')) != NULL) || ((p2 = strchr(p, '(')) != NULL))) { while ((p2 > p) && ((*p2 != 'a') && (*p2 != 'b'))) p2--; if (p2 == p) { strcpy(insn_asm, "Invalid!"); return; } if (*p2 == 'a') strcpy(tmp, "1T"); else strcpy(tmp, "2T"); } else { tmp[0] = '\0'; } switch(tms320c64x->funit.unit) { case TMS320C64X_FUNIT_D: SStream_concat(&ss, ".D%s%u", tmp, tms320c64x->funit.side); break; case TMS320C64X_FUNIT_L: SStream_concat(&ss, ".L%s%u", tmp, tms320c64x->funit.side); break; case TMS320C64X_FUNIT_M: SStream_concat(&ss, ".M%s%u", tmp, tms320c64x->funit.side); break; case TMS320C64X_FUNIT_S: SStream_concat(&ss, ".S%s%u", tmp, tms320c64x->funit.side); break; } if (tms320c64x->funit.crosspath > 0) SStream_concat0(&ss, "X"); if (p != NULL) SStream_concat(&ss, "\t%s", p); if (tms320c64x->parallel != 0) SStream_concat(&ss, "\t||"); /* insn_asm is a buffer from an SStream, so there should be enough space */ strcpy(insn_asm, ss.buffer); } } #define PRINT_ALIAS_INSTR #include "TMS320C64xGenAsmWriter.inc" #define GET_INSTRINFO_ENUM #include "TMS320C64xGenInstrInfo.inc" static void printOperand(MCInst *MI, unsigned OpNo, SStream *O) { MCOperand *Op = MCInst_getOperand(MI, OpNo); unsigned reg; if (MCOperand_isReg(Op)) { reg = MCOperand_getReg(Op); if ((MCInst_getOpcode(MI) == TMS320C64x_MVC_s1_rr) && (OpNo == 1)) { switch(reg) { case TMS320C64X_REG_EFR: SStream_concat0(O, "EFR"); break; case TMS320C64X_REG_IFR: SStream_concat0(O, "IFR"); break; default: SStream_concat0(O, getRegisterName(reg)); break; } } else { SStream_concat0(O, getRegisterName(reg)); } if (MI->csh->detail) { MI->flat_insn->detail->tms320c64x.operands[MI->flat_insn->detail->tms320c64x.op_count].type = TMS320C64X_OP_REG; MI->flat_insn->detail->tms320c64x.operands[MI->flat_insn->detail->tms320c64x.op_count].reg = reg; MI->flat_insn->detail->tms320c64x.op_count++; } } else if (MCOperand_isImm(Op)) { int64_t Imm = MCOperand_getImm(Op); if (Imm >= 0) { if (Imm > HEX_THRESHOLD) SStream_concat(O, "0x%"PRIx64, Imm); else SStream_concat(O, "%"PRIu64, Imm); } else { if (Imm < -HEX_THRESHOLD) SStream_concat(O, "-0x%"PRIx64, -Imm); else SStream_concat(O, "-%"PRIu64, -Imm); } if (MI->csh->detail) { MI->flat_insn->detail->tms320c64x.operands[MI->flat_insn->detail->tms320c64x.op_count].type = TMS320C64X_OP_IMM; MI->flat_insn->detail->tms320c64x.operands[MI->flat_insn->detail->tms320c64x.op_count].imm = Imm; MI->flat_insn->detail->tms320c64x.op_count++; } } } static void printMemOperand(MCInst *MI, unsigned OpNo, SStream *O) { MCOperand *Op = MCInst_getOperand(MI, OpNo); int64_t Val = MCOperand_getImm(Op); unsigned scaled, base, offset, mode, unit; cs_tms320c64x *tms320c64x; char st, nd; scaled = (Val >> 19) & 1; base = (Val >> 12) & 0x7f; offset = (Val >> 5) & 0x7f; mode = (Val >> 1) & 0xf; unit = Val & 1; if (scaled) { st = '['; nd = ']'; } else { st = '('; nd = ')'; } switch(mode) { case 0: SStream_concat(O, "*-%s%c%u%c", getRegisterName(base), st, offset, nd); break; case 1: SStream_concat(O, "*+%s%c%u%c", getRegisterName(base), st, offset, nd); break; case 4: SStream_concat(O, "*-%s%c%s%c", getRegisterName(base), st, getRegisterName(offset), nd); break; case 5: SStream_concat(O, "*+%s%c%s%c", getRegisterName(base), st, getRegisterName(offset), nd); break; case 8: SStream_concat(O, "*--%s%c%u%c", getRegisterName(base), st, offset, nd); break; case 9: SStream_concat(O, "*++%s%c%u%c", getRegisterName(base), st, offset, nd); break; case 10: SStream_concat(O, "*%s--%c%u%c", getRegisterName(base), st, offset, nd); break; case 11: SStream_concat(O, "*%s++%c%u%c", getRegisterName(base), st, offset, nd); break; case 12: SStream_concat(O, "*--%s%c%s%c", getRegisterName(base), st, getRegisterName(offset), nd); break; case 13: SStream_concat(O, "*++%s%c%s%c", getRegisterName(base), st, getRegisterName(offset), nd); break; case 14: SStream_concat(O, "*%s--%c%s%c", getRegisterName(base), st, getRegisterName(offset), nd); break; case 15: SStream_concat(O, "*%s++%c%s%c", getRegisterName(base), st, getRegisterName(offset), nd); break; } if (MI->csh->detail) { tms320c64x = &MI->flat_insn->detail->tms320c64x; tms320c64x->operands[tms320c64x->op_count].type = TMS320C64X_OP_MEM; tms320c64x->operands[tms320c64x->op_count].mem.base = base; tms320c64x->operands[tms320c64x->op_count].mem.disp = offset; tms320c64x->operands[tms320c64x->op_count].mem.unit = unit + 1; tms320c64x->operands[tms320c64x->op_count].mem.scaled = scaled; switch(mode) { case 0: tms320c64x->operands[tms320c64x->op_count].mem.disptype = TMS320C64X_MEM_DISP_CONSTANT; tms320c64x->operands[tms320c64x->op_count].mem.direction = TMS320C64X_MEM_DIR_BW; tms320c64x->operands[tms320c64x->op_count].mem.modify = TMS320C64X_MEM_MOD_NO; break; case 1: tms320c64x->operands[tms320c64x->op_count].mem.disptype = TMS320C64X_MEM_DISP_CONSTANT; tms320c64x->operands[tms320c64x->op_count].mem.direction = TMS320C64X_MEM_DIR_FW; tms320c64x->operands[tms320c64x->op_count].mem.modify = TMS320C64X_MEM_MOD_NO; break; case 4: tms320c64x->operands[tms320c64x->op_count].mem.disptype = TMS320C64X_MEM_DISP_REGISTER; tms320c64x->operands[tms320c64x->op_count].mem.direction = TMS320C64X_MEM_DIR_BW; tms320c64x->operands[tms320c64x->op_count].mem.modify = TMS320C64X_MEM_MOD_NO; break; case 5: tms320c64x->operands[tms320c64x->op_count].mem.disptype = TMS320C64X_MEM_DISP_REGISTER; tms320c64x->operands[tms320c64x->op_count].mem.direction = TMS320C64X_MEM_DIR_FW; tms320c64x->operands[tms320c64x->op_count].mem.modify = TMS320C64X_MEM_MOD_NO; break; case 8: tms320c64x->operands[tms320c64x->op_count].mem.disptype = TMS320C64X_MEM_DISP_CONSTANT; tms320c64x->operands[tms320c64x->op_count].mem.direction = TMS320C64X_MEM_DIR_BW; tms320c64x->operands[tms320c64x->op_count].mem.modify = TMS320C64X_MEM_MOD_PRE; break; case 9: tms320c64x->operands[tms320c64x->op_count].mem.disptype = TMS320C64X_MEM_DISP_CONSTANT; tms320c64x->operands[tms320c64x->op_count].mem.direction = TMS320C64X_MEM_DIR_FW; tms320c64x->operands[tms320c64x->op_count].mem.modify = TMS320C64X_MEM_MOD_PRE; break; case 10: tms320c64x->operands[tms320c64x->op_count].mem.disptype = TMS320C64X_MEM_DISP_CONSTANT; tms320c64x->operands[tms320c64x->op_count].mem.direction = TMS320C64X_MEM_DIR_BW; tms320c64x->operands[tms320c64x->op_count].mem.modify = TMS320C64X_MEM_MOD_POST; break; case 11: tms320c64x->operands[tms320c64x->op_count].mem.disptype = TMS320C64X_MEM_DISP_CONSTANT; tms320c64x->operands[tms320c64x->op_count].mem.direction = TMS320C64X_MEM_DIR_FW; tms320c64x->operands[tms320c64x->op_count].mem.modify = TMS320C64X_MEM_MOD_POST; break; case 12: tms320c64x->operands[tms320c64x->op_count].mem.disptype = TMS320C64X_MEM_DISP_REGISTER; tms320c64x->operands[tms320c64x->op_count].mem.direction = TMS320C64X_MEM_DIR_BW; tms320c64x->operands[tms320c64x->op_count].mem.modify = TMS320C64X_MEM_MOD_PRE; break; case 13: tms320c64x->operands[tms320c64x->op_count].mem.disptype = TMS320C64X_MEM_DISP_REGISTER; tms320c64x->operands[tms320c64x->op_count].mem.direction = TMS320C64X_MEM_DIR_FW; tms320c64x->operands[tms320c64x->op_count].mem.modify = TMS320C64X_MEM_MOD_PRE; break; case 14: tms320c64x->operands[tms320c64x->op_count].mem.disptype = TMS320C64X_MEM_DISP_REGISTER; tms320c64x->operands[tms320c64x->op_count].mem.direction = TMS320C64X_MEM_DIR_BW; tms320c64x->operands[tms320c64x->op_count].mem.modify = TMS320C64X_MEM_MOD_POST; break; case 15: tms320c64x->operands[tms320c64x->op_count].mem.disptype = TMS320C64X_MEM_DISP_REGISTER; tms320c64x->operands[tms320c64x->op_count].mem.direction = TMS320C64X_MEM_DIR_FW; tms320c64x->operands[tms320c64x->op_count].mem.modify = TMS320C64X_MEM_MOD_POST; break; } tms320c64x->op_count++; } } static void printMemOperand2(MCInst *MI, unsigned OpNo, SStream *O) { MCOperand *Op = MCInst_getOperand(MI, OpNo); int64_t Val = MCOperand_getImm(Op); uint16_t offset; unsigned basereg; cs_tms320c64x *tms320c64x; basereg = Val & 0x7f; offset = (Val >> 7) & 0x7fff; SStream_concat(O, "*+%s[0x%x]", getRegisterName(basereg), offset); if (MI->csh->detail) { tms320c64x = &MI->flat_insn->detail->tms320c64x; tms320c64x->operands[tms320c64x->op_count].type = TMS320C64X_OP_MEM; tms320c64x->operands[tms320c64x->op_count].mem.base = basereg; tms320c64x->operands[tms320c64x->op_count].mem.unit = 2; tms320c64x->operands[tms320c64x->op_count].mem.disp = offset; tms320c64x->operands[tms320c64x->op_count].mem.disptype = TMS320C64X_MEM_DISP_CONSTANT; tms320c64x->operands[tms320c64x->op_count].mem.direction = TMS320C64X_MEM_DIR_FW; tms320c64x->operands[tms320c64x->op_count].mem.modify = TMS320C64X_MEM_MOD_NO; tms320c64x->op_count++; } } static void printRegPair(MCInst *MI, unsigned OpNo, SStream *O) { MCOperand *Op = MCInst_getOperand(MI, OpNo); unsigned reg = MCOperand_getReg(Op); cs_tms320c64x *tms320c64x; SStream_concat(O, "%s:%s", getRegisterName(reg + 1), getRegisterName(reg)); if (MI->csh->detail) { tms320c64x = &MI->flat_insn->detail->tms320c64x; tms320c64x->operands[tms320c64x->op_count].type = TMS320C64X_OP_REGPAIR; tms320c64x->operands[tms320c64x->op_count].reg = reg; tms320c64x->op_count++; } } static bool printAliasInstruction(MCInst *MI, SStream *O, MCRegisterInfo *MRI) { unsigned opcode = MCInst_getOpcode(MI); MCOperand *op; switch(opcode) { /* ADD.Dx -i, x, y -> SUB.Dx x, i, y */ case TMS320C64x_ADD_d2_rir: /* ADD.L -i, x, y -> SUB.L x, i, y */ case TMS320C64x_ADD_l1_irr: case TMS320C64x_ADD_l1_ipp: /* ADD.S -i, x, y -> SUB.S x, i, y */ case TMS320C64x_ADD_s1_irr: if ((MCInst_getNumOperands(MI) == 3) && MCOperand_isReg(MCInst_getOperand(MI, 0)) && MCOperand_isReg(MCInst_getOperand(MI, 1)) && MCOperand_isImm(MCInst_getOperand(MI, 2)) && (MCOperand_getImm(MCInst_getOperand(MI, 2)) < 0)) { MCInst_setOpcodePub(MI, TMS320C64X_INS_SUB); op = MCInst_getOperand(MI, 2); MCOperand_setImm(op, -MCOperand_getImm(op)); SStream_concat0(O, "SUB\t"); printOperand(MI, 1, O); SStream_concat0(O, ", "); printOperand(MI, 2, O); SStream_concat0(O, ", "); printOperand(MI, 0, O); return true; } break; } switch(opcode) { /* ADD.D 0, x, y -> MV.D x, y */ case TMS320C64x_ADD_d1_rir: /* OR.D x, 0, y -> MV.D x, y */ case TMS320C64x_OR_d2_rir: /* ADD.L 0, x, y -> MV.L x, y */ case TMS320C64x_ADD_l1_irr: case TMS320C64x_ADD_l1_ipp: /* OR.L 0, x, y -> MV.L x, y */ case TMS320C64x_OR_l1_irr: /* ADD.S 0, x, y -> MV.S x, y */ case TMS320C64x_ADD_s1_irr: /* OR.S 0, x, y -> MV.S x, y */ case TMS320C64x_OR_s1_irr: if ((MCInst_getNumOperands(MI) == 3) && MCOperand_isReg(MCInst_getOperand(MI, 0)) && MCOperand_isReg(MCInst_getOperand(MI, 1)) && MCOperand_isImm(MCInst_getOperand(MI, 2)) && (MCOperand_getImm(MCInst_getOperand(MI, 2)) == 0)) { MCInst_setOpcodePub(MI, TMS320C64X_INS_MV); MI->size--; SStream_concat0(O, "MV\t"); printOperand(MI, 1, O); SStream_concat0(O, ", "); printOperand(MI, 0, O); return true; } break; } switch(opcode) { /* XOR.D -1, x, y -> NOT.D x, y */ case TMS320C64x_XOR_d2_rir: /* XOR.L -1, x, y -> NOT.L x, y */ case TMS320C64x_XOR_l1_irr: /* XOR.S -1, x, y -> NOT.S x, y */ case TMS320C64x_XOR_s1_irr: if ((MCInst_getNumOperands(MI) == 3) && MCOperand_isReg(MCInst_getOperand(MI, 0)) && MCOperand_isReg(MCInst_getOperand(MI, 1)) && MCOperand_isImm(MCInst_getOperand(MI, 2)) && (MCOperand_getImm(MCInst_getOperand(MI, 2)) == -1)) { MCInst_setOpcodePub(MI, TMS320C64X_INS_NOT); MI->size--; SStream_concat0(O, "NOT\t"); printOperand(MI, 1, O); SStream_concat0(O, ", "); printOperand(MI, 0, O); return true; } break; } switch(opcode) { /* MVK.D 0, x -> ZERO.D x */ case TMS320C64x_MVK_d1_rr: /* MVK.L 0, x -> ZERO.L x */ case TMS320C64x_MVK_l2_ir: if ((MCInst_getNumOperands(MI) == 2) && MCOperand_isReg(MCInst_getOperand(MI, 0)) && MCOperand_isImm(MCInst_getOperand(MI, 1)) && (MCOperand_getImm(MCInst_getOperand(MI, 1)) == 0)) { MCInst_setOpcodePub(MI, TMS320C64X_INS_ZERO); MI->size--; SStream_concat0(O, "ZERO\t"); printOperand(MI, 0, O); return true; } break; } switch(opcode) { /* SUB.L x, x, y -> ZERO.L y */ case TMS320C64x_SUB_l1_rrp_x1: /* SUB.S x, x, y -> ZERO.S y */ case TMS320C64x_SUB_s1_rrr: if ((MCInst_getNumOperands(MI) == 3) && MCOperand_isReg(MCInst_getOperand(MI, 0)) && MCOperand_isReg(MCInst_getOperand(MI, 1)) && MCOperand_isReg(MCInst_getOperand(MI, 2)) && (MCOperand_getReg(MCInst_getOperand(MI, 1)) == MCOperand_getReg(MCInst_getOperand(MI, 2)))) { MCInst_setOpcodePub(MI, TMS320C64X_INS_ZERO); MI->size -= 2; SStream_concat0(O, "ZERO\t"); printOperand(MI, 0, O); return true; } break; } switch(opcode) { /* SUB.L 0, x, y -> NEG.L x, y */ case TMS320C64x_SUB_l1_irr: case TMS320C64x_SUB_l1_ipp: /* SUB.S 0, x, y -> NEG.S x, y */ case TMS320C64x_SUB_s1_irr: if ((MCInst_getNumOperands(MI) == 3) && MCOperand_isReg(MCInst_getOperand(MI, 0)) && MCOperand_isReg(MCInst_getOperand(MI, 1)) && MCOperand_isImm(MCInst_getOperand(MI, 2)) && (MCOperand_getImm(MCInst_getOperand(MI, 2)) == 0)) { MCInst_setOpcodePub(MI, TMS320C64X_INS_NEG); MI->size--; SStream_concat0(O, "NEG\t"); printOperand(MI, 1, O); SStream_concat0(O, ", "); printOperand(MI, 0, O); return true; } break; } switch(opcode) { /* PACKLH2.L x, x, y -> SWAP2.L x, y */ case TMS320C64x_PACKLH2_l1_rrr_x2: /* PACKLH2.S x, x, y -> SWAP2.S x, y */ case TMS320C64x_PACKLH2_s1_rrr: if ((MCInst_getNumOperands(MI) == 3) && MCOperand_isReg(MCInst_getOperand(MI, 0)) && MCOperand_isReg(MCInst_getOperand(MI, 1)) && MCOperand_isReg(MCInst_getOperand(MI, 2)) && (MCOperand_getReg(MCInst_getOperand(MI, 1)) == MCOperand_getReg(MCInst_getOperand(MI, 2)))) { MCInst_setOpcodePub(MI, TMS320C64X_INS_SWAP2); MI->size--; SStream_concat0(O, "SWAP2\t"); printOperand(MI, 1, O); SStream_concat0(O, ", "); printOperand(MI, 0, O); return true; } break; } switch(opcode) { /* NOP 16 -> IDLE */ /* NOP 1 -> NOP */ case TMS320C64x_NOP_n: if ((MCInst_getNumOperands(MI) == 1) && MCOperand_isImm(MCInst_getOperand(MI, 0)) && (MCOperand_getReg(MCInst_getOperand(MI, 0)) == 16)) { MCInst_setOpcodePub(MI, TMS320C64X_INS_IDLE); MI->size--; SStream_concat0(O, "IDLE"); return true; } if ((MCInst_getNumOperands(MI) == 1) && MCOperand_isImm(MCInst_getOperand(MI, 0)) && (MCOperand_getReg(MCInst_getOperand(MI, 0)) == 1)) { MI->size--; SStream_concat0(O, "NOP"); return true; } break; } return false; } void TMS320C64x_printInst(MCInst *MI, SStream *O, void *Info) { if (!printAliasInstruction(MI, O, Info)) printInstruction(MI, O, Info); } #endif
the_stack_data/604208.c
const unsigned char crypttestVersionString[] __attribute__ ((used)) = "@(#)PROGRAM:crypttest PROJECT:CryptoPP-5.6.2" "\n"; const double crypttestVersionNumber __attribute__ ((used)) = (double)5.6;
the_stack_data/178264659.c
#include<stdio.h> int main(){ float deposito,taxa,rendimento,total; printf("Digite o valor do depósito\n"); scanf("%f%*c",&deposito); printf("Digite o valor da taxa\n"); scanf("%f%*c",&taxa); rendimento=deposito*taxa/100; total=deposito+rendimento; printf("o valor dos rendimentos é:%f",rendimento); printf("O total é:%f",total); return 0; }
the_stack_data/68888876.c
/* * DHD debugability support * * <<Broadcom-WL-IPTag/Open:>> * * Copyright (C) 1999-2019, Broadcom. * * Unless you and Broadcom execute a separate written software license * agreement governing use of this software, this software is licensed to you * under the terms of the GNU General Public License version 2 (the "GPL"), * available at http://www.broadcom.com/licenses/GPLv2.php, with the * following added to such license: * * As a special exception, the copyright holders of this software give you * permission to link this software with independent modules, and to copy and * distribute the resulting executable under terms of your choice, provided that * you also meet, for each linked independent module, the terms and conditions of * the license of that module. An independent module is a module which is not * derived from this software. The special exception does not apply to any * modifications of the software. * * Notwithstanding the above, under no circumstances may you combine this * software in any way with any other Broadcom software provided under a license * other than the GPL, without Broadcom's express prior written consent. * * $Id: dhd_mschdbg.c 639872 2016-05-25 05:39:30Z $ */ #ifdef SHOW_LOGTRACE #include <typedefs.h> #include <osl.h> #include <bcmutils.h> #include <bcmendian.h> #include <dngl_stats.h> #include <dhd.h> #include <dhd_dbg.h> #include <dhd_debug.h> #include <dhd_mschdbg.h> #include <event_log.h> #include <event_trace.h> #include <msgtrace.h> static const char *head_log = ""; #define MSCH_EVENT_HEAD(space) \ do { \ MSCH_EVENT(("%s_E: ", head_log)); \ if (space > 0) { \ int ii; \ for (ii = 0; ii < space; ii += 4) MSCH_EVENT((" ")); \ } \ } while (0) #define MSCH_EVENT(args) do {if (dhd_msg_level & DHD_EVENT_VAL) printf args;} while (0) static uint64 solt_start_time[4], req_start_time[4], profiler_start_time[4]; static uint32 solt_chanspec[4] = {0, }, req_start[4] = {0, }; static bool lastMessages = FALSE; #define US_PRE_SEC 1000000 #define DATA_UNIT_FOR_LOG_CNT 4 static void dhd_mschdbg_us_to_sec(uint32 time_h, uint32 time_l, uint32 *sec, uint32 *remain) { uint64 cur_time = ((uint64)(ntoh32(time_h)) << 32) | ntoh32(time_l); uint64 r, u = 0; r = cur_time; while (time_h != 0) { u += (uint64)((0xffffffff / US_PRE_SEC)) * time_h; r = cur_time - u * US_PRE_SEC; time_h = (uint32)(r >> 32); } *sec = (uint32)(u + ((uint32)(r) / US_PRE_SEC)); *remain = (uint32)(r) % US_PRE_SEC; } static char *dhd_mschdbg_display_time(uint32 time_h, uint32 time_l) { static char display_time[32]; uint32 s, ss; if (time_h == 0xffffffff && time_l == 0xffffffff) { snprintf(display_time, 31, "-1"); } else { dhd_mschdbg_us_to_sec(time_h, time_l, &s, &ss); snprintf(display_time, 31, "%d.%06d", s, ss); } return display_time; } static void dhd_mschdbg_chanspec_list(int sp, char *data, uint16 ptr, uint16 chanspec_cnt) { int i, cnt = (int)ntoh16(chanspec_cnt); uint16 *chanspec_list = (uint16 *)(data + ntoh16(ptr)); char buf[CHANSPEC_STR_LEN]; chanspec_t c; MSCH_EVENT_HEAD(sp); MSCH_EVENT(("<chanspec_list>:")); for (i = 0; i < cnt; i++) { c = (chanspec_t)ntoh16(chanspec_list[i]); MSCH_EVENT((" %s", wf_chspec_ntoa(c, buf))); } MSCH_EVENT(("\n")); } static void dhd_mschdbg_elem_list(int sp, char *title, char *data, uint16 ptr, uint16 list_cnt) { int i, cnt = (int)ntoh16(list_cnt); uint32 *list = (uint32 *)(data + ntoh16(ptr)); MSCH_EVENT_HEAD(sp); MSCH_EVENT(("%s_list: ", title)); for (i = 0; i < cnt; i++) { MSCH_EVENT(("0x%08x->", ntoh32(list[i]))); } MSCH_EVENT(("null\n")); } static void dhd_mschdbg_req_param_profiler_event_data(int sp, int ver, char *data, uint16 ptr) { int sn = sp + 4; msch_req_param_profiler_event_data_t *p = (msch_req_param_profiler_event_data_t *)(data + ntoh16(ptr)); uint32 type, flags; MSCH_EVENT_HEAD(sp); MSCH_EVENT(("<request parameters>\n")); MSCH_EVENT_HEAD(sn); MSCH_EVENT(("req_type: ")); type = p->req_type; if (type < 4) { char *req_type[] = {"fixed", "start-flexible", "duration-flexible", "both-flexible"}; MSCH_EVENT(("%s", req_type[type])); } else MSCH_EVENT(("unknown(%d)", type)); flags = ntoh16(p->flags); if (flags & WL_MSCH_REQ_FLAGS_CHAN_CONTIGUOUS) MSCH_EVENT((", CHAN_CONTIGUOUS")); if (flags & WL_MSCH_REQ_FLAGS_MERGE_CONT_SLOTS) MSCH_EVENT((", MERGE_CONT_SLOTS")); if (flags & WL_MSCH_REQ_FLAGS_PREMTABLE) MSCH_EVENT((", PREMTABLE")); if (flags & WL_MSCH_REQ_FLAGS_PREMT_CURTS) MSCH_EVENT((", PREMT_CURTS")); if (flags & WL_MSCH_REQ_FLAGS_PREMT_IMMEDIATE) MSCH_EVENT((", PREMT_IMMEDIATE")); MSCH_EVENT((", priority: %d\n", p->priority)); MSCH_EVENT_HEAD(sn); MSCH_EVENT(("start-time: %s, duration: %d(us), interval: %d(us)\n", dhd_mschdbg_display_time(p->start_time_h, p->start_time_l), ntoh32(p->duration), ntoh32(p->interval))); if (type == WL_MSCH_RT_DUR_FLEX) { MSCH_EVENT_HEAD(sn); MSCH_EVENT(("dur_flex: %d(us)\n", ntoh32(p->flex.dur_flex))); } else if (type == WL_MSCH_RT_BOTH_FLEX) { MSCH_EVENT_HEAD(sn); MSCH_EVENT(("min_dur: %d(us), max_away_dur: %d(us)\n", ntoh32(p->flex.bf.min_dur), ntoh32(p->flex.bf.max_away_dur))); MSCH_EVENT_HEAD(sn); MSCH_EVENT(("hi_prio_time: %s, hi_prio_interval: %d(us)\n", dhd_mschdbg_display_time(p->flex.bf.hi_prio_time_h, p->flex.bf.hi_prio_time_l), ntoh32(p->flex.bf.hi_prio_interval))); } } static void dhd_mschdbg_timeslot_profiler_event_data(int sp, int ver, char *title, char *data, uint16 ptr, bool empty) { int s, sn = sp + 4; msch_timeslot_profiler_event_data_t *p = (msch_timeslot_profiler_event_data_t *)(data + ntoh16(ptr)); char *state[] = {"NONE", "CHN_SW", "ONCHAN_FIRE", "OFF_CHN_PREP", "OFF_CHN_DONE", "TS_COMPLETE"}; MSCH_EVENT_HEAD(sp); MSCH_EVENT(("<%s timeslot>: ", title)); if (empty) { MSCH_EVENT((" null\n")); return; } else MSCH_EVENT(("0x%08x\n", ntoh32(p->p_timeslot))); s = (int)(ntoh32(p->state)); if (s > 5) s = 0; MSCH_EVENT_HEAD(sn); MSCH_EVENT(("id: %d, state[%d]: %s, chan_ctxt: [0x%08x]\n", ntoh32(p->timeslot_id), ntoh32(p->state), state[s], ntoh32(p->p_chan_ctxt))); MSCH_EVENT_HEAD(sn); MSCH_EVENT(("fire_time: %s", dhd_mschdbg_display_time(p->fire_time_h, p->fire_time_l))); MSCH_EVENT((", pre_start_time: %s", dhd_mschdbg_display_time(p->pre_start_time_h, p->pre_start_time_l))); MSCH_EVENT((", end_time: %s", dhd_mschdbg_display_time(p->end_time_h, p->end_time_l))); MSCH_EVENT((", sch_dur: %s\n", dhd_mschdbg_display_time(p->sch_dur_h, p->sch_dur_l))); } static void dhd_mschdbg_req_timing_profiler_event_data(int sp, int ver, char *title, char *data, uint16 ptr, bool empty) { int sn = sp + 4; msch_req_timing_profiler_event_data_t *p = (msch_req_timing_profiler_event_data_t *)(data + ntoh16(ptr)); uint32 type; MSCH_EVENT_HEAD(sp); MSCH_EVENT(("<%s req_timing>: ", title)); if (empty) { MSCH_EVENT((" null\n")); return; } else MSCH_EVENT(("0x%08x (prev 0x%08x, next 0x%08x)\n", ntoh32(p->p_req_timing), ntoh32(p->p_prev), ntoh32(p->p_next))); MSCH_EVENT_HEAD(sn); MSCH_EVENT(("flags:")); type = ntoh16(p->flags); if ((type & 0x7f) == 0) MSCH_EVENT((" NONE")); else { if (type & WL_MSCH_RC_FLAGS_ONCHAN_FIRE) MSCH_EVENT((" ONCHAN_FIRE")); if (type & WL_MSCH_RC_FLAGS_START_FIRE_DONE) MSCH_EVENT((" START_FIRE")); if (type & WL_MSCH_RC_FLAGS_END_FIRE_DONE) MSCH_EVENT((" END_FIRE")); if (type & WL_MSCH_RC_FLAGS_ONFIRE_DONE) MSCH_EVENT((" ONFIRE_DONE")); if (type & WL_MSCH_RC_FLAGS_SPLIT_SLOT_START) MSCH_EVENT((" SPLIT_SLOT_START")); if (type & WL_MSCH_RC_FLAGS_SPLIT_SLOT_END) MSCH_EVENT((" SPLIT_SLOT_END")); if (type & WL_MSCH_RC_FLAGS_PRE_ONFIRE_DONE) MSCH_EVENT((" PRE_ONFIRE_DONE")); } MSCH_EVENT(("\n")); MSCH_EVENT_HEAD(sn); MSCH_EVENT(("pre_start_time: %s", dhd_mschdbg_display_time(p->pre_start_time_h, p->pre_start_time_l))); MSCH_EVENT((", start_time: %s", dhd_mschdbg_display_time(p->start_time_h, p->start_time_l))); MSCH_EVENT((", end_time: %s\n", dhd_mschdbg_display_time(p->end_time_h, p->end_time_l))); if (p->p_timeslot && (p->timeslot_ptr == 0)) { MSCH_EVENT_HEAD(sn); MSCH_EVENT(("<%s timeslot>: 0x%08x\n", title, ntoh32(p->p_timeslot))); } else dhd_mschdbg_timeslot_profiler_event_data(sn, ver, title, data, p->timeslot_ptr, (p->timeslot_ptr == 0)); } static void dhd_mschdbg_chan_ctxt_profiler_event_data(int sp, int ver, char *data, uint16 ptr, bool empty) { int sn = sp + 4; msch_chan_ctxt_profiler_event_data_t *p = (msch_chan_ctxt_profiler_event_data_t *)(data + ntoh16(ptr)); chanspec_t c; char buf[CHANSPEC_STR_LEN]; MSCH_EVENT_HEAD(sp); MSCH_EVENT(("<chan_ctxt>: ")); if (empty) { MSCH_EVENT((" null\n")); return; } else MSCH_EVENT(("0x%08x (prev 0x%08x, next 0x%08x)\n", ntoh32(p->p_chan_ctxt), ntoh32(p->p_prev), ntoh32(p->p_next))); c = (chanspec_t)ntoh16(p->chanspec); MSCH_EVENT_HEAD(sn); MSCH_EVENT(("channel: %s, bf_sch_pending: %s, bf_skipped: %d\n", wf_chspec_ntoa(c, buf), p->bf_sch_pending? "TRUE" : "FALSE", ntoh32(p->bf_skipped_count))); MSCH_EVENT_HEAD(sn); MSCH_EVENT(("bf_link: prev 0x%08x, next 0x%08x\n", ntoh32(p->bf_link_prev), ntoh32(p->bf_link_next))); MSCH_EVENT_HEAD(sn); MSCH_EVENT(("onchan_time: %s", dhd_mschdbg_display_time(p->onchan_time_h, p->onchan_time_l))); MSCH_EVENT((", actual_onchan_dur: %s", dhd_mschdbg_display_time(p->actual_onchan_dur_h, p->actual_onchan_dur_l))); MSCH_EVENT((", pend_onchan_dur: %s\n", dhd_mschdbg_display_time(p->pend_onchan_dur_h, p->pend_onchan_dur_l))); dhd_mschdbg_elem_list(sn, "req_entity", data, p->req_entity_list_ptr, p->req_entity_list_cnt); dhd_mschdbg_elem_list(sn, "bf_entity", data, p->bf_entity_list_ptr, p->bf_entity_list_cnt); } static void dhd_mschdbg_req_entity_profiler_event_data(int sp, int ver, char *data, uint16 ptr, bool empty) { int sn = sp + 4; msch_req_entity_profiler_event_data_t *p = (msch_req_entity_profiler_event_data_t *)(data + ntoh16(ptr)); char buf[CHANSPEC_STR_LEN]; chanspec_t c; uint32 flags; MSCH_EVENT_HEAD(sp); MSCH_EVENT(("<req_entity>: ")); if (empty) { MSCH_EVENT((" null\n")); return; } else MSCH_EVENT(("0x%08x (prev 0x%08x, next 0x%08x)\n", ntoh32(p->p_req_entity), ntoh32(p->req_hdl_link_prev), ntoh32(p->req_hdl_link_next))); MSCH_EVENT_HEAD(sn); MSCH_EVENT(("req_hdl: [0x%08x]\n", ntoh32(p->p_req_hdl))); MSCH_EVENT_HEAD(sn); MSCH_EVENT(("chan_ctxt_link: prev 0x%08x, next 0x%08x\n", ntoh32(p->chan_ctxt_link_prev), ntoh32(p->chan_ctxt_link_next))); MSCH_EVENT_HEAD(sn); MSCH_EVENT(("rt_specific_link: prev 0x%08x, next 0x%08x\n", ntoh32(p->rt_specific_link_prev), ntoh32(p->rt_specific_link_next))); MSCH_EVENT_HEAD(sn); MSCH_EVENT(("start_fixed_link: prev 0x%08x, next 0x%08x\n", ntoh32(p->start_fixed_link_prev), ntoh32(p->start_fixed_link_next))); MSCH_EVENT_HEAD(sn); MSCH_EVENT(("both_flex_list: prev 0x%08x, next 0x%08x\n", ntoh32(p->both_flex_list_prev), ntoh32(p->both_flex_list_next))); c = (chanspec_t)ntoh16(p->chanspec); MSCH_EVENT_HEAD(sn); if (ver >= 2) { MSCH_EVENT(("channel: %s, onchan Id %d, current chan Id %d, priority %d", wf_chspec_ntoa(c, buf), ntoh16(p->onchan_chn_idx), ntoh16(p->cur_chn_idx), ntoh16(p->priority))); flags = ntoh32(p->flags); if (flags & WL_MSCH_ENTITY_FLAG_MULTI_INSTANCE) MSCH_EVENT((" : MULTI_INSTANCE\n")); else MSCH_EVENT(("\n")); MSCH_EVENT_HEAD(sn); MSCH_EVENT(("actual_start_time: %s, ", dhd_mschdbg_display_time(p->actual_start_time_h, p->actual_start_time_l))); MSCH_EVENT(("curts_fire_time: %s, ", dhd_mschdbg_display_time(p->curts_fire_time_h, p->curts_fire_time_l))); } else { MSCH_EVENT(("channel: %s, priority %d, ", wf_chspec_ntoa(c, buf), ntoh16(p->priority))); } MSCH_EVENT(("bf_last_serv_time: %s\n", dhd_mschdbg_display_time(p->bf_last_serv_time_h, p->bf_last_serv_time_l))); dhd_mschdbg_req_timing_profiler_event_data(sn, ver, "current", data, p->cur_slot_ptr, (p->cur_slot_ptr == 0)); dhd_mschdbg_req_timing_profiler_event_data(sn, ver, "pending", data, p->pend_slot_ptr, (p->pend_slot_ptr == 0)); if (p->p_chan_ctxt && (p->chan_ctxt_ptr == 0)) { MSCH_EVENT_HEAD(sn); MSCH_EVENT(("<chan_ctxt>: 0x%08x\n", ntoh32(p->p_chan_ctxt))); } else dhd_mschdbg_chan_ctxt_profiler_event_data(sn, ver, data, p->chan_ctxt_ptr, (p->chan_ctxt_ptr == 0)); } static void dhd_mschdbg_req_handle_profiler_event_data(int sp, int ver, char *data, uint16 ptr, bool empty) { int sn = sp + 4; msch_req_handle_profiler_event_data_t *p = (msch_req_handle_profiler_event_data_t *)(data + ntoh16(ptr)); uint32 flags; MSCH_EVENT_HEAD(sp); MSCH_EVENT(("<req_handle>: ")); if (empty) { MSCH_EVENT((" null\n")); return; } else MSCH_EVENT(("0x%08x (prev 0x%08x, next 0x%08x)\n", ntoh32(p->p_req_handle), ntoh32(p->p_prev), ntoh32(p->p_next))); dhd_mschdbg_elem_list(sn, "req_entity", data, p->req_entity_list_ptr, p->req_entity_list_cnt); MSCH_EVENT_HEAD(sn); MSCH_EVENT(("cb_func: [0x%08x], cb_func: [0x%08x]", ntoh32(p->cb_func), ntoh32(p->cb_ctxt))); if (ver < 2) { MSCH_EVENT((", chan_cnt: %d", ntoh16(p->chan_cnt))); } flags = ntoh32(p->flags); if (flags & WL_MSCH_REQ_HDL_FLAGS_NEW_REQ) MSCH_EVENT((", NEW_REQ")); MSCH_EVENT(("\n")); dhd_mschdbg_req_param_profiler_event_data(sn, ver, data, p->req_param_ptr); if (ver >= 2) { MSCH_EVENT_HEAD(sn); MSCH_EVENT(("req_time: %s\n", dhd_mschdbg_display_time(p->req_time_h, p->req_time_l))); MSCH_EVENT_HEAD(sn); MSCH_EVENT(("chan_cnt: %d, chan idx %d, last chan idx %d\n", ntoh16(p->chan_cnt), ntoh16(p->chan_idx), ntoh16(p->last_chan_idx))); if (p->chanspec_list && p->chanspec_cnt) { dhd_mschdbg_chanspec_list(sn, data, p->chanspec_list, p->chanspec_cnt); } } } static void dhd_mschdbg_profiler_profiler_event_data(int sp, int ver, char *data, uint16 ptr) { msch_profiler_profiler_event_data_t *p = (msch_profiler_profiler_event_data_t *)(data + ntoh16(ptr)); uint32 flags; MSCH_EVENT_HEAD(sp); MSCH_EVENT(("free list: req_hdl 0x%08x, req_entity 0x%08x," " chan_ctxt 0x%08x, chanspec 0x%08x\n", ntoh32(p->free_req_hdl_list), ntoh32(p->free_req_entity_list), ntoh32(p->free_chan_ctxt_list), ntoh32(p->free_chanspec_list))); MSCH_EVENT_HEAD(sp); MSCH_EVENT(("alloc count: chanspec %d, req_entity %d, req_hdl %d, " "chan_ctxt %d, timeslot %d\n", ntoh16(p->msch_chanspec_alloc_cnt), ntoh16(p->msch_req_entity_alloc_cnt), ntoh16(p->msch_req_hdl_alloc_cnt), ntoh16(p->msch_chan_ctxt_alloc_cnt), ntoh16(p->msch_timeslot_alloc_cnt))); dhd_mschdbg_elem_list(sp, "req_hdl", data, p->msch_req_hdl_list_ptr, p->msch_req_hdl_list_cnt); dhd_mschdbg_elem_list(sp, "chan_ctxt", data, p->msch_chan_ctxt_list_ptr, p->msch_chan_ctxt_list_cnt); dhd_mschdbg_elem_list(sp, "req_timing", data, p->msch_req_timing_list_ptr, p->msch_req_timing_list_cnt); dhd_mschdbg_elem_list(sp, "start_fixed", data, p->msch_start_fixed_list_ptr, p->msch_start_fixed_list_cnt); dhd_mschdbg_elem_list(sp, "both_flex_req_entity", data, p->msch_both_flex_req_entity_list_ptr, p->msch_both_flex_req_entity_list_cnt); dhd_mschdbg_elem_list(sp, "start_flex", data, p->msch_start_flex_list_ptr, p->msch_start_flex_list_cnt); dhd_mschdbg_elem_list(sp, "both_flex", data, p->msch_both_flex_list_ptr, p->msch_both_flex_list_cnt); if (p->p_cur_msch_timeslot && (p->cur_msch_timeslot_ptr == 0)) { MSCH_EVENT_HEAD(sp); MSCH_EVENT(("<cur_msch timeslot>: 0x%08x\n", ntoh32(p->p_cur_msch_timeslot))); } else dhd_mschdbg_timeslot_profiler_event_data(sp, ver, "cur_msch", data, p->cur_msch_timeslot_ptr, (p->cur_msch_timeslot_ptr == 0)); if (p->p_next_timeslot && (p->next_timeslot_ptr == 0)) { MSCH_EVENT_HEAD(sp); MSCH_EVENT(("<next timeslot>: 0x%08x\n", ntoh32(p->p_next_timeslot))); } else dhd_mschdbg_timeslot_profiler_event_data(sp, ver, "next", data, p->next_timeslot_ptr, (p->next_timeslot_ptr == 0)); MSCH_EVENT_HEAD(sp); MSCH_EVENT(("ts_id: %d, ", ntoh32(p->ts_id))); flags = ntoh32(p->flags); if (flags & WL_MSCH_STATE_IN_TIEMR_CTXT) MSCH_EVENT(("IN_TIEMR_CTXT, ")); if (flags & WL_MSCH_STATE_SCHD_PENDING) MSCH_EVENT(("SCHD_PENDING, ")); MSCH_EVENT(("slotskip_flags: %d, cur_armed_timeslot: 0x%08x\n", (ver >= 2)? ntoh32(p->slotskip_flag) : 0, ntoh32(p->cur_armed_timeslot))); MSCH_EVENT_HEAD(sp); MSCH_EVENT(("flex_list_cnt: %d, service_interval: %d, " "max_lo_prio_interval: %d\n", ntoh16(p->flex_list_cnt), ntoh32(p->service_interval), ntoh32(p->max_lo_prio_interval))); } static void dhd_mschdbg_dump_data(dhd_pub_t *dhdp, void *raw_event_ptr, int type, char *data, int len) { uint64 t = 0, tt = 0; uint32 s = 0, ss = 0; int wlc_index, ver; ver = (type & WL_MSCH_PROFILER_VER_MASK) >> WL_MSCH_PROFILER_VER_SHIFT; wlc_index = (type & WL_MSCH_PROFILER_WLINDEX_MASK) >> WL_MSCH_PROFILER_WLINDEX_SHIFT; if (wlc_index >= 4) return; type &= WL_MSCH_PROFILER_TYPE_MASK; if (type <= WL_MSCH_PROFILER_PROFILE_END) { msch_profiler_event_data_t *pevent = (msch_profiler_event_data_t *)data; tt = ((uint64)(ntoh32(pevent->time_hi)) << 32) | ntoh32(pevent->time_lo); dhd_mschdbg_us_to_sec(pevent->time_hi, pevent->time_lo, &s, &ss); } if (lastMessages && (type != WL_MSCH_PROFILER_MESSAGE) && (type != WL_MSCH_PROFILER_EVENT_LOG)) { MSCH_EVENT_HEAD(0); MSCH_EVENT(("\n")); lastMessages = FALSE; } switch (type) { case WL_MSCH_PROFILER_START: MSCH_EVENT_HEAD(0); MSCH_EVENT(("%06d.%06d START\n", s, ss)); break; case WL_MSCH_PROFILER_EXIT: MSCH_EVENT_HEAD(0); MSCH_EVENT(("%06d.%06d EXIT\n", s, ss)); break; case WL_MSCH_PROFILER_REQ: { msch_req_profiler_event_data_t *p = (msch_req_profiler_event_data_t *)data; MSCH_EVENT_HEAD(0); MSCH_EVENT(("\n")); MSCH_EVENT_HEAD(0); MSCH_EVENT(("===============================\n")); MSCH_EVENT_HEAD(0); MSCH_EVENT(("%06d.%06d [wl%d] REGISTER:\n", s, ss, wlc_index)); dhd_mschdbg_req_param_profiler_event_data(4, ver, data, p->req_param_ptr); dhd_mschdbg_chanspec_list(4, data, p->chanspec_ptr, p->chanspec_cnt); MSCH_EVENT_HEAD(0); MSCH_EVENT(("===============================\n")); MSCH_EVENT_HEAD(0); MSCH_EVENT(("\n")); } break; case WL_MSCH_PROFILER_CALLBACK: { msch_callback_profiler_event_data_t *p = (msch_callback_profiler_event_data_t *)data; char buf[CHANSPEC_STR_LEN]; chanspec_t chanspec; uint16 cbtype; MSCH_EVENT_HEAD(0); MSCH_EVENT(("%06d.%06d [wl%d] CALLBACK: ", s, ss, wlc_index)); chanspec = (chanspec_t)ntoh16(p->chanspec); MSCH_EVENT(("req_hdl[0x%08x], channel %s --", ntoh32(p->p_req_hdl), wf_chspec_ntoa(chanspec, buf))); cbtype = ntoh16(p->type); if (cbtype & WL_MSCH_CT_ON_CHAN) MSCH_EVENT((" ON_CHAN")); if (cbtype & WL_MSCH_CT_OFF_CHAN) MSCH_EVENT((" OFF_CHAN")); if (cbtype & WL_MSCH_CT_REQ_START) MSCH_EVENT((" REQ_START")); if (cbtype & WL_MSCH_CT_REQ_END) MSCH_EVENT((" REQ_END")); if (cbtype & WL_MSCH_CT_SLOT_START) MSCH_EVENT((" SLOT_START")); if (cbtype & WL_MSCH_CT_SLOT_SKIP) MSCH_EVENT((" SLOT_SKIP")); if (cbtype & WL_MSCH_CT_SLOT_END) MSCH_EVENT((" SLOT_END")); if (cbtype & WL_MSCH_CT_OFF_CHAN_DONE) MSCH_EVENT((" OFF_CHAN_DONE")); if (cbtype & WL_MSCH_CT_PARTIAL) MSCH_EVENT((" PARTIAL")); if (cbtype & WL_MSCH_CT_PRE_ONCHAN) MSCH_EVENT((" PRE_ONCHAN")); if (cbtype & WL_MSCH_CT_PRE_REQ_START) MSCH_EVENT((" PRE_REQ_START")); if (cbtype & WL_MSCH_CT_REQ_START) { req_start[wlc_index] = 1; req_start_time[wlc_index] = tt; } else if (cbtype & WL_MSCH_CT_REQ_END) { if (req_start[wlc_index]) { MSCH_EVENT((" : REQ duration %d", (uint32)(tt - req_start_time[wlc_index]))); req_start[wlc_index] = 0; } } if (cbtype & WL_MSCH_CT_SLOT_START) { solt_chanspec[wlc_index] = p->chanspec; solt_start_time[wlc_index] = tt; } else if (cbtype & WL_MSCH_CT_SLOT_END) { if (p->chanspec == solt_chanspec[wlc_index]) { MSCH_EVENT((" : SLOT duration %d", (uint32)(tt - solt_start_time[wlc_index]))); solt_chanspec[wlc_index] = 0; } } MSCH_EVENT(("\n")); if (cbtype & (WL_MSCH_CT_ON_CHAN | WL_MSCH_CT_SLOT_SKIP)) { MSCH_EVENT_HEAD(4); if (cbtype & WL_MSCH_CT_ON_CHAN) { MSCH_EVENT(("ID %d onchan idx %d cur_chan_seq_start %s ", ntoh32(p->timeslot_id), ntoh32(p->onchan_idx), dhd_mschdbg_display_time(p->cur_chan_seq_start_time_h, p->cur_chan_seq_start_time_l))); } t = ((uint64)(ntoh32(p->start_time_h)) << 32) | ntoh32(p->start_time_l); MSCH_EVENT(("start %s ", dhd_mschdbg_display_time(p->start_time_h, p->start_time_l))); tt = ((uint64)(ntoh32(p->end_time_h)) << 32) | ntoh32(p->end_time_l); MSCH_EVENT(("end %s duration %d\n", dhd_mschdbg_display_time(p->end_time_h, p->end_time_l), (p->end_time_h == 0xffffffff && p->end_time_l == 0xffffffff)? -1 : (int)(tt - t))); } } break; case WL_MSCH_PROFILER_EVENT_LOG: { while (len >= (int)WL_MSCH_EVENT_LOG_HEAD_SIZE) { msch_event_log_profiler_event_data_t *p = (msch_event_log_profiler_event_data_t *)data; event_log_hdr_t hdr; int size = WL_MSCH_EVENT_LOG_HEAD_SIZE + p->hdr.count * sizeof(uint32); if (len < size || size > sizeof(msch_event_log_profiler_event_data_t)) { break; } data += size; len -= size; dhd_mschdbg_us_to_sec(p->time_hi, p->time_lo, &s, &ss); MSCH_EVENT_HEAD(0); MSCH_EVENT(("%06d.%06d [wl%d]: ", s, ss, p->hdr.tag)); hdr.tag = EVENT_LOG_TAG_MSCHPROFILE; hdr.count = p->hdr.count + 1; hdr.fmt_num = ntoh16(p->hdr.fmt_num); dhd_dbg_verboselog_printf(dhdp, &hdr, raw_event_ptr, p->data, 0, 0); } lastMessages = TRUE; break; } case WL_MSCH_PROFILER_MESSAGE: { msch_message_profiler_event_data_t *p = (msch_message_profiler_event_data_t *)data; MSCH_EVENT_HEAD(0); MSCH_EVENT(("%06d.%06d [wl%d]: %s", s, ss, wlc_index, p->message)); lastMessages = TRUE; break; } case WL_MSCH_PROFILER_PROFILE_START: profiler_start_time[wlc_index] = tt; MSCH_EVENT_HEAD(0); MSCH_EVENT(("-------------------------------\n")); MSCH_EVENT_HEAD(0); MSCH_EVENT(("%06d.%06d [wl%d] PROFILE DATA:\n", s, ss, wlc_index)); dhd_mschdbg_profiler_profiler_event_data(4, ver, data, 0); break; case WL_MSCH_PROFILER_PROFILE_END: MSCH_EVENT_HEAD(0); MSCH_EVENT(("%06d.%06d [wl%d] PROFILE END: take time %d\n", s, ss, wlc_index, (uint32)(tt - profiler_start_time[wlc_index]))); MSCH_EVENT_HEAD(0); MSCH_EVENT(("-------------------------------\n")); MSCH_EVENT_HEAD(0); MSCH_EVENT(("\n")); break; case WL_MSCH_PROFILER_REQ_HANDLE: dhd_mschdbg_req_handle_profiler_event_data(4, ver, data, 0, FALSE); break; case WL_MSCH_PROFILER_REQ_ENTITY: dhd_mschdbg_req_entity_profiler_event_data(4, ver, data, 0, FALSE); break; case WL_MSCH_PROFILER_CHAN_CTXT: dhd_mschdbg_chan_ctxt_profiler_event_data(4, ver, data, 0, FALSE); break; case WL_MSCH_PROFILER_REQ_TIMING: dhd_mschdbg_req_timing_profiler_event_data(4, ver, "msch", data, 0, FALSE); break; default: MSCH_EVENT_HEAD(0); MSCH_EVENT(("[wl%d] ERROR: unsupported EVENT reason code:%d; ", wlc_index, type)); break; } } void wl_mschdbg_event_handler(dhd_pub_t *dhdp, void *raw_event_ptr, int type, void *data, int len) { head_log = "MSCH"; dhd_mschdbg_dump_data(dhdp, raw_event_ptr, type, (char *)data, len); } void wl_mschdbg_verboselog_handler(dhd_pub_t *dhdp, void *raw_event_ptr, event_log_hdr_t *log_hdr, uint32 *log_ptr) { uint32 log_pyld_len; head_log = "CONSOLE"; if (log_hdr->count == 0) { return; } log_pyld_len = (log_hdr->count - 1) * DATA_UNIT_FOR_LOG_CNT; if (log_hdr->tag == EVENT_LOG_TAG_MSCHPROFILE) { msch_event_log_profiler_event_data_t *p = (msch_event_log_profiler_event_data_t *)log_ptr; event_log_hdr_t hdr; uint32 s, ss; if (log_pyld_len < OFFSETOF(msch_event_log_profiler_event_data_t, data) || log_pyld_len > sizeof(msch_event_log_profiler_event_data_t)) { return; } dhd_mschdbg_us_to_sec(p->time_hi, p->time_lo, &s, &ss); MSCH_EVENT_HEAD(0); MSCH_EVENT(("%06d.%06d [wl%d]: ", s, ss, p->hdr.tag)); hdr.tag = EVENT_LOG_TAG_MSCHPROFILE; hdr.count = p->hdr.count + 1; hdr.fmt_num = ntoh16(p->hdr.fmt_num); dhd_dbg_verboselog_printf(dhdp, &hdr, raw_event_ptr, p->data, 0, 0); } else { msch_collect_tlv_t *p = (msch_collect_tlv_t *)log_ptr; int type = ntoh16(p->type); int len = ntoh16(p->size); if (log_pyld_len < OFFSETOF(msch_collect_tlv_t, value) + len) { return; } dhd_mschdbg_dump_data(dhdp, raw_event_ptr, type, p->value, len); } } #endif /* SHOW_LOGTRACE */
the_stack_data/150140392.c
//===-- X86Disassembler.cpp - Disassembler for x86 and x86_64 -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is part of the X86 Disassembler. // It contains code to translate the data produced by the decoder into // MCInsts. // Documentation for the disassembler can be found in X86Disassembler.h. // //===----------------------------------------------------------------------===// /* Capstone Disassembly Engine */ /* By Nguyen Anh Quynh <[email protected]>, 2013-2015 */ #ifdef CAPSTONE_HAS_X86 #if defined (WIN32) || defined (WIN64) || defined (_WIN32) || defined (_WIN64) #pragma warning(disable:4996) // disable MSVC's warning on strncpy() #pragma warning(disable:28719) // disable MSVC's warning on strncpy() #endif #include <capstone/platform.h> #if defined(CAPSTONE_HAS_OSXKERNEL) #include <Availability.h> #endif #include <string.h> #include "../../cs_priv.h" #include "X86Disassembler.h" #include "X86DisassemblerDecoderCommon.h" #include "X86DisassemblerDecoder.h" #include "../../MCInst.h" #include "../../utils.h" #include "X86Mapping.h" #define GET_REGINFO_ENUM #define GET_REGINFO_MC_DESC #include "X86GenRegisterInfo.inc" #define GET_INSTRINFO_ENUM #ifdef CAPSTONE_X86_REDUCE #include "X86GenInstrInfo_reduce.inc" #else #include "X86GenInstrInfo.inc" #endif // Fill-ins to make the compiler happy. These constants are never actually // assigned; they are just filler to make an automatically-generated switch // statement work. enum { X86_BX_SI = 500, X86_BX_DI = 501, X86_BP_SI = 502, X86_BP_DI = 503, X86_sib = 504, X86_sib64 = 505 }; // // Private code that translates from struct InternalInstructions to MCInsts. // /// translateRegister - Translates an internal register to the appropriate LLVM /// register, and appends it as an operand to an MCInst. /// /// @param mcInst - The MCInst to append to. /// @param reg - The Reg to append. static void translateRegister(MCInst *mcInst, Reg reg) { #define ENTRY(x) X86_##x, uint8_t llvmRegnums[] = { ALL_REGS 0 }; #undef ENTRY uint8_t llvmRegnum = llvmRegnums[reg]; MCOperand_CreateReg0(mcInst, llvmRegnum); } static const uint8_t segmentRegnums[SEG_OVERRIDE_max] = { 0, // SEG_OVERRIDE_NONE X86_CS, X86_SS, X86_DS, X86_ES, X86_FS, X86_GS }; /// translateSrcIndex - Appends a source index operand to an MCInst. /// /// @param mcInst - The MCInst to append to. /// @param insn - The internal instruction. static bool translateSrcIndex(MCInst *mcInst, InternalInstruction *insn) { unsigned baseRegNo; if (insn->mode == MODE_64BIT) baseRegNo = insn->isPrefix67 ? X86_ESI : X86_RSI; else if (insn->mode == MODE_32BIT) baseRegNo = insn->isPrefix67 ? X86_SI : X86_ESI; else { // assert(insn->mode == MODE_16BIT); baseRegNo = insn->isPrefix67 ? X86_ESI : X86_SI; } MCOperand_CreateReg0(mcInst, baseRegNo); MCOperand_CreateReg0(mcInst, segmentRegnums[insn->segmentOverride]); return false; } /// translateDstIndex - Appends a destination index operand to an MCInst. /// /// @param mcInst - The MCInst to append to. /// @param insn - The internal instruction. static bool translateDstIndex(MCInst *mcInst, InternalInstruction *insn) { unsigned baseRegNo; if (insn->mode == MODE_64BIT) baseRegNo = insn->isPrefix67 ? X86_EDI : X86_RDI; else if (insn->mode == MODE_32BIT) baseRegNo = insn->isPrefix67 ? X86_DI : X86_EDI; else { // assert(insn->mode == MODE_16BIT); baseRegNo = insn->isPrefix67 ? X86_EDI : X86_DI; } MCOperand_CreateReg0(mcInst, baseRegNo); return false; } /// translateImmediate - Appends an immediate operand to an MCInst. /// /// @param mcInst - The MCInst to append to. /// @param immediate - The immediate value to append. /// @param operand - The operand, as stored in the descriptor table. /// @param insn - The internal instruction. static void translateImmediate(MCInst *mcInst, uint64_t immediate, const OperandSpecifier *operand, InternalInstruction *insn) { OperandType type; type = (OperandType)operand->type; if (type == TYPE_RELv) { //isBranch = true; //pcrel = insn->startLocation + insn->immediateOffset + insn->immediateSize; switch (insn->displacementSize) { case 1: if (immediate & 0x80) immediate |= ~(0xffull); break; case 2: if (immediate & 0x8000) immediate |= ~(0xffffull); break; case 4: if (immediate & 0x80000000) immediate |= ~(0xffffffffull); break; case 8: break; default: break; } } // By default sign-extend all X86 immediates based on their encoding. else if (type == TYPE_IMM8 || type == TYPE_IMM16 || type == TYPE_IMM32 || type == TYPE_IMM64 || type == TYPE_IMMv) { switch (operand->encoding) { default: break; case ENCODING_IB: if(immediate & 0x80) immediate |= ~(0xffull); break; case ENCODING_IW: if(immediate & 0x8000) immediate |= ~(0xffffull); break; case ENCODING_ID: if(immediate & 0x80000000) immediate |= ~(0xffffffffull); break; case ENCODING_IO: break; } } else if (type == TYPE_IMM3) { #ifndef CAPSTONE_X86_REDUCE // Check for immediates that printSSECC can't handle. if (immediate >= 8) { unsigned NewOpc = 0; switch (MCInst_getOpcode(mcInst)) { default: break; // never reach case X86_CMPPDrmi: NewOpc = X86_CMPPDrmi_alt; break; case X86_CMPPDrri: NewOpc = X86_CMPPDrri_alt; break; case X86_CMPPSrmi: NewOpc = X86_CMPPSrmi_alt; break; case X86_CMPPSrri: NewOpc = X86_CMPPSrri_alt; break; case X86_CMPSDrm: NewOpc = X86_CMPSDrm_alt; break; case X86_CMPSDrr: NewOpc = X86_CMPSDrr_alt; break; case X86_CMPSSrm: NewOpc = X86_CMPSSrm_alt; break; case X86_CMPSSrr: NewOpc = X86_CMPSSrr_alt; break; case X86_VPCOMBri: NewOpc = X86_VPCOMBri_alt; break; case X86_VPCOMBmi: NewOpc = X86_VPCOMBmi_alt; break; case X86_VPCOMWri: NewOpc = X86_VPCOMWri_alt; break; case X86_VPCOMWmi: NewOpc = X86_VPCOMWmi_alt; break; case X86_VPCOMDri: NewOpc = X86_VPCOMDri_alt; break; case X86_VPCOMDmi: NewOpc = X86_VPCOMDmi_alt; break; case X86_VPCOMQri: NewOpc = X86_VPCOMQri_alt; break; case X86_VPCOMQmi: NewOpc = X86_VPCOMQmi_alt; break; case X86_VPCOMUBri: NewOpc = X86_VPCOMUBri_alt; break; case X86_VPCOMUBmi: NewOpc = X86_VPCOMUBmi_alt; break; case X86_VPCOMUWri: NewOpc = X86_VPCOMUWri_alt; break; case X86_VPCOMUWmi: NewOpc = X86_VPCOMUWmi_alt; break; case X86_VPCOMUDri: NewOpc = X86_VPCOMUDri_alt; break; case X86_VPCOMUDmi: NewOpc = X86_VPCOMUDmi_alt; break; case X86_VPCOMUQri: NewOpc = X86_VPCOMUQri_alt; break; case X86_VPCOMUQmi: NewOpc = X86_VPCOMUQmi_alt; break; } // Switch opcode to the one that doesn't get special printing. MCInst_setOpcode(mcInst, NewOpc); } #endif } else if (type == TYPE_IMM5) { #ifndef CAPSTONE_X86_REDUCE // Check for immediates that printAVXCC can't handle. if (immediate >= 32) { unsigned NewOpc = 0; switch (MCInst_getOpcode(mcInst)) { default: break; // unexpected opcode case X86_VCMPPDrmi: NewOpc = X86_VCMPPDrmi_alt; break; case X86_VCMPPDrri: NewOpc = X86_VCMPPDrri_alt; break; case X86_VCMPPSrmi: NewOpc = X86_VCMPPSrmi_alt; break; case X86_VCMPPSrri: NewOpc = X86_VCMPPSrri_alt; break; case X86_VCMPSDrm: NewOpc = X86_VCMPSDrm_alt; break; case X86_VCMPSDrr: NewOpc = X86_VCMPSDrr_alt; break; case X86_VCMPSSrm: NewOpc = X86_VCMPSSrm_alt; break; case X86_VCMPSSrr: NewOpc = X86_VCMPSSrr_alt; break; case X86_VCMPPDYrmi: NewOpc = X86_VCMPPDYrmi_alt; break; case X86_VCMPPDYrri: NewOpc = X86_VCMPPDYrri_alt; break; case X86_VCMPPSYrmi: NewOpc = X86_VCMPPSYrmi_alt; break; case X86_VCMPPSYrri: NewOpc = X86_VCMPPSYrri_alt; break; case X86_VCMPPDZrmi: NewOpc = X86_VCMPPDZrmi_alt; break; case X86_VCMPPDZrri: NewOpc = X86_VCMPPDZrri_alt; break; case X86_VCMPPDZrrib: NewOpc = X86_VCMPPDZrrib_alt; break; case X86_VCMPPSZrmi: NewOpc = X86_VCMPPSZrmi_alt; break; case X86_VCMPPSZrri: NewOpc = X86_VCMPPSZrri_alt; break; case X86_VCMPPSZrrib: NewOpc = X86_VCMPPSZrrib_alt; break; case X86_VCMPSDZrm: NewOpc = X86_VCMPSDZrmi_alt; break; case X86_VCMPSDZrr: NewOpc = X86_VCMPSDZrri_alt; break; case X86_VCMPSSZrm: NewOpc = X86_VCMPSSZrmi_alt; break; case X86_VCMPSSZrr: NewOpc = X86_VCMPSSZrri_alt; break; } // Switch opcode to the one that doesn't get special printing. if (NewOpc != 0) { MCInst_setOpcode(mcInst, NewOpc); } } #endif } else if (type == TYPE_AVX512ICC) { #ifndef CAPSTONE_X86_REDUCE if (immediate >= 8 || ((immediate & 0x3) == 3)) { unsigned NewOpc = 0; switch (MCInst_getOpcode(mcInst)) { default: // llvm_unreachable("unexpected opcode"); case X86_VPCMPBZ128rmi: NewOpc = X86_VPCMPBZ128rmi_alt; break; case X86_VPCMPBZ128rmik: NewOpc = X86_VPCMPBZ128rmik_alt; break; case X86_VPCMPBZ128rri: NewOpc = X86_VPCMPBZ128rri_alt; break; case X86_VPCMPBZ128rrik: NewOpc = X86_VPCMPBZ128rrik_alt; break; case X86_VPCMPBZ256rmi: NewOpc = X86_VPCMPBZ256rmi_alt; break; case X86_VPCMPBZ256rmik: NewOpc = X86_VPCMPBZ256rmik_alt; break; case X86_VPCMPBZ256rri: NewOpc = X86_VPCMPBZ256rri_alt; break; case X86_VPCMPBZ256rrik: NewOpc = X86_VPCMPBZ256rrik_alt; break; case X86_VPCMPBZrmi: NewOpc = X86_VPCMPBZrmi_alt; break; case X86_VPCMPBZrmik: NewOpc = X86_VPCMPBZrmik_alt; break; case X86_VPCMPBZrri: NewOpc = X86_VPCMPBZrri_alt; break; case X86_VPCMPBZrrik: NewOpc = X86_VPCMPBZrrik_alt; break; case X86_VPCMPDZ128rmi: NewOpc = X86_VPCMPDZ128rmi_alt; break; case X86_VPCMPDZ128rmib: NewOpc = X86_VPCMPDZ128rmib_alt; break; case X86_VPCMPDZ128rmibk: NewOpc = X86_VPCMPDZ128rmibk_alt; break; case X86_VPCMPDZ128rmik: NewOpc = X86_VPCMPDZ128rmik_alt; break; case X86_VPCMPDZ128rri: NewOpc = X86_VPCMPDZ128rri_alt; break; case X86_VPCMPDZ128rrik: NewOpc = X86_VPCMPDZ128rrik_alt; break; case X86_VPCMPDZ256rmi: NewOpc = X86_VPCMPDZ256rmi_alt; break; case X86_VPCMPDZ256rmib: NewOpc = X86_VPCMPDZ256rmib_alt; break; case X86_VPCMPDZ256rmibk: NewOpc = X86_VPCMPDZ256rmibk_alt; break; case X86_VPCMPDZ256rmik: NewOpc = X86_VPCMPDZ256rmik_alt; break; case X86_VPCMPDZ256rri: NewOpc = X86_VPCMPDZ256rri_alt; break; case X86_VPCMPDZ256rrik: NewOpc = X86_VPCMPDZ256rrik_alt; break; case X86_VPCMPDZrmi: NewOpc = X86_VPCMPDZrmi_alt; break; case X86_VPCMPDZrmib: NewOpc = X86_VPCMPDZrmib_alt; break; case X86_VPCMPDZrmibk: NewOpc = X86_VPCMPDZrmibk_alt; break; case X86_VPCMPDZrmik: NewOpc = X86_VPCMPDZrmik_alt; break; case X86_VPCMPDZrri: NewOpc = X86_VPCMPDZrri_alt; break; case X86_VPCMPDZrrik: NewOpc = X86_VPCMPDZrrik_alt; break; case X86_VPCMPQZ128rmi: NewOpc = X86_VPCMPQZ128rmi_alt; break; case X86_VPCMPQZ128rmib: NewOpc = X86_VPCMPQZ128rmib_alt; break; case X86_VPCMPQZ128rmibk: NewOpc = X86_VPCMPQZ128rmibk_alt; break; case X86_VPCMPQZ128rmik: NewOpc = X86_VPCMPQZ128rmik_alt; break; case X86_VPCMPQZ128rri: NewOpc = X86_VPCMPQZ128rri_alt; break; case X86_VPCMPQZ128rrik: NewOpc = X86_VPCMPQZ128rrik_alt; break; case X86_VPCMPQZ256rmi: NewOpc = X86_VPCMPQZ256rmi_alt; break; case X86_VPCMPQZ256rmib: NewOpc = X86_VPCMPQZ256rmib_alt; break; case X86_VPCMPQZ256rmibk: NewOpc = X86_VPCMPQZ256rmibk_alt; break; case X86_VPCMPQZ256rmik: NewOpc = X86_VPCMPQZ256rmik_alt; break; case X86_VPCMPQZ256rri: NewOpc = X86_VPCMPQZ256rri_alt; break; case X86_VPCMPQZ256rrik: NewOpc = X86_VPCMPQZ256rrik_alt; break; case X86_VPCMPQZrmi: NewOpc = X86_VPCMPQZrmi_alt; break; case X86_VPCMPQZrmib: NewOpc = X86_VPCMPQZrmib_alt; break; case X86_VPCMPQZrmibk: NewOpc = X86_VPCMPQZrmibk_alt; break; case X86_VPCMPQZrmik: NewOpc = X86_VPCMPQZrmik_alt; break; case X86_VPCMPQZrri: NewOpc = X86_VPCMPQZrri_alt; break; case X86_VPCMPQZrrik: NewOpc = X86_VPCMPQZrrik_alt; break; case X86_VPCMPUBZ128rmi: NewOpc = X86_VPCMPUBZ128rmi_alt; break; case X86_VPCMPUBZ128rmik: NewOpc = X86_VPCMPUBZ128rmik_alt; break; case X86_VPCMPUBZ128rri: NewOpc = X86_VPCMPUBZ128rri_alt; break; case X86_VPCMPUBZ128rrik: NewOpc = X86_VPCMPUBZ128rrik_alt; break; case X86_VPCMPUBZ256rmi: NewOpc = X86_VPCMPUBZ256rmi_alt; break; case X86_VPCMPUBZ256rmik: NewOpc = X86_VPCMPUBZ256rmik_alt; break; case X86_VPCMPUBZ256rri: NewOpc = X86_VPCMPUBZ256rri_alt; break; case X86_VPCMPUBZ256rrik: NewOpc = X86_VPCMPUBZ256rrik_alt; break; case X86_VPCMPUBZrmi: NewOpc = X86_VPCMPUBZrmi_alt; break; case X86_VPCMPUBZrmik: NewOpc = X86_VPCMPUBZrmik_alt; break; case X86_VPCMPUBZrri: NewOpc = X86_VPCMPUBZrri_alt; break; case X86_VPCMPUBZrrik: NewOpc = X86_VPCMPUBZrrik_alt; break; case X86_VPCMPUDZ128rmi: NewOpc = X86_VPCMPUDZ128rmi_alt; break; case X86_VPCMPUDZ128rmib: NewOpc = X86_VPCMPUDZ128rmib_alt; break; case X86_VPCMPUDZ128rmibk: NewOpc = X86_VPCMPUDZ128rmibk_alt; break; case X86_VPCMPUDZ128rmik: NewOpc = X86_VPCMPUDZ128rmik_alt; break; case X86_VPCMPUDZ128rri: NewOpc = X86_VPCMPUDZ128rri_alt; break; case X86_VPCMPUDZ128rrik: NewOpc = X86_VPCMPUDZ128rrik_alt; break; case X86_VPCMPUDZ256rmi: NewOpc = X86_VPCMPUDZ256rmi_alt; break; case X86_VPCMPUDZ256rmib: NewOpc = X86_VPCMPUDZ256rmib_alt; break; case X86_VPCMPUDZ256rmibk: NewOpc = X86_VPCMPUDZ256rmibk_alt; break; case X86_VPCMPUDZ256rmik: NewOpc = X86_VPCMPUDZ256rmik_alt; break; case X86_VPCMPUDZ256rri: NewOpc = X86_VPCMPUDZ256rri_alt; break; case X86_VPCMPUDZ256rrik: NewOpc = X86_VPCMPUDZ256rrik_alt; break; case X86_VPCMPUDZrmi: NewOpc = X86_VPCMPUDZrmi_alt; break; case X86_VPCMPUDZrmib: NewOpc = X86_VPCMPUDZrmib_alt; break; case X86_VPCMPUDZrmibk: NewOpc = X86_VPCMPUDZrmibk_alt; break; case X86_VPCMPUDZrmik: NewOpc = X86_VPCMPUDZrmik_alt; break; case X86_VPCMPUDZrri: NewOpc = X86_VPCMPUDZrri_alt; break; case X86_VPCMPUDZrrik: NewOpc = X86_VPCMPUDZrrik_alt; break; case X86_VPCMPUQZ128rmi: NewOpc = X86_VPCMPUQZ128rmi_alt; break; case X86_VPCMPUQZ128rmib: NewOpc = X86_VPCMPUQZ128rmib_alt; break; case X86_VPCMPUQZ128rmibk: NewOpc = X86_VPCMPUQZ128rmibk_alt; break; case X86_VPCMPUQZ128rmik: NewOpc = X86_VPCMPUQZ128rmik_alt; break; case X86_VPCMPUQZ128rri: NewOpc = X86_VPCMPUQZ128rri_alt; break; case X86_VPCMPUQZ128rrik: NewOpc = X86_VPCMPUQZ128rrik_alt; break; case X86_VPCMPUQZ256rmi: NewOpc = X86_VPCMPUQZ256rmi_alt; break; case X86_VPCMPUQZ256rmib: NewOpc = X86_VPCMPUQZ256rmib_alt; break; case X86_VPCMPUQZ256rmibk: NewOpc = X86_VPCMPUQZ256rmibk_alt; break; case X86_VPCMPUQZ256rmik: NewOpc = X86_VPCMPUQZ256rmik_alt; break; case X86_VPCMPUQZ256rri: NewOpc = X86_VPCMPUQZ256rri_alt; break; case X86_VPCMPUQZ256rrik: NewOpc = X86_VPCMPUQZ256rrik_alt; break; case X86_VPCMPUQZrmi: NewOpc = X86_VPCMPUQZrmi_alt; break; case X86_VPCMPUQZrmib: NewOpc = X86_VPCMPUQZrmib_alt; break; case X86_VPCMPUQZrmibk: NewOpc = X86_VPCMPUQZrmibk_alt; break; case X86_VPCMPUQZrmik: NewOpc = X86_VPCMPUQZrmik_alt; break; case X86_VPCMPUQZrri: NewOpc = X86_VPCMPUQZrri_alt; break; case X86_VPCMPUQZrrik: NewOpc = X86_VPCMPUQZrrik_alt; break; case X86_VPCMPUWZ128rmi: NewOpc = X86_VPCMPUWZ128rmi_alt; break; case X86_VPCMPUWZ128rmik: NewOpc = X86_VPCMPUWZ128rmik_alt; break; case X86_VPCMPUWZ128rri: NewOpc = X86_VPCMPUWZ128rri_alt; break; case X86_VPCMPUWZ128rrik: NewOpc = X86_VPCMPUWZ128rrik_alt; break; case X86_VPCMPUWZ256rmi: NewOpc = X86_VPCMPUWZ256rmi_alt; break; case X86_VPCMPUWZ256rmik: NewOpc = X86_VPCMPUWZ256rmik_alt; break; case X86_VPCMPUWZ256rri: NewOpc = X86_VPCMPUWZ256rri_alt; break; case X86_VPCMPUWZ256rrik: NewOpc = X86_VPCMPUWZ256rrik_alt; break; case X86_VPCMPUWZrmi: NewOpc = X86_VPCMPUWZrmi_alt; break; case X86_VPCMPUWZrmik: NewOpc = X86_VPCMPUWZrmik_alt; break; case X86_VPCMPUWZrri: NewOpc = X86_VPCMPUWZrri_alt; break; case X86_VPCMPUWZrrik: NewOpc = X86_VPCMPUWZrrik_alt; break; case X86_VPCMPWZ128rmi: NewOpc = X86_VPCMPWZ128rmi_alt; break; case X86_VPCMPWZ128rmik: NewOpc = X86_VPCMPWZ128rmik_alt; break; case X86_VPCMPWZ128rri: NewOpc = X86_VPCMPWZ128rri_alt; break; case X86_VPCMPWZ128rrik: NewOpc = X86_VPCMPWZ128rrik_alt; break; case X86_VPCMPWZ256rmi: NewOpc = X86_VPCMPWZ256rmi_alt; break; case X86_VPCMPWZ256rmik: NewOpc = X86_VPCMPWZ256rmik_alt; break; case X86_VPCMPWZ256rri: NewOpc = X86_VPCMPWZ256rri_alt; break; case X86_VPCMPWZ256rrik: NewOpc = X86_VPCMPWZ256rrik_alt; break; case X86_VPCMPWZrmi: NewOpc = X86_VPCMPWZrmi_alt; break; case X86_VPCMPWZrmik: NewOpc = X86_VPCMPWZrmik_alt; break; case X86_VPCMPWZrri: NewOpc = X86_VPCMPWZrri_alt; break; case X86_VPCMPWZrrik: NewOpc = X86_VPCMPWZrrik_alt; break; } // Switch opcode to the one that doesn't get special printing. MCInst_setOpcode(mcInst, NewOpc); } #endif } switch (type) { case TYPE_XMM32: case TYPE_XMM64: case TYPE_XMM128: MCOperand_CreateReg0(mcInst, X86_XMM0 + ((uint32_t)immediate >> 4)); return; case TYPE_XMM256: MCOperand_CreateReg0(mcInst, X86_YMM0 + ((uint32_t)immediate >> 4)); return; case TYPE_XMM512: MCOperand_CreateReg0(mcInst, X86_ZMM0 + ((uint32_t)immediate >> 4)); return; case TYPE_REL8: if(immediate & 0x80) immediate |= ~(0xffull); break; case TYPE_REL32: case TYPE_REL64: if(immediate & 0x80000000) immediate |= ~(0xffffffffull); break; default: // operand is 64 bits wide. Do nothing. break; } MCOperand_CreateImm0(mcInst, immediate); if (type == TYPE_MOFFS8 || type == TYPE_MOFFS16 || type == TYPE_MOFFS32 || type == TYPE_MOFFS64) { MCOperand_CreateReg0(mcInst, segmentRegnums[insn->segmentOverride]); } } /// translateRMRegister - Translates a register stored in the R/M field of the /// ModR/M byte to its LLVM equivalent and appends it to an MCInst. /// @param mcInst - The MCInst to append to. /// @param insn - The internal instruction to extract the R/M field /// from. /// @return - 0 on success; -1 otherwise static bool translateRMRegister(MCInst *mcInst, InternalInstruction *insn) { if (insn->eaBase == EA_BASE_sib || insn->eaBase == EA_BASE_sib64) { //debug("A R/M register operand may not have a SIB byte"); return true; } switch (insn->eaBase) { case EA_BASE_NONE: //debug("EA_BASE_NONE for ModR/M base"); return true; #define ENTRY(x) case EA_BASE_##x: ALL_EA_BASES #undef ENTRY //debug("A R/M register operand may not have a base; " // "the operand must be a register."); return true; #define ENTRY(x) \ case EA_REG_##x: \ MCOperand_CreateReg0(mcInst, X86_##x); break; ALL_REGS #undef ENTRY default: //debug("Unexpected EA base register"); return true; } return false; } /// translateRMMemory - Translates a memory operand stored in the Mod and R/M /// fields of an internal instruction (and possibly its SIB byte) to a memory /// operand in LLVM's format, and appends it to an MCInst. /// /// @param mcInst - The MCInst to append to. /// @param insn - The instruction to extract Mod, R/M, and SIB fields /// from. /// @return - 0 on success; nonzero otherwise static bool translateRMMemory(MCInst *mcInst, InternalInstruction *insn) { // Addresses in an MCInst are represented as five operands: // 1. basereg (register) The R/M base, or (if there is a SIB) the // SIB base // 2. scaleamount (immediate) 1, or (if there is a SIB) the specified // scale amount // 3. indexreg (register) x86_registerNONE, or (if there is a SIB) // the index (which is multiplied by the // scale amount) // 4. displacement (immediate) 0, or the displacement if there is one // 5. segmentreg (register) x86_registerNONE for now, but could be set // if we have segment overrides bool IndexIs512, IndexIs128, IndexIs256; int scaleAmount, indexReg; #ifndef CAPSTONE_X86_REDUCE uint32_t Opcode; #endif if (insn->eaBase == EA_BASE_sib || insn->eaBase == EA_BASE_sib64) { if (insn->sibBase != SIB_BASE_NONE) { switch (insn->sibBase) { #define ENTRY(x) \ case SIB_BASE_##x: \ MCOperand_CreateReg0(mcInst, X86_##x); break; ALL_SIB_BASES #undef ENTRY default: //debug("Unexpected sibBase"); return true; } } else { MCOperand_CreateReg0(mcInst, 0); } // Check whether we are handling VSIB addressing mode for GATHER. // If sibIndex was set to SIB_INDEX_NONE, index offset is 4 and // we should use SIB_INDEX_XMM4|YMM4 for VSIB. // I don't see a way to get the correct IndexReg in readSIB: // We can tell whether it is VSIB or SIB after instruction ID is decoded, // but instruction ID may not be decoded yet when calling readSIB. #ifndef CAPSTONE_X86_REDUCE Opcode = MCInst_getOpcode(mcInst); #endif IndexIs128 = ( #ifndef CAPSTONE_X86_REDUCE Opcode == X86_VGATHERDPDrm || Opcode == X86_VGATHERDPDYrm || Opcode == X86_VGATHERQPDrm || Opcode == X86_VGATHERDPSrm || Opcode == X86_VGATHERQPSrm || Opcode == X86_VPGATHERDQrm || Opcode == X86_VPGATHERDQYrm || Opcode == X86_VPGATHERQQrm || Opcode == X86_VPGATHERDDrm || Opcode == X86_VPGATHERQDrm || #endif false ); IndexIs256 = ( #ifndef CAPSTONE_X86_REDUCE Opcode == X86_VGATHERQPDYrm || Opcode == X86_VGATHERDPSYrm || Opcode == X86_VGATHERQPSYrm || Opcode == X86_VGATHERDPDZrm || Opcode == X86_VPGATHERDQZrm || Opcode == X86_VPGATHERQQYrm || Opcode == X86_VPGATHERDDYrm || Opcode == X86_VPGATHERQDYrm || #endif false ); IndexIs512 = ( #ifndef CAPSTONE_X86_REDUCE Opcode == X86_VGATHERQPDZrm || Opcode == X86_VGATHERDPSZrm || Opcode == X86_VGATHERQPSZrm || Opcode == X86_VPGATHERQQZrm || Opcode == X86_VPGATHERDDZrm || Opcode == X86_VPGATHERQDZrm || #endif false ); if (IndexIs128 || IndexIs256 || IndexIs512) { unsigned IndexOffset = insn->sibIndex - (insn->addressSize == 8 ? SIB_INDEX_RAX:SIB_INDEX_EAX); SIBIndex IndexBase = IndexIs512 ? SIB_INDEX_ZMM0 : IndexIs256 ? SIB_INDEX_YMM0 : SIB_INDEX_XMM0; insn->sibIndex = (SIBIndex)(IndexBase + (insn->sibIndex == SIB_INDEX_NONE ? 4 : IndexOffset)); } if (insn->sibIndex != SIB_INDEX_NONE) { switch (insn->sibIndex) { default: //debug("Unexpected sibIndex"); return true; #define ENTRY(x) \ case SIB_INDEX_##x: \ indexReg = X86_##x; break; EA_BASES_32BIT EA_BASES_64BIT REGS_XMM REGS_YMM REGS_ZMM #undef ENTRY } } else { indexReg = 0; } scaleAmount = insn->sibScale; } else { switch (insn->eaBase) { case EA_BASE_NONE: if (insn->eaDisplacement == EA_DISP_NONE) { //debug("EA_BASE_NONE and EA_DISP_NONE for ModR/M base"); return true; } if (insn->mode == MODE_64BIT) { if (insn->prefix3 == 0x67) // address-size prefix overrides RIP relative addressing MCOperand_CreateReg0(mcInst, X86_EIP); else MCOperand_CreateReg0(mcInst, X86_RIP); // Section 2.2.1.6 } else { MCOperand_CreateReg0(mcInst, 0); } indexReg = 0; break; case EA_BASE_BX_SI: MCOperand_CreateReg0(mcInst, X86_BX); indexReg = X86_SI; break; case EA_BASE_BX_DI: MCOperand_CreateReg0(mcInst, X86_BX); indexReg = X86_DI; break; case EA_BASE_BP_SI: MCOperand_CreateReg0(mcInst, X86_BP); indexReg = X86_SI; break; case EA_BASE_BP_DI: MCOperand_CreateReg0(mcInst, X86_BP); indexReg = X86_DI; break; default: indexReg = 0; switch (insn->eaBase) { default: //debug("Unexpected eaBase"); return true; // Here, we will use the fill-ins defined above. However, // BX_SI, BX_DI, BP_SI, and BP_DI are all handled above and // sib and sib64 were handled in the top-level if, so they're only // placeholders to keep the compiler happy. #define ENTRY(x) \ case EA_BASE_##x: \ MCOperand_CreateReg0(mcInst, X86_##x); break; ALL_EA_BASES #undef ENTRY #define ENTRY(x) case EA_REG_##x: ALL_REGS #undef ENTRY //debug("A R/M memory operand may not be a register; " // "the base field must be a base."); return true; } } scaleAmount = 1; } MCOperand_CreateImm0(mcInst, scaleAmount); MCOperand_CreateReg0(mcInst, indexReg); MCOperand_CreateImm0(mcInst, insn->displacement); MCOperand_CreateReg0(mcInst, segmentRegnums[insn->segmentOverride]); return false; } /// translateRM - Translates an operand stored in the R/M (and possibly SIB) /// byte of an instruction to LLVM form, and appends it to an MCInst. /// /// @param mcInst - The MCInst to append to. /// @param operand - The operand, as stored in the descriptor table. /// @param insn - The instruction to extract Mod, R/M, and SIB fields /// from. /// @return - 0 on success; nonzero otherwise static bool translateRM(MCInst *mcInst, const OperandSpecifier *operand, InternalInstruction *insn) { switch (operand->type) { case TYPE_R8: case TYPE_R16: case TYPE_R32: case TYPE_R64: case TYPE_Rv: case TYPE_MM64: case TYPE_XMM: case TYPE_XMM32: case TYPE_XMM64: case TYPE_XMM128: case TYPE_XMM256: case TYPE_XMM512: case TYPE_VK1: case TYPE_VK8: case TYPE_VK16: case TYPE_DEBUGREG: case TYPE_CONTROLREG: return translateRMRegister(mcInst, insn); case TYPE_M: case TYPE_M8: case TYPE_M16: case TYPE_M32: case TYPE_M64: case TYPE_M128: case TYPE_M256: case TYPE_M512: case TYPE_Mv: case TYPE_M32FP: case TYPE_M64FP: case TYPE_M80FP: case TYPE_M1616: case TYPE_M1632: case TYPE_M1664: case TYPE_LEA: return translateRMMemory(mcInst, insn); default: //debug("Unexpected type for a R/M operand"); return true; } } /// translateFPRegister - Translates a stack position on the FPU stack to its /// LLVM form, and appends it to an MCInst. /// /// @param mcInst - The MCInst to append to. /// @param stackPos - The stack position to translate. static void translateFPRegister(MCInst *mcInst, uint8_t stackPos) { MCOperand_CreateReg0(mcInst, X86_ST0 + stackPos); } /// translateMaskRegister - Translates a 3-bit mask register number to /// LLVM form, and appends it to an MCInst. /// /// @param mcInst - The MCInst to append to. /// @param maskRegNum - Number of mask register from 0 to 7. /// @return - false on success; true otherwise. static bool translateMaskRegister(MCInst *mcInst, uint8_t maskRegNum) { if (maskRegNum >= 8) { // debug("Invalid mask register number"); return true; } MCOperand_CreateReg0(mcInst, X86_K0 + maskRegNum); return false; } /// translateOperand - Translates an operand stored in an internal instruction /// to LLVM's format and appends it to an MCInst. /// /// @param mcInst - The MCInst to append to. /// @param operand - The operand, as stored in the descriptor table. /// @param insn - The internal instruction. /// @return - false on success; true otherwise. static bool translateOperand(MCInst *mcInst, const OperandSpecifier *operand, InternalInstruction *insn) { switch (operand->encoding) { case ENCODING_REG: translateRegister(mcInst, insn->reg); return false; case ENCODING_WRITEMASK: return translateMaskRegister(mcInst, insn->writemask); CASE_ENCODING_RM: return translateRM(mcInst, operand, insn); case ENCODING_CB: case ENCODING_CW: case ENCODING_CD: case ENCODING_CP: case ENCODING_CO: case ENCODING_CT: //debug("Translation of code offsets isn't supported."); return true; case ENCODING_IB: case ENCODING_IW: case ENCODING_ID: case ENCODING_IO: case ENCODING_Iv: case ENCODING_Ia: translateImmediate(mcInst, insn->immediates[insn->numImmediatesTranslated++], operand, insn); return false; case ENCODING_SI: return translateSrcIndex(mcInst, insn); case ENCODING_DI: return translateDstIndex(mcInst, insn); case ENCODING_RB: case ENCODING_RW: case ENCODING_RD: case ENCODING_RO: case ENCODING_Rv: translateRegister(mcInst, insn->opcodeRegister); return false; case ENCODING_FP: translateFPRegister(mcInst, insn->modRM & 7); return false; case ENCODING_VVVV: translateRegister(mcInst, insn->vvvv); return false; case ENCODING_DUP: return translateOperand(mcInst, &insn->operands[operand->type - TYPE_DUP0], insn); default: //debug("Unhandled operand encoding during translation"); return true; } } static bool translateInstruction(MCInst *mcInst, InternalInstruction *insn) { int index; if (!insn->spec) { //debug("Instruction has no specification"); return true; } MCInst_setOpcode(mcInst, insn->instructionID); // If when reading the prefix bytes we determined the overlapping 0xf2 or 0xf3 // prefix bytes should be disassembled as xrelease and xacquire then set the // opcode to those instead of the rep and repne opcodes. #ifndef CAPSTONE_X86_REDUCE if (insn->xAcquireRelease) { if (MCInst_getOpcode(mcInst) == X86_REP_PREFIX) MCInst_setOpcode(mcInst, X86_XRELEASE_PREFIX); else if (MCInst_getOpcode(mcInst) == X86_REPNE_PREFIX) MCInst_setOpcode(mcInst, X86_XACQUIRE_PREFIX); } #endif insn->numImmediatesTranslated = 0; for (index = 0; index < X86_MAX_OPERANDS; ++index) { if (insn->operands[index].encoding != ENCODING_NONE) { if (translateOperand(mcInst, &insn->operands[index], insn)) { return true; } } } return false; } static int reader(const struct reader_info *info, uint8_t *byte, uint64_t address) { if (address - info->offset >= info->size) // out of buffer range return -1; *byte = info->code[address - info->offset]; return 0; } // copy x86 detail information from internal structure to public structure static void update_pub_insn(cs_insn *pub, InternalInstruction *inter) { if (inter->vectorExtensionType != 0) memcpy(pub->detail->x86.opcode, inter->vectorExtensionPrefix, sizeof(pub->detail->x86.opcode)); else { if (inter->twoByteEscape) { if (inter->threeByteEscape) { pub->detail->x86.opcode[0] = inter->twoByteEscape; pub->detail->x86.opcode[1] = inter->threeByteEscape; pub->detail->x86.opcode[2] = inter->opcode; } else { pub->detail->x86.opcode[0] = inter->twoByteEscape; pub->detail->x86.opcode[1] = inter->opcode; } } else { pub->detail->x86.opcode[0] = inter->opcode; } } pub->detail->x86.rex = inter->rexPrefix; pub->detail->x86.addr_size = inter->addressSize; pub->detail->x86.modrm = inter->orgModRM; pub->detail->x86.encoding.modrm_offset = inter->modRMOffset; pub->detail->x86.sib = inter->sib; pub->detail->x86.sib_index = x86_map_sib_index(inter->sibIndex); pub->detail->x86.sib_scale = inter->sibScale; pub->detail->x86.sib_base = x86_map_sib_base(inter->sibBase); pub->detail->x86.disp = inter->displacement; if (inter->consumedDisplacement) { pub->detail->x86.encoding.disp_offset = inter->displacementOffset; pub->detail->x86.encoding.disp_size = inter->displacementSize; } pub->detail->x86.encoding.imm_offset = inter->immediateOffset; if (pub->detail->x86.encoding.imm_size == 0 && inter->immediateOffset != 0) pub->detail->x86.encoding.imm_size = inter->immediateSize; } void X86_init(MCRegisterInfo *MRI) { /* InitMCRegisterInfo(X86RegDesc, 234, RA, PC, X86MCRegisterClasses, 79, X86RegUnitRoots, 119, X86RegDiffLists, X86RegStrings, X86SubRegIdxLists, 7, X86SubRegIdxRanges, X86RegEncodingTable); */ MCRegisterInfo_InitMCRegisterInfo(MRI, X86RegDesc, 234, 0, 0, X86MCRegisterClasses, 79, 0, 0, X86RegDiffLists, 0, X86SubRegIdxLists, 7, 0); } // Public interface for the disassembler bool X86_getInstruction(csh ud, const uint8_t *code, size_t code_len, MCInst *instr, uint16_t *size, uint64_t address, void *_info) { cs_struct *handle = (cs_struct *)(uintptr_t)ud; InternalInstruction insn = {0}; struct reader_info info; int ret; bool result; info.code = code; info.size = code_len; info.offset = address; if (instr->flat_insn->detail) { // instr->flat_insn->detail initialization: 3 alternatives // 1. The whole structure, this is how it's done in other arch disassemblers // Probably overkill since cs_detail is huge because of the 36 operands of ARM //memset(instr->flat_insn->detail, 0, sizeof(cs_detail)); // 2. Only the part relevant to x86 memset(instr->flat_insn->detail, 0, offsetof(cs_detail, x86) + sizeof(cs_x86)); // 3. The relevant part except for x86.operands // sizeof(cs_x86) is 0x1c0, sizeof(x86.operands) is 0x180 // marginally faster, should be okay since x86.op_count is set to 0 //memset(instr->flat_insn->detail, 0, offsetof(cs_detail, x86)+offsetof(cs_x86, operands)); } if (handle->mode & CS_MODE_16) ret = decodeInstruction(&insn, reader, &info, address, MODE_16BIT); else if (handle->mode & CS_MODE_32) ret = decodeInstruction(&insn, reader, &info, address, MODE_32BIT); else ret = decodeInstruction(&insn, reader, &info, address, MODE_64BIT); if (ret) { *size = (uint16_t)(insn.readerCursor - address); // handle some special cases here. // FIXME: fix this in the next major update. switch(*size) { default: break; case 2: { unsigned char b1 = 0, b2 = 0; reader(&info, &b1, address); reader(&info, &b2, address + 1); if (b1 == 0x0f && b2 == 0xff) { instr->Opcode = X86_UD0; instr->OpcodePub = X86_INS_UD0; strncpy(instr->assembly, "ud0", 4); if (instr->flat_insn->detail) { instr->flat_insn->detail->x86.opcode[0] = b1; instr->flat_insn->detail->x86.opcode[1] = b2; } return true; } } return false; case 4: { #ifndef CAPSTONE_X86_REDUCE if (handle->mode != CS_MODE_16) { unsigned char b1 = 0, b2 = 0, b3 = 0, b4 = 0; reader(&info, &b1, address); reader(&info, &b2, address + 1); reader(&info, &b3, address + 2); reader(&info, &b4, address + 3); if (b1 == 0xf3 && b2 == 0x0f && b3 == 0x1e && b4 == 0xfa) { instr->Opcode = X86_ENDBR64; instr->OpcodePub = X86_INS_ENDBR64; strncpy(instr->assembly, "endbr64", 8); if (instr->flat_insn->detail) { instr->flat_insn->detail->x86.opcode[0] = b1; instr->flat_insn->detail->x86.opcode[1] = b2; instr->flat_insn->detail->x86.opcode[2] = b3; instr->flat_insn->detail->x86.opcode[3] = b4; } return true; } else if (b1 == 0xf3 && b2 == 0x0f && b3 == 0x1e && b4 == 0xfb) { instr->Opcode = X86_ENDBR32; instr->OpcodePub = X86_INS_ENDBR32; strncpy(instr->assembly, "endbr32", 8); if (instr->flat_insn->detail) { instr->flat_insn->detail->x86.opcode[0] = b1; instr->flat_insn->detail->x86.opcode[1] = b2; instr->flat_insn->detail->x86.opcode[2] = b3; instr->flat_insn->detail->x86.opcode[3] = b4; } return true; } } #endif } return false; } return false; } else { *size = (uint16_t)insn.length; result = (!translateInstruction(instr, &insn)) ? true : false; if (result) { instr->imm_size = insn.immSize; // copy all prefixes instr->x86_prefix[0] = insn.prefix0; instr->x86_prefix[1] = insn.prefix1; instr->x86_prefix[2] = insn.prefix2; instr->x86_prefix[3] = insn.prefix3; instr->xAcquireRelease = insn.xAcquireRelease; if (handle->detail) { update_pub_insn(instr->flat_insn, &insn); } } return result; } } #endif
the_stack_data/59512751.c
#include <stdio.h> int main() { printf(" ====> C: Howdy!\n"); return 0; }
the_stack_data/198579431.c
#include <sys/types.h> #include <sys/wait.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #define MAX_LINE 80 /* The maximum length command */ #define HISTORY_LEN 10 /* length of the history */ //#define TEST_SPLIT //#define TEST_HISTORY typedef enum inside { BEGIN, IN, OUT } state; int insert( char* str, char** array, int size, int limit ) { int i; #ifdef TEST_HISTORY printf( "#HISTORY# str=%s\n", str ); printf( "#HISTORY# size=%d limit=%d\n", size, limit ); #endif if( size < limit ) size ++; for( i=size-1; i>0; i-- ) array[i] = array[i-1]; array[0] = (char *) malloc( (strlen(str) + 1) * sizeof(char) ); strcpy( array[0], str ); return size; } int split(char* str, char* delimiters, char* split[]) { int ret = 0; int i = 0; int ch = *(str+i); state inside = BEGIN; int split_pos_start = 0; int split_pos_end = 0; while( ch ) { if( strchr( delimiters, ch ) == NULL ) { switch( inside ) { case BEGIN: ret++; inside = IN; split_pos_start = i; break; case IN: break; case OUT: ret++; inside = IN; split_pos_start = i; break; } } else { switch( inside ) { case BEGIN: break; case IN: inside = OUT; split_pos_end = i-1; split[ret-1] = (char *) malloc( (split_pos_end - split_pos_start + 2) * sizeof(char) ); strncpy( split[ret-1], str+split_pos_start, split_pos_end - split_pos_start + 1 ); #ifdef TEST_SPLIT printf( "#SPLIT#%d:%s %d %d\n", ret, split[ret-1], split_pos_start, split_pos_end ); #endif break; case OUT: split_pos_start = i; break; } } i++; ch = *(str+i); } if( inside == IN ) { split_pos_end = i-1; split[ret-1] = (char *) malloc( (split_pos_end - split_pos_start + 2) * sizeof(char) ); strncpy( split[ret-1], str+split_pos_start, split_pos_end - split_pos_start + 1 ); #ifdef TEST_SPLIT printf( "#SPLIT#%d:%s %d %d\n", ret, split[ret-1], split_pos_start, split_pos_end ); #endif } split[ret] = NULL; return ret; } int position( const char* elem, char* array[], int size ) { int i; for( i=0; i<size; i++ ) if( strcmp(elem, array[i]) == 0 ) return i; return -1; } int main(void) { char line[MAX_LINE*4]; char* history[HISTORY_LEN]; int history_size; int argc; char *argv[MAX_LINE/2 + 1]; /* command line arguments */ int background_execution; pid_t pid; int i; int n = -1; history_size = 0; printf( "==========================================\n" ); printf( "OSH Simple shell. Type 'Ctrl+C' to exit...\n" ); printf( "==========================================\n" ); while( 1 ) { printf("osh>"); fflush(stdout); /* read and parse user input */ gets( line ); if( strcmp( line, "exit" ) == 0 ) { puts( "Exiting OSH Simple shell...\n" ); /* deallocation of the history */ for( i=0; i<history_size; i++ ) free( history[i] ); exit(0); } else { /* obtain command and its arguments */ argc = split(line, " \t\n", argv); #ifdef TEST_SPLIT for (i = 0; i<argc; i++) printf( "#SPLIT#%s# ", argv[i] ); printf( "#SPLIT#\n" ); #endif if( strcmp( line, "history" ) == 0 ) { if( history_size > 0 ) { for( i=history_size-1; i>=0; i-- ) printf( "%3d %s\n", (i+1), history[i] ); } else printf("No history.\n"); continue; } else if( strcmp(argv[0], "!!") == 0 ) { if( history_size > 0 ) { strcpy( line, history[0] ); argc = split(line, " \t\n", argv); } else { printf("No commands in history.\n"); continue; } } else if( strcmp(argv[0], "!") == 0 ) { if( argc > 1 ) n = atoi( argv[1] ); if( (n>0) && (history_size >= n) ) { strcpy( line, history[n-1] ); n = -1; argc = split(line, " \t\n", argv); } else { printf("No such command in history.\n"); continue; } } /* insert into history non-history commands */ history_size = insert( line, history, history_size, HISTORY_LEN); /* check if it is background execution */ background_execution = (position( "&", argv, argc ) >= 0)? 1:0; /* fork a child process */ pid = fork(); if (pid < 0) { /* error occurred */ fprintf(stderr, "Fork Failed\n"); break; } if (pid == 0) { /* child process */ /* the child process will invoke execvp() */ execvp(argv[0],argv); } else { /* parent process */ /* if command included &, parent will not wait for the child to complete */ if( !background_execution ) wait(NULL); } /* deallocation of parsed input*/ for (i = 0; i<argc; i++) free( argv[i] ); } } /* deallocation of the history */ for( i=0; i<history_size; i++ ) free( history[i] ); return 0; }
the_stack_data/673906.c
/* ** 2018 June 17 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* */ #include "sqlite3.h" #ifdef SQLITE_TEST #include "sqliteInt.h" #include <tcl.h> extern int getDbPointer(Tcl_Interp *interp, const char *zA, sqlite3 **ppDb); extern const char *sqlite3ErrName(int); typedef struct TestWindow TestWindow; struct TestWindow { Tcl_Obj *xStep; Tcl_Obj *xFinal; Tcl_Obj *xValue; Tcl_Obj *xInverse; Tcl_Interp *interp; }; typedef struct TestWindowCtx TestWindowCtx; struct TestWindowCtx { Tcl_Obj *pVal; }; void doTestWindowStep( int bInverse, sqlite3_context *ctx, int nArg, sqlite3_value **apArg ){ int i; TestWindow *p = (TestWindow*)sqlite3_user_data(ctx); Tcl_Obj *pEval = Tcl_DuplicateObj(bInverse ? p->xInverse : p->xStep); TestWindowCtx *pCtx = sqlite3_aggregate_context(ctx, sizeof(TestWindowCtx)); Tcl_IncrRefCount(pEval); if( pCtx ){ const char *zResult; int rc; if( pCtx->pVal ){ Tcl_ListObjAppendElement(p->interp, pEval, Tcl_DuplicateObj(pCtx->pVal)); }else{ Tcl_ListObjAppendElement(p->interp, pEval, Tcl_NewStringObj("", -1)); } for(i=0; i<nArg; i++){ Tcl_Obj *pArg; pArg = Tcl_NewStringObj((const char*)sqlite3_value_text(apArg[i]), -1); Tcl_ListObjAppendElement(p->interp, pEval, pArg); } rc = Tcl_EvalObjEx(p->interp, pEval, TCL_EVAL_GLOBAL); if( rc!=TCL_OK ){ zResult = Tcl_GetStringResult(p->interp); sqlite3_result_error(ctx, zResult, -1); }else{ if( pCtx->pVal ) Tcl_DecrRefCount(pCtx->pVal); pCtx->pVal = Tcl_DuplicateObj(Tcl_GetObjResult(p->interp)); Tcl_IncrRefCount(pCtx->pVal); } } Tcl_DecrRefCount(pEval); } void doTestWindowFinalize(int bValue, sqlite3_context *ctx){ TestWindow *p = (TestWindow*)sqlite3_user_data(ctx); Tcl_Obj *pEval = Tcl_DuplicateObj(bValue ? p->xValue : p->xFinal); TestWindowCtx *pCtx = sqlite3_aggregate_context(ctx, sizeof(TestWindowCtx)); Tcl_IncrRefCount(pEval); if( pCtx ){ const char *zResult; int rc; if( pCtx->pVal ){ Tcl_ListObjAppendElement(p->interp, pEval, Tcl_DuplicateObj(pCtx->pVal)); }else{ Tcl_ListObjAppendElement(p->interp, pEval, Tcl_NewStringObj("", -1)); } rc = Tcl_EvalObjEx(p->interp, pEval, TCL_EVAL_GLOBAL); zResult = Tcl_GetStringResult(p->interp); if( rc!=TCL_OK ){ sqlite3_result_error(ctx, zResult, -1); }else{ sqlite3_result_text(ctx, zResult, -1, SQLITE_TRANSIENT); } if( bValue==0 ){ if( pCtx->pVal ) Tcl_DecrRefCount(pCtx->pVal); pCtx->pVal = 0; } } Tcl_DecrRefCount(pEval); } void testWindowStep( sqlite3_context *ctx, int nArg, sqlite3_value **apArg ){ doTestWindowStep(0, ctx, nArg, apArg); } void testWindowInverse( sqlite3_context *ctx, int nArg, sqlite3_value **apArg ){ doTestWindowStep(1, ctx, nArg, apArg); } void testWindowFinal(sqlite3_context *ctx){ doTestWindowFinalize(0, ctx); } void testWindowValue(sqlite3_context *ctx){ doTestWindowFinalize(1, ctx); } void testWindowDestroy(void *pCtx){ ckfree(pCtx); } /* ** Usage: sqlite3_create_window_function DB NAME XSTEP XFINAL XVALUE XINVERSE */ int SQLITE_TCLAPI test_create_window( void * clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[] ){ TestWindow *pNew; sqlite3 *db; const char *zName; int rc; if( objc!=7 ){ Tcl_WrongNumArgs(interp, 1, objv, "DB NAME XSTEP XFINAL XVALUE XINVERSE"); return TCL_ERROR; } if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; zName = Tcl_GetString(objv[2]); pNew = (TestWindow*)ckalloc(sizeof(TestWindow)); memset(pNew, 0, sizeof(TestWindow)); pNew->xStep = Tcl_DuplicateObj(objv[3]); pNew->xFinal = Tcl_DuplicateObj(objv[4]); pNew->xValue = Tcl_DuplicateObj(objv[5]); pNew->xInverse = Tcl_DuplicateObj(objv[6]); pNew->interp = interp; Tcl_IncrRefCount(pNew->xStep); Tcl_IncrRefCount(pNew->xFinal); Tcl_IncrRefCount(pNew->xValue); Tcl_IncrRefCount(pNew->xInverse); rc = sqlite3_create_window_function(db, zName, -1, SQLITE_UTF8, (void*)pNew, testWindowStep, testWindowFinal, testWindowValue, testWindowInverse, testWindowDestroy ); if( rc!=SQLITE_OK ){ Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3ErrName(rc), -1)); return TCL_ERROR; } return TCL_OK; } int SQLITE_TCLAPI test_create_window_misuse( void * clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[] ){ sqlite3 *db; int rc; if( objc!=2 ){ Tcl_WrongNumArgs(interp, 1, objv, "DB"); return TCL_ERROR; } if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; rc = sqlite3_create_window_function(db, "fff", -1, SQLITE_UTF8, 0, 0, testWindowFinal, testWindowValue, testWindowInverse, 0 ); if( rc!=SQLITE_MISUSE ) goto error; rc = sqlite3_create_window_function(db, "fff", -1, SQLITE_UTF8, 0, testWindowStep, 0, testWindowValue, testWindowInverse, 0 ); if( rc!=SQLITE_MISUSE ) goto error; rc = sqlite3_create_window_function(db, "fff", -1, SQLITE_UTF8, 0, testWindowStep, testWindowFinal, 0, testWindowInverse, 0 ); if( rc!=SQLITE_MISUSE ) goto error; rc = sqlite3_create_window_function(db, "fff", -1, SQLITE_UTF8, 0, testWindowStep, testWindowFinal, testWindowValue, 0, 0 ); if( rc!=SQLITE_MISUSE ) goto error; return TCL_OK; error: Tcl_SetObjResult(interp, Tcl_NewStringObj("misuse test error", -1)); return TCL_ERROR; } /* ** xStep for sumint(). */ void sumintStep( sqlite3_context *ctx, int nArg, sqlite3_value *apArg[] ){ sqlite3_int64 *pInt; assert( nArg==1 ); if( sqlite3_value_type(apArg[0])!=SQLITE_INTEGER ){ sqlite3_result_error(ctx, "invalid argument", -1); return; } pInt = (sqlite3_int64*)sqlite3_aggregate_context(ctx, sizeof(sqlite3_int64)); if( pInt ){ *pInt += sqlite3_value_int64(apArg[0]); } } /* ** xInverse for sumint(). */ void sumintInverse( sqlite3_context *ctx, int nArg, sqlite3_value *apArg[] ){ sqlite3_int64 *pInt; pInt = (sqlite3_int64*)sqlite3_aggregate_context(ctx, sizeof(sqlite3_int64)); *pInt -= sqlite3_value_int64(apArg[0]); } /* ** xFinal for sumint(). */ void sumintFinal(sqlite3_context *ctx){ sqlite3_int64 res = 0; sqlite3_int64 *pInt; pInt = (sqlite3_int64*)sqlite3_aggregate_context(ctx, 0); if( pInt ) res = *pInt; sqlite3_result_int64(ctx, res); } /* ** xValue for sumint(). */ void sumintValue(sqlite3_context *ctx){ sqlite3_int64 res = 0; sqlite3_int64 *pInt; pInt = (sqlite3_int64*)sqlite3_aggregate_context(ctx, 0); if( pInt ) res = *pInt; sqlite3_result_int64(ctx, res); } int SQLITE_TCLAPI test_create_sumint( void * clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[] ){ sqlite3 *db; int rc; if( objc!=2 ){ Tcl_WrongNumArgs(interp, 1, objv, "DB"); return TCL_ERROR; } if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; rc = sqlite3_create_window_function(db, "sumint", 1, SQLITE_UTF8, 0, sumintStep, sumintFinal, sumintValue, sumintInverse, 0 ); if( rc!=SQLITE_OK ){ Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3ErrName(rc), -1)); return TCL_ERROR; } return TCL_OK; } int SQLITE_TCLAPI test_override_sum( void * clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[] ){ sqlite3 *db; int rc; if( objc!=2 ){ Tcl_WrongNumArgs(interp, 1, objv, "DB"); return TCL_ERROR; } if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR; rc = sqlite3_create_function(db, "sum", -1, SQLITE_UTF8, 0, 0, sumintStep, sumintFinal ); if( rc!=SQLITE_OK ){ Tcl_SetObjResult(interp, Tcl_NewStringObj(sqlite3ErrName(rc), -1)); return TCL_ERROR; } return TCL_OK; } int Sqlitetest_window_Init(Tcl_Interp *interp){ static struct { char *zName; Tcl_ObjCmdProc *xProc; int clientData; } aObjCmd[] = { { "sqlite3_create_window_function", test_create_window, 0 }, { "test_create_window_function_misuse", test_create_window_misuse, 0 }, { "test_create_sumint", test_create_sumint, 0 }, { "test_override_sum", test_override_sum, 0 }, }; int i; for(i=0; i<sizeof(aObjCmd)/sizeof(aObjCmd[0]); i++){ ClientData c = (ClientData)SQLITE_INT_TO_PTR(aObjCmd[i].clientData); Tcl_CreateObjCommand(interp, aObjCmd[i].zName, aObjCmd[i].xProc, c, 0); } return TCL_OK; } #endif
the_stack_data/161080930.c
#include <stdio.h> #include <math.h> int ans[100004]; int max = 1; int search(int n){ for(int i=max;i<=n;i++){ int sq = (int)sqrt(i); if(sq*sq == i){ ans[i] = 1; continue; } int value1 = 0; for(int no1=sq;no1>=1 && i-no1*no1 > 0;no1--){ int remain1 = i-no1*no1; int sqrm1 = (int)sqrt(remain1); if(sqrm1*sqrm1 == remain1){ value1 = 0; continue; } int value2 = 1; for(int no2=sqrm1;no2>=1 && remain1-no2*no2 > 0;no2--){ int remain2 = remain1-no2*no2; value2 &= ans[remain2]; } if(value2){ value1 = 1; break; } } ans[i] = value1; } max = n+1; } int main(){ int t; scanf("%d",&t); for(int i=1;i<=t;i++){ int n; scanf("%d",&n); search(n); if(ans[n]){ printf("Win\n"); } else{ printf("Lose\n"); } } return 0; }
the_stack_data/132081.c
/* ex10_20.c */ #include <stdio.h> int mystery( unsigned bits ); /* prototype */ int main( void ) { unsigned x; /* x will hold an integer entered by the user */ printf( "Enter an integer: " ); scanf( "%u", &x ); printf( "The result is %d\n", mystery( x ) ); return 0; /* indicates successful termination */ } /* end main */ /* What does this function do? */ int mystery( unsigned bits ) { unsigned i; /* counter */ unsigned mask = 1 << 31; /* initialize mask */ unsigned total = 0; /* initialize total */ for ( i = 1; i <= 32; i++, bits <<= 1 ) { if ( ( bits & mask ) == mask ) { total++; } /* end if */ } /* end for */ return !( total % 2 ) ? 1 : 0; } /* end function mystery */ /************************************************************************** * (C) Copyright 1992-2010 by Deitel & Associates, Inc. and * * Pearson Education, Inc. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * *************************************************************************/
the_stack_data/132953430.c
#include <stdio.h> foo () { printf ("foo!\n"); return 0; }//foo()
the_stack_data/64200553.c
#define NULL (void *)0 #define EFIERR(a) (0x8000000000000000 | a) #define EFI_SUCCESS 0 #define EFI_INVALID_PARAMETER EFIERR(2) #define EFI_DEVICE_ERROR EFIERR(7) //******************************************************* // Open Modes //******************************************************* #define EFI_FILE_MODE_READ 0x0000000000000001 #define EFI_FILE_MODE_WRITE 0x0000000000000002 #define EFI_FILE_MODE_CREATE 0x8000000000000000 //******************************************************* // File Attributes //******************************************************* #define EFI_FILE_READ_ONLY 0x0000000000000001 #define EFI_FILE_HIDDEN 0x0000000000000002 #define EFI_FILE_SYSTEM 0x0000000000000004 #define EFI_FILE_RESERVED 0x0000000000000008 #define EFI_FILE_DIRECTORY 0x0000000000000010 #define EFI_FILE_ARCHIVE 0x0000000000000020 #define EFI_FILE_VALID_ATTR 0x0000000000000037 struct EFI_INPUT_KEY { unsigned short ScanCode; unsigned short UnicodeChar; }; struct EFI_GUID { unsigned int Data1; unsigned short Data2; unsigned short Data3; unsigned char Data4[8]; }; struct EFI_SYSTEM_TABLE { char _buf1[44]; struct EFI_SIMPLE_TEXT_INPUT_PROTOCOL { void *_buf; unsigned long long (*ReadKeyStroke)(struct EFI_SIMPLE_TEXT_INPUT_PROTOCOL *, struct EFI_INPUT_KEY *); } *ConIn; void *_buf2; struct EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL { void *_buf; unsigned long long (*OutputString)(struct EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *, unsigned short *); } *ConOut; char _buf3[24]; struct EFI_BOOT_SERVICES { char _buf1[24]; char _buf2[296]; unsigned long long (*LocateProtocol)(struct EFI_GUID *, void *, void **); } *BootServices; }; struct EFI_GRAPHICS_OUTPUT_BLT_PIXEL { unsigned char Blue; unsigned char Green; unsigned char Red; unsigned char Reserved; }; enum EFI_GRAPHICS_OUTPUT_BLT_OPERATION { EfiBltVideoFill, EfiBltVideoToBltBuffer, EfiBltBufferToVideo, EfiBltVideoToVideo, EfiGraphicsOutputBltOperationMax }; enum EFI_GRAPHICS_PIXEL_FORMAT { PixelRedGreenBlueReserved8BitPerColor, PixelBlueGreenRedReserved8BitPerColor, PixelBitMask, PixelBltOnly, PixelFormatMax }; //******************************************************* //EFI_TIME //******************************************************* // This represents the current time information struct EFI_TIME { unsigned short Year; // 1900 – 9999 unsigned char Month; // 1 – 12 unsigned char Day; // 1 – 31 unsigned char Hour; // 0 – 23 unsigned char Minute; // 0 – 59 unsigned char Second; // 0 – 59 unsigned char Pad1; unsigned int Nanosecond; // 0 – 999,999,999 unsigned short TimeZone; // -1440 to 1440 or 2047 unsigned char Daylight; unsigned char Pad2; }; struct EFI_FILE_INFO { unsigned long long Size; unsigned long long FileSize; unsigned long long PhysicalSize; struct EFI_TIME CreateTime; struct EFI_TIME LastAccessTime; struct EFI_TIME ModificationTime; unsigned long long Attribute; unsigned short FileName[]; }; struct EFI_GRAPHICS_OUTPUT_PROTOCOL { void *_buf; unsigned long long (*SetMode)(struct EFI_GRAPHICS_OUTPUT_PROTOCOL *, unsigned int); unsigned long long (*Blt)(struct EFI_GRAPHICS_OUTPUT_PROTOCOL *, struct EFI_GRAPHICS_OUTPUT_BLT_PIXEL *, enum EFI_GRAPHICS_OUTPUT_BLT_OPERATION, unsigned long long SourceX, unsigned long long SourceY, unsigned long long DestinationX, unsigned long long DestinationY, unsigned long long Width, unsigned long long Height, unsigned long long Delta); struct EFI_GRAPHICS_OUTPUT_PROTOCOL_MODE { unsigned int MaxMode; unsigned int Mode; struct EFI_GRAPHICS_OUTPUT_MODE_INFORMATION { unsigned int Version; unsigned int HorizontalResolution; unsigned int VerticalResolution; enum EFI_GRAPHICS_PIXEL_FORMAT PixelFormat; struct EFI_PIXEL_BITMASK { unsigned int RedMask; unsigned int GreenMask; unsigned int BlueMask; unsigned int ReservedMask; } PixelInformation; unsigned int PixelsPerScanLine; } *Info; unsigned long long SizeOfInfo; unsigned long long FrameBufferBase; unsigned long long FrameBufferSize; } *Mode; }; struct EFI_FILE_PROTOCOL { unsigned long long Revision; unsigned long long (*Open)(struct EFI_FILE_PROTOCOL *This, struct EFI_FILE_PROTOCOL **NewHandle, unsigned short *FileName, unsigned long long OpenMode, unsigned long long Attributes); unsigned long long (*Close)(struct EFI_FILE_PROTOCOL *This); unsigned long long (*Delete)(struct EFI_FILE_PROTOCOL *This); unsigned long long (*Read)(struct EFI_FILE_PROTOCOL *This, unsigned long long *BufferSize, void *Buffer); unsigned long long (*Write)(struct EFI_FILE_PROTOCOL *This, unsigned long long *BufferSize, void *Buffer); unsigned long long (*GetPosition)(struct EFI_FILE_PROTOCOL *This, unsigned long long *Position); unsigned long long (*SetPosition)(struct EFI_FILE_PROTOCOL *This, unsigned long long Position); unsigned long long (*GetInfo)(struct EFI_FILE_PROTOCOL *This, struct EFI_GUID *InformationType, unsigned long long *BufferSize, void *Buffer); unsigned long long (*SetInfo)(struct EFI_FILE_PROTOCOL *This, struct EFI_GUID *InformationType, unsigned long long BufferSize, void *Buffer); unsigned long long (*Flush)(struct EFI_FILE_PROTOCOL *This); }; struct EFI_SIMPLE_FILE_SYSTEM_PROTOCOL { unsigned long long Revision; unsigned long long (*OpenVolume)( struct EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *This, struct EFI_FILE_PROTOCOL **Root); }; unsigned short *int_to_unicode(long long val, unsigned char num_digits, unsigned short str[]) { unsigned char digits_base = 0; char i; if (val < 0) { str[digits_base++] = L'-'; val *= -1; } for (i = num_digits - 1; i >= 0; i--) { str[digits_base + i] = L'0' + (val % 10); val /= 10; } str[digits_base + num_digits] = L'\0'; return str; } unsigned short *int_to_unicode_hex(unsigned long long val, unsigned char num_digits, unsigned short str[]) { short i; unsigned short v; for (i = num_digits - 1; i >= 0; i--) { v = (unsigned short)(val & 0x0f); if (v < 0xa) str[i] = L'0' + v; else str[i] = L'A' + (v - 0xa); val >>= 4; } str[num_digits] = L'\0'; return str; } unsigned short *ascii_to_unicode(char ascii[], unsigned char num_digits, unsigned short str[]) { unsigned char i; for (i = 0; i < num_digits; i++) { if (ascii[i] == '\0') { break; } if ('0' <= ascii[i] && ascii[i] <= '9') str[i] = L'0' + (ascii[i] - '0'); else if ('A' <= ascii[i] && ascii[i] <= 'Z') str[i] = L'A' + (ascii[i] - 'A'); else if ('a' <= ascii[i] && ascii[i] <= 'z') str[i] = L'a' + (ascii[i] - 'a'); else { switch (ascii[i]) { case ' ': str[i] = L' '; break; case '-': str[i] = L'-'; break; case '+': str[i] = L'+'; break; case '*': str[i] = L'*'; break; case '/': str[i] = L'/'; break; case '&': str[i] = L'&'; break; case '|': str[i] = L'|'; break; case '%': str[i] = L'%'; break; case '#': str[i] = L'#'; break; case '!': str[i] = L'!'; break; case '\r': str[i] = L'\r'; break; case '\n': str[i] = L'\n'; break; } } } str[i] = L'\0'; return str; } void puts(unsigned short *str, struct EFI_SYSTEM_TABLE *SystemTable) { SystemTable->ConOut->OutputString(SystemTable->ConOut, str); } #define MAX_FILE_BUF 1024 void efi_main(void *ImageHandle __attribute__ ((unused)), struct EFI_SYSTEM_TABLE *SystemTable) { struct EFI_GUID sfsp_guid = {0x0964e5b22, 0x6459,0x11d2, {0x8e, 0x39, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b}}; struct EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *sfsp; struct EFI_FILE_PROTOCOL *root; unsigned long long status; unsigned long long buf_size = MAX_FILE_BUF; char file_buf[MAX_FILE_BUF]; unsigned short str[1024]; status = SystemTable->BootServices->LocateProtocol(&sfsp_guid, NULL, (void **)&sfsp); if (status) { puts(L"error: SystemTable->BootServices->LocateProtocol\r\n", SystemTable); while (1); } status = sfsp->OpenVolume(sfsp, &root); if (status) { puts(L"error: sfsp->OpenVolume\r\n", SystemTable); while (1); } puts(L"before buf_size: ", SystemTable); puts(int_to_unicode(buf_size, 5, str), SystemTable); puts(L"\r\n", SystemTable); puts(L"sizeof EFI_FILE_INFO: ", SystemTable); puts(int_to_unicode(sizeof(struct EFI_FILE_INFO), 5, str), SystemTable); puts(L"\r\n", SystemTable); struct EFI_FILE_INFO *efi; while (1) { status = root->Read(root, &buf_size, (void *)file_buf); puts(L"status: root->Read: ", SystemTable); puts(int_to_unicode_hex(status, 16, str), SystemTable); puts(L"\r\n", SystemTable); if (!buf_size) break; puts(L"after buf_size: ", SystemTable); puts(int_to_unicode(buf_size, 5, str), SystemTable); puts(L"\r\n", SystemTable); efi = (struct EFI_FILE_INFO *)file_buf; puts(L"FileName: ", SystemTable); puts(efi->FileName, SystemTable); puts(L"\r\n", SystemTable); buf_size = MAX_FILE_BUF; } status = root->Close(root); if (status) { puts(L"root->Close\r\n", SystemTable); while (1); } while (1); }
the_stack_data/40761670.c
#include <sys/types.h> #include <unistd.h> #include <stdio.h> int main(int argc, const char* argv[]) { printf("Run a new process with pid = %d and ppid = %d\n", getpid(), getppid()); return 0; }
the_stack_data/712331.c
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> #include <sys/param.h> #include <string.h> #include <errno.h> #ifdef __linux__ #include <sys/prctl.h> #ifndef PR_SET_PTRACER #define PR_SET_PTRACER 0x59616d61 #endif #elif defined (__APPLE__) || defined (__FreeBSD__) || defined(__OpenBSD__) #include <signal.h> #endif static const char crash_switch[] = "--cc-handle-crash"; static const char fatal_err[] = "\n\n*** Fatal Error ***\n"; static const char pipe_err[] = "!!! Failed to create pipe\n"; static const char fork_err[] = "!!! Failed to fork debug process\n"; static const char exec_err[] = "!!! Failed to exec debug process\n"; static char argv0[PATH_MAX]; static char altstack[SIGSTKSZ]; static struct { int signum; pid_t pid; int has_siginfo; siginfo_t siginfo; char buf[4096]; } crash_info; static const struct { const char *name; int signum; } signals[] = { { "Segmentation fault", SIGSEGV }, { "Illegal instruction", SIGILL }, { "FPU exception", SIGFPE }, { "System BUS error", SIGBUS }, { NULL, 0 } }; static const struct { int code; const char *name; } sigill_codes[] = { #ifndef __FreeBSD__ { ILL_ILLOPC, "Illegal opcode" }, { ILL_ILLOPN, "Illegal operand" }, { ILL_ILLADR, "Illegal addressing mode" }, { ILL_ILLTRP, "Illegal trap" }, { ILL_PRVOPC, "Privileged opcode" }, { ILL_PRVREG, "Privileged register" }, { ILL_COPROC, "Coprocessor error" }, { ILL_BADSTK, "Internal stack error" }, #endif { 0, NULL } }; static const struct { int code; const char *name; } sigfpe_codes[] = { { FPE_INTDIV, "Integer divide by zero" }, { FPE_INTOVF, "Integer overflow" }, { FPE_FLTDIV, "Floating point divide by zero" }, { FPE_FLTOVF, "Floating point overflow" }, { FPE_FLTUND, "Floating point underflow" }, { FPE_FLTRES, "Floating point inexact result" }, { FPE_FLTINV, "Floating point invalid operation" }, { FPE_FLTSUB, "Subscript out of range" }, { 0, NULL } }; static const struct { int code; const char *name; } sigsegv_codes[] = { #ifndef __FreeBSD__ { SEGV_MAPERR, "Address not mapped to object" }, { SEGV_ACCERR, "Invalid permissions for mapped object" }, #endif { 0, NULL } }; static const struct { int code; const char *name; } sigbus_codes[] = { #ifndef __FreeBSD__ { BUS_ADRALN, "Invalid address alignment" }, { BUS_ADRERR, "Non-existent physical address" }, { BUS_OBJERR, "Object specific hardware error" }, #endif { 0, NULL } }; static int (*cc_user_info)(char*, char*); static void gdb_info(pid_t pid) { char respfile[64]; char cmd_buf[128]; FILE *f; int fd; /* Create a temp file to put gdb commands into */ strcpy(respfile, "gdb-respfile-XXXXXX"); if((fd=mkstemp(respfile)) >= 0 && (f=fdopen(fd, "w")) != NULL) { fprintf(f, "attach %d\n" "shell echo \"\"\n" "shell echo \"* Loaded Libraries\"\n" "info sharedlibrary\n" "shell echo \"\"\n" "shell echo \"* Threads\"\n" "info threads\n" "shell echo \"\"\n" "shell echo \"* FPU Status\"\n" "info float\n" "shell echo \"\"\n" "shell echo \"* Registers\"\n" "info registers\n" "shell echo \"\"\n" "shell echo \"* Backtrace\"\n" "thread apply all backtrace full\n" "detach\n" "quit\n", pid); fclose(f); /* Run gdb and print process info. */ snprintf(cmd_buf, sizeof(cmd_buf), "gdb --quiet --batch --command=%s", respfile); printf("Executing: %s\n", cmd_buf); fflush(stdout); system(cmd_buf); /* Clean up */ remove(respfile); } else { /* Error creating temp file */ if(fd >= 0) { close(fd); remove(respfile); } printf("!!! Could not create gdb command file\n"); } fflush(stdout); } static void sys_info(void) { #ifdef __unix__ system("echo \"System: `uname -a`\""); putchar('\n'); fflush(stdout); #endif } static size_t safe_write(int fd, const void *buf, size_t len) { size_t ret = 0; while(ret < len) { ssize_t rem; if((rem=write(fd, (const char*)buf+ret, len-ret)) == -1) { if(errno == EINTR) continue; break; } ret += rem; } return ret; } static void crash_catcher(int signum, siginfo_t *siginfo, void *context) { //ucontext_t *ucontext = (ucontext_t*)context; pid_t dbg_pid; int fd[2]; /* Make sure the effective uid is the real uid */ if(getuid() != geteuid()) { raise(signum); return; } safe_write(STDERR_FILENO, fatal_err, sizeof(fatal_err)-1); if(pipe(fd) == -1) { safe_write(STDERR_FILENO, pipe_err, sizeof(pipe_err)-1); raise(signum); return; } crash_info.signum = signum; crash_info.pid = getpid(); crash_info.has_siginfo = !!siginfo; if(siginfo) crash_info.siginfo = *siginfo; if(cc_user_info) cc_user_info(crash_info.buf, crash_info.buf+sizeof(crash_info.buf)); /* Fork off to start a crash handler */ switch((dbg_pid=fork())) { /* Error */ case -1: safe_write(STDERR_FILENO, fork_err, sizeof(fork_err)-1); raise(signum); return; case 0: dup2(fd[0], STDIN_FILENO); close(fd[0]); close(fd[1]); execl(argv0, argv0, crash_switch, NULL); safe_write(STDERR_FILENO, exec_err, sizeof(exec_err)-1); _exit(1); default: #ifdef __linux__ prctl(PR_SET_PTRACER, dbg_pid, 0, 0, 0); #endif safe_write(fd[1], &crash_info, sizeof(crash_info)); close(fd[0]); close(fd[1]); /* Wait; we'll be killed when gdb is done */ do { int status; if(waitpid(dbg_pid, &status, 0) == dbg_pid && (WIFEXITED(status) || WIFSIGNALED(status))) { /* The debug process died before it could kill us */ raise(signum); break; } } while(1); } } static void crash_handler(const char *logfile) { const char *sigdesc = ""; int i; if(fread(&crash_info, sizeof(crash_info), 1, stdin) != 1) { fprintf(stderr, "!!! Failed to retrieve info from crashed process\n"); exit(1); } /* Get the signal description */ for(i = 0;signals[i].name;++i) { if(signals[i].signum == crash_info.signum) { sigdesc = signals[i].name; break; } } if(crash_info.has_siginfo) { switch(crash_info.signum) { case SIGSEGV: for(i = 0;sigsegv_codes[i].name;++i) { if(sigsegv_codes[i].code == crash_info.siginfo.si_code) { sigdesc = sigsegv_codes[i].name; break; } } break; case SIGFPE: for(i = 0;sigfpe_codes[i].name;++i) { if(sigfpe_codes[i].code == crash_info.siginfo.si_code) { sigdesc = sigfpe_codes[i].name; break; } } break; case SIGILL: for(i = 0;sigill_codes[i].name;++i) { if(sigill_codes[i].code == crash_info.siginfo.si_code) { sigdesc = sigill_codes[i].name; break; } } break; case SIGBUS: for(i = 0;sigbus_codes[i].name;++i) { if(sigbus_codes[i].code == crash_info.siginfo.si_code) { sigdesc = sigbus_codes[i].name; break; } } break; } } fprintf(stderr, "%s (signal %i)\n", sigdesc, crash_info.signum); if(crash_info.has_siginfo) fprintf(stderr, "Address: %p\n", crash_info.siginfo.si_addr); fputc('\n', stderr); if(logfile) { /* Create crash log file and redirect shell output to it */ if(freopen(logfile, "wa", stdout) != stdout) { fprintf(stderr, "!!! Could not create %s following signal\n", logfile); exit(1); } fprintf(stderr, "Generating %s and killing process %d, please wait... ", logfile, crash_info.pid); printf("*** Fatal Error ***\n" "%s (signal %i)\n", sigdesc, crash_info.signum); if(crash_info.has_siginfo) printf("Address: %p\n", crash_info.siginfo.si_addr); fputc('\n', stdout); fflush(stdout); } sys_info(); crash_info.buf[sizeof(crash_info.buf)-1] = '\0'; printf("%s\n", crash_info.buf); fflush(stdout); if(crash_info.pid > 0) { gdb_info(crash_info.pid); kill(crash_info.pid, SIGKILL); } if(logfile) { const char *str; char buf[512]; if((str=getenv("KDE_FULL_SESSION")) && strcmp(str, "true") == 0) snprintf(buf, sizeof(buf), "kdialog --title \"Very Fatal Error\" --textbox \"%s\" 800 600", logfile); else if((str=getenv("GNOME_DESKTOP_SESSION_ID")) && str[0] != '\0') snprintf(buf, sizeof(buf), "gxmessage -buttons \"Okay:0\" -geometry 800x600 -title \"Very Fatal Error\" -center -file \"%s\"", logfile); else snprintf(buf, sizeof(buf), "xmessage -buttons \"Okay:0\" -center -file \"%s\"", logfile); system(buf); } exit(0); } int cc_install_handlers(int argc, char **argv, int num_signals, int *signals, const char *logfile, int (*user_info)(char*, char*)) { struct sigaction sa; stack_t altss; int retval; if(argc == 2 && strcmp(argv[1], crash_switch) == 0) crash_handler(logfile); cc_user_info = user_info; if(argv[0][0] == '/') snprintf(argv0, sizeof(argv0), "%s", argv[0]); else { getcwd(argv0, sizeof(argv0)); retval = strlen(argv0); snprintf(argv0+retval, sizeof(argv0)-retval, "/%s", argv[0]); } /* Set an alternate signal stack so SIGSEGVs caused by stack overflows * still run */ altss.ss_sp = altstack; altss.ss_flags = 0; altss.ss_size = sizeof(altstack); sigaltstack(&altss, NULL); memset(&sa, 0, sizeof(sa)); sa.sa_sigaction = crash_catcher; sa.sa_flags = SA_RESETHAND | SA_NODEFER | SA_SIGINFO | SA_ONSTACK; sigemptyset(&sa.sa_mask); retval = 0; while(num_signals--) { if((*signals != SIGSEGV && *signals != SIGILL && *signals != SIGFPE && *signals != SIGBUS) || sigaction(*signals, &sa, NULL) == -1) { *signals = 0; retval = -1; } ++signals; } return retval; }
the_stack_data/200144056.c
/*Write a function called insertString() to insert one character string into another string. The arguments to the function should consist of the source string, the string to be inserted, and the position in the source string where the string is to be inserted. So, the call Click here to view code image insertString (text, "per", 10); with text as originally defined in the previous exercise, results in the character string "per" being inserted inside text, beginning at text[10]. Therefore, the character string "the wrong person" is stored inside the text array after the function returned. */ #include <stdio.h> #include <string.h> int insertString(char a[],char b[],int pos); int main(int argc, char const *argv[]) { char source[50] = "the wrong son"; char insert[50] = "per"; int position = 10; // printf("source length = %ld\n",strlen(source)); // printf("insert length = %ld\n",strlen(insert)); int outcome = insertString(source,insert, position); if(outcome != -1) printf("%s",source ); else printf("bye"); return 0; } int insertString(char a[],char b[],int pos) { int i = 0; int lengthA = strlen(a); int lengthB = strlen(b); if(pos > lengthA) return -1; for(i= lengthA; i >= pos; i--) a[i + lengthB] = a[i]; for ( i = 0; i < lengthB; ++i ) a[i + pos] = b[i]; return 1; }
the_stack_data/87637155.c
#include <stdio.h> #include <unistd.h> #include <pthread.h> void* minhathread(void * arg) { printf("\t\tIniciando a thread. \n", arg); printf("\t\tRecebi o argumento %s do processo pesado. \n", arg); sleep(3); } int main() { int retcode; pthread_t thread_a, thread_b; void * retval; printf("Criando a primeira thread. \n"); /* pthread_create - retorna 0 no caso de sucesso - retorna um código de erro no caso contrário */ retcode = pthread_create(&thread_a, NULL, &minhathread, "a"); if(retcode != 0) { printf("A thread não pode ser criada. Erro %d. \n", retcode); }; sleep(1); printf("Criando a segunda thread. \n"); retcode = pthread_create(&thread_b, NULL, &minhathread, "b"); if(retcode != 0) { printf("A thread não pode ser criada. Erro %d. \n", retcode); }; sleep(1); printf("Esperando pelo término da primeira thread. \n"); /* pthread_join - retorna 0 no caso de sucesso - retorna um código de erro no caso contrário */ retcode = pthread_join(thread_a, &retval); printf("A primeira thread terminou. Esperando a segunda terminar. \n"); retcode = pthread_join(thread_b, &retval); printf("Ambas as threads terminaram, \n"); return 0; }
the_stack_data/133309.c
#define _GNU_SOURCE #include <dlfcn.h> int __dladdr(const void *, Dl_info *); int dladdr(const void *addr, Dl_info *info) { return __dladdr(addr, info); }
the_stack_data/6388325.c
int square(); int printf(); int main() { int i; i=16; printf("the square of %d is %d\n", i, square(i)); return 0; }
the_stack_data/179831971.c
/*same as Fig 4_3 Gulwani pldi 09*/
the_stack_data/75834.c
/* $OpenBSD: s_csqrtl.c,v 1.2 2011/07/20 19:28:33 martynas Exp $ */ /* * Copyright (c) 2008 Stephen L. Moshier <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* csqrtl() * * Complex square root * * * * SYNOPSIS: * * long double complex csqrtl(); * long double complex z, w; * * w = csqrtl( z ); * * * * DESCRIPTION: * * * If z = x + iy, r = |z|, then * * 1/2 * Re w = [ (r + x)/2 ] , * * 1/2 * Im w = [ (r - x)/2 ] . * * Cancellation error in r-x or r+x is avoided by using the * identity 2 Re w Im w = y. * * Note that -w is also a square root of z. The root chosen * is always in the right half plane and Im w has the same sign as y. * * * * ACCURACY: * * Relative error: * arithmetic domain # trials peak rms * IEEE -10,+10 500000 1.1e-19 3.0e-20 * */ #include <complex.h> #include <math.h> long double complex csqrtl(long double complex z) { long double complex w; long double x, y, r, t, scale; x = creall(z); y = cimagl(z); if (y == 0.0L) { if (x < 0.0L) { w = 0.0L + sqrtl(-x) * I; return (w); } else { w = sqrtl(x) + 0.0L * I; return (w); } } if (x == 0.0L) { r = fabsl(y); r = sqrtl(0.5L * r); if (y > 0.0L) w = r + r * I; else w = r - r * I; return (w); } /* Rescale to avoid internal overflow or underflow. */ if ((fabsl(x) > 4.0L) || (fabsl(y) > 4.0L)) { x *= 0.25L; y *= 0.25L; scale = 2.0L; } else { #if 1 x *= 7.3786976294838206464e19; /* 2^66 */ y *= 7.3786976294838206464e19; scale = 1.16415321826934814453125e-10; /* 2^-33 */ #else x *= 4.0L; y *= 4.0L; scale = 0.5L; #endif } w = x + y * I; r = cabsl(w); if (x > 0) { t = sqrtl(0.5L * r + 0.5L * x); r = scale * fabsl((0.5L * y) / t); t *= scale; } else { r = sqrtl(0.5L * r - 0.5L * x); t = scale * fabsl((0.5L * y) / r); r *= scale; } if (y < 0) w = t - r * I; else w = t + r * I; return (w); }
the_stack_data/170451897.c
void ft_putchar(char c); void rush(int x, int y) { int c; int r; r = 1; while (r != y + 1) { c = 1; while (c != x + 1) { if ((r == 1 || r == y) && (c > 1 && c < x)) ft_putchar ('-'); else if ((c == 1 || c == x) && (r > 1 && r < y)) ft_putchar ('|'); else if ((r == 1) || (r == y) || (c == 1) || (c == x)) ft_putchar ('o'); else ft_putchar (' '); c++; } ft_putchar ('\n'); r++; } }
the_stack_data/431607.c
// RUN: clang %loadLLOV %s -o /dev/null 2>&1 | FileCheck %s #include <omp.h> #define N 100 int main() { int sum = 0; #pragma omp parallel num_threads(8) { #pragma omp sections reduction(+ : sum) { for (int i = 0; i < N; i++) { sum += i; } #pragma omp section for (int i = 0; i < N; i++) { sum += i * i; } } } return sum % (N * N); } // CHECK: Region is Data Race Free. // END
the_stack_data/38863.c
/* ** EPITECH PROJECT, 2017 ** CPool_Day07_2017 ** File description: ** task03 */ #include <stdio.h> int my_dest_n_len(char *str) { int i = 0; while (str[i] != '\0') i++; return (i); } char *check_n_param(char *dest, char const *src) { if (src == NULL && dest != NULL) return (dest); else if (src != NULL && dest == NULL) return ((char *)src); return (NULL); } char *my_strncat(char *dest, char const *src, int nb) { int i = 0; int j = my_dest_n_len(dest); if (src == NULL || dest == NULL) return (check_n_param(dest, src)); while (i < nb) { dest[j] = src[i]; i++; j++; } dest[j] = '\0'; return (dest); }
the_stack_data/97021.c
#include<stdio.h> #include<string.h> int main() { char s[10]; gets(s); if(s[8]=='A') { if(s[0]=='1' && s[1]=='2') { s[0] = s[1] = '0'; } } else { if(s[1]=='8') { s[0]='2'; s[1]='0'; } else if(s[2]=='9') { s[0]='2'; s[1]='1'; } else if(!(s[0]=='1' && s[1]=='2')) { s[0]+=1; s[1]+=2; } } s[8]='\0'; puts(s); return 0; }
the_stack_data/167330136.c
#include <stdio.h> #include <time.h> #include <unistd.h> int main(void) { #ifndef NODEBUG time_t currtime = time(NULL); #endif printf("Hello World\n"); sleep(3); // wait 3 seconds #ifndef NODEBUG printf("debug: time take: %ld\n",time(NULL)-currtime); #endif return 0; }
the_stack_data/220456588.c
#include <stdlib.h> #include <stdio.h> #include <stdint.h> int64_t g = 1; const char* m = "hello"; typedef struct { uint64_t len; char buf[0]; } array; array* i64_array(int64_t n) { printf(m); array* a = (array*)malloc(sizeof(array) + sizeof(int64_t)); ((int64_t*)a->buf)[0] = n; return a; } int64_t v_main() { array* a = i64_array(g); return (int64_t)(a->buf[0]); } int64_t upcast(char c) { return (int64_t)c; } int main() { g = 2; printf("%lld", (long long)v_main()); char c=2; printf("%d", upcast(c)); return 0; }
the_stack_data/50221.c
#include <stdio.h> int main() { int counter = 0; int intArray[28] = { 0 }; for (int first = 0; first <= 9; ++first) { for (int second = 0; second <= 9; ++second) { for (int third = 0; third <= 9; ++third) { int index = first + second + third; ++intArray[index]; } } } int total = 0; for (int i = 0; i <= 27; i++) { total += intArray[i] * intArray[i]; } printf("%d", total); return 0; }
the_stack_data/158790.c
/* * A simple program for testing ELF parsing and loading * * Copyright (c) 2004, David H. Hovemeyer <[email protected]> * Copyright (c) 2004, Iulian Neamtiu <[email protected]> * $Revision: 1.24 $ * * This is free software. You are permitted to use, * redistribute, and modify it as specified in the file "COPYING". */ /* ELF_Print only prints NULL-terminated strings; * no formatting or other fancy features */ void ELF_Print(char* msg); char s1[40] = "Hi ! This is the first string\n"; int main(int argc, char** argv) { char s2[40] = "Hi ! This is the second string\n"; ELF_Print(s1); ELF_Print(s2); return 0; }
the_stack_data/77567.c
/* rand.c Copyright (c) 27 Yann BOUCHER (yann) 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. */ static int do_rand(unsigned long *ctx) { #ifdef USE_WEAK_SEEDING /* * Historic implementation compatibility. * The random sequences do not vary much with the seed, * even with overflowing. */ return ((*ctx = *ctx * 1103515245 + 12345) % ((u_long)RAND_MAX + 1)); #else /* !USE_WEAK_SEEDING */ /* * Compute x = (7^5 * x) mod (2^31 - 1) * without overflowing 31 bits: * (2^31 - 1) = 127773 * (7^5) + 2836 * From "Random number generators: good ones are hard to find", * Park and Miller, Communications of the ACM, vol. 31, no. 10, * October 1988, p. 1195. */ long hi, lo, x; /* Must be in [1, 0x7ffffffe] range at this point. */ hi = *ctx / 127773; lo = *ctx % 127773; x = 16807 * lo - 2836 * hi; if (x < 0) x += 0x7fffffff; *ctx = x; /* Transform to [0, 0x7ffffffd] range. */ return (x - 1); #endif /* !USE_WEAK_SEEDING */ } int rand_r(unsigned int *ctx) { unsigned long val; int r; #ifdef USE_WEAK_SEEDING val = *ctx; #else /* Transform to [1, 0x7ffffffe] range. */ val = (*ctx % 0x7ffffffe) + 1; #endif r = do_rand(&val); #ifdef USE_WEAK_SEEDING *ctx = (unsigned int)val; #else *ctx = (unsigned int)(val - 1); #endif return (r); } static unsigned long next = #ifdef USE_WEAK_SEEDING 1; #else 2; #endif int rand() { return (do_rand(&next)); } void srand(unsigned int seed) { next = seed; #ifndef USE_WEAK_SEEDING /* Transform to [1, 0x7ffffffe] range. */ next = (next % 0x7ffffffe) + 1; #endif }
the_stack_data/8326.c
#include <stdio.h> #include <string.h> int main() { int n,i,j,k,len1,len2; char to[150],jo[150],ao[150],aoj[150]; scanf("%d",&n); getchar(); for(i=0; i<n; i++) { gets(to); gets(jo); len1 = strlen(to); len2 = strlen(jo); if(strcmp(to,jo)==0) { printf("Case %d: Yes\n",i+1); } else { k = 0; for(j=0; j<len1; j++) { if(to[j]!=' ') { ao[k] = to[j]; k++; } } ao[k]='\0'; k = 0; for(j=0; j<len2; j++) { if(jo[j]!=' ') { aoj[k] = jo[j]; k++; } } aoj[k]='\0'; if(strcmp(aoj,ao)==0) printf("Case %d: Output Format Error\n",i+1); else printf("Case %d: Wrong Answer\n",i+1); } } return 0; }
the_stack_data/132951963.c
// data.c #ifdef GS_PLATFORM_WEB #define GS_GL_VERSION_STR "#version 300 es\n" #else #define GS_GL_VERSION_STR "#version 330 core\n" #endif const char* v_src = GS_GL_VERSION_STR "layout(location = 0) in vec3 a_pos;\n" "layout (std140) uniform u_vp {\n" " mat4 projection;\n" " mat4 view;\n" "};\n" "uniform mat4 u_model;\n" "void main() {\n" " gl_Position = projection * view * u_model * vec4(a_pos, 1.0);\n" "}\n"; const char* f_red_src = GS_GL_VERSION_STR "precision mediump float;\n" "layout(location = 0) out vec4 frag_color;\n" "void main() {\n" " frag_color = vec4(1.0, 0.0, 0.0, 1.0);\n" "}\n"; const char* f_blue_src = GS_GL_VERSION_STR "precision mediump float;\n" "layout(location = 0) out vec4 frag_color;\n" "void main() {\n" " frag_color = vec4(0.0, 0.0, 1.0, 1.0);\n" "}\n"; const char* f_green_src = GS_GL_VERSION_STR "precision mediump float;\n" "layout(location = 0) out vec4 frag_color;\n" "void main() {\n" " frag_color = vec4(0.0, 1.0, 0.0, 1.0);\n" "}\n"; const char* f_yellow_src = GS_GL_VERSION_STR "precision mediump float;\n" "layout(location = 0) out vec4 frag_color;\n" "void main() {\n" " frag_color = vec4(0.0, 1.0, 1.0, 1.0);\n" "}\n"; // Cube positions float v_data[] = { // positions -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, -0.5f, -0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, -0.5f, };
the_stack_data/321040.c
/* * Input and output a floating point number. */ #include <stdio.h> int main() { float a; printf("Input a floating point number:"); scanf("%f", &a); printf("\nFloating point %.2f", a); return 0; }
the_stack_data/306706.c
/* ** EPITECH PROJECT, 2019 ** my_strlowcase ** File description: ** Function that lowcase all letters */ char *my_strlowcase(char *str) { for (int i = 0; str[i] != '\0'; i++) { if (str[i] >= 'A' && str[i] <= 'Z') { str[i] += 32; } } return (str); }
the_stack_data/111078022.c
#include <stdio.h> int main() { int a = 10; char format[] = "Print this value %d\n"; printf(format, a); printf("%s", format); return 0; }
the_stack_data/146554.c
#include <stdio.h> int main (void){ int x, i; double a, b, c; scanf("%d", &x); for (i = 1; i <= x; i++){ scanf("%lf%lf%lf", &a, &b, &c); printf("%.1lf\n", (((a*2)+(b*3)+(c*5))/10)); } return 0; }
the_stack_data/161212.c
//***************************************************************************** // LPC80x Microcontroller Startup code for use with MCUXpresso IDE // // Version : 180105 //***************************************************************************** // // Copyright(C) NXP Semiconductors, 2017-18 // All rights reserved. // // Software that is described herein is for illustrative purposes only // which provides customers with programming information regarding the // LPC products. This software is supplied "AS IS" without any warranties of // any kind, and NXP Semiconductors and its licensor disclaim any and // all warranties, express or implied, including all implied warranties of // merchantability, fitness for a particular purpose and non-infringement of // intellectual property rights. NXP Semiconductors assumes no responsibility // or liability for the use of the software, conveys no license or rights under any // patent, copyright, mask work right, or any other intellectual property rights in // or to any products. NXP Semiconductors reserves the right to make changes // in the software without notification. NXP Semiconductors also makes no // representation or warranty that such application will be suitable for the // specified use without further testing or modification. // // Permission to use, copy, modify, and distribute this software and its // documentation is hereby granted, under NXP Semiconductors' and its // licensor's relevant copyrights in the software, without fee, provided that it // is used in conjunction with NXP Semiconductors microcontrollers. This // copyright, permission, and disclaimer notice must appear in all copies of // this code. //***************************************************************************** #if defined (DEBUG) #pragma GCC push_options #pragma GCC optimize ("Og") #endif // (DEBUG) #if defined (__cplusplus) #ifdef __REDLIB__ #error Redlib does not support C++ #else //***************************************************************************** // // The entry point for the C++ library startup // //***************************************************************************** extern "C" { extern void __libc_init_array(void); } #endif #endif #define WEAK __attribute__ ((weak)) #define ALIAS(f) __attribute__ ((weak, alias (#f))) //***************************************************************************** #if defined (__cplusplus) extern "C" { #endif //***************************************************************************** #if defined (__USE_CMSIS) || defined (__USE_LPCOPEN) // Declaration of external SystemInit function extern void SystemInit(void); #endif //***************************************************************************** // Patch the AEABI integer divide functions to use MCU's romdivide library #ifdef __USE_ROMDIVIDE // Location in memory that holds the address of the ROM Driver table #define PTR_ROM_DRIVER_TABLE ((unsigned int *)(0x0F001FF8)) // Variables to store addresses of idiv and udiv functions within MCU ROM unsigned int *pDivRom_idiv; unsigned int *pDivRom_uidiv; #endif //***************************************************************************** // // Forward declaration of the default handlers. These are aliased. // When the application defines a handler (with the same name), this will // automatically take precedence over these weak definitions // //***************************************************************************** void ResetISR(void); WEAK void NMI_Handler(void); WEAK void HardFault_Handler(void); WEAK void SVC_Handler(void); WEAK void PendSV_Handler(void); WEAK void SysTick_Handler(void); WEAK void IntDefaultHandler(void); //***************************************************************************** // // Forward declaration of the specific IRQ handlers. These are aliased // to the IntDefaultHandler, which is a 'forever' loop. When the application // defines a handler (with the same name), this will automatically take // precedence over these weak definitions // //***************************************************************************** void SPI0_IRQHandler(void) ALIAS(IntDefaultHandler); void DAC0_IRQHandler(void) ALIAS(IntDefaultHandler); void UART0_IRQHandler(void) ALIAS(IntDefaultHandler); void UART1_IRQHandler(void) ALIAS(IntDefaultHandler); void I2C1_IRQHandler(void) ALIAS(IntDefaultHandler); void I2C0_IRQHandler(void) ALIAS(IntDefaultHandler); void MRT_IRQHandler(void) ALIAS(IntDefaultHandler); void CMP_IRQHandler(void) ALIAS(IntDefaultHandler); void WDT_IRQHandler(void) ALIAS(IntDefaultHandler); void BOD_IRQHandler(void) ALIAS(IntDefaultHandler); void FLASH_IRQHandler(void) ALIAS(IntDefaultHandler); void WKT_IRQHandler(void) ALIAS(IntDefaultHandler); void ADC_SEQA_IRQHandler(void) ALIAS(IntDefaultHandler); void ADC_SEQB_IRQHandler(void) ALIAS(IntDefaultHandler); void ADC_THCMP_IRQHandler(void) ALIAS(IntDefaultHandler); void ADC_OVR_IRQHandler(void) ALIAS(IntDefaultHandler); void CTIMER0_IRQHandler(void) ALIAS(IntDefaultHandler); void PININT0_IRQHandler(void) ALIAS(IntDefaultHandler); void PININT1_IRQHandler(void) ALIAS(IntDefaultHandler); void PININT2_IRQHandler(void) ALIAS(IntDefaultHandler); void PININT3_IRQHandler(void) ALIAS(IntDefaultHandler); void PININT4_IRQHandler(void) ALIAS(IntDefaultHandler); void PININT5_IRQHandler(void) ALIAS(IntDefaultHandler); void PININT6_IRQHandler(void) ALIAS(IntDefaultHandler); void PININT7_IRQHandler(void) ALIAS(IntDefaultHandler); //***************************************************************************** // // The entry point for the application. // __main() is the entry point for Redlib based applications // main() is the entry point for Newlib based applications // //***************************************************************************** #if defined (__REDLIB__) extern void __main(void); #else extern int main(void); #endif //***************************************************************************** // // External declaration for the pointer to the stack top from the Linker Script // //***************************************************************************** extern void _vStackTop(void); //***************************************************************************** // // External declaration for LPC MCU vector table checksum from Linker Script // //***************************************************************************** WEAK extern void __valid_user_code_checksum(); //***************************************************************************** #if defined (__cplusplus) } // extern "C" #endif //***************************************************************************** // // The vector table. // This relies on the linker script to place at correct location in memory. // //***************************************************************************** extern void (* const g_pfnVectors[])(void); __attribute__ ((used, aligned(256))) void (* const g_pfnVectors[])(void) = { // Core Level - CM0plus &_vStackTop, // The initial stack pointer ResetISR, // The reset handler NMI_Handler, // The NMI handler HardFault_Handler, // The hard fault handler 0, // Reserved 0, // Reserved 0, // Reserved __valid_user_code_checksum, // LPC MCU Checksum 0, // Reserved 0, // Reserved 0, // Reserved SVC_Handler, // SVCall handler 0, // Reserved 0, // Reserved PendSV_Handler, // The PendSV handler SysTick_Handler, // The SysTick handler // Chip Level - LPC80x SPI0_IRQHandler, // 0 - SPI0 0, // 1 - Reserved DAC0_IRQHandler, // 2 - DAC0 UART0_IRQHandler, // 3 - UART0 UART1_IRQHandler, // 4 - UART1 0, // 5 - Reserved 0, // 6 - Reserved I2C1_IRQHandler, // 7 - I2C1 I2C0_IRQHandler, // 8 - I2C0 0, // 9 - Reserved MRT_IRQHandler, // 10 - Multi-rate timer CMP_IRQHandler, // 11 - Analog comparator / Cap Touch WDT_IRQHandler, // 12 - Windowed watchdog timer BOD_IRQHandler, // 13 - BOD FLASH_IRQHandler, // 14 - FLASH WKT_IRQHandler, // 15 - Self wake-up timer ADC_SEQA_IRQHandler, // 16 - ADC seq A ADC_SEQB_IRQHandler, // 17 - ADC_seq B ADC_THCMP_IRQHandler, // 18 - ADC threshold compare ADC_OVR_IRQHandler, // 19 - ADC overrun 0, // 20 - Reserved 0, // 21 - Reserved 0, // 22 - Reserved CTIMER0_IRQHandler, // 23 - Timer 0 PININT0_IRQHandler, // 24 - PININT0 PININT1_IRQHandler, // 25 - PININT1 PININT2_IRQHandler, // 26 - PININT2 PININT3_IRQHandler, // 27 - PININT3 PININT4_IRQHandler, // 28 - PININT4 PININT5_IRQHandler, // 29 - PININT5 PININT6_IRQHandler, // 30 - PININT6 PININT7_IRQHandler // 31 - PININT7 }; /* End of g_pfnVectors */ const void __attribute__((used, section(".vectmark"))) *__vectors_start__ = &g_pfnVectors; //***************************************************************************** // Functions to carry out the initialization of RW and BSS data sections. These // are written as separate functions rather than being inlined within the // ResetISR() function in order to cope with MCUs with multiple banks of // memory. //***************************************************************************** __attribute__ ((section(".after_vectors"))) void data_init(unsigned int romstart, unsigned int start, unsigned int len) { unsigned int *pulDest = (unsigned int*) start; unsigned int *pulSrc = (unsigned int*) romstart; unsigned int loop; for (loop = 0; loop < len; loop = loop + 4) *pulDest++ = *pulSrc++; } __attribute__ ((section(".after_vectors"))) void bss_init(unsigned int start, unsigned int len) { unsigned int *pulDest = (unsigned int*) start; unsigned int loop; for (loop = 0; loop < len; loop = loop + 4) *pulDest++ = 0; } //***************************************************************************** // The following symbols are constructs generated by the linker, indicating // the location of various points in the "Global Section Table". This table is // created by the linker via the Code Red managed linker script mechanism. It // contains the load address, execution address and length of each RW data // section and the execution and length of each BSS (zero initialized) section. //***************************************************************************** extern unsigned int __data_section_table; extern unsigned int __data_section_table_end; extern unsigned int __bss_section_table; extern unsigned int __bss_section_table_end; //***************************************************************************** // Reset entry point for your code. // Sets up a simple runtime environment and initializes the C/C++ // library. //***************************************************************************** __attribute__ ((section(".after_vectors"))) void ResetISR(void) { // // Copy the data sections from flash to SRAM. // unsigned int LoadAddr, ExeAddr, SectionLen; unsigned int *SectionTableAddr; // Load base address of Global Section Table SectionTableAddr = &__data_section_table; // Copy the data sections from flash to SRAM. while (SectionTableAddr < &__data_section_table_end) { LoadAddr = *SectionTableAddr++; ExeAddr = *SectionTableAddr++; SectionLen = *SectionTableAddr++; data_init(LoadAddr, ExeAddr, SectionLen); } // At this point, SectionTableAddr = &__bss_section_table; // Zero fill the bss segment while (SectionTableAddr < &__bss_section_table_end) { ExeAddr = *SectionTableAddr++; SectionLen = *SectionTableAddr++; bss_init(ExeAddr, SectionLen); } // Patch the AEABI integer divide functions to use MCU's romdivide library #ifdef __USE_ROMDIVIDE // Get address of Integer division routines function table in ROM unsigned int *div_ptr = (unsigned int *)((unsigned int *)*(PTR_ROM_DRIVER_TABLE))[4]; // Get addresses of integer divide routines in ROM // These address are then used by the code in aeabi_romdiv_patch.s pDivRom_idiv = (unsigned int *)div_ptr[0]; pDivRom_uidiv = (unsigned int *)div_ptr[1]; #endif #if defined (__USE_CMSIS) || defined (__USE_LPCOPEN) SystemInit(); #endif #if defined (__cplusplus) // // Call C++ library initialisation // __libc_init_array(); #endif #if defined (__REDLIB__) // Call the Redlib library, which in turn calls main() __main() ; #else main(); #endif // // main() shouldn't return, but if it does, we'll just enter an infinite loop // while (1) { ; } } //***************************************************************************** // Default exception handlers. Override the ones here by defining your own // handler routines in your application code. //***************************************************************************** __attribute__ ((section(".after_vectors"))) void NMI_Handler(void) { while(1) {} } __attribute__ ((section(".after_vectors"))) void HardFault_Handler(void) { while(1) {} } __attribute__ ((section(".after_vectors"))) void SVC_Handler(void) { while(1) {} } __attribute__ ((section(".after_vectors"))) void PendSV_Handler(void) { while(1) {} } __attribute__ ((section(".after_vectors"))) void SysTick_Handler(void) { while(1) {} } //***************************************************************************** // // Processor ends up here if an unexpected interrupt occurs or a specific // handler is not present in the application code. // //***************************************************************************** __attribute__ ((section(".after_vectors"))) void IntDefaultHandler(void) { while(1) {} } #if defined (DEBUG) #pragma GCC pop_options #endif // (DEBUG)
the_stack_data/20451551.c
#include <stdio.h> #include <stdlib.h> // malloc int main(){ int *p; p=(int *)malloc(sizeof(int)); *p=10; printf("*p is %d \n", *p); free(p); // 指针运算符 * // 取地址运算符 * int a, *q, *t; q = &a; t = q; printf("a is %d\n", a); printf("q is %d\n", *q); printf("t is %d\n", *t); }
the_stack_data/237642229.c
// To create the covmapping for this file on Linux, copy this file to /tmp // cd into /tmp. Use llvm-cov convert-for-testing to extract the covmapping. // This test is Windows-only. It checks that all paths, which are generated // in the index and source coverage reports, are native path. For example, // on Windows all '/' are converted to '\'. // REQUIRES: system-windows // RUN: llvm-profdata merge %S/Inputs/double_dots.proftext -o %t.profdata // RUN: llvm-cov show %S/Inputs/native_separators.covmapping -instr-profile=%t.profdata -o %t.dir // RUN: FileCheck -check-prefixes=TEXT-INDEX -input-file=%t.dir/index.txt %s // RUN: llvm-cov show -format=html %S/Inputs/native_separators.covmapping -instr-profile=%t.profdata -path-equivalence=/tmp,%S %S/../llvm-"config"/../llvm-"cov"/native_separators.c -o %t.dir // RUN: FileCheck -check-prefixes=HTML-INDEX -input-file=%t.dir/index.html %s // RUN: llvm-cov show -format=html %S/Inputs/native_separators.covmapping -instr-profile=%t.profdata -path-equivalence=/tmp,%S %s -o %t.dir // RUN: FileCheck -check-prefixes=HTML -input-file=%t.dir/coverage/tmp/native_separators.c.html %s // TEXT-INDEX: \tmp\native_separators.c // HTML-INDEX: >tmp\native_separators.c</a> // HTML: <pre>\tmp\native_separators.c</pre> int main() {}
the_stack_data/109850.c
#include <stdio.h> int main(void) { int fibo[46]; int x; fibo[0] = 0; fibo[1] = 1; for (int i = 2; i < 46; i++) fibo[i] = fibo[i - 1] + fibo[i - 2]; scanf("%d", &x); printf("%d", fibo[x]); return 0; }
the_stack_data/86074827.c
/* * OQS OpenSSL 3 provider * * Code strongly inspired by OpenSSL common provider capabilities. * * TBC: OQS license * * ToDo: Interop testing. */ #include <assert.h> #include <string.h> #include <openssl/core_dispatch.h> #include <openssl/core_names.h> /* For TLS1_VERSION etc */ #include <openssl/ssl.h> #include <openssl/params.h> // internal, but useful OSSL define: # define OSSL_NELEM(x) (sizeof(x)/sizeof((x)[0])) typedef struct oqs_group_constants_st { unsigned int group_id; /* Group ID */ unsigned int secbits; /* Bits of security */ int mintls; /* Minimum TLS version, -1 unsupported */ int maxtls; /* Maximum TLS version (or 0 for undefined) */ int mindtls; /* Minimum DTLS version, -1 unsupported */ int maxdtls; /* Maximum DTLS version (or 0 for undefined) */ int is_kem; /* Always set */ } OQS_GROUP_CONSTANTS; static const OQS_GROUP_CONSTANTS oqs_group_list[] = { // ad-hoc assignments - take from OQS generate data structures ///// OQS_TEMPLATE_FRAGMENT_GROUP_ASSIGNMENTS_START { 0x0200, 128, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x0201, 128, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x0202, 192, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x0203, 192, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x0204, 256, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x0205, 256, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x0206, 128, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x0207, 192, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x020F, 128, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x0210, 192, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x0211, 256, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x0214, 128, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x0215, 192, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x0216, 256, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x0217, 192, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x0218, 128, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x0219, 192, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x021A, 256, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x021B, 128, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x021C, 128, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x021D, 192, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x021E, 256, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x021F, 128, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x0220, 128, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x0221, 192, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x0222, 256, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x0223, 128, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x0224, 192, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x0229, 128, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x022A, 192, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x022B, 256, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x022C, 128, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x022D, 192, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x022E, 256, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x022F, 128, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x0230, 192, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x0231, 192, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x0232, 128, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x0233, 192, TLS1_3_VERSION, 0, -1, 0, 1 }, { 0x0234, 192, TLS1_3_VERSION, 0, -1, 0, 1 }, ///// OQS_TEMPLATE_FRAGMENT_GROUP_ASSIGNMENTS_END }; #define OQS_GROUP_ENTRY(tlsname, realname, algorithm, idx) \ { \ OSSL_PARAM_utf8_string(OSSL_CAPABILITY_TLS_GROUP_NAME, \ tlsname, \ sizeof(tlsname)), \ OSSL_PARAM_utf8_string(OSSL_CAPABILITY_TLS_GROUP_NAME_INTERNAL, \ realname, \ sizeof(realname)), \ OSSL_PARAM_utf8_string(OSSL_CAPABILITY_TLS_GROUP_ALG, \ algorithm, \ sizeof(algorithm)), \ OSSL_PARAM_uint(OSSL_CAPABILITY_TLS_GROUP_ID, \ (unsigned int *)&oqs_group_list[idx].group_id), \ OSSL_PARAM_uint(OSSL_CAPABILITY_TLS_GROUP_SECURITY_BITS, \ (unsigned int *)&oqs_group_list[idx].secbits), \ OSSL_PARAM_int(OSSL_CAPABILITY_TLS_GROUP_MIN_TLS, \ (unsigned int *)&oqs_group_list[idx].mintls), \ OSSL_PARAM_int(OSSL_CAPABILITY_TLS_GROUP_MAX_TLS, \ (unsigned int *)&oqs_group_list[idx].maxtls), \ OSSL_PARAM_int(OSSL_CAPABILITY_TLS_GROUP_MIN_DTLS, \ (unsigned int *)&oqs_group_list[idx].mindtls), \ OSSL_PARAM_int(OSSL_CAPABILITY_TLS_GROUP_MAX_DTLS, \ (unsigned int *)&oqs_group_list[idx].maxdtls), \ OSSL_PARAM_int(OSSL_CAPABILITY_TLS_GROUP_IS_KEM, \ (unsigned int *)&oqs_group_list[idx].is_kem), \ OSSL_PARAM_END \ } static const OSSL_PARAM oqs_param_group_list[][11] = { ///// OQS_TEMPLATE_FRAGMENT_GROUP_NAMES_START OQS_GROUP_ENTRY("frodo640aes", "frodo640aes", "frodo640aes", 0), OQS_GROUP_ENTRY("frodo640shake", "frodo640shake", "frodo640shake", 1), OQS_GROUP_ENTRY("frodo976aes", "frodo976aes", "frodo976aes", 2), OQS_GROUP_ENTRY("frodo976shake", "frodo976shake", "frodo976shake", 3), OQS_GROUP_ENTRY("frodo1344aes", "frodo1344aes", "frodo1344aes", 4), OQS_GROUP_ENTRY("frodo1344shake", "frodo1344shake", "frodo1344shake", 5), OQS_GROUP_ENTRY("bike1l1cpa", "bike1l1cpa", "bike1l1cpa", 6), OQS_GROUP_ENTRY("bike1l3cpa", "bike1l3cpa", "bike1l3cpa", 7), OQS_GROUP_ENTRY("kyber512", "kyber512", "kyber512", 8), OQS_GROUP_ENTRY("kyber768", "kyber768", "kyber768", 9), OQS_GROUP_ENTRY("kyber1024", "kyber1024", "kyber1024", 10), OQS_GROUP_ENTRY("ntru_hps2048509", "ntru_hps2048509", "ntru_hps2048509", 11), OQS_GROUP_ENTRY("ntru_hps2048677", "ntru_hps2048677", "ntru_hps2048677", 12), OQS_GROUP_ENTRY("ntru_hps4096821", "ntru_hps4096821", "ntru_hps4096821", 13), OQS_GROUP_ENTRY("ntru_hrss701", "ntru_hrss701", "ntru_hrss701", 14), OQS_GROUP_ENTRY("lightsaber", "lightsaber", "lightsaber", 15), OQS_GROUP_ENTRY("saber", "saber", "saber", 16), OQS_GROUP_ENTRY("firesaber", "firesaber", "firesaber", 17), OQS_GROUP_ENTRY("sidhp434", "sidhp434", "sidhp434", 18), OQS_GROUP_ENTRY("sidhp503", "sidhp503", "sidhp503", 19), OQS_GROUP_ENTRY("sidhp610", "sidhp610", "sidhp610", 20), OQS_GROUP_ENTRY("sidhp751", "sidhp751", "sidhp751", 21), OQS_GROUP_ENTRY("sikep434", "sikep434", "sikep434", 22), OQS_GROUP_ENTRY("sikep503", "sikep503", "sikep503", 23), OQS_GROUP_ENTRY("sikep610", "sikep610", "sikep610", 24), OQS_GROUP_ENTRY("sikep751", "sikep751", "sikep751", 25), OQS_GROUP_ENTRY("bike1l1fo", "bike1l1fo", "bike1l1fo", 26), OQS_GROUP_ENTRY("bike1l3fo", "bike1l3fo", "bike1l3fo", 27), OQS_GROUP_ENTRY("kyber90s512", "kyber90s512", "kyber90s512", 28), OQS_GROUP_ENTRY("kyber90s768", "kyber90s768", "kyber90s768", 29), OQS_GROUP_ENTRY("kyber90s1024", "kyber90s1024", "kyber90s1024", 30), OQS_GROUP_ENTRY("hqc128", "hqc128", "hqc128", 31), OQS_GROUP_ENTRY("hqc192", "hqc192", "hqc192", 32), OQS_GROUP_ENTRY("hqc256", "hqc256", "hqc256", 33), OQS_GROUP_ENTRY("ntrulpr653", "ntrulpr653", "ntrulpr653", 34), OQS_GROUP_ENTRY("ntrulpr761", "ntrulpr761", "ntrulpr761", 35), OQS_GROUP_ENTRY("ntrulpr857", "ntrulpr857", "ntrulpr857", 36), OQS_GROUP_ENTRY("sntrup653", "sntrup653", "sntrup653", 37), OQS_GROUP_ENTRY("sntrup761", "sntrup761", "sntrup761", 38), OQS_GROUP_ENTRY("sntrup857", "sntrup857", "sntrup857", 39), ///// OQS_TEMPLATE_FRAGMENT_GROUP_NAMES_END }; static int oqs_group_capability(OSSL_CALLBACK *cb, void *arg) { size_t i; assert(OSSL_NELEM(oqs_param_group_list) == OSSL_NELEM(oqs_group_list)); for (i = 0; i < OSSL_NELEM(oqs_param_group_list); i++) { if (!cb(oqs_param_group_list[i], arg)) return 0; } return 1; } int oqs_provider_get_capabilities(void *provctx, const char *capability, OSSL_CALLBACK *cb, void *arg) { //printf("OQSPROV: get_capabilities...\n"); if (strcasecmp(capability, "TLS-GROUP") == 0) return oqs_group_capability(cb, arg); /* We don't support this capability */ return 0; }
the_stack_data/178264712.c
#include <stdlib.h> #include <stdio.h> #include <math.h> #define DUTY 50 #define OUTPUT_SAMPLE_RATE 22050 #define NPTS OUTPUT_SAMPLE_RATE*2 int main() { FILE* outfile; outfile = fopen ("plot_stair_step.txt","w"); size_t i; double x; double dt = 1.0/OUTPUT_SAMPLE_RATE; double dt0 = dt - dt/DUTY; double dt1 = dt - dt0; double t = 0.0; double T = 1.0/OUTPUT_SAMPLE_RATE; double f0 = 2500.0; double w0 = 2.0*M_PI*f0; //fprintf(outfile, "Time Vadc\r\n"); for(i=0; i < NPTS/2; i++) { x = cos(w0*t); fprintf(outfile, "%.12lf %lf\r\n", t, x); t += dt0; fprintf(outfile, "%.12lf %lf\r\n", t, x); t += dt1; } return 0; }
the_stack_data/45450361.c
/* * Copyright (C) [2020-2022] Futurewei Technologies, Inc. All rights reserved. * * OpenArkCompiler is licensed underthe Mulan Permissive Software License v2. * You can use this software according to the terms and conditions of the MulanPSL - 2.0. * You may obtain a copy of MulanPSL - 2.0 at: * * https://opensource.org/licenses/MulanPSL-2.0 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR * FIT FOR A PARTICULAR PURPOSE. * See the MulanPSL - 2.0 for more details. */ #include <stdio.h> int main() { printf("Hello\n"); return 0; }
the_stack_data/445299.c
long m = 3; int func(int n) { int arr[(n + m) % 10]; int i; for (i = 0; i < (n + m) % 10; i++) { arr[i] = i; } int sum = 0; for (i = 0; i < (n + m) % 10; i++) { sum += arr[i]; } return sum; } int main() { long n = 5; return func(10); }
the_stack_data/25537.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <zconf.h> int myexec(const char *cmd) { FILE *pp = popen(cmd, "r"); if (!pp) { return -1; } char tmp[1024]; char propchar[10]; while (fgets(tmp, sizeof(tmp), pp) != NULL) { if (strncmp(tmp,"propagation",11) == 0){ strncpy(propchar,tmp+24,5); } } int propagation = atoi(propchar); pclose(pp); return propagation; } int main() { int var; float allresult[10][10]; for (var = 50; var <= 500 ; var = var + 50){ for (int ratio = 1 ; ratio <= 10 ; ratio++){ int clause = var * ratio; char dirname[100]; sprintf(dirname, "%d-%d",var, clause); chdir(dirname); int result[10]; int total = 0; printf("%d var & %d clauses : \n",var, clause); for (int i = 0; i < 10; i++) { char exec[20]; sprintf(exec,"minisat %d-%d-%d.txt",var,clause,i+1); result[i] = myexec(exec); total = total + result[i]; printf("%d ", result[i]); if (i == 9){ printf("\nAverage = %f\n\n", (float)total / 10); } int j = var / 50 - 1; allresult[j][clause / 50 - 1] = (float)total / 10; } chdir("/home/parallels/CLionProjects/terminaltry/cmake-build-debug"); } } for (int i = 0; i < 10; i++){ printf("%d var : ", (i + 1) * 50); for (int j = 0; j < 10; j++){ printf("%f ",allresult[i][j]); } printf("\n"); } return 0; }
the_stack_data/897818.c
#include<stdio.h> #include<string.h> #include<ctype.h> #include<stdlib.h> int main() { FILE *fint,*ftab,*flen,*fsym,*fobj; int op1[10],txtlen,txtlen1,i,j=0,len; char add[5],symadd[5],op[5],start[10],temp[30],line[20],label[20],mne[10],operand[10],symtab[10],opmne[10]; fint=fopen("intermediate_file.txt","r"); flen=fopen("program_length.txt","r"); ftab=fopen("optab.txt","r"); fsym=fopen("symtab.txt","r"); fobj=fopen("objectFile.txt","w"); fscanf(fint,"%s%s%s%s",add,label,mne,operand); if(strcmp(mne,"START")==0) { strcpy(start,operand); fscanf(flen,"%x",&len); } printf("H^%s^%s^%x\nT^00%s^15^",label,start,len,start); fprintf(fobj,"H^%s^%s^%x\nT^00%s^15^",label,start,len,start); fscanf(fint,"%s%s%s%s",add,label,mne,operand); while(strcmp(mne,"END")!=0) { fscanf(ftab,"%s%s",opmne,op); while(!feof(ftab)) { if(strcmp(mne,opmne)==0) { fclose(ftab); fscanf(fsym,"%s%s",symadd,symtab); while(!feof(fsym)) { if(strcmp(operand,symtab)==0) { printf("%s%s^",op,symadd); fprintf(fobj,"%s%s^",op,symadd); break; } else fscanf(fsym,"%s%s",symadd,symtab); } break; } else fscanf(ftab,"%s%s",opmne,op); } if((strcmp(mne,"BYTE")==0)||(strcmp(mne,"WORD")==0)) { if(strcmp(mne,"WORD")==0) { printf("00000%s^",operand); fprintf(fobj,"00000%s^",operand); } else { len=strlen(operand); for(i=2;i<len;i++) { printf("%x",operand[i]); fprintf(fobj,"%x",operand[i]); } printf("^"); fprintf(fobj,"^"); } } fscanf(fint,"%s%s%s%s",add,label,mne,operand); ftab=fopen("optab.txt","r"); fseek(ftab,SEEK_SET,0); } printf("\nE^00%s",start); fprintf(fobj,"\nE^00%s",start); fclose(fint); fclose(ftab); fclose(fsym); fclose(flen); return 0; }
the_stack_data/1032960.c
#include <stdio.h> #include <stdlib.h> #include <limits.h> #include <float.h> int main () { printf("Displays a list of 8-bit data types for your current machine (64-bit)\n\n"); printf("Data type\t\tMinimum\t\t\tMaximum\n"); printf("[signed] char\t\t%d\t\t\t%d\n", SCHAR_MIN, SCHAR_MAX); printf("unsigned char\t\t0\t\t\t%d\n", UCHAR_MAX); printf("\n"); printf("[signed] short\t\t%d\t\t\t%d\n", SHRT_MIN, SHRT_MAX); printf("unsigned short\t\t0\t\t\t%d\n", USHRT_MAX); printf("\n"); printf("[signed] int\t\t%d\t\t%d\n", INT_MIN, INT_MAX); printf("unsigned int\t\t0\t\t\t%d\n", UINT_MAX); printf("\n"); printf("[signed] long\t\t%ld\t%ld\n", LONG_MIN, LONG_MAX); printf("unsigned long\t\t0\t\t\t%ld\n", ULONG_MAX); printf("\n"); /* printf("[signed] int32_t\t\t%ld\t\t%ld\n", INT32_MIN, INT32_MAX); printf("unsigned int32_t\t\t0\t\t%d\n", UINT_FAST32_MAX); printf("\n"); printf("[signed] int64_t\t\t%lld\t\t%lld\n", INT64_MIN, INT64_MAX); printf("unsigned int64_t\t\t0\t\t%llu\n", UINT64_MAX); printf("\n"); */ return 0; }
the_stack_data/182954083.c
#include<stdio.h> int main() { int i,j,space,n=4,m; for(i=0;i<=n;i++) { for(space=0;space<=n-i;space++) { printf(" "); } m=1; for(j=0;j<=i;j++) { printf(" %d",m); m=m*(i-j)/(j+1); } printf("\n"); } }
the_stack_data/133242.c
/* Given a sequence of K integers {N_1, N_2, ..., N_K}. A continuous subsequence is defined to be {N_i, N_i+1, ..., N_j} where 1≤i≤j≤K. The Maximum Subsequence is the continuous subsequence which has the largest sum of its elements. For example, given sequence { -2, 11, -4, 13, -5, -2 }, its maximum subsequence is { 11, -4, 13 } with the largest sum being 20. Now you are supposed to find the largest sum, together with the first and the last numbers of the maximum subsequence. Input Specification: Each input file contains one test case. Each case occupies two lines. The first line contains a positive integer K (≤10000). The second line contains K numbers, separated by a space. Output Specification: For each test case, output in one line the largest sum, together with the first and the last numbers of the maximum subsequence. The numbers must be separated by one space, but there must be no extra space at the end of a line. In case that the maximum subsequence is not unique, output the one with the smallest indices i and j (as shown by the sample case). If all the K numbers are negative, then its maximum sum is defined to be 0, and you are supposed to output the first and the last numbers of the whole sequence. Sample Input: 10 -10 1 2 3 4 -5 -23 3 7 -21 Sample Output: 10 1 4 --- 给定K个整数组成的序列{N_1, N_2, ..., N_K},“连续子列”被定义为{N_i, N_i+1, ..., N_j},其中 1≤i≤j≤K。“最大子列和”则被定义为所有连续子列元素的和中最大者。例如给定序列{ -2, 11, -4, 13, -5, -2 },其连续子列{ 11, -4, 13 }有最大的和20。现要求你编写程序,计算给定整数序列的最大子列和。 输入格式: 输入第1行给出正整数K (≤100000);第2行给出K个整数,其间以空格分隔。 输出格式: 对于每个测试用例,在一行中输出最大和,以及最大子序列的第一个和最后一个数字。数字必须用一个空格分隔,但行尾不得有多余的空格。如果最大子序列不是唯一的,请输出索引为 i 和 j 的子序列(如示例案例所示)。如果所有 K 数均为负数,则其最大和定义为 0,并且您应该输出整个序列的第一个和最后一个数字。 输入样例: 6 -10 1 2 3 4 -5 -23 3 7 -21 输出样例: 10 1 4 01-复杂度2 Maximum Subsequence Sum 《数据结构-入门指南》 - xubeijun/续杯君 [第1节 线性表是什么 - 线性表的顺序存储结构](https://www.xubeijun.com/column/data-structures/data-structures-start-guide/chapter-003/section-001/what-is-linear-list) 5组测试用例 1 5 5 -1 -2 -3 0 -5 5 -1 -2 -3 -4 -5 10 -10 1 2 3 4 -5 -23 3 7 -21 15 1 2 3 4 -5 -23 3 7 5 -20 0 4 6 7 -10 */ #include <stdio.h> #include <stdlib.h> /** * 最大子序列的结构体 * maxSum 最大子序列的和 * firstNum 最大子序列的首位索引 * lastNum 最大子序列的末位索引 */ typedef struct maxSub{ int maxSum; int firstNum; int lastNum; } ms; /** * [maxSubSum description] * @param ptr [最大子序列的结构体指针] * @param arr [线性数组] * @param size [线性数组元素个数] */ void maxSubSum(struct maxSub *ptr, int arr[], int size){ int i; int curSum=0,firstIdx=0,count=0; ptr->maxSum=0; for (i = 0; i < size; i++){ curSum += arr[i]; if(curSum > ptr->maxSum){ ptr->maxSum = curSum; ptr->firstNum = arr[firstIdx]; ptr->lastNum = arr[i]; }else if(curSum < 0){ curSum = 0; if(i < size-1){ firstIdx = i+1; } } if(arr[i] >= 0){ count++; } } if(count == 0){ ptr->firstNum = arr[0]; ptr->lastNum = arr[size-1]; } if(ptr->maxSum == 0 && count > 0){ ptr->firstNum = 0; ptr->lastNum = 0; } } int main(){ int k,i,x; // printf( "Enter a count of array: "); x = scanf("%d",&k); if(x!=1){ printf("stdin format is error \n"); exit(-1); } int list[k]; // printf( "Enter an array, split by spaces: "); for (i = 0; i < k; i++){ x = scanf("%d",&list[i]); if(x!=1){ printf("stdin format is error \n"); exit(-1); } } ms m; maxSubSum(&m, list, k); printf("%d %d %d", m.maxSum, m.firstNum, m.lastNum); return 0; }
the_stack_data/114504.c
/* Fig. 5.14: fig05_14.c Recursive factorial function */ #include <stdio.h> long factorial( long number ); /* function prototype */ /* function main begins program execution */ int main( void ) { int i; /* counter */ /* loop 11 times; during each iteration, calculate factorial( i ) and display result */ for ( i = 0; i <= 10; i++ ) { printf( "%2d! = %ld\n", i, factorial( i ) ); } /* end for */ return 0; /* indicates successful termination */ } /* end main */ /* recursive definition of function factorial */ long factorial( long number ) { /* base case */ if ( number <= 1 ) { return 1; } /* end if */ else { /* recursive step */ return ( number * factorial( number - 1 ) ); } /* end else */ } /* end function factorial */ /************************************************************************** * (C) Copyright 1992-2010 by Deitel & Associates, Inc. and * * Pearson Education, Inc. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * *************************************************************************/
the_stack_data/354756.c
#include <sys/types.h> #include <signal.h> #include <stdio.h> void sig(int num) { printf("you pressed ctrl+c\n"); } int main(int argc, char *argv[]) { signal(SIGINT,sig); while(1); return 0; }
the_stack_data/43887910.c
/* * Copyright (c) 2015-2017 Martin McDonough. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Products derived from this software may not be called "Kashyyyk", nor may * "YYY" appear in their name, without prior written permission of * the copyright holders. * * 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 <stdlib.h> #include <pthread.h> #include <assert.h> /*---------------------------------------------------------------------------*/ struct YYY_Monitor { pthread_cond_t cv; pthread_mutex_t mutex; }; /*---------------------------------------------------------------------------*/ unsigned YYY_MonitorSize(){ return sizeof(struct YYY_Monitor); } /*---------------------------------------------------------------------------*/ void YYY_InitMonitor(struct YYY_Monitor *monitor){ int err; pthread_condattr_t cv_attr; pthread_mutexattr_t mx_attr; err = pthread_condattr_init(&cv_attr); err |= pthread_mutexattr_init(&mx_attr); assert(err==0); err = pthread_cond_init(&(monitor->cv), &cv_attr); err |= pthread_mutex_init(&(monitor->mutex), &mx_attr); assert(err==0); err = pthread_condattr_destroy(&cv_attr); err |= pthread_mutexattr_destroy(&mx_attr); assert(err==0); (void)err; } /*---------------------------------------------------------------------------*/ void YYY_DestroyMonitor(struct YYY_Monitor *monitor){ int err; err = pthread_cond_destroy(&(monitor->cv)); err |= pthread_mutex_destroy(&(monitor->mutex)); assert(err==0); (void)err; } /*---------------------------------------------------------------------------*/ void YYY_LockMonitor(struct YYY_Monitor *monitor){ pthread_mutex_lock(&(monitor->mutex)); } /*---------------------------------------------------------------------------*/ void YYY_UnlockMonitor(struct YYY_Monitor *monitor){ pthread_mutex_unlock(&(monitor->mutex)); } /*---------------------------------------------------------------------------*/ void YYY_WaitMonitor(struct YYY_Monitor *monitor){ const int err = pthread_cond_wait(&(monitor->cv), &(monitor->mutex)); assert(err==0); (void)err; } /*---------------------------------------------------------------------------*/ void YYY_NotifyMonitor(struct YYY_Monitor *monitor){ const int err = pthread_cond_signal(&(monitor->cv)); assert(err==0); (void)err; } /*---------------------------------------------------------------------------*/ void YYY_NotifyAllMonitor(struct YYY_Monitor *monitor){ const int err = pthread_cond_broadcast(&(monitor->cv)); assert(err==0); (void)err; }
the_stack_data/220454990.c
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Benchmark Cephes `sin`. */ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <time.h> #include <sys/time.h> #define NAME "sin" #define ITERATIONS 1000000 #define REPEATS 3 /** * Define prototypes for external functions. */ extern double sin( double x ); /** * Prints the TAP version. */ void print_version() { printf( "TAP version 13\n" ); } /** * Prints the TAP summary. * * @param total total number of tests * @param passing total number of passing tests */ void print_summary( int total, int passing ) { printf( "#\n" ); printf( "1..%d\n", total ); // TAP plan printf( "# total %d\n", total ); printf( "# pass %d\n", passing ); printf( "#\n" ); printf( "# ok\n" ); } /** * Prints benchmarks results. * * @param elapsed elapsed time in seconds */ void print_results( double elapsed ) { double rate = (double)ITERATIONS / elapsed; printf( " ---\n" ); printf( " iterations: %d\n", ITERATIONS ); printf( " elapsed: %0.9f\n", elapsed ); printf( " rate: %0.9f\n", rate ); printf( " ...\n" ); } /** * Returns a clock time. * * @return clock time */ double tic() { struct timeval now; gettimeofday( &now, NULL ); return (double)now.tv_sec + (double)now.tv_usec/1.0e6; } /** * Generates a random number on the interval [0,1]. * * @return random number */ double rand_double() { int r = rand(); return (double)r / ( (double)RAND_MAX + 1.0 ); } /** * Runs a benchmark. * * @return elapsed time in seconds */ double benchmark() { double elapsed; double x; double y; double t; int i; t = tic(); for ( i = 0; i < ITERATIONS; i++ ) { x = ( 20.0*rand_double() ) - 10.0; y = sin( x ); if ( y != y ) { printf( "should not return NaN\n" ); break; } } elapsed = tic() - t; if ( y != y ) { printf( "should not return NaN\n" ); } return elapsed; } /** * Main execution sequence. */ int main( void ) { double elapsed; int i; // Use the current time to seed the random number generator: srand( time( NULL ) ); print_version(); for ( i = 0; i < REPEATS; i++ ) { printf( "# c::cephes::%s\n", NAME ); elapsed = benchmark(); print_results( elapsed ); printf( "ok %d benchmark finished\n", i+1 ); } print_summary( REPEATS, REPEATS ); }
the_stack_data/64200418.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #include <unistd.h> #include <pthread.h> #include <assert.h> #define SMAX 80 #define CMAX 10 // 100000 struct Client_t { // 客戶端的資料結構 int fd; // 串流代號 pthread_t thread; // 線程 thread }; struct Client_t clients[CMAX]; // 所有客戶端 void *receiver(void *argu) { int ci = *(int*)argu; int cfd = clients[ci].fd; char msg[SMAX]; while (1) { int n = recv(cfd, msg, SMAX, 0); // 收到某客戶端傳來的訊息 if (n <=0) break; printf("%s", msg); // 印出該訊息 for (int i=0; i<CMAX; i++) { // 廣播給其他人 if (i != ci && clients[i].fd != 0) { // 如果對方不是發訊息者,而且不是空的,那就轉送給他! send(clients[i].fd, msg, strlen(msg)+1, 0); } } } close(cfd); clients[ci].fd = 0; return NULL; } void connectHandler(int sfd) { struct sockaddr_in raddr; socklen_t rAddrLen = sizeof(struct sockaddr); int cfd = accept(sfd, (struct sockaddr*) &raddr, &rAddrLen); for (int i=0; i<CMAX; i++) { if (clients[i].fd == 0) { memset(&clients[i], 0, sizeof(clients[i])); clients[i].fd = cfd; pthread_create(&clients[i].thread, NULL, receiver, &i); break; } } } int main(int argc, char *argv[]) { int port = atoi(argv[1]); printf("port=%d\n", port); int sfd = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in saddr, raddr; memset(&saddr, 0, sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_port = htons(port); char msg[SMAX]; saddr.sin_addr.s_addr = INADDR_ANY; int rb = bind(sfd, (struct sockaddr*) &saddr, sizeof(struct sockaddr)); assert(rb >= 0); int rl = listen(sfd, CMAX); assert(rl >= 0); memset(clients, 0, sizeof(clients)); while (1) { connectHandler(sfd); } close(sfd); return 0; }
the_stack_data/150141151.c
extern void abort(void); void reach_error(){} void __VERIFIER_assert(int cond) { if(!(cond)) { ERROR: {reach_error();abort();} } } int main(void) { unsigned int x = 0; while (x < 100000000) { if (x < 10000000) { x++; } else { x += 2; } } __VERIFIER_assert(x == 100000001) ; }
the_stack_data/59513592.c
/*#include<stdio.h> void main() { int a = 10; int *p = &a; double *pd; pd = p; printf("%lf\n", *pd); system("pause"); return 0; }*/
the_stack_data/909625.c
/* * Copyright (c) 2016, Nest Labs, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #define _GNU_SOURCE 1 #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <stdbool.h> #include <syslog.h> #include <getopt.h> #include <fcntl.h> #include <unistd.h> #include <signal.h> #include <string.h> #include <errno.h> #include <sys/types.h> #include <sys/select.h> #include <sys/ucontext.h> #include <sys/ioctl.h> #include <sys/file.h> #include <linux/spi/spidev.h> #include <execinfo.h> #if HAVE_PTY_H #include <pty.h> #endif #if HAVE_UTIL_H #include <util.h> #endif /* ------------------------------------------------------------------------- */ /* MARK: Macros and Constants */ #define SPI_HDLC_VERSION "0.03" #define MAX_FRAME_SIZE 2048 #define HEADER_LEN 5 #define SPI_HEADER_RESET_FLAG 0x80 #define SPI_HEADER_CRC_FLAG 0x40 #define SPI_HEADER_PATTERN_VALUE 0x02 #define SPI_HEADER_PATTERN_MASK 0x03 #define EXIT_QUIT 65535 #ifndef FAULT_BACKTRACE_STACK_DEPTH #define FAULT_BACKTRACE_STACK_DEPTH 20 #endif #ifndef MSEC_PER_SEC #define MSEC_PER_SEC 1000 #endif #ifndef USEC_PER_MSEC #define USEC_PER_MSEC 1000 #endif #ifndef USEC_PER_SEC #define USEC_PER_SEC (USEC_PER_MSEC * MSEC_PER_SEC) #endif #define SPI_POLL_PERIOD_MSEC (MSEC_PER_SEC/30) #define GPIO_INT_ASSERT_STATE 0 // I̅N̅T̅ is asserted low #define GPIO_RES_ASSERT_STATE 0 // R̅E̅S̅ is asserted low #define SPI_RX_ALIGN_ALLOWANCE_MAX 3 #define SOCKET_DEBUG_BYTES_PER_LINE 16 static const uint8_t kHdlcResetSignal[] = { 0x7E, 0x13, 0x11, 0x7E }; static const uint16_t kHdlcCrcCheckValue = 0xf0b8; static const uint16_t kHdlcCrcResetValue = 0xffff; enum { MODE_STDIO = 0, MODE_PTY = 1, }; // Ignores return value from function 's' #define IGNORE_RETURN_VALUE(s) do { if (s){} } while (0) /* ------------------------------------------------------------------------- */ /* MARK: Global State */ #if HAVE_OPENPTY static int sMode = MODE_PTY; #else static int sMode = MODE_STDIO; #endif static const char* sSpiDevPath = NULL; static const char* sIntGpioDevPath = NULL; static const char* sResGpioDevPath = NULL; static int sVerbose = LOG_NOTICE; static int sSpiDevFd = -1; static int sResGpioValueFd = -1; static int sIntGpioValueFd = -1; static int sHdlcInputFd = -1; static int sHdlcOutputFd = -1; static int sSpiSpeed = 1000000; // in Hz (default: 1MHz) static uint8_t sSpiMode = 0; static int sSpiCsDelay = 20; static int sSpiTransactionDelay = 200; static uint16_t sSpiRxPayloadSize; static uint8_t sSpiRxFrameBuffer[MAX_FRAME_SIZE + SPI_RX_ALIGN_ALLOWANCE_MAX]; static uint16_t sSpiTxPayloadSize; static bool sSpiTxIsReady = false; static bool sSpiTxFlowControl = false; static uint8_t sSpiTxFrameBuffer[MAX_FRAME_SIZE + SPI_RX_ALIGN_ALLOWANCE_MAX]; static int sSpiRxAlignAllowance = 0; static uint32_t sSpiFrameCount = 0; static uint32_t sSpiValidFrameCount = 0; static bool sSlaveDidReset = false; static int sRet = 0; static sig_t sPreviousHandlerForSIGINT; static sig_t sPreviousHandlerForSIGTERM; /* ------------------------------------------------------------------------- */ /* MARK: Signal Handlers */ static void signal_SIGINT(int sig) { static const char message[] = "\nCaught SIGINT!\n"; sRet = EXIT_QUIT; // Can't use syslog() because it isn't async signal safe. // So we write to stderr IGNORE_RETURN_VALUE(write(STDERR_FILENO, message, sizeof(message)-1)); // Restore the previous handler so that if we end up getting // this signal again we peform the system default action. signal(SIGINT, sPreviousHandlerForSIGINT); sPreviousHandlerForSIGINT = NULL; (void)sig; } static void signal_SIGTERM(int sig) { static const char message[] = "\nCaught SIGTERM!\n"; sRet = EXIT_QUIT; // Can't use syslog() because it isn't async signal safe. // So we write to stderr IGNORE_RETURN_VALUE(write(STDERR_FILENO, message, sizeof(message)-1)); // Restore the previous handler so that if we end up getting // this signal again we peform the system default action. signal(SIGTERM, sPreviousHandlerForSIGTERM); sPreviousHandlerForSIGTERM = NULL; (void) sig; } static void signal_SIGHUP(int sig) { static const char message[] = "\nCaught SIGHUP!\n"; sRet = EXIT_FAILURE; // Can't use syslog() because it isn't async signal safe. // So we write to stderr IGNORE_RETURN_VALUE(write(STDERR_FILENO, message, sizeof(message)-1)); // We don't restore the "previous handler" // because we always want to let the main // loop decide what to do for hangups. (void) sig; } static void signal_critical(int sig, siginfo_t * info, void * ucontext) { // This is the last hurah for this process. // We dump the stack, because that's all we can do. void *stack_mem[FAULT_BACKTRACE_STACK_DEPTH]; void **stack = stack_mem; char **stack_symbols; int stack_depth, i; ucontext_t *uc = (ucontext_t*)ucontext; // Shut up compiler warning. (void)uc; (void)info; // We call some functions here which aren't async-signal-safe, // but this function isn't really useful without those calls. // Since we are making a gamble (and we deadlock if we loose), // we are going to set up a two-second watchdog to make sure // we end up terminating like we should. The choice of a two // second timeout is entirely arbitrary, and may be changed // if needs warrant. alarm(2); signal(SIGALRM, SIG_DFL); fprintf(stderr, " *** FATAL ERROR: Caught signal %d (%s):\n", sig, strsignal(sig)); stack_depth = backtrace(stack, FAULT_BACKTRACE_STACK_DEPTH); // Here are are trying to update the pointer in the backtrace // to be the actual location of the fault. #if defined(__x86_64__) stack[1] = (void *) uc->uc_mcontext.gregs[REG_RIP]; #elif defined(__i386__) stack[1] = (void *) uc->uc_mcontext.gregs[REG_EIP]; #elif defined(__arm__) stack[1] = (void *) uc->uc_mcontext.arm_ip; #else #warning TODO: Add this arch to signal_critical #endif // Now dump the symbols to stderr, in case syslog barfs. backtrace_symbols_fd(stack, stack_depth, STDERR_FILENO); // Load up the symbols individually, so we can output to syslog, too. stack_symbols = backtrace_symbols(stack, stack_depth); syslog(LOG_CRIT, " *** FATAL ERROR: Caught signal %d (%s):", sig, strsignal(sig)); for (i = 0; i != stack_depth; i++) { syslog(LOG_CRIT, "[BT] %2d: %s", i, stack_symbols[i]); } free(stack_symbols); exit(EXIT_FAILURE); } static void log_debug_buffer(const char* desc, const uint8_t* buffer_ptr, int buffer_len) { int i = 0; if (sVerbose < LOG_DEBUG) { return; } while (i < buffer_len) { int j; char dump_string[SOCKET_DEBUG_BYTES_PER_LINE*3+1]; for (j = 0; i < buffer_len && j < SOCKET_DEBUG_BYTES_PER_LINE; i++, j++) { sprintf(dump_string+j*3, "%02X ", buffer_ptr[i]); } syslog(LOG_DEBUG, "%s: %s%s", desc, dump_string, (i < buffer_len)?" ...":""); } } /* ------------------------------------------------------------------------- */ /* MARK: SPI Transfer Functions */ static void spi_header_set_flag_byte(uint8_t *header, uint8_t value) { header[0] = value; } static void spi_header_set_accept_len(uint8_t *header, uint16_t len) { header[1] = ((len >> 0) & 0xFF); header[2] = ((len >> 8) & 0xFF); } static void spi_header_set_data_len(uint8_t *header, uint16_t len) { header[3] = ((len >> 0) & 0xFF); header[4] = ((len >> 8) & 0xFF); } static uint8_t spi_header_get_flag_byte(const uint8_t *header) { return header[0]; } static uint16_t spi_header_get_accept_len(const uint8_t *header) { return ( header[1] + (uint16_t)(header[2] << 8) ); } static uint16_t spi_header_get_data_len(const uint8_t *header) { return ( header[3] + (uint16_t)(header[4] << 8) ); } static uint8_t* get_real_rx_frame_start(void) { uint8_t* ret = sSpiRxFrameBuffer; int i = 0; for (i = 0; i < sSpiRxAlignAllowance; i++) { if (ret[0] != 0xFF) { break; } ret++; } return ret; } static int do_spi_xfer(int len) { int ret; struct spi_ioc_transfer xfer[2] = { { // This part is the delay between C̅S̅ being // asserted and the SPI clock starting. This // is not supported by all Linux SPI drivers. .tx_buf = 0, .rx_buf = 0, .len = 0, .delay_usecs = (uint16_t)sSpiCsDelay, .speed_hz = (uint32_t)sSpiSpeed, .bits_per_word = 8, .cs_change = false, }, { // This part is the actual SPI transfer. .tx_buf = (unsigned long)sSpiTxFrameBuffer, .rx_buf = (unsigned long)sSpiRxFrameBuffer, .len = (uint32_t)(len + HEADER_LEN + sSpiRxAlignAllowance), .delay_usecs = 0, .speed_hz = (uint32_t)sSpiSpeed, .bits_per_word = 8, .cs_change = false, } }; if (sSpiCsDelay > 0) { // A C̅S̅ delay has been specified. Start transactions // with both parts. ret = ioctl(sSpiDevFd, SPI_IOC_MESSAGE(2), &xfer[0]); } else { // No C̅S̅ delay has been specified, so we skip the first // part because it causes some SPI drivers to croak. ret = ioctl(sSpiDevFd, SPI_IOC_MESSAGE(1), &xfer[1]); } if (ret != -1) { log_debug_buffer("SPI-TX", sSpiTxFrameBuffer, (int)xfer[1].len); log_debug_buffer("SPI-RX", sSpiRxFrameBuffer, (int)xfer[1].len); if (spi_header_get_flag_byte(sSpiRxFrameBuffer) != 0xFF) { if (spi_header_get_flag_byte(sSpiRxFrameBuffer) & SPI_HEADER_RESET_FLAG) { sSlaveDidReset = true; } } sSpiFrameCount++; } return ret; } static void debug_spi_header(const char* hint) { if (sVerbose >= LOG_DEBUG) { const uint8_t* spiRxFrameBuffer = get_real_rx_frame_start(); syslog(LOG_DEBUG, "%s-TX: H:%02X ACCEPT:%d DATA:%0d\n", hint, spi_header_get_flag_byte(sSpiTxFrameBuffer), spi_header_get_accept_len(sSpiTxFrameBuffer), spi_header_get_data_len(sSpiTxFrameBuffer) ); syslog(LOG_DEBUG, "%s-RX: H:%02X ACCEPT:%d DATA:%0d\n", hint, spi_header_get_flag_byte(spiRxFrameBuffer), spi_header_get_accept_len(spiRxFrameBuffer), spi_header_get_data_len(spiRxFrameBuffer) ); } } static int push_pull_spi(void) { int ret; uint16_t slave_max_rx; uint16_t slave_data_len; int spi_xfer_bytes = 0; const uint8_t* spiRxFrameBuffer = NULL; sSpiTxFlowControl = false; // Fetch the slave's buffer sizes. // Zero out our max rx and data len // so that the slave doesn't think // we are actually trying to transfer // data. if (sSpiValidFrameCount == 0) { spi_header_set_flag_byte(sSpiTxFrameBuffer, SPI_HEADER_RESET_FLAG|SPI_HEADER_PATTERN_VALUE); } else { spi_header_set_flag_byte(sSpiTxFrameBuffer, SPI_HEADER_PATTERN_VALUE); } spi_header_set_accept_len(sSpiTxFrameBuffer, 0); spi_header_set_data_len(sSpiTxFrameBuffer, 0); ret = do_spi_xfer(0); if (ret < 0) { perror("do_spi_xfer"); goto bail; } spiRxFrameBuffer = get_real_rx_frame_start(); debug_spi_header("push_pull_1"); if (spi_header_get_flag_byte(spiRxFrameBuffer) == 0xFF) { // Device is off or in a bad state. sSpiTxFlowControl = true; syslog(LOG_DEBUG, "Discarded frame. (1)"); goto bail; } slave_max_rx = spi_header_get_accept_len(spiRxFrameBuffer); slave_data_len = spi_header_get_data_len(spiRxFrameBuffer); if ( (slave_max_rx > MAX_FRAME_SIZE) || (slave_data_len > MAX_FRAME_SIZE) ) { sSpiTxFlowControl = true; syslog( LOG_INFO, "Gibberish in header (max_rx:%d, data_len:%d)", slave_max_rx, slave_data_len ); goto bail; } sSpiValidFrameCount++; if (!sSpiTxIsReady && (slave_data_len == 0)) { // Nothing to do. goto bail; } if ( sSpiTxIsReady && (sSpiTxPayloadSize <= slave_max_rx) ) { spi_xfer_bytes = sSpiTxPayloadSize; spi_header_set_data_len(sSpiTxFrameBuffer, sSpiTxPayloadSize); } else if (sSpiTxIsReady && (sSpiTxPayloadSize > slave_max_rx)) { // The slave isn't ready for what we have to // send them. Turn on rate limiting so that we // don't waste a ton of CPU bombarding them // with useless SPI transfers. sSpiTxFlowControl = true; } if ( (slave_data_len != 0) && (sSpiRxPayloadSize == 0) ) { spi_header_set_accept_len(sSpiTxFrameBuffer, slave_data_len); if (slave_data_len > spi_xfer_bytes) { spi_xfer_bytes = slave_data_len; } } usleep((unsigned int)sSpiTransactionDelay); spi_header_set_flag_byte(sSpiTxFrameBuffer, SPI_HEADER_PATTERN_VALUE); // This is the real transfer. ret = do_spi_xfer(spi_xfer_bytes); if (ret < 0) { perror("do_spi_xfer"); goto bail; } spiRxFrameBuffer = get_real_rx_frame_start(); debug_spi_header("push_pull_2"); if (spi_header_get_flag_byte(spiRxFrameBuffer) == 0xFF) { // Device is off or in a bad state. sSpiTxFlowControl = true; syslog(LOG_DEBUG, "Discarded frame. (2)"); goto bail; } slave_max_rx = spi_header_get_accept_len(spiRxFrameBuffer); slave_data_len = spi_header_get_data_len(spiRxFrameBuffer); if ( (slave_max_rx > MAX_FRAME_SIZE) || (slave_data_len > MAX_FRAME_SIZE) ) { sSpiTxFlowControl = true; syslog( LOG_INFO, "Gibberish in header (max_rx:%d, data_len:%d)", slave_max_rx, slave_data_len ); goto bail; } sSpiValidFrameCount++; if ( (sSpiRxPayloadSize == 0) && (slave_data_len <= spi_header_get_accept_len(sSpiTxFrameBuffer)) ) { // We have received a packet. Set sSpiRxPayloadSize so that // the packet will eventually get queued up by push_hdlc(). sSpiRxPayloadSize = slave_data_len; } if ( (sSpiTxPayloadSize == spi_header_get_data_len(sSpiTxFrameBuffer)) && (spi_header_get_data_len(sSpiTxFrameBuffer) <= slave_max_rx) ) { // Out outbound packet has been successfully transmitted. Clear // sSpiTxPayloadSize and sSpiTxIsReady so that pull_hdlc() can // pull another packet for us to send. sSpiTxIsReady = false; sSpiTxPayloadSize = 0; } bail: return ret; } static bool check_and_clear_interrupt(void) { char value[5] = ""; ssize_t len; lseek(sIntGpioValueFd, 0, SEEK_SET); len = read(sIntGpioValueFd, value, sizeof(value)-1); if (len < 0) { perror("check_and_clear_interrupt"); sRet = EXIT_FAILURE; } // The interrupt pin is active low. return GPIO_INT_ASSERT_STATE == atoi(value); } /* ------------------------------------------------------------------------- */ /* MARK: HDLC Transfer Functions */ #define HDLC_BYTE_FLAG 0x7E #define HDLC_BYTE_ESC 0x7D #define HDLC_BYTE_XON 0x11 #define HDLC_BYTE_XOFF 0x13 #define HDLC_BYTE_SPECIAL 0xF8 #define HDLC_ESCAPE_XFORM 0x20 static uint16_t hdlc_crc16(uint16_t aFcs, uint8_t aByte) { #if 1 // CRC-16/CCITT, CRC-16/CCITT-TRUE, CRC-CCITT // width=16 poly=0x1021 init=0x0000 refin=true refout=true xorout=0x0000 check=0x2189 name="KERMIT" // http://reveng.sourceforge.net/crc-catalogue/16.htm#crc.cat.kermit static const uint16_t sFcsTable[256] = { 0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf, 0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7, 0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e, 0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876, 0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd, 0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5, 0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c, 0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974, 0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb, 0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3, 0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a, 0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72, 0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9, 0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1, 0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738, 0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70, 0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7, 0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff, 0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036, 0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e, 0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5, 0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd, 0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134, 0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c, 0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3, 0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb, 0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232, 0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a, 0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1, 0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9, 0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330, 0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78 }; return (aFcs >> 8) ^ sFcsTable[(aFcs ^ aByte) & 0xff]; #else // CRC-16/CCITT-FALSE, same CRC as 802.15.4 // width=16 poly=0x1021 init=0xffff refin=false refout=false xorout=0x0000 check=0x29b1 name="CRC-16/CCITT-FALSE" // http://reveng.sourceforge.net/crc-catalogue/16.htm#crc.cat.crc-16-ccitt-false aFcs = (uint16_t)((aFcs >> 8) | (aFcs << 8)); aFcs ^= aByte; aFcs ^= ((aFcs & 0xff) >> 4); aFcs ^= (aFcs << 12); aFcs ^= ((aFcs & 0xff) << 5); return aFcs; #endif } static bool hdlc_byte_needs_escape(uint8_t byte) { switch(byte) { case HDLC_BYTE_SPECIAL: case HDLC_BYTE_ESC: case HDLC_BYTE_FLAG: case HDLC_BYTE_XOFF: case HDLC_BYTE_XON: return true; default: return false; } } static int push_hdlc(void) { int ret = 0; const uint8_t* spiRxFrameBuffer = get_real_rx_frame_start(); static uint8_t escaped_frame_buffer[MAX_FRAME_SIZE*2]; static uint16_t escaped_frame_len; static uint16_t escaped_frame_sent; if (escaped_frame_len == 0) { if (sSlaveDidReset) { // Indicate an MCU reset. memcpy(escaped_frame_buffer, kHdlcResetSignal, sizeof(kHdlcResetSignal)); escaped_frame_len = sizeof(kHdlcResetSignal); sSlaveDidReset = false; } else if (sSpiRxPayloadSize != 0) { // Escape the frame. uint8_t c; uint16_t fcs = kHdlcCrcResetValue; uint16_t i; for (i = 0; i < sSpiRxPayloadSize; i++) { c = spiRxFrameBuffer[i + HEADER_LEN]; fcs = hdlc_crc16(fcs, c); if (hdlc_byte_needs_escape(c)) { escaped_frame_buffer[escaped_frame_len++] = HDLC_BYTE_ESC; escaped_frame_buffer[escaped_frame_len++] = c ^ HDLC_ESCAPE_XFORM; } else { escaped_frame_buffer[escaped_frame_len++] = c; } } fcs ^= 0xFFFF; c = fcs & 0xFF; if (hdlc_byte_needs_escape(c)) { escaped_frame_buffer[escaped_frame_len++] = HDLC_BYTE_ESC; escaped_frame_buffer[escaped_frame_len++] = c ^ HDLC_ESCAPE_XFORM; } else { escaped_frame_buffer[escaped_frame_len++] = c; } c = (fcs >> 8) & 0xFF; if (hdlc_byte_needs_escape(c)) { escaped_frame_buffer[escaped_frame_len++] = HDLC_BYTE_ESC; escaped_frame_buffer[escaped_frame_len++] = c ^ HDLC_ESCAPE_XFORM; } else { escaped_frame_buffer[escaped_frame_len++] = c; } escaped_frame_buffer[escaped_frame_len++] = HDLC_BYTE_FLAG; escaped_frame_sent = 0; sSpiRxPayloadSize = 0; } else { // Nothing to do. goto bail; } } ret = (int)write( sHdlcOutputFd, escaped_frame_buffer + escaped_frame_sent, escaped_frame_len - escaped_frame_sent ); if (ret < 0) { if (errno == EAGAIN) { ret = 0; } else { perror("push_hdlc:write"); syslog(LOG_ERR, "push_hdlc:write: errno=%d (%s)", errno, strerror(errno)); } goto bail; } escaped_frame_sent += ret; // Reset state once we have sent the entire frame. if (escaped_frame_len == escaped_frame_sent) { escaped_frame_len = escaped_frame_sent = 0; } ret = 0; bail: return ret; } static int pull_hdlc(void) { int ret = 0; static uint16_t fcs; static bool unescape_next_byte = false; if (!sSpiTxIsReady) { uint8_t byte; while ((ret = (int)read(sHdlcInputFd, &byte, 1)) == 1) { if (sSpiTxPayloadSize >= (MAX_FRAME_SIZE - HEADER_LEN)) { syslog(LOG_WARNING, "HDLC frame was too big"); unescape_next_byte = false; sSpiTxPayloadSize = 0; fcs = kHdlcCrcResetValue; } else if (byte == HDLC_BYTE_FLAG) { if (sSpiTxPayloadSize <= 2) { unescape_next_byte = false; sSpiTxPayloadSize = 0; fcs = kHdlcCrcResetValue; continue; } else if (fcs != kHdlcCrcCheckValue) { syslog(LOG_WARNING, "HDLC frame with bad CRC (LEN:%d, FCS:0x%04X)", sSpiTxPayloadSize, fcs); unescape_next_byte = false; sSpiTxPayloadSize = 0; fcs = kHdlcCrcResetValue; continue; } // Clip off the CRC sSpiTxPayloadSize -= 2; // Indicate that a frame is ready to go out sSpiTxIsReady = true; // Clean up for the next frame unescape_next_byte = false; fcs = kHdlcCrcResetValue; break; } else if (byte == HDLC_BYTE_ESC) { unescape_next_byte = true; continue; } else if (hdlc_byte_needs_escape(byte)) { // Skip all other control codes. continue; } else if (unescape_next_byte) { byte = byte ^ HDLC_ESCAPE_XFORM; unescape_next_byte = false; } fcs = hdlc_crc16(fcs, byte); sSpiTxFrameBuffer[HEADER_LEN + sSpiTxPayloadSize++] = byte; } } if (ret < 0) { if (errno == EAGAIN) { ret = 0; } else { perror("pull_hdlc:read"); syslog(LOG_ERR, "pull_hdlc:read: errno=%d (%s)", errno, strerror(errno)); } } return ret < 0 ? ret : 0; } /* ------------------------------------------------------------------------- */ /* MARK: Setup Functions */ static bool update_spi_mode(int x) { sSpiMode = (uint8_t)x; if ( (sSpiDevFd >= 0) && (ioctl(sSpiDevFd, SPI_IOC_WR_MODE, &sSpiMode) < 0) ) { perror("ioctl(SPI_IOC_WR_MODE)"); return false; } return true; } static bool update_spi_speed(int x) { sSpiSpeed = x; if ( (sSpiDevFd >= 0) && (ioctl(sSpiDevFd, SPI_IOC_WR_MAX_SPEED_HZ, &sSpiSpeed) < 0) ) { perror("ioctl(SPI_IOC_WR_MAX_SPEED_HZ)"); return false; } return true; } static bool setup_spi_dev(const char* path) { int fd = -1; const uint8_t spi_word_bits = 8; int ret; sSpiDevPath = path; fd = open(path, O_RDWR); if (fd < 0) { perror("open"); goto bail; } // Set the SPI mode. ret = ioctl(fd, SPI_IOC_WR_MODE, &sSpiMode); if (ret < 0) { perror("ioctl(SPI_IOC_WR_MODE)"); goto bail; } // Set the SPI clock speed. ret = ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &sSpiSpeed); if (ret < 0) { perror("ioctl(SPI_IOC_WR_MAX_SPEED_HZ)"); goto bail; } // Set the SPI word size. ret = ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &spi_word_bits); if (ret < 0) { perror("ioctl(SPI_IOC_WR_BITS_PER_WORD)"); goto bail; } // Lock the file descriptor if (flock(fd, LOCK_EX | LOCK_NB) < 0) { perror("flock"); goto bail; } sSpiDevFd = fd; fd = -1; bail: if (fd >= 0) { close(fd); } return sSpiDevFd >= 0; } static bool setup_res_gpio(const char* path) { int setup_fd = -1; char* dir_path = NULL; char* value_path = NULL; int len; sResGpioDevPath = path; len = asprintf(&dir_path, "%s/direction", path); if (len < 0) { perror("asprintf"); goto bail; } len = asprintf(&value_path, "%s/value", path); if (len < 0) { perror("asprintf"); goto bail; } setup_fd = open(dir_path, O_WRONLY); if (setup_fd >= 0) { if (-1 == write(setup_fd, "high\n", 5)) { perror("set_res_direction"); goto bail; } } sResGpioValueFd = open(value_path, O_WRONLY); bail: if (setup_fd >= 0) { close(setup_fd); } if (dir_path) { free(dir_path); } if (value_path) { free(value_path); } return sResGpioValueFd >= 0; } static void trigger_reset(void) { if (sResGpioValueFd >= 0) { char str[] = { '0' + GPIO_RES_ASSERT_STATE, '\n' }; lseek(sResGpioValueFd, 0, SEEK_SET); if (write(sResGpioValueFd, str, sizeof(str)) == -1) { syslog(LOG_ERR, "trigger_reset(): error on write: %d (%s)", errno, strerror(errno)); } usleep(10 * USEC_PER_MSEC); // Set the string to switch to the not-asserted state. str[0] = '0' + !GPIO_RES_ASSERT_STATE; lseek(sResGpioValueFd, 0, SEEK_SET); if (write(sResGpioValueFd, str, sizeof(str)) == -1) { syslog(LOG_ERR, "trigger_reset(): error on write: %d (%s)", errno, strerror(errno)); } syslog(LOG_NOTICE, "Triggered hardware reset"); } } static bool setup_int_gpio(const char* path) { char* edge_path = NULL; char* dir_path = NULL; char* value_path = NULL; ssize_t len; int setup_fd = -1; sIntGpioValueFd = -1; sIntGpioDevPath = path; len = asprintf(&dir_path, "%s/direction", path); if (len < 0) { perror("asprintf"); goto bail; } len = asprintf(&edge_path, "%s/edge", path); if (len < 0) { perror("asprintf"); goto bail; } len = asprintf(&value_path, "%s/value", path); if (len < 0) { perror("asprintf"); goto bail; } setup_fd = open(dir_path, O_WRONLY); if (setup_fd >= 0) { len = write(setup_fd, "in", 2); if (len < 0) { perror("write"); goto bail; } close(setup_fd); setup_fd = -1; } setup_fd = open(edge_path, O_WRONLY); if (setup_fd >= 0) { len = write(setup_fd, "falling", 7); if (len < 0) { perror("write"); goto bail; } close(setup_fd); setup_fd = -1; } sIntGpioValueFd = open(value_path, O_RDONLY); bail: if (setup_fd >= 0) { close(setup_fd); } if (edge_path) { free(edge_path); } if (dir_path) { free(dir_path); } if (value_path) { free(value_path); } return sIntGpioValueFd >= 0; } /* ------------------------------------------------------------------------- */ /* MARK: Help */ static void print_version(void) { printf("spi-hdlc " SPI_HDLC_VERSION "(" __TIME__ " " __DATE__ ")\n"); printf("Copyright (c) 2016 Nest Labs, All Rights Reserved\n"); } static void print_help(void) { print_version(); const char* help = "\n" "Syntax:\n" "\n" " spi-hdlc [options] <spi-device-path>\n" "\n" "Options:\n" "\n" " --stdio ...................... Use `stdin` and `stdout` for HDLC input and\n" " output. Useful when directly started by the\n" " program that will be using it.\n" #if HAVE_OPENPTY " --pty ........................ Create a pseudoterminal for HDLC input and\n" " output. The path of the newly-created PTY\n" " will be written to `stdout`, followed by a\n" " newline.\n" #endif // HAVE_OPENPTY " -i/--gpio-int[=gpio-path] .... Specify a path to the Linux sysfs-exported\n" " GPIO directory for the `I̅N̅T̅` pin. If not\n" " specified, `spi-hdlc` will fall back to\n" " polling, which is inefficient.\n" " -r/--gpio-reset[=gpio-path] .. Specify a path to the Linux sysfs-exported\n" " GPIO directory for the `R̅E̅S̅` pin.\n" " --spi-mode[=mode] ............ Specify the SPI mode to use (0-3).\n" " --spi-speed[=hertz] .......... Specify the SPI speed in hertz.\n" " --spi-cs-delay[=usec] ........ Specify the delay after C̅S̅ assertion, in usec\n" " --spi-align-allowance[=n] .... Specify the the maximum number of FF bytes to\n" " clip from start of RX frame.\n" " -v/--verbose ................. Increase debug verbosity. (Repeatable)\n" " -h/-?/--help ................. Print out usage information and exit.\n" "\n"; printf("%s", help); } /* ------------------------------------------------------------------------- */ /* MARK: Main Loop */ int main(int argc, char *argv[]) { int i = 0; const char* prog = argv[0]; struct sigaction sigact; static fd_set read_set; static fd_set write_set; static fd_set error_set; struct timeval timeout; int max_fd = -1; enum { ARG_SPI_MODE = 1001, ARG_SPI_SPEED = 1002, ARG_VERBOSE = 1003, ARG_SPI_CS_DELAY = 1004, ARG_SPI_ALIGN_ALLOWANCE = 1005, }; static struct option options[] = { { "stdio", no_argument, &sMode, MODE_STDIO }, { "pty", no_argument, &sMode, MODE_PTY }, { "gpio-int", required_argument, NULL, 'i' }, { "gpio-res", required_argument, NULL, 'r' }, { "verbose", optional_argument, NULL, ARG_VERBOSE }, { "version", no_argument, NULL, 'V' }, { "help", no_argument, NULL, 'h' }, { "spi-mode", required_argument, NULL, ARG_SPI_MODE }, { "spi-speed", required_argument, NULL, ARG_SPI_SPEED }, { "spi-cs-delay",required_argument,NULL, ARG_SPI_CS_DELAY }, { "spi-align-allowance", required_argument, NULL, ARG_SPI_ALIGN_ALLOWANCE }, { NULL, 0, NULL, 0 }, }; if (argc < 2) { print_help(); exit(EXIT_FAILURE); } // ======================================================================== // INITIALIZATION sPreviousHandlerForSIGINT = signal(SIGINT, &signal_SIGINT); sPreviousHandlerForSIGTERM = signal(SIGTERM, &signal_SIGTERM); signal(SIGHUP, &signal_SIGHUP); sigact.sa_sigaction = &signal_critical; sigact.sa_flags = SA_RESTART | SA_SIGINFO | SA_NOCLDWAIT; sigaction(SIGSEGV, &sigact, (struct sigaction *)NULL); sigaction(SIGBUS, &sigact, (struct sigaction *)NULL); sigaction(SIGILL, &sigact, (struct sigaction *)NULL); sigaction(SIGABRT, &sigact, (struct sigaction *)NULL); // ======================================================================== // ARGUMENT PARSING openlog(basename(prog), LOG_PERROR | LOG_PID | LOG_CONS, LOG_DAEMON); setlogmask(setlogmask(0) & LOG_UPTO(sVerbose)); while (1) { int c = getopt_long(argc, argv, "i:r:vVh?", options, NULL); if (c == -1) { break; } else { switch (c) { case 'i': if (!setup_int_gpio(optarg)) { syslog(LOG_ERR, "Unable to setup INT GPIO \"%s\", %s", optarg, strerror(errno)); exit(EXIT_FAILURE); } break; case ARG_SPI_ALIGN_ALLOWANCE: errno = 0; sSpiRxAlignAllowance = atoi(optarg); if (errno != 0 || (sSpiRxAlignAllowance > SPI_RX_ALIGN_ALLOWANCE_MAX)) { syslog(LOG_ERR, "Invalid SPI RX Align Allowance \"%s\" (MAX: %d)", optarg, SPI_RX_ALIGN_ALLOWANCE_MAX); exit(EXIT_FAILURE); } break; case ARG_SPI_MODE: if (!update_spi_mode(atoi(optarg))) { syslog(LOG_ERR, "Unable to set SPI mode to \"%s\", %s", optarg, strerror(errno)); exit(EXIT_FAILURE); } break; case ARG_SPI_SPEED: if (!update_spi_speed(atoi(optarg))) { syslog(LOG_ERR, "Unable to set SPI speed to \"%s\", %s", optarg, strerror(errno)); exit(EXIT_FAILURE); } break; case ARG_SPI_CS_DELAY: sSpiCsDelay = atoi(optarg); syslog(LOG_NOTICE, "SPI CS Delay set to %d usec", sSpiCsDelay); break; case 'r': if (!setup_res_gpio(optarg)) { syslog(LOG_ERR, "Unable to setup RES GPIO \"%s\", %s", optarg, strerror(errno)); exit(EXIT_FAILURE); } break; case 'v': case ARG_VERBOSE: if (sVerbose < LOG_DEBUG) { if (optarg) { sVerbose += atoi(optarg); } else { sVerbose++; } setlogmask(setlogmask(0) | LOG_UPTO(sVerbose)); syslog(sVerbose, "Verbosity set to level %d", sVerbose); } break; case 'V': print_version(); exit(EXIT_SUCCESS); break; case 'h': case '?': print_help(); exit(EXIT_SUCCESS); break; } } } argc -= optind; argv += optind; if (argc >= 1) { if (!setup_spi_dev(argv[0])) { syslog(LOG_ERR, "%s: Unable to open SPI device \"%s\", %s", prog, argv[0], strerror(errno)); exit(EXIT_FAILURE); } argc--; argv++; } if (argc >= 1) { fprintf(stderr, "%s: Unexpected argument \"%s\"\n", prog, argv[0]); exit(EXIT_FAILURE); } if (sSpiDevPath == NULL) { fprintf(stderr, "%s: Missing SPI device path\n", prog); exit(EXIT_FAILURE); } if (sMode == MODE_STDIO) { sHdlcInputFd = dup(STDIN_FILENO); sHdlcOutputFd = dup(STDOUT_FILENO); close(STDIN_FILENO); close(STDOUT_FILENO); } else if (sMode == MODE_PTY) { #if HAVE_OPENPTY static int pty_slave_fd = -1; char pty_name[1024]; sRet = openpty(&sHdlcInputFd, &pty_slave_fd, pty_name, NULL, NULL); if (sRet != 0) { perror("openpty"); goto bail; } sHdlcOutputFd = dup(sHdlcInputFd); printf("%s\n", pty_name); close(STDOUT_FILENO); #else // if HAVE_OPENPTY syslog(LOG_ERR, "Not built with support for `--pty`."); sRet = EXIT_FAILURE; goto bail; #endif // else HAVE_OPENPTY } else { sRet = EXIT_FAILURE; goto bail; } // Set up sHdlcInputFd for non-blocking I/O if (-1 == (i = fcntl(sHdlcInputFd, F_GETFL, 0))) { i = 0; } fcntl(sHdlcInputFd, F_SETFL, i | O_NONBLOCK); // Since there are so few file descriptors in // this program, we calcualte `max_fd` once // instead of trying to optimize its value // at every iteration. max_fd = sHdlcInputFd; if (max_fd < sHdlcOutputFd) { max_fd = sHdlcOutputFd; } if (max_fd < sIntGpioValueFd) { max_fd = sIntGpioValueFd; } if (sIntGpioValueFd < 0) { syslog(LOG_WARNING, "Interrupt pin was not set, must poll SPI. Performance will suffer."); } trigger_reset(); // ======================================================================== // MAIN LOOP while (sRet == 0) { int timeout_ms = MSEC_PER_SEC * 60 * 60 * 24; // 24 hours FD_ZERO(&read_set); FD_ZERO(&write_set); FD_ZERO(&error_set); if (!sSpiTxIsReady) { FD_SET(sHdlcInputFd, &read_set); } else if (sSpiTxFlowControl) { // We are being rate-limited by the NCP. timeout_ms = SPI_POLL_PERIOD_MSEC; syslog(LOG_INFO, "Rate limiting transactions"); } else { // We have data to send to the slave. Unless we // are being rate-limited, proceed immediately. timeout_ms = 0; } if (sSpiRxPayloadSize != 0) { FD_SET(sHdlcOutputFd, &write_set); } else if (sIntGpioValueFd >= 0) { if (check_and_clear_interrupt()) { // Interrupt pin is asserted, // set the timeout to be 0. timeout_ms = 0; syslog(LOG_DEBUG, "Interrupt."); } else { FD_SET(sIntGpioValueFd, &error_set); } } else if (timeout_ms > SPI_POLL_PERIOD_MSEC) { timeout_ms = SPI_POLL_PERIOD_MSEC; } // Calculate the timeout value. timeout.tv_sec = timeout_ms / MSEC_PER_SEC; timeout.tv_usec = (timeout_ms % MSEC_PER_SEC) * USEC_PER_MSEC; // Wait for something to happen. i = select(max_fd + 1, &read_set, &write_set, &error_set, &timeout); // Handle serial input. if (FD_ISSET(sHdlcInputFd, &read_set)) { // Read in the data. if (pull_hdlc() < 0) { sRet = EXIT_FAILURE; break; } } // Handle serial output. if (FD_ISSET(sHdlcOutputFd, &write_set)) { // Write out the data. if (push_hdlc() < 0) { sRet = EXIT_FAILURE; break; } } // Service the SPI port if we can receive // a packet or we have a packet to be sent. if ((sSpiRxPayloadSize == 0) || sSpiTxIsReady) { if (push_pull_spi() < 0) { sRet = EXIT_FAILURE; } } } // ======================================================================== // SHUTDOWN bail: syslog(LOG_NOTICE, "Shutdown. (sRet = %d)", sRet); if (sRet == EXIT_QUIT) { sRet = EXIT_SUCCESS; } else if (sRet == -1) { sRet = EXIT_FAILURE; } return sRet; }
the_stack_data/23576071.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 'islessequal_float2float2.cl' */ source_code = read_buffer("islessequal_float2float2.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, "islessequal_float2float2", &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_float2 *src_0_host_buffer; src_0_host_buffer = malloc(num_elem * sizeof(cl_float2)); for (int i = 0; i < num_elem; i++) src_0_host_buffer[i] = (cl_float2){{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_float2), 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_float2), src_0_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueWriteBuffer' failed\n"); exit(1); } /* Create and init host side src buffer 1 */ cl_float2 *src_1_host_buffer; src_1_host_buffer = malloc(num_elem * sizeof(cl_float2)); for (int i = 0; i < num_elem; i++) src_1_host_buffer[i] = (cl_float2){{2.0, 2.0}}; /* Create and init device side src buffer 1 */ cl_mem src_1_device_buffer; src_1_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_float2), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create source buffer\n"); exit(1); } ret = clEnqueueWriteBuffer(command_queue, src_1_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_float2), src_1_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueWriteBuffer' failed\n"); exit(1); } /* Create host dst buffer */ cl_int2 *dst_host_buffer; dst_host_buffer = malloc(num_elem * sizeof(cl_int2)); memset((void *)dst_host_buffer, 1, num_elem * sizeof(cl_int2)); /* Create device dst buffer */ cl_mem dst_device_buffer; dst_device_buffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY, num_elem *sizeof(cl_int2), 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), &src_1_device_buffer); ret |= clSetKernelArg(kernel, 2, 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_int2), 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_int2)); 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); } /* Free host side src buffer 1 */ free(src_1_host_buffer); /* Free device side src buffer 1 */ ret = clReleaseMemObject(src_1_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/154827770.c
/* * * (C) 2014 David Lettier. * * http://www.lettier.com/ * * NTP client. * * Compiled with gcc version 4.7.2 20121109 (Red Hat 4.7.2-8) (GCC). * * Tested on Linux 3.8.11-200.fc18.x86_64 #1 SMP Wed May 1 19:44:27 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux. * * To compile: $ gcc main.c -o ntpClient.out * * Usage: $ ./ntpClient.out * */ #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #define NTP_TIMESTAMP_DELTA 2208988800ull #define LI(packet) (uint8_t) ((packet.li_vn_mode & 0xC0) >> 6) // (li & 11 000 000) >> 6 #define VN(packet) (uint8_t) ((packet.li_vn_mode & 0x38) >> 3) // (vn & 00 111 000) >> 3 #define MODE(packet) (uint8_t) ((packet.li_vn_mode & 0x07) >> 0) // (mode & 00 000 111) >> 0 void error( char* msg ) { perror( msg ); // Print the error message to stderr. exit( 0 ); // Quit the process. } void printBits(size_t const size, void const * const ptr) { unsigned char *b = (unsigned char*) ptr; unsigned char byte; int i, j; for (i = size-1; i >= 0; i--) { for (j = 7; j >= 0; j--) { byte = (b[i] >> j) & 1; printf("%u", byte); } } puts(""); } int main( int argc, char* argv[ ] ) { int sockfd, n; // Socket file descriptor and the n return result from writing/reading from the socket. int portno = 123; // NTP UDP port number. char* host_name; if (argc == 1) { host_name = "us.pool.ntp.org"; // NTP server host-name. } else { host_name = argv[1]; } printf("Getting time from %s\n", host_name); // Structure that defines the 48 byte NTP packet protocol. typedef struct { uint8_t li_vn_mode; // Eight bits. li, vn, and mode. // li. Two bits. Leap indicator. // vn. Three bits. Version number of the protocol. // mode. Three bits. Client will pick mode 3 for client. uint8_t stratum; // Eight bits. Stratum level of the local clock. uint8_t poll; // Eight bits. Maximum interval between successive messages. uint8_t precision; // Eight bits. Precision of the local clock. uint32_t rootDelay; // 32 bits. Total round trip delay time. uint32_t rootDispersion; // 32 bits. Max error aloud from primary clock source. uint32_t refId; // 32 bits. Reference clock identifier. uint32_t refTm_s; // 32 bits. Reference time-stamp seconds. uint32_t refTm_f; // 32 bits. Reference time-stamp fraction of a second. uint32_t origTm_s; // 32 bits. Originate time-stamp seconds. uint32_t origTm_f; // 32 bits. Originate time-stamp fraction of a second. uint32_t rxTm_s; // 32 bits. Received time-stamp seconds. uint32_t rxTm_f; // 32 bits. Received time-stamp fraction of a second. uint32_t txTm_s; // 32 bits and the most important field the client cares about. Transmit time-stamp seconds. uint32_t txTm_f; // 32 bits. Transmit time-stamp fraction of a second. } ntp_packet; // Total: 384 bits or 48 bytes. // Create and zero out the packet. All 48 bytes worth. ntp_packet packet = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; memset( &packet, 0, sizeof( ntp_packet ) ); // Set the first byte's bits to 00,011,011 for li = 0, vn = 3, and mode = 3. The rest will be left set to zero. *( ( char * ) &packet + 0 ) = 0x1b; // Represents 27 in base 10 or 00011011 in base 2. // Create a UDP socket, convert the host-name to an IP address, set the port number, // connect to the server, send the packet, and then read in the return packet. struct sockaddr_in serv_addr; // Server address data structure. struct hostent *server; // Server data structure. sockfd = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP ); // Create a UDP socket. if ( sockfd < 0 ) error( "ERROR opening socket" ); server = gethostbyname( host_name ); // Convert URL to IP. if ( server == NULL ) error( "ERROR, no such host" ); // Zero out the server address structure. bzero( ( char* ) &serv_addr, sizeof( serv_addr ) ); serv_addr.sin_family = AF_INET; // Copy the server's IP address to the server address structure. bcopy( ( char* )server->h_addr, ( char* ) &serv_addr.sin_addr.s_addr, server->h_length ); // Convert the port number integer to network big-endian style and save it to the server address structure. serv_addr.sin_port = htons( portno ); // Call up the server using its IP address and port number. if ( connect( sockfd, ( struct sockaddr * ) &serv_addr, sizeof( serv_addr) ) < 0 ) error( "ERROR connecting" ); // Send it the NTP packet it wants. If n == -1, it failed. n = write( sockfd, ( char* ) &packet, sizeof( ntp_packet ) ); if ( n < 0 ) error( "ERROR writing to socket" ); // Wait and receive the packet back from the server. If n == -1, it failed. n = read( sockfd, ( char* ) &packet, sizeof( ntp_packet ) ); if ( n < 0 ) error( "ERROR reading from socket" ); // These two fields contain the time-stamp seconds as the packet left the NTP server. // The number of seconds correspond to the seconds passed since 1900. // ntohl() converts the bit/byte order from the network's to host's "endianness". packet.txTm_s = ntohl( packet.txTm_s ); // Time-stamp seconds. packet.txTm_f = ntohl( packet.txTm_f ); // Time-stamp fraction of a second. // Extract the 32 bits that represent the time-stamp seconds (since NTP epoch) from when the packet left the server. // Subtract 70 years worth of seconds from the seconds since 1900. // This leaves the seconds since the UNIX epoch of 1970. // (1900)------------------(1970)**************************************(Time Packet Left the Server) time_t txTm = ( time_t ) ( packet.txTm_s - NTP_TIMESTAMP_DELTA ); // Print the time we got from the server, accounting for local timezone and conversion from UTC time. printf("Time :%s", ctime( ( const time_t* ) &txTm ) ); printf("Ref :%ud\n", packet.refTm_s); printf("Stratum :%04x ", packet.stratum); printBits(sizeof(packet.stratum), &packet.stratum); return 0; }
the_stack_data/132951828.c
#include "stdio.h" #include "stdlib.h" struct node { int data; struct node *prev; int n; struct node *next; struct node *link; }; struct node *head = NULL, *x, *y, *z,*h,*temp,*temp1,*temp2,*temp4; void insert1(); void insert2(); void insert3(); void traversebeg(); void traverseend(int); void sort1(); void search1(); void update1(); void delete(); int count = 0; void create(); void ins_at_beg(); void ins_at_pos(); void del_at_beg(); void del_at_pos(); void traverse(); void search(); void sort(); void update(); void rev_traverse(struct node *p); main() { char choice; printf("Please enter your choice for SINGLE LINKED LIST(s) OR DOUBLY LINKED LIST(d)\n"); scanf(" %c",&choice); if (choice == 's') { int ch; printf("\n SINGLE LINKED LIST \n"); printf("--------------------------------MENU-----------------------------------"); printf("\n 1.Creation \n 2.Insertion at beginning \n 3.Insertion at remaining"); printf("\n 4.Deletion at beginning \n 5.Deletion at remaining \n 6.Traverse"); printf("\n 7.Search\n 8.Sort\n 9.Update\n 10.Reaverse\n 11.Exit\n"); printf("-----------------------------------------------------------------------"); while (1) { printf("\n Please enter your choice:"); scanf("%d", &ch); switch(ch) { case 1: create(); break; case 2: ins_at_beg(); break; case 3: ins_at_pos(); break; case 4: del_at_beg(); break; case 5: del_at_pos(); break; case 6: traverse(); break; case 7: search(); break; case 8: sort(); break; case 9: update(); break; case 10: rev_traverse(head); break; case 11: exit(0); default: printf("Sorry wrong input\n"); } } } else if (choice == 'd') { int ch1; h = NULL; temp = temp1 = NULL; printf("\n DOUBLY LINKED LIST \n"); printf("--------------------------------MENU-----------------------------------"); printf("\n 1.Insert at beginning \n 2.Insert at end\n 3.Insert at remaining"); printf("\n 4.Delete at remaining\n 5.Display from beginning\n 6.Display from end"); printf("\n 7.Search for element\n 8.Sort the list\n 9.Update an element"); printf("\n 10.Exit\n"); printf("-----------------------------------------------------------------------"); while (1) { printf("\n Please enter choice : "); scanf("%d", &ch1); switch (ch1) { case 1: insert1(); break; case 2: insert2(); break; case 3: insert3(); break; case 4: delete(); break; case 5: traversebeg(); break; case 6: temp2 = h; if (temp2 == NULL) printf("\n Error : List empty to display "); else { printf("\n Reverse order of linked list is : "); traverseend(temp2->n); } break; case 7: search1(); break; case 8: sort1(); break; case 9: update1(); break; case 10: exit(0); default: printf("\n Wrong choice menu"); } } } } /* TO create an empty node in double linked list*/ void create1() { int data; temp =(struct node *)malloc(1*sizeof(struct node)); temp->prev = NULL; temp->next = NULL; printf("\n Enter value to node : "); scanf("%d", &data); temp->n = data; count++; } /* TO insert at beginning */ void insert1() { if (h == NULL) { create1(); h = temp; temp1 = h; } else { create1(); temp->next = h; h->prev = temp; h = temp; } } /* To insert at end */ void insert2() { if (h == NULL) { create1(); h = temp; temp1 = h; } else { create1(); temp1->next = temp; temp->prev = temp1; temp1 = temp; } } /* To insert at any position */ void insert3() { int pos, i = 2; printf("\n Enter position to be inserted : "); scanf("%d", &pos); temp2 = h; if ((pos < 1) || (pos >= count + 1)) { printf("\n Position out of range to insert"); return; } if ((h == NULL) && (pos != 1)) { printf("\n Empty list cannot insert other than 1st position"); return; } if ((h == NULL) && (pos == 1)) { create1(); h = temp; temp1 = h; return; } else { while (i < pos) { temp2 = temp2->next; i++; } create1(); temp->prev = temp2; temp->next = temp2->next; temp2->next->prev = temp; temp2->next = temp; } } /* To delete an element */ void delete() { int i = 1, pos; printf("\n Enter position to be deleted : "); scanf("%d", &pos); temp2 = h; if ((pos < 1) || (pos >= count + 1)) { printf("\n Error : Position out of range to delete"); return; } if (h == NULL) { printf("\n Error : Empty list no elements to delete"); return; } else { while (i < pos) { temp2 = temp2->next; i++; } if (i == 1) { if (temp2->next == NULL) { printf("\n Node deleted from list"); free(temp2); temp2 = h = NULL; return; } } if (temp2->next == NULL) { temp2->prev->next = NULL; free(temp2); printf("\n Node deleted from list"); return; } temp2->next->prev = temp2->prev; if (i != 1) temp2->prev->next = temp2->next; /* Might not need this statement if i == 1 check */ if (i == 1) h = temp2->next; printf("\n Node deleted"); free(temp2); } count--; } /* Traverse from beginning */ void traversebeg() { temp2 = h; if (temp2 == NULL) { printf(" List empty to display \n"); return; } printf("\n Linked list elements from begining : "); while (temp2->next != NULL) { printf(" %d ", temp2->n); temp2 = temp2->next; } printf(" %d ", temp2->n); } /* To traverse from end recursively */ void traverseend(int i) { if (temp2 != NULL) { i = temp2->n; temp2 = temp2->next; traverseend(i); printf(" %d ", i); } } /* To search for an element in the list */ void search1() { int data, count = 0; temp2 = h; if (temp2 == NULL) { printf("\n Error : List empty to search for data"); return; } printf("\n Enter value to search : "); scanf("%d", &data); while (temp2 != NULL) { if (temp2->n == data) { printf("\n Data found in %d position",count + 1); return; } else temp2 = temp2->next; count++; } printf("\n Error : %d not found in list", data); } /* To update a node value in the list */ void update1() { int data, data1; printf("\n Enter node data to be updated : "); scanf("%d", &data); printf("\n Enter new data : "); scanf("%d", &data1); temp2 = h; if (temp2 == NULL) { printf("\n Error : List empty no node to update"); return; } while (temp2 != NULL) { if (temp2->n == data) { temp2->n = data1; traversebeg(); return; } else temp2 = temp2->next; } printf("\n Error : %d not found in list to update", data); } /* To sort the linked list */ void sort1() { int i, j, x; temp2 = h; temp4 = h; if (temp2 == NULL) { printf("\n List empty to sort"); return; } for (temp2 = h; temp2 != NULL; temp2 = temp2->next) { for (temp4 = temp2->next; temp4 != NULL; temp4 = temp4->next) { if (temp2->n > temp4->n) { x = temp2->n; temp2->n = temp4->n; temp4->n = x; } } } traversebeg(); } /*Function to create a new single linked list*/ void create() { char c; x = (struct node*)malloc(sizeof(struct node)); printf("\n Enter the data:"); scanf("%d", &x->data); x->link = x; head = x; printf("\n If you wish to continue press y otherwise n:"); scanf(" %c", &c); while (c != 'n') { y = (struct node*)malloc(sizeof(struct node)); printf("\n Enter the data:"); scanf("%d", &y->data); x->link = y; y->link = head; x = y; printf("\n If you wish to continue press y otherwise n:"); scanf(" %c", &c); } } /*Function to insert an element at the begining of the list*/ void ins_at_beg() { x = head; y = (struct node*)malloc(sizeof(struct node)); printf("\n Enter the data:"); scanf("%d", &y->data); while (x->link != head) { x = x->link; } x->link = y; y->link = head; head = y; } /*Function to insert an element at any position the list*/ void ins_at_pos() { struct node *ptr; int c = 1, pos, count = 1; y = (struct node*)malloc(sizeof(struct node)); if (head == NULL) { printf("\n Cannot enter an element at this place"); } printf("\n Enter the data:"); scanf("%d", &y->data); printf("\n Enter the position to be inserted:"); scanf("%d", &pos); x = head; ptr = head; while (ptr->link != head) { count++; ptr = ptr->link; } count++; if (pos > count) { printf("\n OUT OF BOUND"); return; } while (c < pos) { z = x; x = x->link; c++; } y->link = x; z->link = y; } /*Function to delete an element at any begining of the list*/ void del_at_beg() { if (head == NULL) printf("\n List is empty"); else { x = head; y = head; while (x->link != head) { x = x->link; } head = y->link; x->link = head; free(y); } } /*Function to delete an element at any position the list*/ void del_at_pos() { if (head == NULL) printf("\n List is empty"); else { int c = 1, pos; printf("\n Enter the position to be deleted:"); scanf("%d", &pos); x = head; while (c < pos) { y = x; x = x->link; c++; } y->link = x->link; free(x); } } /*Function to display the elements in the list*/ void traverse() { if (head == NULL) printf("\n List is empty"); else { x = head; while (x->link != head) { printf("%d->", x->data); x = x->link; } printf("%d", x->data); } } /*Function to search an element in the list*/ void search() { int search_val, count = 0, flag = 0; printf("\n Enter the element to search\n"); scanf("%d", &search_val); if (head == NULL) printf("\n List is empty nothing to search"); else { x = head; while (x->link != head) { if (x->data == search_val) { printf("\n The element is found at %d", count); flag = 1; break; } count++; x = x->link; } if (flag == 0) { printf("\n Element not found"); } } } /*Function to sort the list in ascending order*/ void sort() { struct node *ptr, *nxt; int temp; if (head == NULL) { printf("\n Empty linkedlist"); } else { ptr = head; while (ptr->link != head) { nxt = ptr->link; while (nxt != head) { if (nxt != head) { if (ptr->data > nxt->data) { temp = ptr->data; ptr->data = nxt->data; nxt->data = temp; } } else { break; } nxt = nxt->link; } ptr = ptr->link; } } } /*Function to update an element at any position the list*/ void update() { struct node *ptr; int search_val; int replace_val; int flag = 0; if (head == NULL) { printf("\n Empty list"); } else { printf("\n Enter the value to be edited\n"); scanf("%d", &search_val); fflush(stdin); printf("\n Enter the value to be replace\n"); scanf("%d", &replace_val); ptr = head; while (ptr->link != head) { if (ptr->data == search_val) { ptr->data = replace_val; flag = 1; break; } ptr = ptr->link; } if (ptr->data == search_val) { ptr->data = replace_val; flag = 1; } if (flag == 1) { printf("\n UPdate sucessful"); } else { printf("\n Update not successful"); } } } /*Function to display the elements of the list in reverse order*/ void rev_traverse(struct node *p) { int i = 0; if (head == NULL) { printf(" Empty linked list\n"); } else { if (p->link != head) { i = p->data; rev_traverse(p->link); printf(" %d", i); } if (p->link == head) { printf(" %d", p->data); } } }
the_stack_data/963134.c
/* * Written by Martin Milata in 2012. * Published under WTFPL, see LICENSE. * */ #define _GNU_SOURCE /* needed for asprintf */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdarg.h> int seecore_message_level = 0; void message(int level, const char *fmt, ...) { va_list ap; if (level > seecore_message_level) return; va_start(ap, fmt); vfprintf(stderr, fmt, ap); fprintf(stderr, "\n"); va_end(ap); } void fail(const char *fmt, ...) { va_list ap; va_start(ap, fmt); fprintf(stderr, "error: "); vfprintf(stderr, fmt, ap); fprintf(stderr, "\n"); va_end(ap); exit(EXIT_FAILURE); } void fail_if(int p, const char *fmt, ...) { va_list ap; if (!p) return; va_start(ap, fmt); fprintf(stderr, "error: "); vfprintf(stderr, fmt, ap); fprintf(stderr, "\n"); va_end(ap); exit(EXIT_FAILURE); } char* xstrdup(const char *s) { if (!s) return NULL; char *d = strdup(s); fail_if(!d, "strdup"); return d; } void* xalloc(size_t size) { void *p = calloc(1, size); fail_if(!p, "calloc"); return p; } char *xsprintf(const char *fmt, ...) { int ret; char *str; va_list ap; va_start(ap, fmt); ret = vasprintf(&str, fmt, ap); va_end(ap); fail_if(ret == -1, "vasprintf"); return str; }
the_stack_data/62637411.c
//--------------------------------------------------------------------- // sorted_snackbar.c // CS223 - Spring 2022 // Ask the user for a list of snacks and store them in alphabetical order // Name: Paige Schaefer // #include <stdio.h> #include <stdlib.h> #include <string.h> struct snack { char name[32]; int quantity; float cost; struct snack* next; }; // Insert a new node to a list (implemented as a linked list). // The new node should store the given properties // Param snacks: the first item in the list (NULL if empty) // Param name: the snack name (max length is 32 characters) // Param quantity: the snack quantity // Param cost: the snack cost // Returns the first item in the list struct snack* insert_sorted(struct snack* snacks, const char* name, int quantity, float cost) { struct snack * new_snack = NULL; new_snack = (struct snack *)malloc(sizeof(struct snack)); if(new_snack == NULL){ printf("Failed to insert element. Out of memory"); exit(1); } strcpy(new_snack -> name,name); new_snack -> cost = cost; new_snack -> quantity = quantity; new_snack -> next = NULL; if(snacks == NULL){ snacks = new_snack; } else if(strcmp(new_snack->name,snacks->name) < 0){ new_snack->next = snacks; snacks = new_snack; } else{ struct snack * current = snacks; while(current->next != NULL){ if(strcmp(current->next->name,new_snack->name)> 0){ new_snack->next = current->next; current->next = new_snack; break; } current = current->next; } if(strcmp(current->name,new_snack->name)< 0){ current->next = new_snack; } } return snacks; } // Delete (e.g. free) all nodes in the given list of snacks // Param snacks: the first node in the list (NULL if empty) void clear(struct snack* snacks) { struct snack* temp; while (snacks != NULL){ temp = snacks; snacks = snacks -> next; free(temp); } } void print(struct snack* snacks){ printf("\n"); for(struct snack * new_snack = snacks; new_snack != NULL; new_snack = new_snack->next){ printf("%s\t cost: $%0.2f \t quantity: %d \n",new_snack->name,new_snack->cost,new_snack->quantity); } } int main() { int numSnacks; printf("Enter a number of snacks: "); scanf(" %d",&numSnacks); struct snack *snackPointer = NULL; char tempName[32]; int tempQuantity; float tempCost; for(int i = 0; i < numSnacks; i++){ printf("Enter a name: "); scanf("%s",tempName); printf("Enter a cost: "); scanf("%f",&tempCost); printf("Enter a quantity: "); scanf("%d",&tempQuantity); snackPointer = insert_sorted(snackPointer,tempName,tempQuantity,tempCost); } printf("\n"); printf("Welcome to Sorted Sally's Snack Bar.\n"); print(snackPointer); return 0; }
the_stack_data/116857.c
// Copyright (c) Open Enclave SDK contributors. // Licensed under the MIT License. extern int debugger_test; extern int is_module_init; void notify_module_done_wrapper(); __attribute__((constructor)) void init_module() { if (!debugger_test) is_module_init = 1; } __attribute__((destructor)) void fini_module() { if (!debugger_test) notify_module_done_wrapper(); } int square(volatile int a) { volatile int r = 0; if (!debugger_test) r = a * a; return r; } int k = 500; int add_with_constant(volatile int a, volatile int b) { volatile int t = 0; if (!debugger_test) t = a + b + k; else t = -1; return t; }
the_stack_data/538739.c
#include<stdio.h> int main(void) { int n1, n2; printf("Digite o primeiro numero: "); scanf("%d", &n1); printf("Digite o segundo numero: "); scanf("%d", &n2); printf("\n"); if(n1 == n2) { printf("Sao iguais"); } if(n1 > n2) { printf("Numero 1 e maior que numero 2"); } if(n2 > n1) { printf("Numero 2 e maior que numero 1"); } return 0; }
the_stack_data/38928.c
//1.insertion in linklist 2.deletion in linklist 3.display 4.search 5.reverse 6.create sorted link list 7.sort existing link list #include <stdio.h> #include <stdlib.h> struct node{int info; struct node *next;}*top=NULL,*ptr,*cur; /*Pairwise swap elements of a given linked list by changing links Given a singly linked list, write a function to swap elements pairwise. For example, if the linked list is 1->2->3->4->5->6->7 then the function should change it to 2->1->4->3->6->5->7, and if the linked list is 1->2->3->4->5->6 then the function should change it to 2->1->4->3->6->5 This problem has been discussed here. The solution provided there swaps data of nodes. If data contains many fields, there will be many swap operations. So changing links is a better idea in general. Following is a C implementation that changes links instead of swapping data.*/ void swap(int *a,int *b) { int temp=*a; *a=*b; *b=temp; } void pair_swap() { cur=top; while(cur!=NULL && cur->next!=NULL) { swap(&cur->info,&cur->next->info); cur=cur->next->next; } } void delete_dulicate_sortedlinklist() { //cur pointing to start of linklist cur=top; //empty link list if(cur==NULL) return ;//comeout of function while(cur->next!=NULL) { if(cur->info==cur->next->info) { ptr=cur->next->next; free(ptr); cur->next=ptr; } else cur=cur->next; } } void delete_duplicate() { struct node *temp; cur=top;//pointing to start of linklist /* Pick elements one by one */ while(cur->next!=NULL && cur!=NULL) { //ptr is equated to cur ptr=cur; while(ptr->next!=NULL) { //if duplicate elemnt found then delete it if(cur->info==ptr->next->info) {//delete of element temp=ptr->next->next; free(ptr->next); ptr->next=temp; } else//move to next element ptr=ptr->next; } cur=cur->next; } } void sort_existing() { struct node *ptr1,*ptr2; ptr1=top; ptr2=top; while(ptr1!=NULL) {ptr2=ptr1; while(ptr2!=NULL) { if(ptr1->info>ptr2->info) { int temp=ptr1->info; ptr1->info=ptr2->info; ptr2->info=temp; } ptr2=ptr2->next; } ptr1=ptr1->next; } } void create_sorted(int n) { ptr=(struct node*)malloc(sizeof(struct node)); ptr->info=n; ptr->next=NULL; if(top==NULL) { top=ptr; } if(ptr->info<top->info) { ptr->next=top; top=ptr; } cur=top; while(cur->next!=NULL) { if(ptr->info<cur->next->info) { if(ptr->info>cur->info) { ptr->next=cur->next; cur->next=ptr; } } cur=cur->next; } } void reverse() { struct node *ptr1,*var=NULL; ptr=top; while(ptr!=NULL) { ptr1=var; var=ptr; ptr=ptr->next; var->next=ptr1; } top=var; } void search_count(int num) { int ct=0; ptr=top; while(ptr!=NULL) { if(ptr->info==num) ct++; ptr=ptr->next; } printf("The number-%d occur %d times",num,ct); } void insert_begin(int n) { ptr=(struct node*)malloc(sizeof(struct node)); ptr->info=n; ptr->next=NULL; if(top==NULL)//list is empty { top=ptr; cur=ptr; } else//list is empty { ptr->next=top; top=ptr; } } void insert_end(int n) { ptr=(struct node*)malloc(sizeof(struct node)); ptr->info=n; ptr->next=NULL; if(top==NULL) { top=ptr; cur=ptr; } else { while(cur->next!=NULL) { cur=cur->next; } cur->next=ptr; cur=ptr; } } void insert_mid(int n,int pos) { ptr=(struct node*)malloc(sizeof(struct node)); ptr->info=n; ptr->next=NULL; { int i=1; cur=top; while(pos!=i+1) { cur=cur->next; i++; } if(pos==i+1) { ptr->next=cur->next; cur->next=ptr; } } } void display() { ptr=top; printf("\nElements are->\n"); while(ptr!=NULL) {printf("%d\t",ptr->info); ptr=ptr->next;} } void delete_begin() {if(top==NULL) printf("\nLIST is Empty"); else { ptr=top; top=top->next; free(ptr); } } void delete_end() { cur=top; while(cur->next->next!=NULL) cur=cur->next; ptr=cur->next->next; cur->next=NULL; free(ptr); } void delete_mid(int pos) {int i=1; cur=top; while(pos!=i+1) { cur=cur->next; i++; } if(pos==i+1) { ptr=cur->next; cur->next=ptr->next; free(ptr); } } int main() { int n,pos,ch,num; char choi,p; do{printf("\n1.Insertion at beginning\n2.Insertion at middle\n3.Insertion at end\n4.Delete from beginning\n5.Delete from end\n6.Delete from middle\n7.Delete duplicate elements\n8.Search and count occurence of number\n9.Reverse list\n10.Sort existing link list\n11.Display\n12.create a sorted linked list\n13.Delete duplicate elements in a sorted linklist\n14.Pairwise swap elements\n=>"); scanf("%d",&ch); if(ch==1) { printf("\nEnter the element->"); scanf("%d",&n); insert_begin(n); } else if(ch==2) { printf("\nEnter the element & position->"); scanf("%d",&n); scanf("%d",&pos); insert_mid(n,pos); } else if(ch==3) { printf("\nEnter the element->"); scanf("%d",&n); insert_end(n); } else if(ch==4) delete_begin(); else if(ch==5) delete_end(); else if(ch==6) { printf("Enter position to delete=>"); scanf("%d",&pos); delete_mid(pos); } else if(ch==7) { delete_duplicate(); display(); } else if(ch==8) { printf("\nEnter the element to search and count occurence->"); scanf("%d",&num); search_count(num); } else if(ch==9) { reverse(); display(); } else if(ch==10) { sort_existing(); display(); } else if(ch==11) display(); else if(ch==12) { do{ printf("\nEnter elments->"); scanf("%d",&n); create_sorted(n); printf("\nAdd more elements(y/n)->"); scanf(" %c",&p);}while(p=='y'); } else if(ch==13) { delete_dulicate_sortedlinklist(); display(); } else if(ch==14) { pair_swap(); display(); } printf("\nDo u wanna contd(y/n)->"); scanf(" %c",&choi); }while(choi=='y'); return 0; }
the_stack_data/170452707.c
/** SOM.c code from https://github.com/tsotne95/SOM/blob/master/som.c (https://github.com/tsotne95/SOM) **/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #define SQR(x) ((x)*(x)) //square struct N_config { int n_in; //capter(data vector) size int n_l_out; // neuron map row number int n_c_out; // neuron map column number int n_out; //total neuron (n_l_out * n_c_out) int nb_it; // iteration number double minAlpha;//starting value int train; //training layer operation num int ftrain; //first layer operation num }N_conf; struct node //neuron (node) struct { double act; //euc. dist. char *etiq; double *w; //weight (memory) vector }; typedef struct node t_node; struct bmu { double act; // euclidian distance int r; int c; }; struct vec { double *arr; char *name; double norm; }; struct vec * array_vec; typedef struct bmu t_bmu; t_bmu *Bmu = NULL; int Bmu_size=1; struct net { int nhd_r; // neighbourhood radius t_node **map; double *captors; // current data vector double alpha; // learning coeficient char *etiq; } Net; void alloc_array_struct(int n) { array_vec=malloc(n*sizeof(struct vec)); int i; for(i=0;i<n;i++) { array_vec[i].arr=malloc(N_conf.n_in*sizeof(double)); array_vec[i].name=malloc(20*sizeof(char)); } } double *aver,*min,*max; void average_vec(int n) { aver=malloc(N_conf.n_in*sizeof(double)); memset(aver,0,N_conf.n_in*sizeof(double)); int i,j; for(i=0;i<N_conf.n_in;i++) { for(j=0;j<n;j++) aver[i]+=array_vec[j].arr[i]; aver[i]/=n; } } void min_vec(double k) { min=malloc(N_conf.n_in*sizeof(double)); int i; for(i=0;i<N_conf.n_in;i++) min[i]=aver[i]-k; } void max_vec(double k) { max=malloc(N_conf.n_in*sizeof(double)); int i; for(i=0;i<N_conf.n_in;i++) max[i]=aver[i]+k; } void norm_array_vec(int i,int size) { double sum=0.; int j; for(j=0;j<size;j++) sum+=SQR(array_vec[i].arr[j]); array_vec[i].norm=sqrt(sum); } void denorm_array_vec(int n) { int i,j; for(i=0;i<n;i++) { for(j=0;j<N_conf.n_in;j++) array_vec[i].arr[j]/=array_vec[i].norm; } } double* init_rand_w() { int i; double k=(double)rand()/RAND_MAX; double *tmp_w=malloc(N_conf.n_in*sizeof(double)); for(i=0;i<N_conf.n_in;i++) { tmp_w[i]=k*(max[i]-min[i])+min[i]; } double norm=0.; for(i=0;i<N_conf.n_in;i++) { norm+=SQR(tmp_w[i]); } for(i=0;i<N_conf.n_in;i++) { tmp_w[i]/=norm; } return tmp_w; } int * index_array; void init_shuffle(int n) { index_array=malloc(sizeof(int)*n); int i; for(i=0;i<n;i++) index_array[i]=i; } void array_shuffle(int n) { int i,r_and,k; srand(time(NULL)); for(i=0;i<n;i++) { r_and=rand()%n; k=index_array[i]; index_array[i]=index_array[r_and]; index_array[r_and]=k; } } double euc_distance(double *a1, double *a2, int n) { double sum=0.; int i; for(i=0;i<n;i++) { sum+=(SQR(a1[i] - a2[i])); } return sqrt(sum); } void calc_alpha(int it_n, int tot_it) { Net.alpha = N_conf.minAlpha * (1 - ((double)it_n/(double)tot_it)); } void update(t_bmu* b_mu) { int nr=Net.nhd_r; int i,j,x1,x2,y1,y2;//top and bottom for(;nr>=0;nr--) { if(b_mu->r-nr<0) x1=0; else x1=b_mu->r-nr; if(b_mu->c-nr<0) y1=0; else y1=b_mu->c-nr; if(b_mu->r+nr>N_conf.n_l_out-1) x2=N_conf.n_l_out-1; else x2=b_mu->r+nr; if(b_mu->c+nr>N_conf.n_c_out-1) y2=N_conf.n_c_out-1; else y2=b_mu->c+nr; for(i=x1;i<=x2;i++) for(j=y1;j<=y2;j++) { int k; for(k=0;k<N_conf.n_in;k++) { Net.map[i][j].w[k]+=Net.alpha*(Net.captors[k]-Net.map[i][j].w[k]); } } } } void init_n_conf() { N_conf.n_l_out=6; N_conf.n_c_out=10; N_conf.n_out=N_conf.n_l_out*N_conf.n_c_out; N_conf.n_in=4; N_conf.nb_it=30000; N_conf.minAlpha=0.7; N_conf.ftrain=N_conf.nb_it/5; N_conf.train=2; } void read_data() { FILE * in; char *str=malloc(sizeof(char)*500); in=fopen("iris.data","r"); int i,j; for(i=0;i<150;i++) { fscanf(in,"%s",str); char *tok=strtok(str,","); for(j=0;j<N_conf.n_in;j++) { array_vec[i].arr[j]=atof(tok); tok=strtok(NULL,","); } if (strcmp(tok, "Iris-setosa") == 0) strcpy(array_vec[i].name,"A"); else if(strcmp(tok,"Iris-versicolor")==0) strcpy(array_vec[i].name,"B"); else strcpy(array_vec[i].name,"C"); norm_array_vec(i,N_conf.n_in); } fclose(in); free(str); } void create_neuron_map() { int i,j; Net.map=malloc(N_conf.n_l_out*sizeof(t_node *)); for(i=0;i<N_conf.n_l_out;i++) { Net.map[i]=malloc(N_conf.n_c_out*sizeof(t_node)); } for(i=0;i<N_conf.n_l_out;i++) { for (j=0;j<N_conf.n_c_out;j++) { Net.map[i][j].w=(double*)malloc(sizeof(double)*N_conf.n_in); Net.map[i][j].w=init_rand_w(); Net.map[i][j].etiq=malloc(20*sizeof(char)); strcpy(Net.map[i][j].etiq, "."); } } } void print_map() { int i,j; for(i=0;i<N_conf.n_l_out;i++) { for(j=0;j<N_conf.n_c_out;j++) { printf("%s ",Net.map[i][j].etiq); } printf("\n"); } } void training() { int i,j,p,u,it; double min_d,dist; Bmu=malloc(sizeof(t_bmu)); for(p=0;p<N_conf.train;p++) { int cur_n_it; if(!p) { cur_n_it=N_conf.ftrain; } else { cur_n_it=N_conf.nb_it-N_conf.ftrain; N_conf.minAlpha=0.07; Net.nhd_r=1; } for(it=0;it<cur_n_it;it++) { calc_alpha(it,cur_n_it); if(it%(N_conf.ftrain/2)==0&&it!=0&&p==0) { Net.nhd_r-=1; } array_shuffle(150); for(u=0;u<150;u++) { Net.captors=array_vec[index_array[u]].arr; min_d=1000.; for(i=0;i<N_conf.n_l_out;i++) { for(j=0;j<N_conf.n_c_out;j++) { dist=euc_distance(Net.captors,Net.map[i][j].w,N_conf.n_in); Net.map[i][j].act=dist; if(dist<min_d) { min_d=dist; if(Bmu_size>1) { Bmu_size=1; Bmu=realloc(Bmu,Bmu_size*sizeof(t_bmu)); } Bmu[0].act=dist; Bmu[0].r=i; Bmu[0].c=j; } else if(dist==min_d) { Bmu_size++; Bmu=realloc(Bmu,Bmu_size*sizeof(t_bmu)); Bmu[Bmu_size-1].act=dist; Bmu[Bmu_size-1].r=i; Bmu[Bmu_size-1].c=j; } } } if(Bmu_size>1) { int t=rand()%(Bmu_size); Bmu[0]=Bmu[t]; } strcpy(Net.map[Bmu[0].r][Bmu[0].c].etiq, array_vec[index_array[u]].name); update(Bmu); } } } } int main() { init_n_conf(); alloc_array_struct(150); read_data(); denorm_array_vec(150); average_vec(150); min_vec(0.005); max_vec(0.005); init_shuffle(150); //create neuron map with random neuron create_neuron_map(); printf("starting map:\n"); print_map(); printf("\n"); Net.nhd_r=6; Net.alpha=0; training(); printf("after:\n"); print_map(); free(aver); free(min); free(max); return 0; }
the_stack_data/62636799.c
/* * program_05_10A.c * * Program to generate a table of prime numbers. */ #include <stdio.h> #include <stdbool.h> int main (void) { int p, d; bool isPrime; for (p = 2; p <= 50; ++p) { isPrime = true; for (d = 2; d < p; ++d) if (p % d == 0) isPrime = false; if (isPrime != false) printf ("%i ", p); } printf ("\n"); return 0; }
the_stack_data/20450792.c
#include <stdio.h> #include <string.h> #include <stdlib.h> typedef struct { char nome[10]; int idade; float altura; }dados_do_usuario; int main(){ dados_do_usuario aluno; printf("Digite seu nome: "); gets(aluno.nome); fflush(stdin); printf("Digite sua idade: "); scanf("%d", &aluno.idade); printf("Digite sua altura: "); scanf("%f", &aluno.altura); printf("Dados do Aluno:\n"); printf("NOME: %s\n", aluno.nome); printf("IDADE: %d\n", aluno.idade); printf("ALTURA: %f\n", aluno.altura); return 0; }
the_stack_data/68560.c
#include <stdio.h> #include <stdlib.h> #include <ctype.h> int top = -1; float eval(char*); void push(int*,int); int pop(int*); int main() { char postfix[10]; printf("Enter postfix expression : "); scanf("%s", postfix); printf("Answer = %f\n", eval(postfix)); } float eval(char *postfix) { int i = 0; int stack[10]; char c; int ans = 0; int op1,op2; while(postfix[i]) { c = postfix[i]; if (c=='+' || c=='-' || c=='/' || c=='*') { op1 = pop(stack); op2 = pop(stack); switch(c) { case '+': { ans = op1+op2; //printf("%d\n",ans); break; } case '-': { ans = op2-op1; break; } case '*': { ans = op1*op2; break; } case '/': { ans = op2/op1; break; } } push(stack,ans); } else { push(stack,c-48); } i+=1; } return pop(stack); } void push(int *s, int val) { top+=1; s[top]=val; } int pop(int *s) { int c = s[top]; top--; return c; }
the_stack_data/147797.c
/* rs.c */ /* This program is an encoder/decoder for Reed-Solomon codes. Encoding is in systematic form, decoding via the Berlekamp iterative algorithm. In the present form , the constants mm, nn, tt, and kk=nn-2tt must be specified (the double letters are used simply to avoid clashes with other n,k,t used in other programs into which this was incorporated!) Also, the irreducible polynomial used to generate GF(2**mm) must also be entered -- these can be found in Lin and Costello, and also Clark and Cain. The representation of the elements of GF(2**m) is either in index form, where the number is the power of the primitive element alpha, which is convenient for multiplication (add the powers modulo 2**m-1) or in polynomial form, where the bits represent the coefficients of the polynomial representation of the number, which is the most convenient form for addition. The two forms are swapped between via lookup tables. This leads to fairly messy looking expressions, but unfortunately, there is no easy alternative when working with Galois arithmetic. The code is not written in the most elegant way, but to the best of my knowledge, (no absolute guarantees!), it works. However, when including it into a simulation program, you may want to do some conversion of global variables (used here because I am lazy!) to local variables where appropriate, and passing parameters (eg array addresses) to the functions may be a sensible move to reduce the number of global variables and thus decrease the chance of a bug being introduced. This program does not handle erasures at present, but should not be hard to adapt to do this, as it is just an adjustment to the Berlekamp-Massey algorithm. It also does not attempt to decode past the BCH bound -- see Blahut "Theory and practice of error control codes" for how to do this. Simon Rockliff, University of Adelaide 21/9/89 26/6/91 Slight modifications to remove a compiler dependent bug which hadn't previously surfaced. A few extra comments added for clarity. Appears to all work fine, ready for posting to net! Notice -------- This program may be freely modified and/or given to whoever wants it. A condition of such distribution is that the author's contribution be acknowledged by his name being left in the comments heading the program, however no responsibility is accepted for any financial or other loss which may result from some unforseen errors or malfunctioning of the program during use. Simon Rockliff, 26th June 1991 */ #include <math.h> #include <stdio.h> #include <stdlib.h> #define mm 8 /* RS code over GF(2**4) - change to suit */ #define nn 255 /* nn=2**mm -1 length of codeword */ #define tt 8 /* number of errors that can be corrected */ #define kk 239 /* kk = nn-2*tt */ static int pp [mm+1] = { 1, 0, 1, 1, 1, 0, 0, 0, 1} ; /* specify irreducible polynomial coeffts */ static int alpha_to [nn+1], index_of [nn+1], gg [nn-kk+1] ; static int recd [nn], data [kk], bb [nn-kk] ; static inited = 0; static void generate_gf() /* generate GF(2**mm) from the irreducible polynomial p(X) in pp[0]..pp[mm] lookup tables: index->polynomial form alpha_to[] contains j=alpha**i; polynomial form -> index form index_of[j=alpha**i] = i alpha=2 is the primitive element of GF(2**mm) */ { register int i, mask ; mask = 1 ; alpha_to[mm] = 0 ; for (i=0; i<mm; i++) { alpha_to[i] = mask ; index_of[alpha_to[i]] = i ; if (pp[i]!=0) alpha_to[mm] ^= mask ; mask <<= 1 ; } index_of[alpha_to[mm]] = mm ; mask >>= 1 ; for (i=mm+1; i<nn; i++) { if (alpha_to[i-1] >= mask) alpha_to[i] = alpha_to[mm] ^ ((alpha_to[i-1]^mask)<<1) ; else alpha_to[i] = alpha_to[i-1]<<1 ; index_of[alpha_to[i]] = i ; } index_of[0] = -1 ; } static void gen_poly() /* Obtain the generator polynomial of the tt-error correcting, length nn=(2**mm -1) Reed Solomon code from the product of (X+alpha**i), i=1..2*tt */ { register int i,j ; gg[0] = 2 ; /* primitive element alpha = 2 for GF(2**mm) */ gg[1] = 1 ; /* g(x) = (X+alpha) initially */ for (i=2; i<=nn-kk; i++) { gg[i] = 1 ; for (j=i-1; j>0; j--) if (gg[j] != 0) gg[j] = gg[j-1]^ alpha_to[(index_of[gg[j]]+i)%nn] ; else gg[j] = gg[j-1] ; gg[0] = alpha_to[(index_of[gg[0]]+i)%nn] ; /* gg[0] can never be zero */ } /* convert gg[] to index form for quicker encoding */ for (i=0; i<=nn-kk; i++) gg[i] = index_of[gg[i]] ; } static void encode_rs() /* take the string of symbols in data[i], i=0..(k-1) and encode systematically to produce 2*tt parity symbols in bb[0]..bb[2*tt-1] data[] is input and bb[] is output in polynomial form. Encoding is done by using a feedback shift register with appropriate connections specified by the elements of gg[], which was generated above. Codeword is c(X) = data(X)*X**(nn-kk)+ b(X) */ { register int i,j ; int feedback ; for (i=0; i<nn-kk; i++) bb[i] = 0 ; for (i=kk-1; i>=0; i--) { feedback = index_of[data[i]^bb[nn-kk-1]] ; if (feedback != -1) { for (j=nn-kk-1; j>0; j--) if (gg[j] != -1) bb[j] = bb[j-1]^alpha_to[(gg[j]+feedback)%nn] ; else bb[j] = bb[j-1] ; bb[0] = alpha_to[(gg[0]+feedback)%nn] ; } else { for (j=nn-kk-1; j>0; j--) bb[j] = bb[j-1] ; bb[0] = 0 ; } ; } ; } ; static void decode_rs() /* assume we have received bits grouped into mm-bit symbols in recd[i], i=0..(nn-1), and recd[i] is index form (ie as powers of alpha). We first compute the 2*tt syndromes by substituting alpha**i into rec(X) and evaluating, storing the syndromes in s[i], i=1..2tt (leave s[0] zero) . Then we use the Berlekamp iteration to find the error location polynomial elp[i]. If the degree of the elp is >tt, we cannot correct all the errors and hence just put out the information symbols uncorrected. If the degree of elp is <=tt, we substitute alpha**i , i=1..n into the elp to get the roots, hence the inverse roots, the error location numbers. If the number of errors located does not equal the degree of the elp, we have more than tt errors and cannot correct them. Otherwise, we then solve for the error value at the error location and correct the error. The procedure is that found in Lin and Costello. For the cases where the number of errors is known to be too large to correct, the information symbols as received are output (the advantage of systematic encoding is that hopefully some of the information symbols will be okay and that if we are in luck, the errors are in the parity part of the transmitted codeword). Of course, these insoluble cases can be returned as error flags to the calling routine if desired. */ { register int i,j,u,q ; int elp[nn-kk+2][nn-kk], d[nn-kk+2], l[nn-kk+2], u_lu[nn-kk+2], s[nn-kk+1] ; int count=0, syn_error=0, root[tt], loc[tt], z[tt+1], err[nn], reg[tt+1] ; /* first form the syndromes */ for (i=1; i<=nn-kk; i++) { s[i] = 0 ; for (j=0; j<nn; j++) if (recd[j]!=-1) s[i] ^= alpha_to[(recd[j]+i*j)%nn] ; /* recd[j] in index form */ /* convert syndrome from polynomial form to index form */ if (s[i]!=0) syn_error=1 ; /* set flag if non-zero syndrome => error */ s[i] = index_of[s[i]] ; } ; if (syn_error) /* if errors, try and correct */ { /* printf("RS: errors detected\n"); */ /* compute the error location polynomial via the Berlekamp iterative algorithm, following the terminology of Lin and Costello : d[u] is the 'mu'th discrepancy, where u='mu'+1 and 'mu' (the Greek letter!) is the step number ranging from -1 to 2*tt (see L&C), l[u] is the degree of the elp at that step, and u_l[u] is the difference between the step number and the degree of the elp. */ /* initialise table entries */ d[0] = 0 ; /* index form */ d[1] = s[1] ; /* index form */ elp[0][0] = 0 ; /* index form */ elp[1][0] = 1 ; /* polynomial form */ for (i=1; i<nn-kk; i++) { elp[0][i] = -1 ; /* index form */ elp[1][i] = 0 ; /* polynomial form */ } l[0] = 0 ; l[1] = 0 ; u_lu[0] = -1 ; u_lu[1] = 0 ; u = 0 ; do { u++ ; if (d[u]==-1) { l[u+1] = l[u] ; for (i=0; i<=l[u]; i++) { elp[u+1][i] = elp[u][i] ; elp[u][i] = index_of[elp[u][i]] ; } } else /* search for words with greatest u_lu[q] for which d[q]!=0 */ { q = u-1 ; while ((d[q]==-1) && (q>0)) q-- ; /* have found first non-zero d[q] */ if (q>0) { j=q ; do { j-- ; if ((d[j]!=-1) && (u_lu[q]<u_lu[j])) q = j ; }while (j>0) ; } ; /* have now found q such that d[u]!=0 and u_lu[q] is maximum */ /* store degree of new elp polynomial */ if (l[u]>l[q]+u-q) l[u+1] = l[u] ; else l[u+1] = l[q]+u-q ; /* form new elp(x) */ for (i=0; i<nn-kk; i++) elp[u+1][i] = 0 ; for (i=0; i<=l[q]; i++) if (elp[q][i]!=-1) elp[u+1][i+u-q] = alpha_to[(d[u]+nn-d[q]+elp[q][i])%nn] ; for (i=0; i<=l[u]; i++) { elp[u+1][i] ^= elp[u][i] ; elp[u][i] = index_of[elp[u][i]] ; /*convert old elp value to index*/ } } u_lu[u+1] = u-l[u+1] ; /* form (u+1)th discrepancy */ if (u<nn-kk) /* no discrepancy computed on last iteration */ { if (s[u+1]!=-1) d[u+1] = alpha_to[s[u+1]] ; else d[u+1] = 0 ; for (i=1; i<=l[u+1]; i++) if ((s[u+1-i]!=-1) && (elp[u+1][i]!=0)) d[u+1] ^= alpha_to[(s[u+1-i]+index_of[elp[u+1][i]])%nn] ; d[u+1] = index_of[d[u+1]] ; /* put d[u+1] into index form */ } } while ((u<nn-kk) && (l[u+1]<=tt)) ; u++ ; if (l[u]<=tt) /* can correct error */ { /* put elp into index form */ for (i=0; i<=l[u]; i++) elp[u][i] = index_of[elp[u][i]] ; /* find roots of the error location polynomial */ for (i=1; i<=l[u]; i++) reg[i] = elp[u][i] ; count = 0 ; for (i=1; i<=nn; i++) { q = 1 ; for (j=1; j<=l[u]; j++) if (reg[j]!=-1) { reg[j] = (reg[j]+j)%nn ; q ^= alpha_to[reg[j]] ; } ; if (!q) /* store root and error location number indices */ { root[count] = i; loc[count] = nn-i ; count++ ; }; } ; if (count==l[u]) /* no. roots = degree of elp hence <= tt errors */ { /* form polynomial z(x) */ for (i=1; i<=l[u]; i++) /* Z[0] = 1 always - do not need */ { if ((s[i]!=-1) && (elp[u][i]!=-1)) z[i] = alpha_to[s[i]] ^ alpha_to[elp[u][i]] ; else if ((s[i]!=-1) && (elp[u][i]==-1)) z[i] = alpha_to[s[i]] ; else if ((s[i]==-1) && (elp[u][i]!=-1)) z[i] = alpha_to[elp[u][i]] ; else z[i] = 0 ; for (j=1; j<i; j++) if ((s[j]!=-1) && (elp[u][i-j]!=-1)) z[i] ^= alpha_to[(elp[u][i-j] + s[j])%nn] ; z[i] = index_of[z[i]] ; /* put into index form */ } ; /* evaluate errors at locations given by error location numbers loc[i] */ for (i=0; i<nn; i++) { err[i] = 0 ; if (recd[i]!=-1) /* convert recd[] to polynomial form */ recd[i] = alpha_to[recd[i]] ; else recd[i] = 0 ; } for (i=0; i<l[u]; i++) /* compute numerator of error term first */ { err[loc[i]] = 1; /* accounts for z[0] */ for (j=1; j<=l[u]; j++) if (z[j]!=-1) err[loc[i]] ^= alpha_to[(z[j]+j*root[i])%nn] ; if (err[loc[i]]!=0) { err[loc[i]] = index_of[err[loc[i]]] ; q = 0 ; /* form denominator of error term */ for (j=0; j<l[u]; j++) if (j!=i) q += index_of[1^alpha_to[(loc[j]+root[i])%nn]] ; q = q % nn ; err[loc[i]] = alpha_to[(err[loc[i]]-q+nn)%nn] ; recd[loc[i]] ^= err[loc[i]] ; /*recd[i] must be in polynomial form */ } } } else /* no. roots != degree of elp => >tt errors and cannot solve */ for (i=0; i<nn; i++) /* could return error flag if desired */ if (recd[i]!=-1) /* convert recd[] to polynomial form */ recd[i] = alpha_to[recd[i]] ; else recd[i] = 0 ; /* just output received codeword as is */ } else /* elp has degree has degree >tt hence cannot solve */ for (i=0; i<nn; i++) /* could return error flag if desired */ if (recd[i]!=-1) /* convert recd[] to polynomial form */ recd[i] = alpha_to[recd[i]] ; else recd[i] = 0 ; /* just output received codeword as is */ } else /* no non-zero syndromes => no errors: output received codeword */ for (i=0; i<nn; i++) if (recd[i]!=-1) /* convert recd[] to polynomial form */ recd[i] = alpha_to[recd[i]] ; else recd[i] = 0 ; } void rsdec_204(unsigned char* data_out, unsigned char* data_in) { int i; if (!inited) { /* generate the Galois Field GF(2**mm) */ generate_gf(); /* compute the generator polynomial for this RS code */ gen_poly(); inited = 1; } /* put the transmitted codeword, made up of data plus parity, in recd[] */ /* parity */ for (i=0; i<204-188; ++i) { recd[i] = data_in[188 + i]; } /* zeroes */ for (i=0; i<255-204; ++i) { recd[204-188 + i] = 0; } /* data */ for (i=0; i<188; ++i) { recd[255-188 + i] = data_in[i]; } for (i=0; i<nn; i++) recd[i] = index_of[recd[i]] ; /* put recd[i] into index form */ /* decode recv[] */ decode_rs() ; /* recd[] is returned in polynomial form */ for (i=0; i<188; ++i) { data_out [i] = recd[255-188 + i]; } } void rsenc_204(unsigned char* data_out, unsigned char* data_in) { int i; if (!inited) { /* generate the Galois Field GF(2**mm) */ generate_gf(); /* compute the generator polynomial for this RS code */ gen_poly(); inited = 1; } /* zeroes */ for (i=0; i<255-204; ++i) { data[i] = 0; } /* data */ for (i=0; i<188; ++i) { data[255-204 + i] = data_in[i]; } encode_rs(); for (i=0; i<188; ++i) { data_out[i] = data_in[i]; } for (i=0; i<204-188; ++i) { data_out[188+i] = bb[i]; } } int main(void) { unsigned char rs_in[204], rs_out[204]; int i, j, k; #ifdef SMALL_PROBLEM_SIZE #define LENGTH 15000 #else #define LENGTH 150000 #endif #ifdef __MINGW32__ #define random() rand() #endif for (i=0; i<LENGTH; ++i) { /* Generate random data */ for (j=0; j<188; ++j) { rs_in[j] = (random() & 0xFF); } rsenc_204(rs_out, rs_in); /* Number of errors to insert */ k = random() & 0x7F; for (j=0; j<k; ++j) { rs_out[random() % 204] = (random() & 0xFF); } rsdec_204(rs_in, rs_out); } return 0; }
the_stack_data/31387916.c
//oddeven1 by zawa-ch. //入力された値の2で割ったあまりを求め、偶数・奇数を判断する #include<stdio.h> int main(void) { int va; //初期化処理 puts("整数を入力してください。\n偶数・奇数を判別します。"); //整数の入力を求める printf("整数 : "); scanf("%d", &va); if (va % 2) //2で割ったあまりを求める(1なら奇数、0なら偶数) printf("%dは奇数です。\n", va); else printf("%dは偶数です。\n", va); return 0; }
the_stack_data/1270661.c
// Amstrong Number // #include<stdio.h> int main() { int n,r,sum=0,temp; printf("enter the number="); scanf("%d",&n); temp=n; while(n>0) { r=n%10; sum=sum+(r*r*r); n=n/10; } if(temp==sum) printf("armstrong number "); else printf("not armstrong number"); return 0; }
the_stack_data/175142365.c
int one() { int x; char y; return -1; } int main() { return -1; }
the_stack_data/1017375.c
#include <stdio.h> int main(int argc, char** argv) { printf("Hello, world!\n"); return 0; }
the_stack_data/237642362.c
#include<stdio.h> int main() { int n,p,k,m,i; p=0; scanf("%d",&n); scanf("%d",&m); scanf("%d",&k); for(i=0;i<n;i++) { p=m+p-(i/k*(2*m/100)); } printf("\n%d",p); return 0; }
the_stack_data/500133.c
/* Chris Long */ /* Version 1.1 */ /* Now does both strings and rings. If the 2nd character in the first argument is an "r" (e.g. -r), it searches for rings; otherwise it looks for strings. A minor error in the listing creation was corrected, and (long)s were added before constant parameters. Ideally, the size of the word list or the length of the words should not have to be specified in advance. /* /* (length)-letter word ring/string program; (word_count) should equal the number of (length)-letter words in your word list, plus 1. This program is likely to run extremely slowly if (word_count) is substantially larger than (15.8)^(length-1) */ #include <stdio.h> #include <string.h> /* Adjust the following to fit your needs. (word_count) is the number of words in our word list; (length) is the length of the words in our word list; (max_answer) is the space allocated for the word rings/strings found */ #define word_count (7365) #define length (4) #define max_answer (400) typedef enum {FALSE,TRUE} boolean; typedef enum {RING,STRING} options; typedef char answer_string[max_answer]; typedef char our_string[length]; typedef long listing_type[word_count][length][2]; typedef our_string word_list_type[word_count]; typedef boolean dup_type[word_count]; /* CURRENT_OPTION stores whether we are looking for rings or strings */ static options current_option; /* ANSWER_STRING is the current (possibly partial) answer string */ static answer_string answer; /* position of M atching word in our list word P osition length of BEST string found so far Current TOTAL */ static long m, p, best, ctotal; /* These are all loop control variables */ long x, y, z, zz; /* This LISTING contains information pertaining to which words start with which letters */ static listing_type listing; /* This is our LIST of (length)-letter WORDs */ static word_list_type word_list; /* This array is used to insure that we aren't trying to DUPlicate a word already used */ static dup_type dups; static boolean in_list(c_string, first, last, n) /* Returns TRUE iff the first n+1 letters of C_STRING start a word in the word list between words in positions (first) and (last), inclusive. This is a simple, but effective, binary search. */ /* FIRST word to check LAST word to check N (+1) is the number of letters to check */ our_string c_string; long first, last, n; { /* L ower U pper letter P osition current comparison STATUS */ long l, u, p, status; l = first; u = last; while ((l <= u)) { m = (l + u) / 2; status = 0; for (p = 0; p <= n; ++p) { if (c_string[p] > word_list[m][p]) { status = 1; break; } if (c_string[p] < word_list[m][p]) { status = 2; break; } } if ((status == 1)) l = m + 1; else if ((status == 2)) u = m - 1; else { return(TRUE); } } return(FALSE); } static void find_ring(current_string, p, best, ctotal, w1, w2) /* Exhaustively tries to extend current_string to find all rings */ /* CURRENT_STRING is the current word string word P osition length of BEST string found so far Current TOTAL */ answer_string current_string; long *p, *best, *ctotal, w1, w2; { /* B egining word E nding word X is a loop control variable TRY is a temporary (length)-letter string, used for checking if words starting with certain letters exist */ our_string try; long b, e, x; for (x = 0; x <= length-2; ++x) { try[x] = current_string[(*p)+x]; } if (!(in_list(try, (long) 1, (long) word_count, (long) length-2))) { return; } if (w1==w2) { for (x = 0;x<=(*p)+length-2; ++x) { printf("%c",current_string[x]); } printf("%c%d\n",' ',(*ctotal)); (*best) = (*ctotal); return; } b = listing[m][length-1][0]; e = listing[m][length-1][1]; for (x = b; x <= e; ++x) { if ((dups[x]) && !(x==w1)) { continue; } dups[x] = TRUE; (*p) = (*p)+1; (*ctotal) = (*ctotal)+1; current_string[(*p)+length-2] = word_list[x][length-1]; find_ring(current_string,&(*p),&(*best),&(*ctotal),w1,x); (*ctotal) = (*ctotal)-1; (*p) = (*p)-1; dups[x] = FALSE; } } static void find_string(current_string, p, best, ctotal) /* Exhaustively tries to extend current_string enough to equal or beat (best) letters */ /* CURRENT_STRING is the current word string word P osition length of BEST string found so far Current TOTAL */ answer_string current_string; long *p, *best, *ctotal; { /* B egining word E nding word X is a loop control variable */ our_string try; long b, e, x; for (x = 0; x <= length-2; ++x) { try[x] = current_string[(*p)+x]; } if (!(in_list(try, (long) 1, (long) word_count, (long) length-2))) { if ((*ctotal) >= (*best)) { for (x = 0;x<=(*p)+length-2; ++x) { printf("%c",current_string[x]); } printf("%c%d\n",' ',(*ctotal)); (*best) = (*ctotal); } return; } b = listing[m][length-1][0]; e = listing[m][length-1][1]; for (x = b; x <= e; ++x) { if ((dups[x])) { continue; } dups[x] = TRUE; (*p) = (*p)+1; (*ctotal) = (*ctotal)+1; current_string[(*p)+length-2] = word_list[x][length-1]; find_string(current_string,&(*p),&(*best),&(*ctotal)); (*ctotal) = (*ctotal)-1; (*p) = (*p)-1; dups[x] = FALSE; } } int main(argc, argv) int argc; char *argv[]; { current_option = STRING; if ((argc>1) && (argv[1][1] == (int)'r')) current_option = RING; if (current_option == RING) printf("%s\n\n", "Looking for rings."); else printf("%s\n\n", "Looking for strings."); /* Read in the word list */ for (x = 1; x <= word_count-1; ++x) { scanf("%s",word_list[x]); dups[x] = FALSE; } /* Make the partial word listing. (listing[x][y][0]) is the position in the word list of the first word that starts with the same (y) letters as word (x) does; (listing[x][y][1]) is the last such word */ for (y = 1; y <= length-1; ++y) { listing[1][y][0] = 1; } for (x = 1; x <= word_count-2; ++x) { for (y = 0; y <= length-1; ++y) { if (word_list[x][y] != word_list[x+1][y]) { z = y+1; break; } } for (y = 1; y <= z-1; ++y) { listing[x+1][y][0] = listing[x][y][0]; } for (y = z; y <= length-1; ++y) { listing[x+1][y][0] = x + 1; } for (y = z; y <= length-1; ++y) { for (zz = listing[x][y][0]; zz <= x; ++zz) { listing[zz][y][1] = x; } } } for (y = 1; y <= length-1; ++y) { for (z = listing[word_count-1][y][0]; z <= word_count-1; ++z) { listing[z][y][1] = word_count-1; } } /* The longest currently known string has length 0 */ best = 0; /* Try all words as the starting word */ for (x = 1; x <= word_count-1; ++x) { for (y = 0; y <= length-1; ++y) { answer[y] = word_list[x][y]; } p=1; ctotal=length; dups[x]=TRUE; if (current_option == RING) find_ring(answer, &(p), &(best), &(ctotal), x, (long) 0); else find_string(answer, &(p), &(best), &(ctotal)); dups[x]=FALSE; } return 0; }
the_stack_data/1030433.c
#include <stdio.h> #include <string.h> int main(int argc, char **argv) // 用c语言解析特殊格式的数据 { FILE *f; char line[1024], cmd[1024]; char *w; int n = 0, l, i; if (argc < 2) { printf("Usage: %s queue_name\n", argv[0]); return -1; } sprintf(cmd, "/usr/sw-mpp/bin/qload -w %s", argv[1]); if ((f = popen(cmd, "r")) == NULL) { printf("0\n"); return 0; } l = strlen(argv[1]); while (fgets(line, 1023, f) != NULL) { if (strncmp(line, "Error:", 6) == 0) break; if (strncmp(line, argv[1], l) != 0) continue; w = strtok(line, " "); for (i = 0; w != NULL; w = strtok(NULL, " ")) { if (w[0] == '\0' || w[0] == 27) continue; i++; if (i == 10) { if(sscanf(w, "%d", &n) != 1) fprintf(stderr, "wrong format %s\n", w); break; } } } fclose(f); printf("%d\n", n); return 0; }
the_stack_data/88026.c
#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/mman.h> #include <errno.h> #include <pthread.h> #include <semaphore.h> // barriera di n threads // mutex e barrier sono implementati tramite due semafori senza nome // vedere anche: // https://github.com/marcotessarotto/exOpSys/tree/master/008.04threads-barrier #define N 10 int count; pthread_barrier_t thread_barrier; sem_t mutex; int number_of_threads = N; void * rendezvous(void * arg) { int s; printf("rendezvous\n"); // https://linux.die.net/man/3/pthread_barrier_wait s = pthread_barrier_wait(&thread_barrier); /* The pthread_barrier_wait() function shall synchronize participating threads at the barrier referenced by barrier. The calling thread shall block until the required number of threads have called pthread_barrier_wait() specifying the barrier. */ printf("critical point\n"); if (sem_wait(&mutex) == -1) { perror("sem_wait"); exit(EXIT_FAILURE); } count++; if (sem_post(&mutex) == -1) { perror("sem_post"); exit(EXIT_FAILURE); } return NULL; } #define CHECK_ERR(a,msg) {if ((a) == -1) { perror((msg)); exit(EXIT_FAILURE); } } #define CHECK_ERR2(a,msg) {if ((a) != 0) { perror((msg)); exit(EXIT_FAILURE); } } int main() { int s; pthread_t threads[N]; s = sem_init(&mutex, 0, // 1 => il semaforo è condiviso tra processi, // 0 => il semaforo è condiviso tra threads del processo 1 // valore iniziale del semaforo ); CHECK_ERR(s,"sem_init") // https://linux.die.net/man/3/pthread_barrier_init s = pthread_barrier_init(&thread_barrier, NULL, N); CHECK_ERR(s,"pthread_barrier_init") for (int i=0; i < number_of_threads; i++) { s = pthread_create(&threads[i], NULL, rendezvous, NULL); CHECK_ERR2(s,"pthread_create") } for (int i=0; i < number_of_threads; i++) { s = pthread_join(threads[i], NULL); CHECK_ERR2(s,"pthread_join") } // https://linux.die.net/man/3/pthread_barrier_init s = pthread_barrier_destroy(&thread_barrier); CHECK_ERR(s,"pthread_barrier_destroy") s = sem_destroy(&mutex); CHECK_ERR(s,"sem_destroy") printf("count expected %d, count obtained %d\n", N, count); printf("bye\n"); return 0; }
the_stack_data/27864.c
// kernel BUG at lib/string.c:LINE! (2) // https://syzkaller.appspot.com/bug?id=94db2e2f55a3e780c88d001422dce7afe647ff03 // status:fixed // autogenerated by syzkaller (http://github.com/google/syzkaller) #define _GNU_SOURCE #include <arpa/inet.h> #include <endian.h> #include <errno.h> #include <fcntl.h> #include <linux/if.h> #include <linux/if_ether.h> #include <linux/if_tun.h> #include <linux/ip.h> #include <linux/tcp.h> #include <net/if_arp.h> #include <sched.h> #include <signal.h> #include <stdarg.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <sys/ioctl.h> #include <sys/prctl.h> #include <sys/resource.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/time.h> #include <sys/uio.h> #include <sys/wait.h> #include <unistd.h> __attribute__((noreturn)) static void doexit(int status) { volatile unsigned i; syscall(__NR_exit_group, status); for (i = 0;; i++) { } } #include <errno.h> #include <setjmp.h> #include <signal.h> #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> const int kFailStatus = 67; const int kRetryStatus = 69; static void fail(const char* msg, ...) { int e = errno; va_list args; va_start(args, msg); vfprintf(stderr, msg, args); va_end(args); fprintf(stderr, " (errno %d)\n", e); doexit((e == ENOMEM || e == EAGAIN) ? kRetryStatus : kFailStatus); } static __thread int skip_segv; static __thread jmp_buf segv_env; static void segv_handler(int sig, siginfo_t* info, void* uctx) { uintptr_t addr = (uintptr_t)info->si_addr; const uintptr_t prog_start = 1 << 20; const uintptr_t prog_end = 100 << 20; if (__atomic_load_n(&skip_segv, __ATOMIC_RELAXED) && (addr < prog_start || addr > prog_end)) { _longjmp(segv_env, 1); } doexit(sig); } static void install_segv_handler() { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = SIG_IGN; syscall(SYS_rt_sigaction, 0x20, &sa, NULL, 8); syscall(SYS_rt_sigaction, 0x21, &sa, NULL, 8); memset(&sa, 0, sizeof(sa)); sa.sa_sigaction = segv_handler; sa.sa_flags = SA_NODEFER | SA_SIGINFO; sigaction(SIGSEGV, &sa, NULL); sigaction(SIGBUS, &sa, NULL); } #define NONFAILING(...) \ { \ __atomic_fetch_add(&skip_segv, 1, __ATOMIC_SEQ_CST); \ if (_setjmp(segv_env) == 0) { \ __VA_ARGS__; \ } \ __atomic_fetch_sub(&skip_segv, 1, __ATOMIC_SEQ_CST); \ } static void use_temporary_dir() { char tmpdir_template[] = "./syzkaller.XXXXXX"; char* tmpdir = mkdtemp(tmpdir_template); if (!tmpdir) fail("failed to mkdtemp"); if (chmod(tmpdir, 0777)) fail("failed to chmod"); if (chdir(tmpdir)) fail("failed to chdir"); } static void vsnprintf_check(char* str, size_t size, const char* format, va_list args) { int rv; rv = vsnprintf(str, size, format, args); if (rv < 0) fail("tun: snprintf failed"); if ((size_t)rv >= size) fail("tun: string '%s...' doesn't fit into buffer", str); } static void snprintf_check(char* str, size_t size, const char* format, ...) { va_list args; va_start(args, format); vsnprintf_check(str, size, format, args); va_end(args); } #define COMMAND_MAX_LEN 128 #define PATH_PREFIX \ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin " #define PATH_PREFIX_LEN (sizeof(PATH_PREFIX) - 1) static void execute_command(bool panic, const char* format, ...) { va_list args; char command[PATH_PREFIX_LEN + COMMAND_MAX_LEN]; int rv; va_start(args, format); memcpy(command, PATH_PREFIX, PATH_PREFIX_LEN); vsnprintf_check(command + PATH_PREFIX_LEN, COMMAND_MAX_LEN, format, args); rv = system(command); if (panic && rv != 0) fail("tun: command \"%s\" failed with code %d", &command[0], rv); va_end(args); } static int tunfd = -1; static int tun_frags_enabled; #define SYZ_TUN_MAX_PACKET_SIZE 1000 #define TUN_IFACE "syz_tun" #define LOCAL_MAC "aa:aa:aa:aa:aa:aa" #define REMOTE_MAC "aa:aa:aa:aa:aa:bb" #define LOCAL_IPV4 "172.20.20.170" #define REMOTE_IPV4 "172.20.20.187" #define LOCAL_IPV6 "fe80::aa" #define REMOTE_IPV6 "fe80::bb" #define IFF_NAPI 0x0010 #define IFF_NAPI_FRAGS 0x0020 static void initialize_tun(void) { tunfd = open("/dev/net/tun", O_RDWR | O_NONBLOCK); if (tunfd == -1) { printf("tun: can't open /dev/net/tun: please enable CONFIG_TUN=y\n"); printf("otherwise fuzzing or reproducing might not work as intended\n"); return; } const int kTunFd = 252; if (dup2(tunfd, kTunFd) < 0) fail("dup2(tunfd, kTunFd) failed"); close(tunfd); tunfd = kTunFd; struct ifreq ifr; memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, TUN_IFACE, IFNAMSIZ); ifr.ifr_flags = IFF_TAP | IFF_NO_PI | IFF_NAPI | IFF_NAPI_FRAGS; if (ioctl(tunfd, TUNSETIFF, (void*)&ifr) < 0) { ifr.ifr_flags = IFF_TAP | IFF_NO_PI; if (ioctl(tunfd, TUNSETIFF, (void*)&ifr) < 0) fail("tun: ioctl(TUNSETIFF) failed"); } if (ioctl(tunfd, TUNGETIFF, (void*)&ifr) < 0) fail("tun: ioctl(TUNGETIFF) failed"); tun_frags_enabled = (ifr.ifr_flags & IFF_NAPI_FRAGS) != 0; execute_command(1, "sysctl -w net.ipv6.conf.%s.accept_dad=0", TUN_IFACE); execute_command(1, "sysctl -w net.ipv6.conf.%s.router_solicitations=0", TUN_IFACE); execute_command(1, "ip link set dev %s address %s", TUN_IFACE, LOCAL_MAC); execute_command(1, "ip addr add %s/24 dev %s", LOCAL_IPV4, TUN_IFACE); execute_command(1, "ip -6 addr add %s/120 dev %s", LOCAL_IPV6, TUN_IFACE); execute_command(1, "ip neigh add %s lladdr %s dev %s nud permanent", REMOTE_IPV4, REMOTE_MAC, TUN_IFACE); execute_command(1, "ip -6 neigh add %s lladdr %s dev %s nud permanent", REMOTE_IPV6, REMOTE_MAC, TUN_IFACE); execute_command(1, "ip link set dev %s up", TUN_IFACE); } #define DEV_IPV4 "172.20.20.%d" #define DEV_IPV6 "fe80::%02hx" #define DEV_MAC "aa:aa:aa:aa:aa:%02hx" static void initialize_netdevices(void) { unsigned i; const char* devtypes[] = {"ip6gretap", "bridge", "vcan", "bond", "veth"}; const char* devnames[] = {"lo", "sit0", "bridge0", "vcan0", "tunl0", "gre0", "gretap0", "ip_vti0", "ip6_vti0", "ip6tnl0", "ip6gre0", "ip6gretap0", "erspan0", "bond0", "veth0", "veth1"}; for (i = 0; i < sizeof(devtypes) / (sizeof(devtypes[0])); i++) execute_command(0, "ip link add dev %s0 type %s", devtypes[i], devtypes[i]); execute_command(0, "ip link add dev veth1 type veth"); for (i = 0; i < sizeof(devnames) / (sizeof(devnames[0])); i++) { char addr[32]; snprintf_check(addr, sizeof(addr), DEV_IPV4, i + 10); execute_command(0, "ip -4 addr add %s/24 dev %s", addr, devnames[i]); snprintf_check(addr, sizeof(addr), DEV_IPV6, i + 10); execute_command(0, "ip -6 addr add %s/120 dev %s", addr, devnames[i]); snprintf_check(addr, sizeof(addr), DEV_MAC, i + 10); execute_command(0, "ip link set dev %s address %s", devnames[i], addr); execute_command(0, "ip link set dev %s up", devnames[i]); } } static void loop(); static void sandbox_common() { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); setpgrp(); setsid(); struct rlimit rlim; rlim.rlim_cur = rlim.rlim_max = 128 << 20; setrlimit(RLIMIT_AS, &rlim); rlim.rlim_cur = rlim.rlim_max = 8 << 20; setrlimit(RLIMIT_MEMLOCK, &rlim); rlim.rlim_cur = rlim.rlim_max = 1 << 20; setrlimit(RLIMIT_FSIZE, &rlim); rlim.rlim_cur = rlim.rlim_max = 1 << 20; setrlimit(RLIMIT_STACK, &rlim); rlim.rlim_cur = rlim.rlim_max = 0; setrlimit(RLIMIT_CORE, &rlim); #define CLONE_NEWCGROUP 0x02000000 if (unshare(CLONE_NEWNS)) { } if (unshare(CLONE_NEWIPC)) { } if (unshare(CLONE_NEWCGROUP)) { } if (unshare(CLONE_NEWUTS)) { } if (unshare(CLONE_SYSVSEM)) { } } static int do_sandbox_none(void) { if (unshare(CLONE_NEWPID)) { } int pid = fork(); if (pid < 0) fail("sandbox fork failed"); if (pid) return pid; sandbox_common(); if (unshare(CLONE_NEWNET)) { } initialize_tun(); initialize_netdevices(); loop(); doexit(1); } uint64_t r[1] = {0xffffffffffffffff}; void loop() { long res; NONFAILING(memcpy((void*)0x200000c0, "/dev/infiniband/rdma_cm", 24)); res = syscall(__NR_openat, 0xffffffffffffff9c, 0x200000c0, 2, 0); if (res != -1) r[0] = res; NONFAILING(memcpy( (void*)0x20000100, "\x10\x00\x00\x00\x00\x00\x00\xfa\x8d\x30\xe8\xc4\x73\x0a\xc8\x2f\xce\xe0" "\x4b\x76\x75\x7e\x26\x11\x1b\x00\x00\x00\x00\x00\x00\x00\x00\xdd\xf1\xbe" "\x51\x48\x6a\x09\x7d\x7d\x98\xc5\xa9\x1c\x73\x9e\xc3\x1b\x5d\xf3\x73\x94" "\x38\xa1\xa4\xbd\xa7\x6e\x16\x4b\xec\x02\xdb\x25\xbc\x6e\xb6\x24\x3e\x7a" "\x06\xb4\xad\xc5\x51\x0d\x2b\x54\xf9\x64\xd2\x7c\xaa\x58\x4b", 87)); NONFAILING(*(uint64_t*)0x20000157 = 0x20000080); NONFAILING(*(uint32_t*)0x20000080 = -1); NONFAILING(*(uint32_t*)0x2000015f = -1); syscall(__NR_write, r[0], 0x20000100, 0x63); } int main() { syscall(__NR_mmap, 0x20000000, 0x1000000, 3, 0x32, -1, 0); install_segv_handler(); use_temporary_dir(); int pid = do_sandbox_none(); int status = 0; while (waitpid(pid, &status, __WALL) != pid) { } return 0; }
the_stack_data/111078169.c
#include <stdio.h> #include <stdlib.h> int main (void) { double d; int c; if (scanf ("%lg", &d) != 0) { printf ("scanf didn't failed\n"); exit (1); } c = getchar (); if (c != ' ') { printf ("c is `%c', not ` '\n", c); exit (1); } return 0; }
the_stack_data/61075060.c
/* Exercise 1 - Calculations Write a C program to input marks of two subjects. Calculate and print the average of the two marks. */ #include <stdio.h> int main() { float mark1,mark2; float tot,avg; //user inputs printf("Input the mark of subject 1- "); scanf("%f",&mark1); printf("\nInput the mark of subject 2- "); scanf("%f",&mark2); tot=mark1+mark2;//calculating the total avg=tot/2;//calculating the average //prinying the average printf("\nAverage marks of subjects- %2.f",avg); return 0; }
the_stack_data/32949830.c
/* Copyright (c) 2015,2016 Jeremy Iverson 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. */ #ifndef _GNU_SOURCE # define _GNU_SOURCE 1 #endif /****************************************************************************/ /*! Pthread configurations. */ /****************************************************************************/ #ifdef USE_THREAD # include <pthread.h> /* pthread library */ # include <sys/syscall.h> /* SYS_gettid */ # include <unistd.h> /* syscall */ # include "common.h" # include "lock.h" /*****************************************************************************/ /* MT-Safe */ /*****************************************************************************/ SBMA_EXTERN int lock_let_int(char const * const func, int const line, char const * const lock_str, pthread_mutex_t * const lock) { int retval; retval = pthread_mutex_unlock(lock); ERRCHK(RETURN, 0 != retval); DL_PRINTF("[%5d] mtx let %s:%d %s (%p)\n", (int)syscall(SYS_gettid), func,\ line, lock_str, (void*)(lock)); RETURN: return retval; } #else /* Required incase USE_THREAD is not defined, so that this is not an empty * translation unit. */ typedef int make_iso_compilers_happy; #endif #ifdef TEST #include <stddef.h> /* NULL */ int main(int argc, char * argv[]) { if (0 == argc || NULL == argv) {} return 0; } #endif
the_stack_data/149409.c
#include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/ip.h> #include <netinet/ip_icmp.h> #include <arpa/inet.h> unsigned short checksum(unsigned short *buf, int bufsz) { unsigned long sum = 0; while (bufsz > 1) { sum += *buf; buf++; bufsz -= 2; } if (bufsz == 1) { sum += *(unsigned char *)buf; } sum = (sum & 0xffff) + (sum >> 16); sum = (sum & 0xffff) + (sum >> 16); return ~sum; } int main(int argc, char *argv[]) { int sock; struct icmphdr hdr; struct sockaddr_in addr; int n; char buf[2000]; struct icmphdr *icmphdrptr; struct iphdr *iphdrptr; if (argc != 2) { printf("usage : %s IPADDR\n", argv[0]); return 1; } addr.sin_family = AF_INET; inet_pton(AF_INET, argv[1], &addr.sin_addr); sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); if (sock < 0) { perror("socket"); return 1; } memset(&hdr, 0, sizeof(hdr)); hdr.type = ICMP_ECHO; hdr.code = 0; hdr.checksum = 0; hdr.un.echo.id = 0; hdr.un.echo.sequence = 0; hdr.checksum = checksum((unsigned short *)&hdr, sizeof(hdr)); n = sendto(sock, (char *)&hdr, sizeof(hdr), 0, (struct sockaddr *)&addr, sizeof(addr)); if (n < 1) { perror("sendto"); return 1; } int on = 1; if (setsockopt(sock, SOL_IP, IP_HDRINCL, &on, sizeof(on)) != 0) { perror("setsockopt"); } memset(buf, 0, sizeof(buf)); n = recv(sock, buf, sizeof(buf), 0); if (n < 1) { perror("recv"); return 1; } iphdrptr = (struct iphdr *)buf; icmphdrptr = (struct icmphdr *)(buf + (iphdrptr->ihl * 4)); if (icmphdrptr->type == ICMP_ECHOREPLY) { printf("received ICMP ECHO REPLY\n"); } else { printf("received ICMP %d\n", icmphdrptr->type); } close(sock); return 0; }
the_stack_data/28872.c
void fence() { asm("sync"); } void lwfence() { asm("lwsync"); } void isync() { asm("isync"); } int __unbuffered_cnt = 0; int __unbuffered_p0_r1 = 0; int __unbuffered_p0_r3 = 0; int __unbuffered_p1_r1 = 0; int __unbuffered_p1_r3 = 0; int __unbuffered_p2_r1 = 0; int __unbuffered_p2_r3 = 0; int x = 0; int y = 0; void *P0(void *arg) { __unbuffered_p0_r1 = 1; y = __unbuffered_p0_r1; fence(); __unbuffered_p0_r3 = 2; y = __unbuffered_p0_r3; // Instrumentation for CPROVER fence(); __unbuffered_cnt++; } void *P1(void *arg) { __unbuffered_p1_r1 = y; fence(); __unbuffered_p1_r3 = 1; x = __unbuffered_p1_r3; // Instrumentation for CPROVER fence(); __unbuffered_cnt++; } void *P2(void *arg) { __unbuffered_p2_r1 = x; lwfence(); __unbuffered_p2_r3 = y; // Instrumentation for CPROVER fence(); __unbuffered_cnt++; } int main() { __CPROVER_ASYNC_0: P0(0); __CPROVER_ASYNC_1: P1(0); __CPROVER_ASYNC_2: P2(0); __CPROVER_assume(__unbuffered_cnt == 3); fence(); // EXPECT:exists __CPROVER_assert( !(y == 2 && __unbuffered_p1_r1 == 2 && __unbuffered_p2_r1 == 1 && __unbuffered_p2_r3 == 0), "Program was expected to be safe for PPC, model checker should have said " "NO.\nThis likely is a bug in the tool chain."); return 0; }
the_stack_data/87030.c
/* * File: Lab9-StringFunc.c * Author: Erik * * Created on April 22, 2015, 9:15 PM */ #include <stdio.h> #include <stdlib.h> int my_strlen(char string[]) { int i = 0; // We keep counting until NULL while (string[i] != '\0'){ i++; } // Return length of string return i; } int my_strcpy(char dest[], char source[]) { int des = my_strlen(dest); int src = my_strlen(source); // Compare length to ensure destination string is larger if (des >= src) { int i; // Loop and copy source string into destination string for (i = 0; source[i] != '\0'; i++) { dest[i] = source[i]; } dest[i] = '\0'; // String was copied, exit with 1 to state success return 1; } else { // Exit with -1 if string is smaller return -1; } } char *my_strcat(char *dest, char *source){ // Dynamically allocate a new string int lendes = my_strlen(dest); int lensrc = my_strlen(source); char *catstr; // Allocate the new string catstr = (char*)malloc(sizeof(char)*(lendes+lensrc+1)); int i; // Cant use my_strcpy since length is less than source for (i = 0; dest+i != '\0'; i++) { catstr+=i; catstr = dest+i; } catstr-=i; // Continue from first string for (i = lendes; i < (lendes+lensrc); i++){ catstr+=i; catstr = source+(i-lendes); } // Terminate string catstr+=(1); catstr = '\0'; // Pass the pointer to the new string return catstr; } void my_strreverse(char *string) { int length, c; char *begin, *end, temp; // Get length of string length = my_strlen(string); // Initialize pointer swappers begin = string; end = string; // Set the end pointer to the end end+= length-1; // Begin swap up to the middle for (c = 0; c < length/2; c++) { // Temp store end so we don't lose it, then lets swap! temp = *end; *end = *begin; *begin = temp; // Move forwards from beginning backwards on end begin++; end--; } } int main() { // String length function test section int stringlen = 0; char strCopyOne[] = "This string is long enough to accept the second string"; char strCopyTwo[] = "This string is short enough"; stringlen = my_strlen(strCopyOne); printf("Test string one: %s \nTest string one is %i characters long\n", strCopyOne, stringlen); stringlen = my_strlen(strCopyTwo); printf("Test string two: %s \nTest string two is %i characters long\n", strCopyTwo, stringlen); // String copy function test section char strCopyFail[] = "This string is too long to copy from"; int copySuccess = 0; printf("\nPASS\nString to copy into: %s\nString to copy from: %s\n", strCopyOne, strCopyTwo); copySuccess = my_strcpy(strCopyOne, strCopyTwo); printf("Copy function success: %i\nCopy function result: %s\n", copySuccess, strCopyOne); printf("\nFAIL\nString to copy into: %s\nString to copy from: %s\n", strCopyTwo, strCopyFail); copySuccess = my_strcpy(strCopyTwo, strCopyFail); printf("Copy function success: %i\nCopy function result: %s\n", copySuccess, strCopyTwo); // String concatenation function test section // Declare pointer to place concatenated string into char *catString; char stringCatOne[] = "Hello "; char stringCatTwo[] = "World!"; printf("\nStrings to concatenate\nString One: %s\nString Two: %s\n", stringCatOne, stringCatTwo); catString = my_strcat(stringCatOne, stringCatTwo); printf("Results of concatenated string: %s\n", catString); free((void*)catString); // Good habit to free allocated pointers // String reverse function test section char stringToRev[] = "I am not a palindrome"; printf("\nString to reverse: %s\n", stringToRev); my_strreverse(stringToRev); printf("Reversed string: %s\n", stringToRev); return (0); }
the_stack_data/168892476.c
/* * Programação de Computadores e Algoritmos * Trabalho 1 * Questão 2.7 * Equipe: Benjamin Borges * Davi Tavares * Manoel Souza * Lucas Botinelly * Jackson Gomes * Robson Borges * Grupo 1 - */ #include <stdio.h> int main(int argc, const char *argv[]) { int a, b, c; printf("Digite um numero: \n"); scanf("%d", &a); printf("Digite outro numero: \n"); scanf("%d", &b); printf("Digite outro numero: \n"); scanf("%d", &c); if (a<b && a<c) { printf("%d", a); } else if(b<a && b<c) { printf("%d", b); } else if(c<a && c<b) { printf("%d", c); } return 0; }
the_stack_data/727935.c
/* Header Files stdio.h - For output sys/sysinfo.h - For system information such as load time.h - for time and ctime */ #include <stdio.h> #include <sys/sysinfo.h> #include <time.h> /* Main Function */ int main() { /* Variables Reference: http://man7.org/linux/man-pages/man2/sysinfo.2.html */ struct sysinfo sinfo; int days, hours, mins, secs; float loads0, loads1, loads2; time_t t = time(NULL); /* Return struct. In this case, &t is datatype of time_t. Reference to localtime and struct tm: http://pubs.opengroup.org/onlinepubs/7908799/xsh/time.h.html */ struct tm *string_time = localtime(&t); if(sysinfo(&sinfo) == 0) { /* Converstions to readable format */ days = sinfo.uptime / 86400; hours = (sinfo.uptime / 3600) - (days * 24); mins = (sinfo.uptime / 60) - (days * 1440) - (hours * 60); secs = sinfo.uptime % 60; /* Conversion of average load 1, 5 and 15 mins */ loads0 = (float) sinfo.loads[0] / (1 << SI_LOAD_SHIFT); loads1 = (float) sinfo.loads[1] / (1 << SI_LOAD_SHIFT); loads2 = (float) sinfo.loads[2] / (1 << SI_LOAD_SHIFT); /* Print details to screen */ printf("%02d:%02d:%02d up %u days, %dh:%dm:%ds, load average: %.2f, %.2f, %.2f\n",string_time->tm_hour, string_time->tm_min, string_time->tm_sec, days, hours, mins, secs, loads0, loads1, loads2); /* Success return code */ return 0; } else { /* Fault return code */ return 1; } }