diff --git a/.gitignore b/.gitignore index 400befc8..f5f20051 100644 --- a/.gitignore +++ b/.gitignore @@ -18,4 +18,5 @@ tags \#*\# *vcd r -.#* \ No newline at end of file +.#* +subprojects/tomlplusplus-3.3.0 \ No newline at end of file diff --git a/Inc/ext_fileformats.h b/Inc/ext_fileformats.h index cc06f7e8..10894a38 100644 --- a/Inc/ext_fileformats.h +++ b/Inc/ext_fileformats.h @@ -22,8 +22,7 @@ extern "C" { /* Execution of an instruction. We maintain a lot of information, but it's a PC, so we've got the room :-) */ -struct execEntryHash -{ +struct execEntryHash { /* The address in the memory map of the target */ uint32_t addr; uint32_t codes; @@ -51,22 +50,19 @@ struct execEntryHash /* Signature for a source/dest calling pair */ -struct subcallSig -{ +struct subcallSig { uint32_t src; /* Where the call is from */ uint32_t dst; /* Where the call is to */ }; -struct subcallAccount -{ +struct subcallAccount { struct subcallSig sig; uint64_t inTicks; bool tailChained; }; /* Processed subcalls from routine to routine */ -struct subcall -{ +struct subcall { struct subcallSig sig; /* Calling and called side record, forming an index entry */ struct execEntryHash *srch; /* Calling side */ diff --git a/Inc/external/cJSON.h b/Inc/external/cJSON.h index c514141b..4765c79b 100644 --- a/Inc/external/cJSON.h +++ b/Inc/external/cJSON.h @@ -99,8 +99,7 @@ then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJ #define cJSON_StringIsConst 512 /* The cJSON structure: */ -typedef struct cJSON -{ +typedef struct cJSON { /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */ struct cJSON *next; struct cJSON *prev; @@ -121,8 +120,7 @@ typedef struct cJSON char *string; } cJSON; -typedef struct cJSON_Hooks -{ +typedef struct cJSON_Hooks { /* malloc/free are CDECL on Windows regardless of the default calling convention of the compiler, so ensure the hooks allow passing those functions directly. */ void *( CJSON_CDECL *malloc_fn )( size_t sz ); void ( CJSON_CDECL *free_fn )( void *ptr ); diff --git a/Inc/external/uthash.h b/Inc/external/uthash.h index 0fd9de22..725d274e 100644 --- a/Inc/external/uthash.h +++ b/Inc/external/uthash.h @@ -774,7 +774,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } \ _ha_head->hh_head = (addhh); \ if ((_ha_head->count >= ((_ha_head->expand_mult + 1U) * HASH_BKT_CAPACITY_THRESH)) \ - && !(addhh)->tbl->noexpand) { \ + && !(addhh)->tbl->noexpand) { \ HASH_EXPAND_BUCKETS(addhh,(addhh)->tbl, oomed); \ IF_HASH_NONFATAL_OOM( \ if (oomed) { \ @@ -984,8 +984,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. if ((src) != NULL) { \ for (_src_bkt=0; _src_bkt < (src)->hh_src.tbl->num_buckets; _src_bkt++) { \ for (_src_hh = (src)->hh_src.tbl->buckets[_src_bkt].hh_head; \ - _src_hh != NULL; \ - _src_hh = _src_hh->hh_next) { \ + _src_hh != NULL; \ + _src_hh = _src_hh->hh_next) { \ _elt = ELMT_FROM_HH((src)->hh_src.tbl, _src_hh); \ if (cond(_elt)) { \ IF_HASH_NONFATAL_OOM( int _hs_oomed = 0; ) \ @@ -1054,19 +1054,18 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifdef NO_DECLTYPE #define HASH_ITER(hh,head,el,tmp) \ for(((el)=(head)), ((*(char**)(&(tmp)))=(char*)((head!=NULL)?(head)->hh.next:NULL)); \ - (el) != NULL; ((el)=(tmp)), ((*(char**)(&(tmp)))=(char*)((tmp!=NULL)?(tmp)->hh.next:NULL))) + (el) != NULL; ((el)=(tmp)), ((*(char**)(&(tmp)))=(char*)((tmp!=NULL)?(tmp)->hh.next:NULL))) #else #define HASH_ITER(hh,head,el,tmp) \ for(((el)=(head)), ((tmp)=DECLTYPE(el)((head!=NULL)?(head)->hh.next:NULL)); \ - (el) != NULL; ((el)=(tmp)), ((tmp)=DECLTYPE(el)((tmp!=NULL)?(tmp)->hh.next:NULL))) + (el) != NULL; ((el)=(tmp)), ((tmp)=DECLTYPE(el)((tmp!=NULL)?(tmp)->hh.next:NULL))) #endif /* obtain a count of items in the hash */ #define HASH_COUNT(head) HASH_CNT(hh,head) #define HASH_CNT(hh,head) ((head != NULL)?((head)->hh.tbl->num_items):0U) -typedef struct UT_hash_bucket -{ +typedef struct UT_hash_bucket { struct UT_hash_handle *hh_head; unsigned count; @@ -1090,8 +1089,7 @@ typedef struct UT_hash_bucket #define HASH_SIGNATURE 0xa0111fe1u #define HASH_BLOOM_SIGNATURE 0xb12220f2u -typedef struct UT_hash_table -{ +typedef struct UT_hash_table { UT_hash_bucket *buckets; unsigned num_buckets, log2_num_buckets; unsigned num_items; @@ -1124,8 +1122,7 @@ typedef struct UT_hash_table } UT_hash_table; -typedef struct UT_hash_handle -{ +typedef struct UT_hash_handle { struct UT_hash_table *tbl; void *prev; /* prev element in app order */ void *next; /* next element in app order */ diff --git a/Inc/itmDecoder.h b/Inc/itmDecoder.h index bc4b37f0..da15fa69 100644 --- a/Inc/itmDecoder.h +++ b/Inc/itmDecoder.h @@ -20,8 +20,7 @@ extern "C" { #endif /* Hardware event numbers (used for the event fifo) */ -enum hwEvents -{ +enum hwEvents { HWEVENT_TS, HWEVENT_EXCEPTION, HWEVENT_PCSample, @@ -34,8 +33,7 @@ enum hwEvents }; /* Exception events */ -enum ExceptionEvents -{ +enum ExceptionEvents { EXEVENT_UNKNOWN, EXEVENT_ENTER, EXEVENT_EXIT, @@ -56,8 +54,7 @@ enum ITMPacketType }; /* Events from the process of pumping bytes through the ITM decoder */ -enum ITMPumpEvent -{ +enum ITMPumpEvent { ITM_EV_NONE, ITM_EV_PACKET_RXED, ITM_EV_UNSYNCED, @@ -67,8 +64,7 @@ enum ITMPumpEvent }; /* Internal states of the protocol machine */ -enum _protoState -{ +enum _protoState { ITM_UNSYNCED, ITM_IDLE, ITM_TS, diff --git a/Inc/loadelf.h b/Inc/loadelf.h index 1695cd34..9c964e47 100644 --- a/Inc/loadelf.h +++ b/Inc/loadelf.h @@ -4,18 +4,21 @@ #include #include +#ifdef __cplusplus +extern "C" { +#endif + typedef unsigned long int symbolMemaddr; typedef unsigned char *symbolMemptr; #define MEMADDRF "%08lx" -#define NO_LINE (-1) -#define NO_FILE (-1) -#define NO_DESTADDRESS (-1) -#define NO_ADDRESS (-1) +#define NO_LINE ((uint32_t)(-1)) +#define NO_FILE ((uint32_t)(-1)) +#define NO_DESTADDRESS ((uint32_t)(-1)) +#define NO_ADDRESS ((uint32_t)(-1)) /* Structure for a memory segment */ -struct symbolMemoryStore -{ +struct symbolMemoryStore { symbolMemaddr start; /* Low address of the memory segment */ symbolMemaddr len; /* Length of the memory segment */ char *name; /* Name of the segment as defined by the linker */ @@ -24,8 +27,7 @@ struct symbolMemoryStore /* Structure for a line memory region identified in the image */ -struct symbolLineStore -{ +struct symbolLineStore { unsigned int filename; /* Filename index for this line */ unsigned int startline; /* First line in source code covered by this line region */ bool isinline; @@ -35,8 +37,7 @@ struct symbolLineStore }; /* Structure for a Function identified in the image */ -struct symbolFunctionStore -{ +struct symbolFunctionStore { char *funcname; /* What is the name of the function */ unsigned int producer; /* What code/options produced it? */ unsigned int filename; /* What filename + path off the source root? */ @@ -50,8 +51,7 @@ struct symbolFunctionStore unsigned int nlines; /* Number of lines in line number storage */ }; -struct symbolSourcecodeStore -{ +struct symbolSourcecodeStore { char **linetext; /* Table of text lines in this file */ @@ -60,8 +60,7 @@ struct symbolSourcecodeStore enum symbolTables { PT_PRODUCER, PT_FILENAME, PT_NUMTABLES }; -struct symbol -{ +struct symbol { char **stringTable[PT_NUMTABLES]; /* Strings that we don't want to duplicate, so we give them an index */ unsigned int tableLen[PT_NUMTABLES]; /* Number of strings for each of the deduplication tables */ @@ -76,14 +75,19 @@ struct symbol struct symbolLineStore **line; /* Table of source code address indexes, sorted by start address */ unsigned int nlines; /* Number of lines in source code line table */ - unsigned int cachedSearchIndex; /* Cached memory search region, to speed up memory fetches */ + int cachedSearchIndex; /* Cached memory search region, to speed up memory fetches */ int fd; /* Handle that we read elf from */ csh caphandle; }; -enum instructionClass { LE_IC_NONE, LE_IC_JUMP = ( 1 << 0 ), LE_IC_4BYTE = ( 1 << 1 ), LE_IC_CALL = ( 1 << 2 ), LE_IC_IMMEDIATE = ( 1 << 3 ), LE_IC_IRET = ( 1 << 4 ) }; +#define LE_IC_NONE 0 +#define LE_IC_JUMP ( 1 << 0 ) +#define LE_IC_4BYTE ( 1 << 1 ) +#define LE_IC_CALL ( 1 << 2 ) +#define LE_IC_IMMEDIATE ( 1 << 3 ) +#define LE_IC_IRET ( 1 << 4 ) // ==================================================================================================== @@ -115,7 +119,7 @@ const char *symbolGetFilename( struct symbol *p, unsigned int index ); symbolMemptr symbolCodeAt( struct symbol *p, symbolMemaddr addr, unsigned int *len ); /* Return assembly code representing this line, with annotations */ -char *symbolDisassembleLine( struct symbol *p, enum instructionClass *ic, symbolMemaddr addr, symbolMemaddr *newaddr ); +char *symbolDisassembleLine( struct symbol *p, int *ic, symbolMemaddr addr, symbolMemaddr *newaddr ); /* Delete symbol set */ void symbolDelete( struct symbol *p ); @@ -128,4 +132,7 @@ bool symbolSetValid( struct symbol *p ); // ==================================================================================================== +#ifdef __cplusplus +} +#endif #endif diff --git a/Inc/msgDecoder.h b/Inc/msgDecoder.h index 34ca366b..36aa8b66 100644 --- a/Inc/msgDecoder.h +++ b/Inc/msgDecoder.h @@ -11,8 +11,7 @@ extern "C" { #include /* Do not change the order of existing message types! */ -enum MSGType -{ +enum MSGType { MSG_UNKNOWN, MSG_RESERVED, MSG_ERROR, @@ -33,14 +32,12 @@ enum MSGType }; /* Generic message with no content */ -struct genericMsg -{ +struct genericMsg { enum MSGType msgtype; uint64_t ts; }; -struct TSMsg -{ +struct TSMsg { enum MSGType msgtype; uint64_t ts; uint8_t timeStatus; @@ -48,8 +45,7 @@ struct TSMsg }; /* Software message */ -struct swMsg -{ +struct swMsg { enum MSGType msgtype; uint64_t ts; uint8_t srcAddr; @@ -58,8 +54,7 @@ struct swMsg }; /* NISYNC message */ -struct nisyncMsg -{ +struct nisyncMsg { enum MSGType msgtype; uint64_t ts; uint8_t type; @@ -67,8 +62,7 @@ struct nisyncMsg }; /* PC sample message */ -struct pcSampleMsg -{ +struct pcSampleMsg { enum MSGType msgtype; uint64_t ts; bool sleep; @@ -76,8 +70,7 @@ struct pcSampleMsg }; /* offset write message */ -struct oswMsg -{ +struct oswMsg { enum MSGType msgtype; uint64_t ts; uint8_t comp; @@ -85,8 +78,7 @@ struct oswMsg }; /* watchpoint */ -struct wptMsg -{ +struct wptMsg { enum MSGType msgtype; uint64_t ts; uint8_t comp; @@ -94,8 +86,7 @@ struct wptMsg }; /* watch pointer */ -struct watchMsg -{ +struct watchMsg { enum MSGType msgtype; uint64_t ts; uint8_t comp; @@ -104,16 +95,14 @@ struct watchMsg }; /* DWT event */ -struct dwtMsg -{ +struct dwtMsg { enum MSGType msgtype; uint64_t ts; uint8_t event; }; /* Exception */ -struct excMsg -{ +struct excMsg { enum MSGType msgtype; uint64_t ts; uint32_t exceptionNumber; @@ -121,11 +110,9 @@ struct excMsg }; -struct msg -{ +struct msg { /* ...all the possible types of message that could be conveyed */ - union - { + union { struct genericMsg genericMsg; struct swMsg swMsg; struct nisyncMsg nisyncMsg; diff --git a/Inc/orblcd_protocol.h b/Inc/orblcd_protocol.h index 30fa8081..625a0a4c 100644 --- a/Inc/orblcd_protocol.h +++ b/Inc/orblcd_protocol.h @@ -1,6 +1,10 @@ #ifndef _ORBLCD_PROTOCOL_H_ #define _ORBLCD_PROTOCOL_H_ +#ifdef __cplusplus +extern "C" { +#endif + #define LCD_DATA_CHANNEL (28) #define LCD_COMMAND_CHANNEL (LCD_DATA_CHANNEL+1) @@ -30,4 +34,7 @@ #define ORBLCD_CLOSE_SCREEN (ORBLCD_ENCODE_C(ORBLCD_CMD_CLOSE_SCREEN)) #define ORBLCD_CLEAR (ORBLCD_ENCODE_C(ORBLCD_CMD_CLEAR)) +#ifdef __cplusplus +} +#endif #endif diff --git a/Inc/orbtraceIf.h b/Inc/orbtraceIf.h index cbf1a0f5..92c66b8c 100644 --- a/Inc/orbtraceIf.h +++ b/Inc/orbtraceIf.h @@ -47,15 +47,13 @@ enum Channel {CH_VTREF, CH_VTPWR, CH_MAX, CH_NONE, CH_ALL = 0xff}; { "all" , CH_ALL }, \ { NULL , CH_NONE } \ -struct OrbtraceInterfaceType -{ +struct OrbtraceInterfaceType { int vid; int pid; enum ORBTraceDevice devtype; }; -struct OrbtraceIfDevice -{ +struct OrbtraceIfDevice { char *sn; char *manufacturer; char *product; @@ -70,15 +68,13 @@ struct OrbtraceIfDevice const struct OrbtraceInterfaceType *type; }; -struct dataBlock -{ +struct dataBlock { ssize_t fillLevel; /* How full this block is */ uint8_t buffer[USB_TRANSFER_SIZE]; /* Block buffer */ struct libusb_transfer *usbtfr; /* USB Transfer handle */ }; -struct OrbtraceIf -{ +struct OrbtraceIf { int activeDevice; /* Number in the list of devices of the active device */ libusb_device_handle *handle; libusb_device *dev; /* usb handle for currently active device (or NULL for non active) */ @@ -91,7 +87,7 @@ struct OrbtraceIf uint8_t ep; /* Endpoint used for data transfer */ uint8_t iface; /* ...and the interface */ - int numDevices; /* Number of matching devices found */ + unsigned int numDevices; /* Number of matching devices found */ struct OrbtraceIfDevice *devices; /* List of matching devices found */ }; // ==================================================================================================== @@ -99,23 +95,23 @@ struct OrbtraceIf int OrbtraceIfValidateVoltage( struct OrbtraceIf *o, int vmv ); /* Device access */ -static inline char *OrbtraceIfGetManufacturer( struct OrbtraceIf *o, unsigned int e ) +static inline const char *OrbtraceIfGetManufacturer( struct OrbtraceIf *o, unsigned int e ) { return ( ( e < o->numDevices ) && ( o->devices[e].manufacturer ) ) ? o->devices[e].manufacturer : ""; } -static inline char *OrbtraceIfGetProduct( struct OrbtraceIf *o, unsigned int e ) +static inline const char *OrbtraceIfGetProduct( struct OrbtraceIf *o, unsigned int e ) { return ( ( e < o->numDevices ) && ( o->devices[e].product ) ) ? o->devices[e].product : ""; } static inline enum ORBTraceDevice OrbtraceIfGetDevtype( struct OrbtraceIf *o, unsigned int e ) { - return ( ( e < o->numDevices ) && ( o->devices[e].devtype ) ) ? o->devices[e].devtype : 0; + return ( ( e < o->numDevices ) && ( o->devices[e].devtype ) ) ? o->devices[e].devtype : DEVICE_NULL; } -static inline char *OrbtraceIfGetVersion( struct OrbtraceIf *o, unsigned int e ) +static inline const char *OrbtraceIfGetVersion( struct OrbtraceIf *o, unsigned int e ) { return ( ( e < o->numDevices ) && ( o->devices[e].version ) ) ? o->devices[e].version : ""; } -static inline char *OrbtraceIfGetSN( struct OrbtraceIf *o, unsigned int e ) +static inline const char *OrbtraceIfGetSN( struct OrbtraceIf *o, unsigned int e ) { return ( ( e < o->numDevices ) && ( o->devices[e].sn ) ) ? o->devices[e].sn : ""; } @@ -144,7 +140,7 @@ static inline libusb_device_handle *OrbtraceIfGetHandle( struct OrbtraceIf *o ) int OrbtraceIfGetDeviceList( struct OrbtraceIf *o, char *sn, uint32_t devmask ); void OrbtraceIfListDevices( struct OrbtraceIf *o ); int OrbtraceIfSelectDevice( struct OrbtraceIf *o ); -bool OrbtraceIfOpenDevice( struct OrbtraceIf *o, int entry ); +bool OrbtraceIfOpenDevice( struct OrbtraceIf *o, unsigned int entry ); bool OrbtraceGetIfandEP( struct OrbtraceIf *o ); void OrbtraceIfCloseDevice( struct OrbtraceIf *o ); enum Channel OrbtraceIfNameToChannel( char *x ); diff --git a/Inc/readsource.h b/Inc/readsource.h index 2d7958f0..185bb1d0 100644 --- a/Inc/readsource.h +++ b/Inc/readsource.h @@ -1,11 +1,19 @@ #ifndef _READSOURCE_H_ #define _READSOURCE_H_ +#include + +#ifdef __cplusplus +extern "C" { +#endif + // ==================================================================================================== char *readsourcefile( char *path, size_t *l ); // ==================================================================================================== - +#ifdef __cplusplus +} +#endif #endif diff --git a/Inc/sio.h b/Inc/sio.h index 4e91e07e..d48b2ad6 100644 --- a/Inc/sio.h +++ b/Inc/sio.h @@ -32,8 +32,7 @@ enum SIOEvent { SIO_EV_NONE, SIO_EV_HOLD, SIO_EV_QUIT, SIO_EV_SAVE, SIO_EV_CONSU enum LineType { LT_SOURCE, LT_ASSEMBLY, LT_NASSEMBLY, LT_MU_SOURCE, LT_EVENT, LT_LABEL, LT_FILE, LT_DEBUG }; /* Definition for a single line...collections of these are what get displayed */ -struct sioline -{ +struct sioline { enum LineType lt; bool isRef; char *buffer; diff --git a/Inc/stream.h b/Inc/stream.h index 345cfe76..1060b057 100644 --- a/Inc/stream.h +++ b/Inc/stream.h @@ -8,16 +8,14 @@ extern "C" { #endif -enum ReceiveResult -{ +enum ReceiveResult { RECEIVE_RESULT_OK, RECEIVE_RESULT_TIMEOUT, RECEIVE_RESULT_EOF, RECEIVE_RESULT_ERROR, }; -struct Stream -{ +struct Stream { enum ReceiveResult ( *receive )( struct Stream *stream, void *buffer, size_t bufferSize, struct timeval *timeout, size_t *receivedSize ); void ( *close )( struct Stream *stream ); diff --git a/Inc/stream_win32.h b/Inc/stream_win32.h index d3e09a11..2cb15d97 100644 --- a/Inc/stream_win32.h +++ b/Inc/stream_win32.h @@ -10,8 +10,7 @@ extern "C" { #endif -struct Win32Stream -{ +struct Win32Stream { struct Stream base; HANDLE source; HANDLE readDoneEvent; diff --git a/Inc/symbols.h b/Inc/symbols.h index 19aa5548..9c75ceec 100644 --- a/Inc/symbols.h +++ b/Inc/symbols.h @@ -33,7 +33,7 @@ extern "C" { #define INTERRUPT (SPECIALS_MASK|0xd) #define FN_INTERRUPT_STR "INTERRUPT" -enum symbolErr { SYMBOL_OK, SYMBOL_NOELF, SYMBOL_NOOBJDUMP, SYMBOL_UNSPECIFIED }; +enum symbolErr { SYMBOL_OK, SYMBOL_NOELF, SYMBOL_NOOBJDUMP, SYMBOL_UNSPECIFIED, SYMBOL_OOM }; /* Mapping of lines numbers to indicies */ struct assyLineEntry @@ -87,8 +87,7 @@ struct sourceLineEntry }; /* The full set of symbols */ -struct SymbolSet -{ +struct SymbolSet { char *elfFile; /* File containing structure info */ char *deleteMaterial; /* Material to strip off filenames */ char *odoptions; /* Any options to pass directly to objdump */ @@ -111,8 +110,7 @@ struct SymbolSet }; /* An entry in the names table ... what we return to our caller */ -struct nameEntry -{ +struct nameEntry { uint32_t fileindex; /* Index of filename */ uint32_t functionindex; /* Index of functionname */ uint32_t line; /* Source line containing the address */ diff --git a/Inc/tpiuDecoder.h b/Inc/tpiuDecoder.h index df2bfcd4..799a430e 100644 --- a/Inc/tpiuDecoder.h +++ b/Inc/tpiuDecoder.h @@ -17,8 +17,7 @@ extern "C" { #endif -enum TPIUPumpEvent -{ +enum TPIUPumpEvent { TPIU_EV_NONE, TPIU_EV_UNSYNCED, TPIU_EV_SYNCED, @@ -28,8 +27,7 @@ enum TPIUPumpEvent TPIU_EV_ERROR }; -enum TPIUPumpState -{ +enum TPIUPumpState { TPIU_UNSYNCED, TPIU_SYNCED, TPIU_RXING, @@ -47,8 +45,7 @@ struct TPIUCommsStats uint32_t totalFrames; /* Total frames received */ }; -struct TPIUDecoderStats -{ +struct TPIUDecoderStats { uint32_t lostSync; /* Number of times sync has been lost */ uint32_t syncCount; /* Number of times a sync event has been received */ uint32_t halfSyncCount; /* Number of times a half sync event has been received */ @@ -56,8 +53,7 @@ struct TPIUDecoderStats uint32_t error; /* Number of times an error has been received */ }; -struct TPIUDecoder -{ +struct TPIUDecoder { enum TPIUPumpState state; /* Current state of TPIU decoder */ uint8_t byteCount; /* Current byte number in reception */ uint8_t currentStream; /* Currently selected stream */ @@ -71,11 +67,9 @@ struct TPIUDecoder struct TPIUCommsStats commsStats; /* Record of Comms stats */ }; -struct TPIUPacket -{ +struct TPIUPacket { uint8_t len; /* Received length (after pre-processing) */ - struct - { + struct { int8_t s; /* Stream to which this byte relates */ int8_t d; /* ...the byte itself */ } packet[TPIU_PACKET_LEN]; diff --git a/Inc/traceDecoder.h b/Inc/traceDecoder.h index fc7b85de..8cfbc8fe 100644 --- a/Inc/traceDecoder.h +++ b/Inc/traceDecoder.h @@ -18,8 +18,7 @@ extern "C" { #endif /* Protocol format */ -enum TRACEprotocol -{ +enum TRACEprotocol { TRACE_PROT_LIST_START = 0, TRACE_PROT_ETM35 = TRACE_PROT_LIST_START, TRACE_PROT_MTB, @@ -33,8 +32,7 @@ enum TRACEprotocol /* Events from the process of pumping bytes through the TRACE decoder */ -enum TRACEDecoderPumpEvent -{ +enum TRACEDecoderPumpEvent { TRACE_EV_NONE, TRACE_EV_UNSYNCED, TRACE_EV_SYNCED, @@ -42,8 +40,8 @@ enum TRACEDecoderPumpEvent TRACE_EV_MSG_RXED }; -enum TRACEchanges -{ +enum TRACEchanges { + EV_CH_NONE, EV_CH_EX_ENTRY, EV_CH_EX_EXIT, EV_CH_CLOCKSPEED, @@ -93,14 +91,12 @@ enum Mode { TRACE_ADDRMODE_THUMB, TRACE_ADDRMODE_ARM, TRACE_ADDRMODE_JAZELLE }; enum Reason { TRACE_REASON_PERIODIC, TRACE_REASON_TRACEON, TRACE_REASON_TRACEOVF, TRACE_REASON_EXITDBG }; /* TRACE Decoder statistics */ -struct TRACEDecoderStats -{ +struct TRACEDecoderStats { uint32_t lostSyncCount; /* Number of times sync has been lost */ uint32_t syncCount; /* Number of times a sync event has been received */ }; -struct TRACECPUState -{ +struct TRACECPUState { uint32_t changeRecord; /* Record of what changed since last report */ // Gross processor state... @@ -153,8 +149,7 @@ typedef void ( *traceDecodeCB )( void *d ); struct TRACEDecoder; -struct TRACEDecoderEngine -{ +struct TRACEDecoderEngine { bool ( *action ) ( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu, uint8_t c ); bool ( *actionPair ) ( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu, uint32_t source, uint32_t dest ); void ( *destroy ) ( struct TRACEDecoderEngine *e ); @@ -163,7 +158,7 @@ struct TRACEDecoderEngine const char ( *name ) ( void ); /* Config specific to ETM3.5 */ - void ( *altAddrEncode ) ( struct TRACEDecoderEngine *e, bool using ); + void ( *altAddrEncode ) ( struct TRACEDecoderEngine *e, bool amusing ); }; struct TRACEDecoder diff --git a/Inc/uicolours_default.h b/Inc/uicolours_default.h index 5a0ac1c3..dfd8451f 100644 --- a/Inc/uicolours_default.h +++ b/Inc/uicolours_default.h @@ -1,5 +1,11 @@ /* SPDX-License-Identifier: BSD-3-Clause */ +#ifndef _UICOLOURS_DEFAULT_ +#define _UICOLOURS_DEFAULT_ +#ifdef __cplusplus +extern "C" { +#endif + /* Default user interface colours */ #define C_OVF_IND C_LRED /* Toggile Overflow indicator */ @@ -23,3 +29,8 @@ #define C_SEL C_LCYAN /* Element selection */ #define C_ELEMENT C_YELLOW /* Data */ + +#ifdef __cplusplus +} +#endif +#endif diff --git a/README.md b/README.md index 6f7f5809..d60b8e45 100644 --- a/README.md +++ b/README.md @@ -369,37 +369,43 @@ to catch up. The easiest way to see this in action is to pause a client (e.g. `C see orbuculum's data transfer go to zero. When you re-start the client (e.g. `fg` to bring it back into the foreground) then it will carry on from where it left off and no client will lose data. -Command Line Options -==================== +Program Options +=============== -For `orbuculum`, the specific command line options of note are; +Options can be set either on the command line or via a configuration file. By default that is called `.orbcfg.toml` and is read from the +current directory. The reading of this file can be prevented by setting the `-C-` command line option, and it's name can be overridden +by specifying a new name in the `-C` option. Options are read from the config file first, and are overridden by command line options. The +config file is in [TOML](https://toml.io/en/v1.0.0) format. - `-a, --serial-speed: [serialSpeed]`: Use serial port and set device speed. +For `orbuculum`, the specific command line options (and equivalent TOML entries) of note are; - `-E, --eof`: When reading from file, ignore eof. + `-a, --serial-speed: [serialSpeed]`: Use serial port and set device speed. Equivalent config file entry `orbuculum.source.serial.speed`. - `-f, --input-file [filename]`: Take input from file rather than device. + `-E, --eof`: When reading from file, ignore eof. Equivalent config file entry `orbuculum.source.exit_at_eof`. - `-h, --help`: Brief help. + `-f, --input-file [filename]`: Take input from file rather than device. Equivalent config file entry `orbuculum.source.file`. + + `-h, --help`: Brief help. No config file equivalent. - `-H, --hires`: Use high resolution time. This limits probe interface timeouts to 1ms, which makes host-side timing more accurate, but at the expense of _much_ higher load (literally perhaps x100). Use sparingly. + `-H, --hires`: Use high resolution time. This limits probe interface timeouts to 1ms, which makes host-side timing more accurate, but at the expense of _much_ higher load (literally perhaps x100). Use sparingly. Equivalent config file entry `orbuculum.processing.hires`. - `-m, --monitor`: Monitor interval (in ms) for reporting on state of the link. If baudrate is specified (using `-a`) and is greater than 100bps then the percentage link occupancy is also reported. + `-m, --monitor`: Monitor interval (in ms) for reporting on state of the link. If baudrate is specified (using `-a`) and is greater than 100bps then the percentage link occupancy is also reported. Equivalent config file entry `orbuculum.presentation.monitor_interval`. - `-n, --serial-number`: Set a specific serial number for the ORBTrace or BMP device to connect to. Any unambigious sequence is sufficient. Ignored for other probe types. + `-n, --serial-number`: Set a specific serial number for the ORBTrace or BMP device to connect to. Any unambigious sequence is sufficient. Ignored for other probe types. Equivalent config file entry `orbuculum.source.serial_number`. - `-o, --output-file [filename]`: Record trace data locally. This is unfettered data directly from the source device, can be useful for replay purposes or other tool testing. + `-o, --output-file [filename]`: Record trace data locally. This is unfettered data directly from the source device, can be useful for replay purposes or other tool testing. Equivalent config file entry `orbuculum.output.file`. - `-O ""`: Run orbtrace on each detected connection of a probe, with the specified options. + `-O ""`: Run orbtrace on each detected connection of a probe, with the specified options. Equivalent config file entry `orbuculum.presentation.run_orbtrace`. - `-p, --serial-port [serialPort]`: to use. If not specified then the program defaults to Blackmagic probe. + `-p, --serial-port [serialPort]`: to use. If not specified then the program defaults to Blackmagic probe or ORBTrace probe, with a selection dialog if multiples are found. Equivalent config file entry `orbuculum.source.port`. - `-P, --pace [us delay]`: between file blocks. Used to slow down orbuculum feeding from a file to a set of clients. + `-P, --pace [us delay]`: between file blocks. Used to slow down orbuculum feeding from a file to a set of clients. Equivalent config file entry `orbuculum.output.pace_delay`. - `-s, --server [address]:[port]`: Set address for explicit TCP Source connection, (default none:2332). + `-s, --server [address]:[port]`: Set address for explicit TCP Source connection, (default none:2332). Equivalent config file entries `orbuculum.source.server.name` and `orbuculum.source.server.port`. - `-t, --tpiu x,y,...`: Remove TPIU formatting and issue streams x, y etc over incrementing IP port numbers. + `-t, --tpiu x,y,...`: Remove TPIU formatting and issue streams x, y etc over incrementing IP port numbers. Equvalent config file entry `tpiu_channels`. +The config file also let's the data link speed be set independently of the serial link speed by means of the `orbuculum.presentation.data_speed` entry. Orbfifo ------- diff --git a/Src/ext_fileformats.c b/Src/ext_fileformats.c index 7b2d86d4..d4b03217 100644 --- a/Src/ext_fileformats.c +++ b/Src/ext_fileformats.c @@ -33,8 +33,7 @@ static int _calls_src_sort_fn( const void *a, const void *b ) { int i; - if ( ( i = ( int )( ( ( struct subcall * )a )->srch->functionindex ) - ( int )( ( ( struct subcall * )b )->srch->functionindex ) ) ) - { + if ( ( i = ( int )( ( ( struct subcall * )a )->srch->functionindex ) - ( int )( ( ( struct subcall * )b )->srch->functionindex ) ) ) { return i; } @@ -49,8 +48,7 @@ static int _calls_dst_sort_fn( const void *a, const void *b ) { int i; - if ( ( i = ( int )( ( ( struct subcall * )a )->dsth->functionindex ) - ( int )( ( ( struct subcall * )b )->dsth->functionindex ) ) ) - { + if ( ( i = ( int )( ( ( struct subcall * )a )->dsth->functionindex ) - ( int )( ( ( struct subcall * )b )->dsth->functionindex ) ) ) { return i; } @@ -80,13 +78,11 @@ bool ext_ff_outputDot( char *dotfile, struct subcall *subcallList, struct Symbol uint64_t cnt; struct subcall *s; - if ( !dotfile ) - { + if ( !dotfile ) { return false; } - if ( !subcallList ) - { + if ( !subcallList ) { return false; } @@ -102,19 +98,17 @@ bool ext_ff_outputDot( char *dotfile, struct subcall *subcallList, struct Symbol s = subcallList; - while ( s ) - { + while ( s ) { functionidx = s->srch->functionindex; fileidx = s->srch->fileindex; dfunctionidx = s->dsth->functionindex; cnt = s->count; - s = s->hh.next; + s = ( struct subcall * )s->hh.next; - while ( ( s ) && ( functionidx == s->srch->functionindex ) && ( dfunctionidx == s->dsth->functionindex ) ) - { + while ( ( s ) && ( functionidx == s->srch->functionindex ) && ( dfunctionidx == s->dsth->functionindex ) ) { cnt += s->count; - s = s->hh.next; + s = ( struct subcall * )s->hh.next; } fprintf( c, " \"\n(%s)\n%s\n\n\" -- ", SymbolFilename( ss, fileidx ), SymbolFunction( ss, functionidx ) ); @@ -145,20 +139,16 @@ bool ext_ff_outputProfile( char *profile, char *elffile, char *deleteMaterial, b char *d = deleteMaterial; FILE *c; - if ( !profile ) - { + if ( !profile ) { return false; } c = fopen( profile, "w" ); fprintf( c, "# callgrind format\n" ); - if ( includeVisits ) - { + if ( includeVisits ) { fprintf( c, "creator: orbprofile\npositions: instr line\nevent: Inst : CPU Instructions\nevent: Visits : Visits to source line\nevents: Inst Visits\n" ); - } - else - { + } else { fprintf( c, "creator: orbprofile\npositions: instr line\nevent: Inst : CPU Instructions\nevents: Inst\n" ); } @@ -166,16 +156,13 @@ bool ext_ff_outputProfile( char *profile, char *elffile, char *deleteMaterial, b fprintf( c, "summary: %" PRIu64 "\n", timelen ); /* Try to remove frontmatter off the elfile if nessessary and possible */ - if ( deleteMaterial ) - { - while ( ( *d ) && ( *d == *e ) ) - { + if ( deleteMaterial ) { + while ( ( *d ) && ( *d == *e ) ) { d++; e++; } - if ( e - elffile != strlen( deleteMaterial ) ) - { + if ( e - elffile != ( long int )strlen( deleteMaterial ) ) { /* Strings don't match, give up and use the file elffile name */ e = elffile; } @@ -187,51 +174,36 @@ bool ext_ff_outputProfile( char *profile, char *elffile, char *deleteMaterial, b HASH_SORT( insthead, _inst_sort_fn ); struct execEntryHash *f = insthead; - while ( f ) - { + while ( f ) { SymbolLookup( ss, f->addr, &n ); - if ( prevfile != n.fileindex ) - { + if ( prevfile != n.fileindex ) { fprintf( c, "fl=(%u) %s%s\n", n.fileindex & HANDLE_MASK, deleteMaterial ? deleteMaterial : "", SymbolFilename( ss, n.fileindex ) ); } - if ( prevfn != n.functionindex ) - { + if ( prevfn != n.functionindex ) { fprintf( c, "fn=(%u) %s\n", n.functionindex & HANDLE_MASK, SymbolFunction( ss, n.functionindex ) ); } - if ( ( prevline == NO_LINE ) || ( prevaddr == NO_FUNCTION ) ) - { + if ( ( prevline == NO_LINE ) || ( prevaddr == NO_FUNCTION ) ) { fprintf( c, "0x%08x %d ", f->addr, n.line ); - } - else - { - if ( prevaddr == f->addr ) - { + } else { + if ( prevaddr == f->addr ) { fprintf( c, "* " ); - } - else - { + } else { fprintf( c, "%s%d ", f->addr > prevaddr ? "+" : "", ( int )f->addr - prevaddr ); } - if ( prevline == n.line ) - { + if ( prevline == n.line ) { fprintf( c, "* " ); - } - else - { + } else { fprintf( c, "%s%d ", n.line > prevline ? "+" : "", ( int )n.line - prevline ); } } - if ( includeVisits ) - { + if ( includeVisits ) { fprintf( c, "%" PRIu64 " %" PRIu64 "\n", f->count, f->scount ); - } - else - { + } else { fprintf( c, "%" PRIu64 "\n", f->count ); } @@ -240,24 +212,21 @@ bool ext_ff_outputProfile( char *profile, char *elffile, char *deleteMaterial, b prevaddr = f->addr; prevfile = n.fileindex; prevfn = n.functionindex; - f = f->hh.next; + f = ( struct execEntryHash * )f->hh.next; } fprintf( c, "\n\n## ------------------- Calls Follow ------------------------\n" ); HASH_SORT( subcallList, _calls_src_sort_fn ); struct subcall *s = subcallList; - while ( s ) - { + while ( s ) { /* Now publish the call destination. By definition is is known, so can be shortformed */ - if ( prevfile != s->srch->fileindex ) - { + if ( prevfile != s->srch->fileindex ) { fprintf( c, "fl=(%u)\n", s->srch->fileindex & HANDLE_MASK ); prevfile = s->srch->fileindex; } - if ( prevfn != s->srch->functionindex ) - { + if ( prevfn != s->srch->functionindex ) { fprintf( c, "fn=(%u)\n", s->srch->functionindex & HANDLE_MASK ); prevfn = s->srch->functionindex; } @@ -265,16 +234,13 @@ bool ext_ff_outputProfile( char *profile, char *elffile, char *deleteMaterial, b fprintf( c, "cfl=(%d)\ncfn=(%d)\n", s->dsth->fileindex, s->dsth->functionindex ); fprintf( c, "calls=%" PRIu64 " 0x%08x %d\n", s->count, s->sig.dst, s->dsth->line ); - if ( includeVisits ) - { + if ( includeVisits ) { fprintf( c, "0x%08x %d %" PRIu64 " %" PRIu64 "\n", s->sig.src, s->srch->line, s->myCost, s->count ); - } - else - { + } else { fprintf( c, "0x%08x %d %" PRIu64 "\n", s->sig.src, s->srch->line, s->myCost ); } - s = s->hh.next; + s = ( struct subcall * )s->hh.next; } fclose( c ); diff --git a/Src/external/cJSON.c b/Src/external/cJSON.c index 0aab5613..66d7ceed 100644 --- a/Src/external/cJSON.c +++ b/Src/external/cJSON.c @@ -68,8 +68,7 @@ #endif #define false ((cJSON_bool)0) -typedef struct -{ +typedef struct { const unsigned char *json; size_t position; } error; @@ -82,8 +81,7 @@ CJSON_PUBLIC( const char * ) cJSON_GetErrorPtr( void ) CJSON_PUBLIC( char * ) cJSON_GetStringValue( cJSON *item ) { - if ( !cJSON_IsString( item ) ) - { + if ( !cJSON_IsString( item ) ) { return NULL; } @@ -106,20 +104,16 @@ CJSON_PUBLIC( const char * ) cJSON_Version( void ) /* Case insensitive string comparison, doesn't consider two NULL pointers equal though */ static int case_insensitive_strcmp( const unsigned char *string1, const unsigned char *string2 ) { - if ( ( string1 == NULL ) || ( string2 == NULL ) ) - { + if ( ( string1 == NULL ) || ( string2 == NULL ) ) { return 1; } - if ( string1 == string2 ) - { + if ( string1 == string2 ) { return 0; } - for ( ; tolower( *string1 ) == tolower( *string2 ); ( void )string1++, string2++ ) - { - if ( *string1 == '\0' ) - { + for ( ; tolower( *string1 ) == tolower( *string2 ); ( void )string1++, string2++ ) { + if ( *string1 == '\0' ) { return 0; } } @@ -127,8 +121,7 @@ static int case_insensitive_strcmp( const unsigned char *string1, const unsigned return tolower( *string1 ) - tolower( *string2 ); } -typedef struct internal_hooks -{ +typedef struct internal_hooks { void *( CJSON_CDECL *allocate )( size_t size ); void ( CJSON_CDECL *deallocate )( void *pointer ); void *( CJSON_CDECL *reallocate )( void *pointer, size_t size ); @@ -164,16 +157,14 @@ static unsigned char *cJSON_strdup( const unsigned char *string, const internal_ size_t length = 0; unsigned char *copy = NULL; - if ( string == NULL ) - { + if ( string == NULL ) { return NULL; } length = strlen( ( const char * )string ) + sizeof( "" ); copy = ( unsigned char * )hooks->allocate( length ); - if ( copy == NULL ) - { + if ( copy == NULL ) { return NULL; } @@ -184,8 +175,7 @@ static unsigned char *cJSON_strdup( const unsigned char *string, const internal_ CJSON_PUBLIC( void ) cJSON_InitHooks( cJSON_Hooks *hooks ) { - if ( hooks == NULL ) - { + if ( hooks == NULL ) { /* Reset hooks */ global_hooks.allocate = malloc; global_hooks.deallocate = free; @@ -195,23 +185,20 @@ CJSON_PUBLIC( void ) cJSON_InitHooks( cJSON_Hooks *hooks ) global_hooks.allocate = malloc; - if ( hooks->malloc_fn != NULL ) - { + if ( hooks->malloc_fn != NULL ) { global_hooks.allocate = hooks->malloc_fn; } global_hooks.deallocate = free; - if ( hooks->free_fn != NULL ) - { + if ( hooks->free_fn != NULL ) { global_hooks.deallocate = hooks->free_fn; } /* use realloc only if both free and malloc are used */ global_hooks.reallocate = NULL; - if ( ( global_hooks.allocate == malloc ) && ( global_hooks.deallocate == free ) ) - { + if ( ( global_hooks.allocate == malloc ) && ( global_hooks.deallocate == free ) ) { global_hooks.reallocate = realloc; } } @@ -221,8 +208,7 @@ static cJSON *cJSON_New_Item( const internal_hooks *const hooks ) { cJSON *node = ( cJSON * )hooks->allocate( sizeof( cJSON ) ); - if ( node ) - { + if ( node ) { memset( node, '\0', sizeof( cJSON ) ); } @@ -234,22 +220,18 @@ CJSON_PUBLIC( void ) cJSON_Delete( cJSON *item ) { cJSON *next = NULL; - while ( item != NULL ) - { + while ( item != NULL ) { next = item->next; - if ( !( item->type & cJSON_IsReference ) && ( item->child != NULL ) ) - { + if ( !( item->type & cJSON_IsReference ) && ( item->child != NULL ) ) { cJSON_Delete( item->child ); } - if ( !( item->type & cJSON_IsReference ) && ( item->valuestring != NULL ) ) - { + if ( !( item->type & cJSON_IsReference ) && ( item->valuestring != NULL ) ) { global_hooks.deallocate( item->valuestring ); } - if ( !( item->type & cJSON_StringIsConst ) && ( item->string != NULL ) ) - { + if ( !( item->type & cJSON_StringIsConst ) && ( item->string != NULL ) ) { global_hooks.deallocate( item->string ); } @@ -269,8 +251,7 @@ static unsigned char get_decimal_point( void ) #endif } -typedef struct -{ +typedef struct { const unsigned char *content; size_t length; size_t offset; @@ -295,18 +276,15 @@ static cJSON_bool parse_number( cJSON *const item, parse_buffer *const input_buf unsigned char decimal_point = get_decimal_point(); size_t i = 0; - if ( ( input_buffer == NULL ) || ( input_buffer->content == NULL ) ) - { + if ( ( input_buffer == NULL ) || ( input_buffer->content == NULL ) ) { return false; } /* copy the number into a temporary buffer and replace '.' with the decimal point * of the current locale (for strtod) * This also takes care of '\0' not necessarily being available for marking the end of the input */ - for ( i = 0; ( i < ( sizeof( number_c_string ) - 1 ) ) && can_access_at_index( input_buffer, i ); i++ ) - { - switch ( buffer_at_offset( input_buffer )[i] ) - { + for ( i = 0; ( i < ( sizeof( number_c_string ) - 1 ) ) && can_access_at_index( input_buffer, i ); i++ ) { + switch ( buffer_at_offset( input_buffer )[i] ) { case '0': case '1': case '2': @@ -338,24 +316,18 @@ static cJSON_bool parse_number( cJSON *const item, parse_buffer *const input_buf number = strtod( ( const char * )number_c_string, ( char ** )&after_end ); - if ( number_c_string == after_end ) - { + if ( number_c_string == after_end ) { return false; /* parse_error */ } item->valuedouble = number; /* use saturation in case of overflow */ - if ( number >= INT_MAX ) - { + if ( number >= INT_MAX ) { item->valueint = INT_MAX; - } - else if ( number <= ( double )INT_MIN ) - { + } else if ( number <= ( double )INT_MIN ) { item->valueint = INT_MIN; - } - else - { + } else { item->valueint = ( int )number; } @@ -368,24 +340,18 @@ static cJSON_bool parse_number( cJSON *const item, parse_buffer *const input_buf /* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */ CJSON_PUBLIC( double ) cJSON_SetNumberHelper( cJSON *object, double number ) { - if ( number >= INT_MAX ) - { + if ( number >= INT_MAX ) { object->valueint = INT_MAX; - } - else if ( number <= ( double )INT_MIN ) - { + } else if ( number <= ( double )INT_MIN ) { object->valueint = INT_MIN; - } - else - { + } else { object->valueint = ( int )number; } return object->valuedouble = number; } -typedef struct -{ +typedef struct { unsigned char *buffer; size_t length; size_t offset; @@ -401,74 +367,58 @@ static unsigned char *ensure( printbuffer *const p, size_t needed ) unsigned char *newbuffer = NULL; size_t newsize = 0; - if ( ( p == NULL ) || ( p->buffer == NULL ) ) - { + if ( ( p == NULL ) || ( p->buffer == NULL ) ) { return NULL; } - if ( ( p->length > 0 ) && ( p->offset >= p->length ) ) - { + if ( ( p->length > 0 ) && ( p->offset >= p->length ) ) { /* make sure that offset is valid */ return NULL; } - if ( needed > INT_MAX ) - { + if ( needed > INT_MAX ) { /* sizes bigger than INT_MAX are currently not supported */ return NULL; } needed += p->offset + 1; - if ( needed <= p->length ) - { + if ( needed <= p->length ) { return p->buffer + p->offset; } - if ( p->noalloc ) - { + if ( p->noalloc ) { return NULL; } /* calculate new buffer size */ - if ( needed > ( INT_MAX / 2 ) ) - { + if ( needed > ( INT_MAX / 2 ) ) { /* overflow of int, use INT_MAX if possible */ - if ( needed <= INT_MAX ) - { + if ( needed <= INT_MAX ) { newsize = INT_MAX; - } - else - { + } else { return NULL; } - } - else - { + } else { newsize = needed * 2; } - if ( p->hooks.reallocate != NULL ) - { + if ( p->hooks.reallocate != NULL ) { /* reallocate with realloc if available */ newbuffer = ( unsigned char * )p->hooks.reallocate( p->buffer, newsize ); - if ( newbuffer == NULL ) - { + if ( newbuffer == NULL ) { p->hooks.deallocate( p->buffer ); p->length = 0; p->buffer = NULL; return NULL; } - } - else - { + } else { /* otherwise reallocate manually */ newbuffer = ( unsigned char * )p->hooks.allocate( newsize ); - if ( !newbuffer ) - { + if ( !newbuffer ) { p->hooks.deallocate( p->buffer ); p->length = 0; p->buffer = NULL; @@ -476,8 +426,7 @@ static unsigned char *ensure( printbuffer *const p, size_t needed ) return NULL; } - if ( newbuffer ) - { + if ( newbuffer ) { memcpy( newbuffer, p->buffer, p->offset + 1 ); } @@ -495,8 +444,7 @@ static void update_offset( printbuffer *const buffer ) { const unsigned char *buffer_pointer = NULL; - if ( ( buffer == NULL ) || ( buffer->buffer == NULL ) ) - { + if ( ( buffer == NULL ) || ( buffer->buffer == NULL ) ) { return; } @@ -516,49 +464,40 @@ static cJSON_bool print_number( const cJSON *const item, printbuffer *const outp unsigned char decimal_point = get_decimal_point(); double test; - if ( output_buffer == NULL ) - { + if ( output_buffer == NULL ) { return false; } /* This checks for NaN and Infinity */ - if ( ( d * 0 ) != 0 ) - { + if ( ( d * 0 ) != 0 ) { length = sprintf( ( char * )number_buffer, "null" ); - } - else - { + } else { /* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */ length = sprintf( ( char * )number_buffer, "%1.15g", d ); /* Check whether the original double can be recovered */ - if ( ( sscanf( ( char * )number_buffer, "%lg", &test ) != 1 ) || ( ( double )test != d ) ) - { + if ( ( sscanf( ( char * )number_buffer, "%lg", &test ) != 1 ) || ( ( double )test != d ) ) { /* If not, print with 17 decimal places of precision */ length = sprintf( ( char * )number_buffer, "%1.17g", d ); } } /* sprintf failed or buffer overrun occurred */ - if ( ( length < 0 ) || ( length > ( int )( sizeof( number_buffer ) - 1 ) ) ) - { + if ( ( length < 0 ) || ( length > ( int )( sizeof( number_buffer ) - 1 ) ) ) { return false; } /* reserve appropriate space in the output */ output_pointer = ensure( output_buffer, ( size_t )length + sizeof( "" ) ); - if ( output_pointer == NULL ) - { + if ( output_pointer == NULL ) { return false; } /* copy the printed number to the output and replace locale * dependent decimal point with '.' */ - for ( i = 0; i < ( ( size_t )length ); i++ ) - { - if ( number_buffer[i] == decimal_point ) - { + for ( i = 0; i < ( ( size_t )length ); i++ ) { + if ( number_buffer[i] == decimal_point ) { output_pointer[i] = '.'; continue; } @@ -579,28 +518,19 @@ static unsigned parse_hex4( const unsigned char *const input ) unsigned int h = 0; size_t i = 0; - for ( i = 0; i < 4; i++ ) - { + for ( i = 0; i < 4; i++ ) { /* parse digit */ - if ( ( input[i] >= '0' ) && ( input[i] <= '9' ) ) - { + if ( ( input[i] >= '0' ) && ( input[i] <= '9' ) ) { h += ( unsigned int ) input[i] - '0'; - } - else if ( ( input[i] >= 'A' ) && ( input[i] <= 'F' ) ) - { + } else if ( ( input[i] >= 'A' ) && ( input[i] <= 'F' ) ) { h += ( unsigned int ) 10 + input[i] - 'A'; - } - else if ( ( input[i] >= 'a' ) && ( input[i] <= 'f' ) ) - { + } else if ( ( input[i] >= 'a' ) && ( input[i] <= 'f' ) ) { h += ( unsigned int ) 10 + input[i] - 'a'; - } - else /* invalid */ - { + } else { /* invalid */ return 0; } - if ( i < 3 ) - { + if ( i < 3 ) { /* shift left to make place for the next nibble */ h = h << 4; } @@ -621,8 +551,7 @@ static unsigned char utf16_literal_to_utf8( const unsigned char *const input_poi unsigned char sequence_length = 0; unsigned char first_byte_mark = 0; - if ( ( input_end - first_sequence ) < 6 ) - { + if ( ( input_end - first_sequence ) < 6 ) { /* input ends unexpectedly */ goto fail; } @@ -631,26 +560,22 @@ static unsigned char utf16_literal_to_utf8( const unsigned char *const input_poi first_code = parse_hex4( first_sequence + 2 ); /* check that the code is valid */ - if ( ( ( first_code >= 0xDC00 ) && ( first_code <= 0xDFFF ) ) ) - { + if ( ( ( first_code >= 0xDC00 ) && ( first_code <= 0xDFFF ) ) ) { goto fail; } /* UTF16 surrogate pair */ - if ( ( first_code >= 0xD800 ) && ( first_code <= 0xDBFF ) ) - { + if ( ( first_code >= 0xD800 ) && ( first_code <= 0xDBFF ) ) { const unsigned char *second_sequence = first_sequence + 6; unsigned int second_code = 0; sequence_length = 12; /* \uXXXX\uXXXX */ - if ( ( input_end - second_sequence ) < 6 ) - { + if ( ( input_end - second_sequence ) < 6 ) { /* input ends unexpectedly */ goto fail; } - if ( ( second_sequence[0] != '\\' ) || ( second_sequence[1] != 'u' ) ) - { + if ( ( second_sequence[0] != '\\' ) || ( second_sequence[1] != 'u' ) ) { /* missing second half of the surrogate pair */ goto fail; } @@ -659,8 +584,7 @@ static unsigned char utf16_literal_to_utf8( const unsigned char *const input_poi second_code = parse_hex4( second_sequence + 2 ); /* check that the code is valid */ - if ( ( second_code < 0xDC00 ) || ( second_code > 0xDFFF ) ) - { + if ( ( second_code < 0xDC00 ) || ( second_code > 0xDFFF ) ) { /* invalid second half of the surrogate pair */ goto fail; } @@ -668,9 +592,7 @@ static unsigned char utf16_literal_to_utf8( const unsigned char *const input_poi /* calculate the unicode codepoint from the surrogate pair */ codepoint = 0x10000 + ( ( ( first_code & 0x3FF ) << 10 ) | ( second_code & 0x3FF ) ); - } - else - { + } else { sequence_length = 6; /* \uXXXX */ codepoint = first_code; } @@ -678,50 +600,37 @@ static unsigned char utf16_literal_to_utf8( const unsigned char *const input_poi /* encode as UTF-8 * takes at maximum 4 bytes to encode: * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */ - if ( codepoint < 0x80 ) - { + if ( codepoint < 0x80 ) { /* normal ascii, encoding 0xxxxxxx */ utf8_length = 1; - } - else if ( codepoint < 0x800 ) - { + } else if ( codepoint < 0x800 ) { /* two bytes, encoding 110xxxxx 10xxxxxx */ utf8_length = 2; first_byte_mark = 0xC0; /* 11000000 */ - } - else if ( codepoint < 0x10000 ) - { + } else if ( codepoint < 0x10000 ) { /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */ utf8_length = 3; first_byte_mark = 0xE0; /* 11100000 */ - } - else if ( codepoint <= 0x10FFFF ) - { + } else if ( codepoint <= 0x10FFFF ) { /* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */ utf8_length = 4; first_byte_mark = 0xF0; /* 11110000 */ - } - else - { + } else { /* invalid unicode codepoint */ goto fail; } /* encode as utf8 */ - for ( utf8_position = ( unsigned char )( utf8_length - 1 ); utf8_position > 0; utf8_position-- ) - { + for ( utf8_position = ( unsigned char )( utf8_length - 1 ); utf8_position > 0; utf8_position-- ) { /* 10xxxxxx */ ( *output_pointer )[utf8_position] = ( unsigned char )( ( codepoint | 0x80 ) & 0xBF ); codepoint >>= 6; } /* encode first byte */ - if ( utf8_length > 1 ) - { + if ( utf8_length > 1 ) { ( *output_pointer )[0] = ( unsigned char )( ( codepoint | first_byte_mark ) & 0xFF ); - } - else - { + } else { ( *output_pointer )[0] = ( unsigned char )( codepoint & 0x7F ); } @@ -742,8 +651,7 @@ static cJSON_bool parse_string( cJSON *const item, parse_buffer *const input_buf unsigned char *output = NULL; /* not a string */ - if ( buffer_at_offset( input_buffer )[0] != '\"' ) - { + if ( buffer_at_offset( input_buffer )[0] != '\"' ) { goto fail; } @@ -752,13 +660,10 @@ static cJSON_bool parse_string( cJSON *const item, parse_buffer *const input_buf size_t allocation_length = 0; size_t skipped_bytes = 0; - while ( ( ( size_t )( input_end - input_buffer->content ) < input_buffer->length ) && ( *input_end != '\"' ) ) - { + while ( ( ( size_t )( input_end - input_buffer->content ) < input_buffer->length ) && ( *input_end != '\"' ) ) { /* is escape sequence */ - if ( input_end[0] == '\\' ) - { - if ( ( size_t )( input_end + 1 - input_buffer->content ) >= input_buffer->length ) - { + if ( input_end[0] == '\\' ) { + if ( ( size_t )( input_end + 1 - input_buffer->content ) >= input_buffer->length ) { /* prevent buffer overflow when last input character is a backslash */ goto fail; } @@ -770,8 +675,7 @@ static cJSON_bool parse_string( cJSON *const item, parse_buffer *const input_buf input_end++; } - if ( ( ( size_t )( input_end - input_buffer->content ) >= input_buffer->length ) || ( *input_end != '\"' ) ) - { + if ( ( ( size_t )( input_end - input_buffer->content ) >= input_buffer->length ) || ( *input_end != '\"' ) ) { goto fail; /* string ended unexpectedly */ } @@ -779,8 +683,7 @@ static cJSON_bool parse_string( cJSON *const item, parse_buffer *const input_buf allocation_length = ( size_t ) ( input_end - buffer_at_offset( input_buffer ) ) - skipped_bytes; output = ( unsigned char * )input_buffer->hooks.allocate( allocation_length + sizeof( "" ) ); - if ( output == NULL ) - { + if ( output == NULL ) { goto fail; /* allocation failure */ } } @@ -788,24 +691,19 @@ static cJSON_bool parse_string( cJSON *const item, parse_buffer *const input_buf output_pointer = output; /* loop through the string literal */ - while ( input_pointer < input_end ) - { - if ( *input_pointer != '\\' ) - { + while ( input_pointer < input_end ) { + if ( *input_pointer != '\\' ) { *output_pointer++ = *input_pointer++; } /* escape sequence */ - else - { + else { unsigned char sequence_length = 2; - if ( ( input_end - input_pointer ) < 1 ) - { + if ( ( input_end - input_pointer ) < 1 ) { goto fail; } - switch ( input_pointer[1] ) - { + switch ( input_pointer[1] ) { case 'b': *output_pointer++ = '\b'; break; @@ -836,8 +734,7 @@ static cJSON_bool parse_string( cJSON *const item, parse_buffer *const input_buf case 'u': sequence_length = utf16_literal_to_utf8( input_pointer, input_end, &output_pointer ); - if ( sequence_length == 0 ) - { + if ( sequence_length == 0 ) { /* failed to convert UTF16-literal to UTF-8 */ goto fail; } @@ -865,13 +762,11 @@ static cJSON_bool parse_string( cJSON *const item, parse_buffer *const input_buf fail: - if ( output != NULL ) - { + if ( output != NULL ) { input_buffer->hooks.deallocate( output ); } - if ( input_pointer != NULL ) - { + if ( input_pointer != NULL ) { input_buffer->offset = ( size_t )( input_pointer - input_buffer->content ); } @@ -888,18 +783,15 @@ static cJSON_bool print_string_ptr( const unsigned char *const input, printbuffe /* numbers of additional characters needed for escaping */ size_t escape_characters = 0; - if ( output_buffer == NULL ) - { + if ( output_buffer == NULL ) { return false; } /* empty string */ - if ( input == NULL ) - { + if ( input == NULL ) { output = ensure( output_buffer, sizeof( "\"\"" ) ); - if ( output == NULL ) - { + if ( output == NULL ) { return false; } @@ -909,10 +801,8 @@ static cJSON_bool print_string_ptr( const unsigned char *const input, printbuffe } /* set "flag" to 1 if something needs to be escaped */ - for ( input_pointer = input; *input_pointer; input_pointer++ ) - { - switch ( *input_pointer ) - { + for ( input_pointer = input; *input_pointer; input_pointer++ ) { + switch ( *input_pointer ) { case '\"': case '\\': case '\b': @@ -925,8 +815,7 @@ static cJSON_bool print_string_ptr( const unsigned char *const input, printbuffe break; default: - if ( *input_pointer < 32 ) - { + if ( *input_pointer < 32 ) { /* UTF-16 escape sequence uXXXX */ escape_characters += 5; } @@ -939,14 +828,12 @@ static cJSON_bool print_string_ptr( const unsigned char *const input, printbuffe output = ensure( output_buffer, output_length + sizeof( "\"\"" ) ); - if ( output == NULL ) - { + if ( output == NULL ) { return false; } /* no characters have to be escaped */ - if ( escape_characters == 0 ) - { + if ( escape_characters == 0 ) { output[0] = '\"'; memcpy( output + 1, input, output_length ); output[output_length + 1] = '\"'; @@ -959,20 +846,15 @@ static cJSON_bool print_string_ptr( const unsigned char *const input, printbuffe output_pointer = output + 1; /* copy the string */ - for ( input_pointer = input; *input_pointer != '\0'; ( void )input_pointer++, output_pointer++ ) - { - if ( ( *input_pointer > 31 ) && ( *input_pointer != '\"' ) && ( *input_pointer != '\\' ) ) - { + for ( input_pointer = input; *input_pointer != '\0'; ( void )input_pointer++, output_pointer++ ) { + if ( ( *input_pointer > 31 ) && ( *input_pointer != '\"' ) && ( *input_pointer != '\\' ) ) { /* normal character, copy */ *output_pointer = *input_pointer; - } - else - { + } else { /* character needs to be escaped */ *output_pointer++ = '\\'; - switch ( *input_pointer ) - { + switch ( *input_pointer ) { case '\\': *output_pointer = '\\'; break; @@ -1033,18 +915,15 @@ static cJSON_bool print_object( const cJSON *const item, printbuffer *const outp /* Utility to jump whitespace and cr/lf */ static parse_buffer *buffer_skip_whitespace( parse_buffer *const buffer ) { - if ( ( buffer == NULL ) || ( buffer->content == NULL ) ) - { + if ( ( buffer == NULL ) || ( buffer->content == NULL ) ) { return NULL; } - while ( can_access_at_index( buffer, 0 ) && ( buffer_at_offset( buffer )[0] <= 32 ) ) - { + while ( can_access_at_index( buffer, 0 ) && ( buffer_at_offset( buffer )[0] <= 32 ) ) { buffer->offset++; } - if ( buffer->offset == buffer->length ) - { + if ( buffer->offset == buffer->length ) { buffer->offset--; } @@ -1054,13 +933,11 @@ static parse_buffer *buffer_skip_whitespace( parse_buffer *const buffer ) /* skip the UTF-8 BOM (byte order mark) if it is at the beginning of a buffer */ static parse_buffer *skip_utf8_bom( parse_buffer *const buffer ) { - if ( ( buffer == NULL ) || ( buffer->content == NULL ) || ( buffer->offset != 0 ) ) - { + if ( ( buffer == NULL ) || ( buffer->content == NULL ) || ( buffer->offset != 0 ) ) { return NULL; } - if ( can_access_at_index( buffer, 4 ) && ( strncmp( ( const char * )buffer_at_offset( buffer ), "\xEF\xBB\xBF", 3 ) == 0 ) ) - { + if ( can_access_at_index( buffer, 4 ) && ( strncmp( ( const char * )buffer_at_offset( buffer ), "\xEF\xBB\xBF", 3 ) == 0 ) ) { buffer->offset += 3; } @@ -1077,8 +954,7 @@ CJSON_PUBLIC( cJSON * ) cJSON_ParseWithOpts( const char *value, const char **ret global_error.json = NULL; global_error.position = 0; - if ( value == NULL ) - { + if ( value == NULL ) { goto fail; } @@ -1089,30 +965,25 @@ CJSON_PUBLIC( cJSON * ) cJSON_ParseWithOpts( const char *value, const char **ret item = cJSON_New_Item( &global_hooks ); - if ( item == NULL ) /* memory fail */ - { + if ( item == NULL ) { /* memory fail */ goto fail; } - if ( !parse_value( item, buffer_skip_whitespace( skip_utf8_bom( &buffer ) ) ) ) - { + if ( !parse_value( item, buffer_skip_whitespace( skip_utf8_bom( &buffer ) ) ) ) { /* parse failure. ep is set. */ goto fail; } /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */ - if ( require_null_terminated ) - { + if ( require_null_terminated ) { buffer_skip_whitespace( &buffer ); - if ( ( buffer.offset >= buffer.length ) || buffer_at_offset( &buffer )[0] != '\0' ) - { + if ( ( buffer.offset >= buffer.length ) || buffer_at_offset( &buffer )[0] != '\0' ) { goto fail; } } - if ( return_parse_end ) - { + if ( return_parse_end ) { *return_parse_end = ( const char * )buffer_at_offset( &buffer ); } @@ -1120,28 +991,22 @@ CJSON_PUBLIC( cJSON * ) cJSON_ParseWithOpts( const char *value, const char **ret fail: - if ( item != NULL ) - { + if ( item != NULL ) { cJSON_Delete( item ); } - if ( value != NULL ) - { + if ( value != NULL ) { error local_error; local_error.json = ( const unsigned char * )value; local_error.position = 0; - if ( buffer.offset < buffer.length ) - { + if ( buffer.offset < buffer.length ) { local_error.position = buffer.offset; - } - else if ( buffer.length > 0 ) - { + } else if ( buffer.length > 0 ) { local_error.position = buffer.length - 1; } - if ( return_parse_end != NULL ) - { + if ( return_parse_end != NULL ) { *return_parse_end = ( const char * )local_error.json + local_error.position; } @@ -1173,37 +1038,30 @@ static unsigned char *print( const cJSON *const item, cJSON_bool format, const i buffer->format = format; buffer->hooks = *hooks; - if ( buffer->buffer == NULL ) - { + if ( buffer->buffer == NULL ) { goto fail; } /* print the value */ - if ( !print_value( item, buffer ) ) - { + if ( !print_value( item, buffer ) ) { goto fail; } update_offset( buffer ); /* check if reallocate is available */ - if ( hooks->reallocate != NULL ) - { + if ( hooks->reallocate != NULL ) { printed = ( unsigned char * ) hooks->reallocate( buffer->buffer, buffer->offset + 1 ); - if ( printed == NULL ) - { + if ( printed == NULL ) { goto fail; } buffer->buffer = NULL; - } - else /* otherwise copy the JSON over to a new buffer */ - { + } else { /* otherwise copy the JSON over to a new buffer */ printed = ( unsigned char * ) hooks->allocate( buffer->offset + 1 ); - if ( printed == NULL ) - { + if ( printed == NULL ) { goto fail; } @@ -1218,13 +1076,11 @@ static unsigned char *print( const cJSON *const item, cJSON_bool format, const i fail: - if ( buffer->buffer != NULL ) - { + if ( buffer->buffer != NULL ) { hooks->deallocate( buffer->buffer ); } - if ( printed != NULL ) - { + if ( printed != NULL ) { hooks->deallocate( printed ); } @@ -1246,15 +1102,13 @@ CJSON_PUBLIC( char * ) cJSON_PrintBuffered( const cJSON *item, int prebuffer, cJ { printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; - if ( prebuffer < 0 ) - { + if ( prebuffer < 0 ) { return NULL; } p.buffer = ( unsigned char * )global_hooks.allocate( ( size_t )prebuffer ); - if ( !p.buffer ) - { + if ( !p.buffer ) { return NULL; } @@ -1264,8 +1118,7 @@ CJSON_PUBLIC( char * ) cJSON_PrintBuffered( const cJSON *item, int prebuffer, cJ p.format = fmt; p.hooks = global_hooks; - if ( !print_value( item, &p ) ) - { + if ( !print_value( item, &p ) ) { global_hooks.deallocate( p.buffer ); return NULL; } @@ -1277,8 +1130,7 @@ CJSON_PUBLIC( cJSON_bool ) cJSON_PrintPreallocated( cJSON *item, char *buf, cons { printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; - if ( ( len < 0 ) || ( buf == NULL ) ) - { + if ( ( len < 0 ) || ( buf == NULL ) ) { return false; } @@ -1295,31 +1147,27 @@ CJSON_PUBLIC( cJSON_bool ) cJSON_PrintPreallocated( cJSON *item, char *buf, cons /* Parser core - when encountering text, process appropriately. */ static cJSON_bool parse_value( cJSON *const item, parse_buffer *const input_buffer ) { - if ( ( input_buffer == NULL ) || ( input_buffer->content == NULL ) ) - { + if ( ( input_buffer == NULL ) || ( input_buffer->content == NULL ) ) { return false; /* no input */ } /* parse the different types of values */ /* null */ - if ( can_read( input_buffer, 4 ) && ( strncmp( ( const char * )buffer_at_offset( input_buffer ), "null", 4 ) == 0 ) ) - { + if ( can_read( input_buffer, 4 ) && ( strncmp( ( const char * )buffer_at_offset( input_buffer ), "null", 4 ) == 0 ) ) { item->type = cJSON_NULL; input_buffer->offset += 4; return true; } /* false */ - if ( can_read( input_buffer, 5 ) && ( strncmp( ( const char * )buffer_at_offset( input_buffer ), "false", 5 ) == 0 ) ) - { + if ( can_read( input_buffer, 5 ) && ( strncmp( ( const char * )buffer_at_offset( input_buffer ), "false", 5 ) == 0 ) ) { item->type = cJSON_False; input_buffer->offset += 5; return true; } /* true */ - if ( can_read( input_buffer, 4 ) && ( strncmp( ( const char * )buffer_at_offset( input_buffer ), "true", 4 ) == 0 ) ) - { + if ( can_read( input_buffer, 4 ) && ( strncmp( ( const char * )buffer_at_offset( input_buffer ), "true", 4 ) == 0 ) ) { item->type = cJSON_True; item->valueint = 1; input_buffer->offset += 4; @@ -1327,27 +1175,23 @@ static cJSON_bool parse_value( cJSON *const item, parse_buffer *const input_buff } /* string */ - if ( can_access_at_index( input_buffer, 0 ) && ( buffer_at_offset( input_buffer )[0] == '\"' ) ) - { + if ( can_access_at_index( input_buffer, 0 ) && ( buffer_at_offset( input_buffer )[0] == '\"' ) ) { return parse_string( item, input_buffer ); } /* number */ if ( can_access_at_index( input_buffer, 0 ) && ( ( buffer_at_offset( input_buffer )[0] == '-' ) || ( ( buffer_at_offset( input_buffer )[0] >= '0' ) - && ( buffer_at_offset( input_buffer )[0] <= '9' ) ) ) ) - { + && ( buffer_at_offset( input_buffer )[0] <= '9' ) ) ) ) { return parse_number( item, input_buffer ); } /* array */ - if ( can_access_at_index( input_buffer, 0 ) && ( buffer_at_offset( input_buffer )[0] == '[' ) ) - { + if ( can_access_at_index( input_buffer, 0 ) && ( buffer_at_offset( input_buffer )[0] == '[' ) ) { return parse_array( item, input_buffer ); } /* object */ - if ( can_access_at_index( input_buffer, 0 ) && ( buffer_at_offset( input_buffer )[0] == '{' ) ) - { + if ( can_access_at_index( input_buffer, 0 ) && ( buffer_at_offset( input_buffer )[0] == '{' ) ) { return parse_object( item, input_buffer ); } @@ -1359,18 +1203,15 @@ static cJSON_bool print_value( const cJSON *const item, printbuffer *const outpu { unsigned char *output = NULL; - if ( ( item == NULL ) || ( output_buffer == NULL ) ) - { + if ( ( item == NULL ) || ( output_buffer == NULL ) ) { return false; } - switch ( ( item->type ) & 0xFF ) - { + switch ( ( item->type ) & 0xFF ) { case cJSON_NULL: output = ensure( output_buffer, 5 ); - if ( output == NULL ) - { + if ( output == NULL ) { return false; } @@ -1380,8 +1221,7 @@ static cJSON_bool print_value( const cJSON *const item, printbuffer *const outpu case cJSON_False: output = ensure( output_buffer, 6 ); - if ( output == NULL ) - { + if ( output == NULL ) { return false; } @@ -1391,8 +1231,7 @@ static cJSON_bool print_value( const cJSON *const item, printbuffer *const outpu case cJSON_True: output = ensure( output_buffer, 5 ); - if ( output == NULL ) - { + if ( output == NULL ) { return false; } @@ -1402,20 +1241,17 @@ static cJSON_bool print_value( const cJSON *const item, printbuffer *const outpu case cJSON_Number: return print_number( item, output_buffer ); - case cJSON_Raw: - { + case cJSON_Raw: { size_t raw_length = 0; - if ( item->valuestring == NULL ) - { + if ( item->valuestring == NULL ) { return false; } raw_length = strlen( item->valuestring ) + sizeof( "" ); output = ensure( output_buffer, raw_length ); - if ( output == NULL ) - { + if ( output == NULL ) { return false; } @@ -1443,15 +1279,13 @@ static cJSON_bool parse_array( cJSON *const item, parse_buffer *const input_buff cJSON *head = NULL; /* head of the linked list */ cJSON *current_item = NULL; - if ( input_buffer->depth >= CJSON_NESTING_LIMIT ) - { + if ( input_buffer->depth >= CJSON_NESTING_LIMIT ) { return false; /* to deeply nested */ } input_buffer->depth++; - if ( buffer_at_offset( input_buffer )[0] != '[' ) - { + if ( buffer_at_offset( input_buffer )[0] != '[' ) { /* not an array */ goto fail; } @@ -1459,15 +1293,13 @@ static cJSON_bool parse_array( cJSON *const item, parse_buffer *const input_buff input_buffer->offset++; buffer_skip_whitespace( input_buffer ); - if ( can_access_at_index( input_buffer, 0 ) && ( buffer_at_offset( input_buffer )[0] == ']' ) ) - { + if ( can_access_at_index( input_buffer, 0 ) && ( buffer_at_offset( input_buffer )[0] == ']' ) ) { /* empty array */ goto success; } /* check if we skipped to the end of the buffer */ - if ( cannot_access_at_index( input_buffer, 0 ) ) - { + if ( cannot_access_at_index( input_buffer, 0 ) ) { input_buffer->offset--; goto fail; } @@ -1476,24 +1308,19 @@ static cJSON_bool parse_array( cJSON *const item, parse_buffer *const input_buff input_buffer->offset--; /* loop through the comma separated array elements */ - do - { + do { /* allocate next item */ cJSON *new_item = cJSON_New_Item( &( input_buffer->hooks ) ); - if ( new_item == NULL ) - { + if ( new_item == NULL ) { goto fail; /* allocation failure */ } /* attach next item to list */ - if ( head == NULL ) - { + if ( head == NULL ) { /* start the linked list */ current_item = head = new_item; - } - else - { + } else { /* add to the end and advance */ current_item->next = new_item; new_item->prev = current_item; @@ -1504,17 +1331,14 @@ static cJSON_bool parse_array( cJSON *const item, parse_buffer *const input_buff input_buffer->offset++; buffer_skip_whitespace( input_buffer ); - if ( !parse_value( current_item, input_buffer ) ) - { + if ( !parse_value( current_item, input_buffer ) ) { goto fail; /* failed to parse value */ } buffer_skip_whitespace( input_buffer ); - } - while ( can_access_at_index( input_buffer, 0 ) && ( buffer_at_offset( input_buffer )[0] == ',' ) ); + } while ( can_access_at_index( input_buffer, 0 ) && ( buffer_at_offset( input_buffer )[0] == ',' ) ); - if ( cannot_access_at_index( input_buffer, 0 ) || buffer_at_offset( input_buffer )[0] != ']' ) - { + if ( cannot_access_at_index( input_buffer, 0 ) || buffer_at_offset( input_buffer )[0] != ']' ) { goto fail; /* expected end of array */ } @@ -1530,8 +1354,7 @@ static cJSON_bool parse_array( cJSON *const item, parse_buffer *const input_buff fail: - if ( head != NULL ) - { + if ( head != NULL ) { cJSON_Delete( head ); } @@ -1545,8 +1368,7 @@ static cJSON_bool print_array( const cJSON *const item, printbuffer *const outpu size_t length = 0; cJSON *current_element = item->child; - if ( output_buffer == NULL ) - { + if ( output_buffer == NULL ) { return false; } @@ -1554,8 +1376,7 @@ static cJSON_bool print_array( const cJSON *const item, printbuffer *const outpu /* opening square bracket */ output_pointer = ensure( output_buffer, 1 ); - if ( output_pointer == NULL ) - { + if ( output_pointer == NULL ) { return false; } @@ -1563,29 +1384,24 @@ static cJSON_bool print_array( const cJSON *const item, printbuffer *const outpu output_buffer->offset++; output_buffer->depth++; - while ( current_element != NULL ) - { - if ( !print_value( current_element, output_buffer ) ) - { + while ( current_element != NULL ) { + if ( !print_value( current_element, output_buffer ) ) { return false; } update_offset( output_buffer ); - if ( current_element->next ) - { + if ( current_element->next ) { length = ( size_t ) ( output_buffer->format ? 2 : 1 ); output_pointer = ensure( output_buffer, length + 1 ); - if ( output_pointer == NULL ) - { + if ( output_pointer == NULL ) { return false; } *output_pointer++ = ','; - if ( output_buffer->format ) - { + if ( output_buffer->format ) { *output_pointer++ = ' '; } @@ -1598,8 +1414,7 @@ static cJSON_bool print_array( const cJSON *const item, printbuffer *const outpu output_pointer = ensure( output_buffer, 2 ); - if ( output_pointer == NULL ) - { + if ( output_pointer == NULL ) { return false; } @@ -1616,29 +1431,25 @@ static cJSON_bool parse_object( cJSON *const item, parse_buffer *const input_buf cJSON *head = NULL; /* linked list head */ cJSON *current_item = NULL; - if ( input_buffer->depth >= CJSON_NESTING_LIMIT ) - { + if ( input_buffer->depth >= CJSON_NESTING_LIMIT ) { return false; /* to deeply nested */ } input_buffer->depth++; - if ( cannot_access_at_index( input_buffer, 0 ) || ( buffer_at_offset( input_buffer )[0] != '{' ) ) - { + if ( cannot_access_at_index( input_buffer, 0 ) || ( buffer_at_offset( input_buffer )[0] != '{' ) ) { goto fail; /* not an object */ } input_buffer->offset++; buffer_skip_whitespace( input_buffer ); - if ( can_access_at_index( input_buffer, 0 ) && ( buffer_at_offset( input_buffer )[0] == '}' ) ) - { + if ( can_access_at_index( input_buffer, 0 ) && ( buffer_at_offset( input_buffer )[0] == '}' ) ) { goto success; /* empty object */ } /* check if we skipped to the end of the buffer */ - if ( cannot_access_at_index( input_buffer, 0 ) ) - { + if ( cannot_access_at_index( input_buffer, 0 ) ) { input_buffer->offset--; goto fail; } @@ -1647,24 +1458,19 @@ static cJSON_bool parse_object( cJSON *const item, parse_buffer *const input_buf input_buffer->offset--; /* loop through the comma separated array elements */ - do - { + do { /* allocate next item */ cJSON *new_item = cJSON_New_Item( &( input_buffer->hooks ) ); - if ( new_item == NULL ) - { + if ( new_item == NULL ) { goto fail; /* allocation failure */ } /* attach next item to list */ - if ( head == NULL ) - { + if ( head == NULL ) { /* start the linked list */ current_item = head = new_item; - } - else - { + } else { /* add to the end and advance */ current_item->next = new_item; new_item->prev = current_item; @@ -1675,8 +1481,7 @@ static cJSON_bool parse_object( cJSON *const item, parse_buffer *const input_buf input_buffer->offset++; buffer_skip_whitespace( input_buffer ); - if ( !parse_string( current_item, input_buffer ) ) - { + if ( !parse_string( current_item, input_buffer ) ) { goto fail; /* failed to parse name */ } @@ -1686,8 +1491,7 @@ static cJSON_bool parse_object( cJSON *const item, parse_buffer *const input_buf current_item->string = current_item->valuestring; current_item->valuestring = NULL; - if ( cannot_access_at_index( input_buffer, 0 ) || ( buffer_at_offset( input_buffer )[0] != ':' ) ) - { + if ( cannot_access_at_index( input_buffer, 0 ) || ( buffer_at_offset( input_buffer )[0] != ':' ) ) { goto fail; /* invalid object */ } @@ -1695,17 +1499,14 @@ static cJSON_bool parse_object( cJSON *const item, parse_buffer *const input_buf input_buffer->offset++; buffer_skip_whitespace( input_buffer ); - if ( !parse_value( current_item, input_buffer ) ) - { + if ( !parse_value( current_item, input_buffer ) ) { goto fail; /* failed to parse value */ } buffer_skip_whitespace( input_buffer ); - } - while ( can_access_at_index( input_buffer, 0 ) && ( buffer_at_offset( input_buffer )[0] == ',' ) ); + } while ( can_access_at_index( input_buffer, 0 ) && ( buffer_at_offset( input_buffer )[0] == ',' ) ); - if ( cannot_access_at_index( input_buffer, 0 ) || ( buffer_at_offset( input_buffer )[0] != '}' ) ) - { + if ( cannot_access_at_index( input_buffer, 0 ) || ( buffer_at_offset( input_buffer )[0] != '}' ) ) { goto fail; /* expected end of object */ } @@ -1720,8 +1521,7 @@ static cJSON_bool parse_object( cJSON *const item, parse_buffer *const input_buf fail: - if ( head != NULL ) - { + if ( head != NULL ) { cJSON_Delete( head ); } @@ -1735,8 +1535,7 @@ static cJSON_bool print_object( const cJSON *const item, printbuffer *const outp size_t length = 0; cJSON *current_item = item->child; - if ( output_buffer == NULL ) - { + if ( output_buffer == NULL ) { return false; } @@ -1744,35 +1543,29 @@ static cJSON_bool print_object( const cJSON *const item, printbuffer *const outp length = ( size_t ) ( output_buffer->format ? 2 : 1 ); /* fmt: {\n */ output_pointer = ensure( output_buffer, length + 1 ); - if ( output_pointer == NULL ) - { + if ( output_pointer == NULL ) { return false; } *output_pointer++ = '{'; output_buffer->depth++; - if ( output_buffer->format ) - { + if ( output_buffer->format ) { *output_pointer++ = '\n'; } output_buffer->offset += length; - while ( current_item ) - { - if ( output_buffer->format ) - { + while ( current_item ) { + if ( output_buffer->format ) { size_t i; output_pointer = ensure( output_buffer, output_buffer->depth ); - if ( output_pointer == NULL ) - { + if ( output_pointer == NULL ) { return false; } - for ( i = 0; i < output_buffer->depth; i++ ) - { + for ( i = 0; i < output_buffer->depth; i++ ) { *output_pointer++ = '\t'; } @@ -1780,8 +1573,7 @@ static cJSON_bool print_object( const cJSON *const item, printbuffer *const outp } /* print key */ - if ( !print_string_ptr( ( unsigned char * )current_item->string, output_buffer ) ) - { + if ( !print_string_ptr( ( unsigned char * )current_item->string, output_buffer ) ) { return false; } @@ -1790,23 +1582,20 @@ static cJSON_bool print_object( const cJSON *const item, printbuffer *const outp length = ( size_t ) ( output_buffer->format ? 2 : 1 ); output_pointer = ensure( output_buffer, length ); - if ( output_pointer == NULL ) - { + if ( output_pointer == NULL ) { return false; } *output_pointer++ = ':'; - if ( output_buffer->format ) - { + if ( output_buffer->format ) { *output_pointer++ = '\t'; } output_buffer->offset += length; /* print value */ - if ( !print_value( current_item, output_buffer ) ) - { + if ( !print_value( current_item, output_buffer ) ) { return false; } @@ -1816,18 +1605,15 @@ static cJSON_bool print_object( const cJSON *const item, printbuffer *const outp length = ( ( size_t )( output_buffer->format ? 1 : 0 ) + ( size_t )( current_item->next ? 1 : 0 ) ); output_pointer = ensure( output_buffer, length + 1 ); - if ( output_pointer == NULL ) - { + if ( output_pointer == NULL ) { return false; } - if ( current_item->next ) - { + if ( current_item->next ) { *output_pointer++ = ','; } - if ( output_buffer->format ) - { + if ( output_buffer->format ) { *output_pointer++ = '\n'; } @@ -1839,17 +1625,14 @@ static cJSON_bool print_object( const cJSON *const item, printbuffer *const outp output_pointer = ensure( output_buffer, output_buffer->format ? ( output_buffer->depth + 1 ) : 2 ); - if ( output_pointer == NULL ) - { + if ( output_pointer == NULL ) { return false; } - if ( output_buffer->format ) - { + if ( output_buffer->format ) { size_t i; - for ( i = 0; i < ( output_buffer->depth - 1 ); i++ ) - { + for ( i = 0; i < ( output_buffer->depth - 1 ); i++ ) { *output_pointer++ = '\t'; } } @@ -1867,15 +1650,13 @@ CJSON_PUBLIC( int ) cJSON_GetArraySize( const cJSON *array ) cJSON *child = NULL; size_t size = 0; - if ( array == NULL ) - { + if ( array == NULL ) { return 0; } child = array->child; - while ( child != NULL ) - { + while ( child != NULL ) { size++; child = child->next; } @@ -1889,15 +1670,13 @@ static cJSON *get_array_item( const cJSON *array, size_t index ) { cJSON *current_child = NULL; - if ( array == NULL ) - { + if ( array == NULL ) { return NULL; } current_child = array->child; - while ( ( current_child != NULL ) && ( index > 0 ) ) - { + while ( ( current_child != NULL ) && ( index > 0 ) ) { index--; current_child = current_child->next; } @@ -1907,8 +1686,7 @@ static cJSON *get_array_item( const cJSON *array, size_t index ) CJSON_PUBLIC( cJSON * ) cJSON_GetArrayItem( const cJSON *array, int index ) { - if ( index < 0 ) - { + if ( index < 0 ) { return NULL; } @@ -1919,30 +1697,23 @@ static cJSON *get_object_item( const cJSON *const object, const char *const name { cJSON *current_element = NULL; - if ( ( object == NULL ) || ( name == NULL ) ) - { + if ( ( object == NULL ) || ( name == NULL ) ) { return NULL; } current_element = object->child; - if ( case_sensitive ) - { - while ( ( current_element != NULL ) && ( current_element->string != NULL ) && ( strcmp( name, current_element->string ) != 0 ) ) - { + if ( case_sensitive ) { + while ( ( current_element != NULL ) && ( current_element->string != NULL ) && ( strcmp( name, current_element->string ) != 0 ) ) { current_element = current_element->next; } - } - else - { - while ( ( current_element != NULL ) && ( case_insensitive_strcmp( ( const unsigned char * )name, ( const unsigned char * )( current_element->string ) ) != 0 ) ) - { + } else { + while ( ( current_element != NULL ) && ( case_insensitive_strcmp( ( const unsigned char * )name, ( const unsigned char * )( current_element->string ) ) != 0 ) ) { current_element = current_element->next; } } - if ( ( current_element == NULL ) || ( current_element->string == NULL ) ) - { + if ( ( current_element == NULL ) || ( current_element->string == NULL ) ) { return NULL; } @@ -1976,15 +1747,13 @@ static cJSON *create_reference( const cJSON *item, const internal_hooks *const h { cJSON *reference = NULL; - if ( item == NULL ) - { + if ( item == NULL ) { return NULL; } reference = cJSON_New_Item( hooks ); - if ( reference == NULL ) - { + if ( reference == NULL ) { return NULL; } @@ -1999,23 +1768,18 @@ static cJSON_bool add_item_to_array( cJSON *array, cJSON *item ) { cJSON *child = NULL; - if ( ( item == NULL ) || ( array == NULL ) ) - { + if ( ( item == NULL ) || ( array == NULL ) ) { return false; } child = array->child; - if ( child == NULL ) - { + if ( child == NULL ) { /* list is empty, start new one */ array->child = item; - } - else - { + } else { /* append to the end */ - while ( child->next ) - { + while ( child->next ) { child = child->next; } @@ -2052,30 +1816,24 @@ static cJSON_bool add_item_to_object( cJSON *const object, const char *const str char *new_key = NULL; int new_type = cJSON_Invalid; - if ( ( object == NULL ) || ( string == NULL ) || ( item == NULL ) ) - { + if ( ( object == NULL ) || ( string == NULL ) || ( item == NULL ) ) { return false; } - if ( constant_key ) - { + if ( constant_key ) { new_key = ( char * )cast_away_const( string ); new_type = item->type | cJSON_StringIsConst; - } - else - { + } else { new_key = ( char * )cJSON_strdup( ( const unsigned char * )string, hooks ); - if ( new_key == NULL ) - { + if ( new_key == NULL ) { return false; } new_type = item->type & ~cJSON_StringIsConst; } - if ( !( item->type & cJSON_StringIsConst ) && ( item->string != NULL ) ) - { + if ( !( item->type & cJSON_StringIsConst ) && ( item->string != NULL ) ) { hooks->deallocate( item->string ); } @@ -2098,8 +1856,7 @@ CJSON_PUBLIC( void ) cJSON_AddItemToObjectCS( cJSON *object, const char *string, CJSON_PUBLIC( void ) cJSON_AddItemReferenceToArray( cJSON *array, cJSON *item ) { - if ( array == NULL ) - { + if ( array == NULL ) { return; } @@ -2108,8 +1865,7 @@ CJSON_PUBLIC( void ) cJSON_AddItemReferenceToArray( cJSON *array, cJSON *item ) CJSON_PUBLIC( void ) cJSON_AddItemReferenceToObject( cJSON *object, const char *string, cJSON *item ) { - if ( ( object == NULL ) || ( string == NULL ) ) - { + if ( ( object == NULL ) || ( string == NULL ) ) { return; } @@ -2120,8 +1876,7 @@ CJSON_PUBLIC( cJSON * ) cJSON_AddNullToObject( cJSON *const object, const char * { cJSON *null = cJSON_CreateNull(); - if ( add_item_to_object( object, name, null, &global_hooks, false ) ) - { + if ( add_item_to_object( object, name, null, &global_hooks, false ) ) { return null; } @@ -2133,8 +1888,7 @@ CJSON_PUBLIC( cJSON * ) cJSON_AddTrueToObject( cJSON *const object, const char * { cJSON *true_item = cJSON_CreateTrue(); - if ( add_item_to_object( object, name, true_item, &global_hooks, false ) ) - { + if ( add_item_to_object( object, name, true_item, &global_hooks, false ) ) { return true_item; } @@ -2146,8 +1900,7 @@ CJSON_PUBLIC( cJSON * ) cJSON_AddFalseToObject( cJSON *const object, const char { cJSON *false_item = cJSON_CreateFalse(); - if ( add_item_to_object( object, name, false_item, &global_hooks, false ) ) - { + if ( add_item_to_object( object, name, false_item, &global_hooks, false ) ) { return false_item; } @@ -2159,8 +1912,7 @@ CJSON_PUBLIC( cJSON * ) cJSON_AddBoolToObject( cJSON *const object, const char * { cJSON *bool_item = cJSON_CreateBool( boolean ); - if ( add_item_to_object( object, name, bool_item, &global_hooks, false ) ) - { + if ( add_item_to_object( object, name, bool_item, &global_hooks, false ) ) { return bool_item; } @@ -2172,8 +1924,7 @@ CJSON_PUBLIC( cJSON * ) cJSON_AddNumberToObject( cJSON *const object, const char { cJSON *number_item = cJSON_CreateNumber( number ); - if ( add_item_to_object( object, name, number_item, &global_hooks, false ) ) - { + if ( add_item_to_object( object, name, number_item, &global_hooks, false ) ) { return number_item; } @@ -2185,8 +1936,7 @@ CJSON_PUBLIC( cJSON * ) cJSON_AddStringToObject( cJSON *const object, const char { cJSON *string_item = cJSON_CreateString( string ); - if ( add_item_to_object( object, name, string_item, &global_hooks, false ) ) - { + if ( add_item_to_object( object, name, string_item, &global_hooks, false ) ) { return string_item; } @@ -2198,8 +1948,7 @@ CJSON_PUBLIC( cJSON * ) cJSON_AddRawToObject( cJSON *const object, const char *c { cJSON *raw_item = cJSON_CreateRaw( raw ); - if ( add_item_to_object( object, name, raw_item, &global_hooks, false ) ) - { + if ( add_item_to_object( object, name, raw_item, &global_hooks, false ) ) { return raw_item; } @@ -2211,8 +1960,7 @@ CJSON_PUBLIC( cJSON * ) cJSON_AddObjectToObject( cJSON *const object, const char { cJSON *object_item = cJSON_CreateObject(); - if ( add_item_to_object( object, name, object_item, &global_hooks, false ) ) - { + if ( add_item_to_object( object, name, object_item, &global_hooks, false ) ) { return object_item; } @@ -2224,8 +1972,7 @@ CJSON_PUBLIC( cJSON * ) cJSON_AddArrayToObject( cJSON *const object, const char { cJSON *array = cJSON_CreateArray(); - if ( add_item_to_object( object, name, array, &global_hooks, false ) ) - { + if ( add_item_to_object( object, name, array, &global_hooks, false ) ) { return array; } @@ -2235,30 +1982,25 @@ CJSON_PUBLIC( cJSON * ) cJSON_AddArrayToObject( cJSON *const object, const char CJSON_PUBLIC( cJSON * ) cJSON_DetachItemViaPointer( cJSON *parent, cJSON *const item ) { - if ( item == NULL ) - { + if ( item == NULL ) { return NULL; } - if ( parent == NULL ) - { + if ( parent == NULL ) { return NULL; } - if ( item->prev != NULL ) - { + if ( item->prev != NULL ) { /* not the first element */ item->prev->next = item->next; } - if ( item->next != NULL ) - { + if ( item->next != NULL ) { /* not the last element */ item->next->prev = item->prev; } - if ( item == parent->child ) - { + if ( item == parent->child ) { /* first element */ parent->child = item->next; } @@ -2272,8 +2014,7 @@ CJSON_PUBLIC( cJSON * ) cJSON_DetachItemViaPointer( cJSON *parent, cJSON *const CJSON_PUBLIC( cJSON * ) cJSON_DetachItemFromArray( cJSON *array, int which ) { - if ( which < 0 ) - { + if ( which < 0 ) { return NULL; } @@ -2314,20 +2055,17 @@ CJSON_PUBLIC( void ) cJSON_InsertItemInArray( cJSON *array, int which, cJSON *ne { cJSON *after_inserted = NULL; - if ( NULL == array ) - { + if ( NULL == array ) { return; } - if ( which < 0 ) - { + if ( which < 0 ) { return; } after_inserted = get_array_item( array, ( size_t )which ); - if ( after_inserted == NULL ) - { + if ( after_inserted == NULL ) { add_item_to_array( array, newitem ); return; } @@ -2336,43 +2074,35 @@ CJSON_PUBLIC( void ) cJSON_InsertItemInArray( cJSON *array, int which, cJSON *ne newitem->prev = after_inserted->prev; after_inserted->prev = newitem; - if ( after_inserted == array->child ) - { + if ( after_inserted == array->child ) { array->child = newitem; - } - else - { + } else { newitem->prev->next = newitem; } } CJSON_PUBLIC( cJSON_bool ) cJSON_ReplaceItemViaPointer( cJSON *const parent, cJSON *const item, cJSON *replacement ) { - if ( ( parent == NULL ) || ( replacement == NULL ) || ( item == NULL ) ) - { + if ( ( parent == NULL ) || ( replacement == NULL ) || ( item == NULL ) ) { return false; } - if ( replacement == item ) - { + if ( replacement == item ) { return true; } replacement->next = item->next; replacement->prev = item->prev; - if ( replacement->next != NULL ) - { + if ( replacement->next != NULL ) { replacement->next->prev = replacement; } - if ( replacement->prev != NULL ) - { + if ( replacement->prev != NULL ) { replacement->prev->next = replacement; } - if ( parent->child == item ) - { + if ( parent->child == item ) { parent->child = replacement; } @@ -2385,8 +2115,7 @@ CJSON_PUBLIC( cJSON_bool ) cJSON_ReplaceItemViaPointer( cJSON *const parent, cJS CJSON_PUBLIC( void ) cJSON_ReplaceItemInArray( cJSON *array, int which, cJSON *newitem ) { - if ( which < 0 ) - { + if ( which < 0 ) { return; } @@ -2395,14 +2124,12 @@ CJSON_PUBLIC( void ) cJSON_ReplaceItemInArray( cJSON *array, int which, cJSON *n static cJSON_bool replace_item_in_object( cJSON *object, const char *string, cJSON *replacement, cJSON_bool case_sensitive ) { - if ( ( replacement == NULL ) || ( string == NULL ) ) - { + if ( ( replacement == NULL ) || ( string == NULL ) ) { return false; } /* replace the name in the replacement */ - if ( !( replacement->type & cJSON_StringIsConst ) && ( replacement->string != NULL ) ) - { + if ( !( replacement->type & cJSON_StringIsConst ) && ( replacement->string != NULL ) ) { cJSON_free( replacement->string ); } @@ -2429,8 +2156,7 @@ CJSON_PUBLIC( cJSON * ) cJSON_CreateNull( void ) { cJSON *item = cJSON_New_Item( &global_hooks ); - if ( item ) - { + if ( item ) { item->type = cJSON_NULL; } @@ -2441,8 +2167,7 @@ CJSON_PUBLIC( cJSON * ) cJSON_CreateTrue( void ) { cJSON *item = cJSON_New_Item( &global_hooks ); - if ( item ) - { + if ( item ) { item->type = cJSON_True; } @@ -2453,8 +2178,7 @@ CJSON_PUBLIC( cJSON * ) cJSON_CreateFalse( void ) { cJSON *item = cJSON_New_Item( &global_hooks ); - if ( item ) - { + if ( item ) { item->type = cJSON_False; } @@ -2465,8 +2189,7 @@ CJSON_PUBLIC( cJSON * ) cJSON_CreateBool( cJSON_bool b ) { cJSON *item = cJSON_New_Item( &global_hooks ); - if ( item ) - { + if ( item ) { item->type = b ? cJSON_True : cJSON_False; } @@ -2477,22 +2200,16 @@ CJSON_PUBLIC( cJSON * ) cJSON_CreateNumber( double num ) { cJSON *item = cJSON_New_Item( &global_hooks ); - if ( item ) - { + if ( item ) { item->type = cJSON_Number; item->valuedouble = num; /* use saturation in case of overflow */ - if ( num >= INT_MAX ) - { + if ( num >= INT_MAX ) { item->valueint = INT_MAX; - } - else if ( num <= ( double )INT_MIN ) - { + } else if ( num <= ( double )INT_MIN ) { item->valueint = INT_MIN; - } - else - { + } else { item->valueint = ( int )num; } } @@ -2504,13 +2221,11 @@ CJSON_PUBLIC( cJSON * ) cJSON_CreateString( const char *string ) { cJSON *item = cJSON_New_Item( &global_hooks ); - if ( item ) - { + if ( item ) { item->type = cJSON_String; item->valuestring = ( char * )cJSON_strdup( ( const unsigned char * )string, &global_hooks ); - if ( !item->valuestring ) - { + if ( !item->valuestring ) { cJSON_Delete( item ); return NULL; } @@ -2523,8 +2238,7 @@ CJSON_PUBLIC( cJSON * ) cJSON_CreateStringReference( const char *string ) { cJSON *item = cJSON_New_Item( &global_hooks ); - if ( item != NULL ) - { + if ( item != NULL ) { item->type = cJSON_String | cJSON_IsReference; item->valuestring = ( char * )cast_away_const( string ); } @@ -2536,8 +2250,7 @@ CJSON_PUBLIC( cJSON * ) cJSON_CreateObjectReference( const cJSON *child ) { cJSON *item = cJSON_New_Item( &global_hooks ); - if ( item != NULL ) - { + if ( item != NULL ) { item->type = cJSON_Object | cJSON_IsReference; item->child = ( cJSON * )cast_away_const( child ); } @@ -2549,8 +2262,7 @@ CJSON_PUBLIC( cJSON * ) cJSON_CreateArrayReference( const cJSON *child ) { cJSON *item = cJSON_New_Item( &global_hooks ); - if ( item != NULL ) - { + if ( item != NULL ) { item->type = cJSON_Array | cJSON_IsReference; item->child = ( cJSON * )cast_away_const( child ); } @@ -2562,13 +2274,11 @@ CJSON_PUBLIC( cJSON * ) cJSON_CreateRaw( const char *raw ) { cJSON *item = cJSON_New_Item( &global_hooks ); - if ( item ) - { + if ( item ) { item->type = cJSON_Raw; item->valuestring = ( char * )cJSON_strdup( ( const unsigned char * )raw, &global_hooks ); - if ( !item->valuestring ) - { + if ( !item->valuestring ) { cJSON_Delete( item ); return NULL; } @@ -2581,8 +2291,7 @@ CJSON_PUBLIC( cJSON * ) cJSON_CreateArray( void ) { cJSON *item = cJSON_New_Item( &global_hooks ); - if ( item ) - { + if ( item ) { item->type = cJSON_Array; } @@ -2593,8 +2302,7 @@ CJSON_PUBLIC( cJSON * ) cJSON_CreateObject( void ) { cJSON *item = cJSON_New_Item( &global_hooks ); - if ( item ) - { + if ( item ) { item->type = cJSON_Object; } @@ -2609,29 +2317,23 @@ CJSON_PUBLIC( cJSON * ) cJSON_CreateIntArray( const int *numbers, int count ) cJSON *p = NULL; cJSON *a = NULL; - if ( ( count < 0 ) || ( numbers == NULL ) ) - { + if ( ( count < 0 ) || ( numbers == NULL ) ) { return NULL; } a = cJSON_CreateArray(); - for ( i = 0; a && ( i < ( size_t )count ); i++ ) - { + for ( i = 0; a && ( i < ( size_t )count ); i++ ) { n = cJSON_CreateNumber( numbers[i] ); - if ( !n ) - { + if ( !n ) { cJSON_Delete( a ); return NULL; } - if ( !i ) - { + if ( !i ) { a->child = n; - } - else - { + } else { suffix_object( p, n ); } @@ -2648,29 +2350,23 @@ CJSON_PUBLIC( cJSON * ) cJSON_CreateFloatArray( const float *numbers, int count cJSON *p = NULL; cJSON *a = NULL; - if ( ( count < 0 ) || ( numbers == NULL ) ) - { + if ( ( count < 0 ) || ( numbers == NULL ) ) { return NULL; } a = cJSON_CreateArray(); - for ( i = 0; a && ( i < ( size_t )count ); i++ ) - { + for ( i = 0; a && ( i < ( size_t )count ); i++ ) { n = cJSON_CreateNumber( ( double )numbers[i] ); - if ( !n ) - { + if ( !n ) { cJSON_Delete( a ); return NULL; } - if ( !i ) - { + if ( !i ) { a->child = n; - } - else - { + } else { suffix_object( p, n ); } @@ -2687,29 +2383,23 @@ CJSON_PUBLIC( cJSON * ) cJSON_CreateDoubleArray( const double *numbers, int coun cJSON *p = NULL; cJSON *a = NULL; - if ( ( count < 0 ) || ( numbers == NULL ) ) - { + if ( ( count < 0 ) || ( numbers == NULL ) ) { return NULL; } a = cJSON_CreateArray(); - for ( i = 0; a && ( i < ( size_t )count ); i++ ) - { + for ( i = 0; a && ( i < ( size_t )count ); i++ ) { n = cJSON_CreateNumber( numbers[i] ); - if ( !n ) - { + if ( !n ) { cJSON_Delete( a ); return NULL; } - if ( !i ) - { + if ( !i ) { a->child = n; - } - else - { + } else { suffix_object( p, n ); } @@ -2726,29 +2416,23 @@ CJSON_PUBLIC( cJSON * ) cJSON_CreateStringArray( const char **strings, int count cJSON *p = NULL; cJSON *a = NULL; - if ( ( count < 0 ) || ( strings == NULL ) ) - { + if ( ( count < 0 ) || ( strings == NULL ) ) { return NULL; } a = cJSON_CreateArray(); - for ( i = 0; a && ( i < ( size_t )count ); i++ ) - { + for ( i = 0; a && ( i < ( size_t )count ); i++ ) { n = cJSON_CreateString( strings[i] ); - if ( !n ) - { + if ( !n ) { cJSON_Delete( a ); return NULL; } - if ( !i ) - { + if ( !i ) { a->child = n; - } - else - { + } else { suffix_object( p, n ); } @@ -2767,16 +2451,14 @@ CJSON_PUBLIC( cJSON * ) cJSON_Duplicate( const cJSON *item, cJSON_bool recurse ) cJSON *newchild = NULL; /* Bail on bad ptr */ - if ( !item ) - { + if ( !item ) { goto fail; } /* Create new item */ newitem = cJSON_New_Item( &global_hooks ); - if ( !newitem ) - { + if ( !newitem ) { goto fail; } @@ -2785,53 +2467,43 @@ CJSON_PUBLIC( cJSON * ) cJSON_Duplicate( const cJSON *item, cJSON_bool recurse ) newitem->valueint = item->valueint; newitem->valuedouble = item->valuedouble; - if ( item->valuestring ) - { + if ( item->valuestring ) { newitem->valuestring = ( char * )cJSON_strdup( ( unsigned char * )item->valuestring, &global_hooks ); - if ( !newitem->valuestring ) - { + if ( !newitem->valuestring ) { goto fail; } } - if ( item->string ) - { + if ( item->string ) { newitem->string = ( item->type & cJSON_StringIsConst ) ? item->string : ( char * )cJSON_strdup( ( unsigned char * )item->string, &global_hooks ); - if ( !newitem->string ) - { + if ( !newitem->string ) { goto fail; } } /* If non-recursive, then we're done! */ - if ( !recurse ) - { + if ( !recurse ) { return newitem; } /* Walk the ->next chain for the child. */ child = item->child; - while ( child != NULL ) - { + while ( child != NULL ) { newchild = cJSON_Duplicate( child, true ); /* Duplicate (with recurse) each item in the ->next chain */ - if ( !newchild ) - { + if ( !newchild ) { goto fail; } - if ( next != NULL ) - { + if ( next != NULL ) { /* If newitem->child already set, then crosswire ->prev and ->next and move on */ next->next = newchild; newchild->prev = next; next = newchild; - } - else - { + } else { /* Set newitem->child and move to it */ newitem->child = newchild; next = newchild; @@ -2844,8 +2516,7 @@ CJSON_PUBLIC( cJSON * ) cJSON_Duplicate( const cJSON *item, cJSON_bool recurse ) fail: - if ( newitem != NULL ) - { + if ( newitem != NULL ) { cJSON_Delete( newitem ); } @@ -2856,10 +2527,8 @@ static void skip_oneline_comment( char **input ) { *input += static_strlen( "//" ); - for ( ; ( *input )[0] != '\0'; ++( *input ) ) - { - if ( ( *input )[0] == '\n' ) - { + for ( ; ( *input )[0] != '\0'; ++( *input ) ) { + if ( ( *input )[0] == '\n' ) { *input += static_strlen( "\n" ); return; } @@ -2870,10 +2539,8 @@ static void skip_multiline_comment( char **input ) { *input += static_strlen( "/*" ); - for ( ; ( *input )[0] != '\0'; ++( *input ) ) - { - if ( ( ( *input )[0] == '*' ) && ( ( *input )[1] == '/' ) ) - { + for ( ; ( *input )[0] != '\0'; ++( *input ) ) { + if ( ( ( *input )[0] == '*' ) && ( ( *input )[1] == '/' ) ) { *input += static_strlen( "*/" ); return; } @@ -2887,19 +2554,15 @@ static void minify_string( char **input, char **output ) *output += static_strlen( "\"" ); - for ( ; ( *input )[0] != '\0'; ( void )++( *input ), ++( *output ) ) - { + for ( ; ( *input )[0] != '\0'; ( void )++( *input ), ++( *output ) ) { ( *output )[0] = ( *input )[0]; - if ( ( *input )[0] == '\"' ) - { + if ( ( *input )[0] == '\"' ) { ( *output )[0] = '\"'; *input += static_strlen( "\"" ); *output += static_strlen( "\"" ); return; - } - else if ( ( ( *input )[0] == '\\' ) && ( ( *input )[1] == '\"' ) ) - { + } else if ( ( ( *input )[0] == '\\' ) && ( ( *input )[1] == '\"' ) ) { ( *output )[1] = ( *input )[1]; *input += static_strlen( "\"" ); *output += static_strlen( "\"" ); @@ -2911,15 +2574,12 @@ CJSON_PUBLIC( void ) cJSON_Minify( char *json ) { char *into = json; - if ( json == NULL ) - { + if ( json == NULL ) { return; } - while ( json[0] != '\0' ) - { - switch ( json[0] ) - { + while ( json[0] != '\0' ) { + switch ( json[0] ) { case ' ': case '\t': case '\r': @@ -2928,16 +2588,11 @@ CJSON_PUBLIC( void ) cJSON_Minify( char *json ) break; case '/': - if ( json[1] == '/' ) - { + if ( json[1] == '/' ) { skip_oneline_comment( &json ); - } - else if ( json[1] == '*' ) - { + } else if ( json[1] == '*' ) { skip_multiline_comment( &json ); - } - else - { + } else { json++; } @@ -2960,8 +2615,7 @@ CJSON_PUBLIC( void ) cJSON_Minify( char *json ) CJSON_PUBLIC( cJSON_bool ) cJSON_IsInvalid( const cJSON *const item ) { - if ( item == NULL ) - { + if ( item == NULL ) { return false; } @@ -2970,8 +2624,7 @@ CJSON_PUBLIC( cJSON_bool ) cJSON_IsInvalid( const cJSON *const item ) CJSON_PUBLIC( cJSON_bool ) cJSON_IsFalse( const cJSON *const item ) { - if ( item == NULL ) - { + if ( item == NULL ) { return false; } @@ -2980,8 +2633,7 @@ CJSON_PUBLIC( cJSON_bool ) cJSON_IsFalse( const cJSON *const item ) CJSON_PUBLIC( cJSON_bool ) cJSON_IsTrue( const cJSON *const item ) { - if ( item == NULL ) - { + if ( item == NULL ) { return false; } @@ -2991,8 +2643,7 @@ CJSON_PUBLIC( cJSON_bool ) cJSON_IsTrue( const cJSON *const item ) CJSON_PUBLIC( cJSON_bool ) cJSON_IsBool( const cJSON *const item ) { - if ( item == NULL ) - { + if ( item == NULL ) { return false; } @@ -3000,8 +2651,7 @@ CJSON_PUBLIC( cJSON_bool ) cJSON_IsBool( const cJSON *const item ) } CJSON_PUBLIC( cJSON_bool ) cJSON_IsNull( const cJSON *const item ) { - if ( item == NULL ) - { + if ( item == NULL ) { return false; } @@ -3010,8 +2660,7 @@ CJSON_PUBLIC( cJSON_bool ) cJSON_IsNull( const cJSON *const item ) CJSON_PUBLIC( cJSON_bool ) cJSON_IsNumber( const cJSON *const item ) { - if ( item == NULL ) - { + if ( item == NULL ) { return false; } @@ -3020,8 +2669,7 @@ CJSON_PUBLIC( cJSON_bool ) cJSON_IsNumber( const cJSON *const item ) CJSON_PUBLIC( cJSON_bool ) cJSON_IsString( const cJSON *const item ) { - if ( item == NULL ) - { + if ( item == NULL ) { return false; } @@ -3030,8 +2678,7 @@ CJSON_PUBLIC( cJSON_bool ) cJSON_IsString( const cJSON *const item ) CJSON_PUBLIC( cJSON_bool ) cJSON_IsArray( const cJSON *const item ) { - if ( item == NULL ) - { + if ( item == NULL ) { return false; } @@ -3040,8 +2687,7 @@ CJSON_PUBLIC( cJSON_bool ) cJSON_IsArray( const cJSON *const item ) CJSON_PUBLIC( cJSON_bool ) cJSON_IsObject( const cJSON *const item ) { - if ( item == NULL ) - { + if ( item == NULL ) { return false; } @@ -3050,8 +2696,7 @@ CJSON_PUBLIC( cJSON_bool ) cJSON_IsObject( const cJSON *const item ) CJSON_PUBLIC( cJSON_bool ) cJSON_IsRaw( const cJSON *const item ) { - if ( item == NULL ) - { + if ( item == NULL ) { return false; } @@ -3060,14 +2705,12 @@ CJSON_PUBLIC( cJSON_bool ) cJSON_IsRaw( const cJSON *const item ) CJSON_PUBLIC( cJSON_bool ) cJSON_Compare( const cJSON *const a, const cJSON *const b, const cJSON_bool case_sensitive ) { - if ( ( a == NULL ) || ( b == NULL ) || ( ( a->type & 0xFF ) != ( b->type & 0xFF ) ) || cJSON_IsInvalid( a ) ) - { + if ( ( a == NULL ) || ( b == NULL ) || ( ( a->type & 0xFF ) != ( b->type & 0xFF ) ) || cJSON_IsInvalid( a ) ) { return false; } /* check if type is valid */ - switch ( a->type & 0xFF ) - { + switch ( a->type & 0xFF ) { case cJSON_False: case cJSON_True: case cJSON_NULL: @@ -3083,13 +2726,11 @@ CJSON_PUBLIC( cJSON_bool ) cJSON_Compare( const cJSON *const a, const cJSON *con } /* identical objects are equal */ - if ( a == b ) - { + if ( a == b ) { return true; } - switch ( a->type & 0xFF ) - { + switch ( a->type & 0xFF ) { /* in these cases and equal type is enough */ case cJSON_False: case cJSON_True: @@ -3097,8 +2738,7 @@ CJSON_PUBLIC( cJSON_bool ) cJSON_Compare( const cJSON *const a, const cJSON *con return true; case cJSON_Number: - if ( a->valuedouble == b->valuedouble ) - { + if ( a->valuedouble == b->valuedouble ) { return true; } @@ -3106,27 +2746,22 @@ CJSON_PUBLIC( cJSON_bool ) cJSON_Compare( const cJSON *const a, const cJSON *con case cJSON_String: case cJSON_Raw: - if ( ( a->valuestring == NULL ) || ( b->valuestring == NULL ) ) - { + if ( ( a->valuestring == NULL ) || ( b->valuestring == NULL ) ) { return false; } - if ( strcmp( a->valuestring, b->valuestring ) == 0 ) - { + if ( strcmp( a->valuestring, b->valuestring ) == 0 ) { return true; } return false; - case cJSON_Array: - { + case cJSON_Array: { cJSON *a_element = a->child; cJSON *b_element = b->child; - for ( ; ( a_element != NULL ) && ( b_element != NULL ); ) - { - if ( !cJSON_Compare( a_element, b_element, case_sensitive ) ) - { + for ( ; ( a_element != NULL ) && ( b_element != NULL ); ) { + if ( !cJSON_Compare( a_element, b_element, case_sensitive ) ) { return false; } @@ -3135,47 +2770,39 @@ CJSON_PUBLIC( cJSON_bool ) cJSON_Compare( const cJSON *const a, const cJSON *con } /* one of the arrays is longer than the other */ - if ( a_element != b_element ) - { + if ( a_element != b_element ) { return false; } return true; } - case cJSON_Object: - { + case cJSON_Object: { cJSON *a_element = NULL; cJSON *b_element = NULL; - cJSON_ArrayForEach( a_element, a ) - { + cJSON_ArrayForEach( a_element, a ) { /* TODO This has O(n^2) runtime, which is horrible! */ b_element = get_object_item( b, a_element->string, case_sensitive ); - if ( b_element == NULL ) - { + if ( b_element == NULL ) { return false; } - if ( !cJSON_Compare( a_element, b_element, case_sensitive ) ) - { + if ( !cJSON_Compare( a_element, b_element, case_sensitive ) ) { return false; } } /* doing this twice, once on a and b to prevent true comparison if a subset of b * TODO: Do this the proper way, this is just a fix for now */ - cJSON_ArrayForEach( b_element, b ) - { + cJSON_ArrayForEach( b_element, b ) { a_element = get_object_item( a, b_element->string, case_sensitive ); - if ( a_element == NULL ) - { + if ( a_element == NULL ) { return false; } - if ( !cJSON_Compare( b_element, a_element, case_sensitive ) ) - { + if ( !cJSON_Compare( b_element, a_element, case_sensitive ) ) { return false; } } diff --git a/Src/filewriter.c b/Src/filewriter.c index dec6e825..949d4d2d 100644 --- a/Src/filewriter.c +++ b/Src/filewriter.c @@ -22,10 +22,8 @@ enum fwState { FW_STATE_CLOSED, FW_STATE_GETNAMEA, FW_STATE_GETNAMEE, FW_STATE_U #define MAX_STRLEN 4096 #define MAX_CONCAT_FILENAMELEN (MAX_STRLEN) -static struct -{ - struct - { +static struct { + struct { enum fwState s; /* Current state of the handle */ FILE *f; /* Handle for the handle */ char name[MAX_FILENAMELEN]; /* Filename */ @@ -52,14 +50,11 @@ void _processCompleteName( uint32_t n ) char *compareName; /* Concat strings */ - if ( _f.basedir ) - { + if ( _f.basedir ) { strncpy( workingName, _f.basedir, MAX_CONCAT_FILENAMELEN - 1 ); strcat( workingName, "/" ); strncat( workingName, _f.file[n].name, MAX_CONCAT_FILENAMELEN - 1 ); - } - else - { + } else { strncpy( workingName, _f.file[n].name, MAX_CONCAT_FILENAMELEN - 1 ); } @@ -68,13 +63,10 @@ void _processCompleteName( uint32_t n ) /* real path of the current directory. */ resolvedName = realpath( dirname( workingName ), NULL ); - if ( _f.basedir ) - { + if ( _f.basedir ) { compareName = realpath( _f.basedir, NULL ); - } - else - { - compareName = realpath( dirname( "" ), NULL ); + } else { + compareName = realpath( dirname( ( char * )"" ), NULL ); } /* Now check that the first part matches, up to the length of the comparison Name */ @@ -82,8 +74,7 @@ void _processCompleteName( uint32_t n ) free( resolvedName ); free( compareName ); - if ( !goodDirectory ) - { + if ( !goodDirectory ) { genericsReport( V_WARN, "Path to [%s] is not in or below current directory" EOL, workingName ); return; } @@ -91,19 +82,15 @@ void _processCompleteName( uint32_t n ) genericsReport( V_DEBUG, "Complete name to work with is [%s]" EOL, workingName ); /* OK, now decide what to do... */ - switch ( _f.file[n].s ) - { + switch ( _f.file[n].s ) { // ----------------------- case FW_STATE_GETNAMEA: // This is a file append operation _f.file[n].f = fopen( workingName, "ab+" ); - if ( _f.file[n].f ) - { + if ( _f.file[n].f ) { genericsReport( V_INFO, "File [%s] opened for append" EOL, workingName, n ); _f.file[n].s = FW_STATE_OPEN; - } - else - { + } else { genericsReport( V_WARN, "Failed to open [%s] for append" EOL, workingName ); memset( _f.file[n].name, 0, MAX_FILENAMELEN ); _f.file[n].s = FW_STATE_CLOSED; @@ -115,13 +102,10 @@ void _processCompleteName( uint32_t n ) case FW_STATE_GETNAMEE: // This is a file replacement operation _f.file[n].f = fopen( workingName, "wb+" ); - if ( _f.file[n].f ) - { + if ( _f.file[n].f ) { genericsReport( V_INFO, "File [%s] opened for write" EOL, workingName, n ); _f.file[n].s = FW_STATE_OPEN; - } - else - { + } else { genericsReport( V_WARN, "Failed to open [%s] for write" EOL, workingName ); memset( _f.file[n].name, 0, MAX_FILENAMELEN ); _f.file[n].s = FW_STATE_CLOSED; @@ -131,12 +115,9 @@ void _processCompleteName( uint32_t n ) // ----------------------- case FW_STATE_UNLINK: // this is a file delete operation - if ( !unlink( workingName ) ) - { + if ( !unlink( workingName ) ) { genericsReport( V_INFO, "Removed file [%s]" EOL, workingName ); - } - else - { + } else { genericsReport( V_WARN, "Failed to remove file [%s]" EOL, workingName ); } @@ -158,23 +139,16 @@ void _handleNameBytes( uint32_t n, uint8_t h, uint8_t *d ) { /* Spin through the received bytes and append them to the filename string */ - while ( h-- ) - { - if ( *d ) - { - if ( strlen( _f.file[n].name ) < MAX_FILENAMELEN - 2 ) - { + while ( h-- ) { + if ( *d ) { + if ( strlen( _f.file[n].name ) < MAX_FILENAMELEN - 2 ) { _f.file[n].name[strlen( _f.file[n].name )] = *d; - } - else - { + } else { genericsReport( V_WARN, "Attempt to write an overlong filename [%s]" EOL, _f.file[n].name ); } d++; - } - else - { + } else { genericsReport( V_DEBUG, "Got complete name [%s]" EOL, _f.file[n].name ); _processCompleteName( n ); break; @@ -195,19 +169,21 @@ bool filewriterProcess( struct swMsg *m ) { /* Split 32-bit word back into its compoenent parts without punning issues */ - uint8_t d[4] = { m->value & 0xff, ( m->value >> 8 ) & 0xff, ( m->value >> 16 ) & 0xff, ( m->value > 24 ) & 0xff}; + uint8_t d[4] = { ( uint8_t )( m->value & 0xff ), + ( uint8_t )( ( m->value >> 8 ) & 0xff ), + ( uint8_t )( ( m->value >> 16 ) & 0xff ), + ( uint8_t )( ( m->value > 24 ) & 0xff ) + }; uint8_t c = d[0]; /* Extract the control word for convinience */ - switch ( FW_MASK_COMMAND( c ) ) - { + switch ( FW_MASK_COMMAND( c ) ) { // ----------------------- case FW_CMD_OPENA: // Open file for appending write case FW_CMD_OPENE: // Open file for empty write (i.e. flush and write) genericsReport( V_DEBUG, "Attempt to open or create file" EOL ); - if ( _f.file[FW_GET_FILEID( c )].f ) - { + if ( _f.file[FW_GET_FILEID( c )].f ) { /* There was a file open, close it */ genericsReport( V_WARN, "Attempt to write to descriptor %d while open writing %s" EOL, FW_GET_FILEID( c ), _f.file[FW_GET_FILEID( c )].name ); @@ -219,12 +195,9 @@ bool filewriterProcess( struct swMsg *m ) memset( _f.file[FW_GET_FILEID( c )].name, 0, MAX_FILENAMELEN ); /* Start collecting the name */ - if ( FW_MASK_COMMAND( c ) == FW_CMD_OPENA ) - { + if ( FW_MASK_COMMAND( c ) == FW_CMD_OPENA ) { _f.file[FW_GET_FILEID( c )].s = FW_STATE_GETNAMEA; - } - else - { + } else { _f.file[FW_GET_FILEID( c )].s = FW_STATE_GETNAMEE; } @@ -234,13 +207,10 @@ bool filewriterProcess( struct swMsg *m ) // ----------------------- case FW_CMD_CLOSE: // Close file - if ( !_f.file[FW_GET_FILEID( c )].f ) - { + if ( !_f.file[FW_GET_FILEID( c )].f ) { /* There was no file open, complain */ genericsReport( V_DEBUG, "Attempt to close descriptor %d while not open" EOL, FW_GET_FILEID( c ) ); - } - else - { + } else { genericsReport( V_INFO, "Close %s" EOL, _f.file[FW_GET_FILEID( c )].name ); fclose( _f.file[FW_GET_FILEID( c )].f ); _f.file[FW_GET_FILEID( c )].f = NULL; @@ -253,12 +223,9 @@ bool filewriterProcess( struct swMsg *m ) // ----------------------- case FW_CMD_ERASE: // Erase file - if ( _f.file[FW_GET_FILEID( c )].s != FW_STATE_CLOSED ) - { + if ( _f.file[FW_GET_FILEID( c )].s != FW_STATE_CLOSED ) { genericsReport( V_WARN, "Attempt to use open descriptor %d to erase a file" EOL, FW_GET_FILEID( c ) ); - } - else - { + } else { memset( _f.file[FW_GET_FILEID( c )].name, 0, MAX_FILENAMELEN ); _f.file[FW_GET_FILEID( c )].s = FW_STATE_UNLINK; _handleNameBytes( FW_GET_FILEID( c ), FW_GET_BYTES( c ), &d[1] ); @@ -269,18 +236,12 @@ bool filewriterProcess( struct swMsg *m ) // ----------------------- case FW_CMD_WRITE: // Write to file - if ( _f.file[FW_GET_FILEID( c )].s == FW_STATE_CLOSED ) - { + if ( _f.file[FW_GET_FILEID( c )].s == FW_STATE_CLOSED ) { genericsReport( V_WARN, "Request for write on descriptor %d while file closed" EOL, FW_GET_FILEID( c ) ); - } - else - { - if ( _f.file[FW_GET_FILEID( c )].s != FW_STATE_OPEN ) - { + } else { + if ( _f.file[FW_GET_FILEID( c )].s != FW_STATE_OPEN ) { _handleNameBytes( FW_GET_FILEID( c ), FW_GET_BYTES( c ), &d[1] ); - } - else - { + } else { genericsReport( V_DEBUG, "Wrote %d bytes on descriptor %d" EOL, FW_GET_BYTES( c ), FW_GET_FILEID( c ) ); fwrite( &d[1], 1, FW_GET_BYTES( c ), _f.file[FW_GET_FILEID( c )].f ); } diff --git a/Src/generics.c b/Src/generics.c index 513d7042..d8bf546b 100644 --- a/Src/generics.c +++ b/Src/generics.c @@ -38,10 +38,8 @@ char *genericsEscape( char *str ) char *d = workingBuffer; char *s = str; - do - { - switch ( *s ) - { + do { + switch ( *s ) { case 0: break; @@ -83,8 +81,7 @@ char *genericsEscape( char *str ) default: *d++ = *s; } - } - while ( ( *s++ ) && ( d - workingBuffer < ( _POSIX_ARG_MAX - 1 ) ) ); + } while ( ( *s++ ) && ( d - workingBuffer < ( _POSIX_ARG_MAX - 1 ) ) ); *d = 0; return workingBuffer; @@ -97,15 +94,12 @@ char *genericsUnescape( char *str ) char *d = workingBuffer; char *s = str; - do - { - if ( *s == '\\' ) - { + do { + if ( *s == '\\' ) { /* This is an escape....put the correct code in its place */ s++; - switch ( *s ) - { + switch ( *s ) { case 0: break; @@ -140,8 +134,7 @@ char *genericsUnescape( char *str ) case '0'...'7': /* Direct octal number for ASCII Code */ *d = 0; - while ( ( *s >= '0' ) && ( *s <= '7' ) ) - { + while ( ( *s >= '0' ) && ( *s <= '7' ) ) { *d = ( ( *d ) * 8 ) + ( ( *s++ ) - '0' ); } @@ -151,13 +144,10 @@ char *genericsUnescape( char *str ) default: *d++ = *s; } - } - else - { + } else { *d++ = *s; } - } - while ( ( *s++ ) && ( d - workingBuffer < ( _POSIX_ARG_MAX - 1 ) ) ); + } while ( ( *s++ ) && ( d - workingBuffer < ( _POSIX_ARG_MAX - 1 ) ) ); *d = 0; return workingBuffer; @@ -196,13 +186,11 @@ uint32_t genericsTimestampmS( void ) static int _htoi( char c ) { - if ( ( c >= '0' ) && ( c <= '9' ) ) - { + if ( ( c >= '0' ) && ( c <= '9' ) ) { return c - '0'; } - if ( ( c >= 'a' ) && ( c <= 'f' ) ) - { + if ( ( c >= 'a' ) && ( c <= 'f' ) ) { return c - 'a' + 10; } @@ -216,8 +204,7 @@ const char *genericsBasename( const char *n ) { const char *p = n + strlen( n ); - while ( ( p != n ) && ( *( p - 1 ) != '/' ) ) - { + while ( ( p != n ) && ( *( p - 1 ) != '/' ) ) { p--; } @@ -231,12 +218,10 @@ const char *genericsBasenameN( const char *n, int c ) { const char *p = n + strlen( n ); - while ( ( p != n ) && ( c ) && ( *( p - 1 ) != '/' ) ) - { + while ( ( p != n ) && ( c ) && ( *( p - 1 ) != '/' ) ) { p--; - if ( *p == '/' ) - { + if ( *p == '/' ) { c--; } } @@ -248,66 +233,60 @@ char *genericsGetBaseDirectory( void ) { #ifdef WIN32 size_t currentSize = MAX_PATH; - char *exePath = malloc( currentSize ); + char *exePath = ( char * )malloc( currentSize ); - while ( true ) - { + while ( true ) { DWORD n = GetModuleFileNameA( NULL, exePath, currentSize ); - if ( n < ( currentSize - 1 ) ) - { + if ( n < ( currentSize - 1 ) ) { break; } currentSize *= 2; - exePath = realloc( exePath, currentSize ); + exePath = ( char * )realloc( exePath, currentSize ); } - char *dirPath = malloc( currentSize ); + char *dirPath = ( char * )malloc( currentSize ); char drive[_MAX_DRIVE]; _splitpath_s( exePath, drive, sizeof( drive ), dirPath, currentSize, NULL, 0, NULL, 0 ); free( exePath ); - char *concatPath = malloc( strlen( drive ) + strlen( dirPath ) + 1 ); + char *concatPath = ( char * )malloc( strlen( drive ) + strlen( dirPath ) + 1 ); *concatPath = '\0'; strcat( concatPath, drive ); strcat( concatPath, dirPath ); free( dirPath ); return concatPath; #else - size_t currentSize = 256; - char *exePath = malloc( currentSize ); + ssize_t currentSize = 256; + char *exePath = ( char * )malloc( currentSize ); - if ( !exePath ) - { + if ( !exePath ) { return NULL; } - while ( true ) - { + while ( true ) { ssize_t n = readlink( "/proc/self/exe", exePath, currentSize - 1 ); - if ( n == -1 ) - { + if ( n == -1 ) { // Failed to resolve path to current executable, let's hope it is not needed to correctly resolve orbtrace path // https://stackoverflow.com/a/933996/995351 strcpy( exePath, "" ); return exePath; } - if ( n < ( currentSize - 1 ) ) - { + if ( n < ( currentSize - 1 ) ) { // readlink does not insert null terminator exePath[n] = 0; break; } currentSize *= 2; - exePath = realloc( exePath, currentSize ); + exePath = ( char * )realloc( exePath, currentSize ); } const char *dirPath = dirname( exePath ); - char *path = malloc( strlen( dirPath ) + 2 ); + char *path = ( char * )malloc( strlen( dirPath ) + 2 ); *path = 0; strcat( path, dirPath ); strcat( path, "/" ); @@ -329,22 +308,16 @@ void genericsPrintf( const char *fmt, ... ) vsnprintf( op, MAX_STRLEN, fmt, va ); va_end( va ); - while ( *p ) - { - if ( *p != CMD_ALERT[0] ) - { + while ( *p ) { + if ( *p != CMD_ALERT[0] ) { putc( *p++, stderr ); - } - else - { + } else { p++; - switch ( *p ) - { + switch ( *p ) { case '0'...'9': case 'a'...'f': - if ( _screenHandling ) - { + if ( _screenHandling ) { fprintf( stderr, CC_COLOUR, _htoi( *p ) > 7, _htoi( *p ) & 7 ); } @@ -352,8 +325,7 @@ void genericsPrintf( const char *fmt, ... ) break; case 'u': - if ( _screenHandling ) - { + if ( _screenHandling ) { fprintf( stderr, CC_PREV_LN ); } @@ -361,8 +333,7 @@ void genericsPrintf( const char *fmt, ... ) break; case 'U': - if ( _screenHandling ) - { + if ( _screenHandling ) { fprintf( stderr, CC_CLR_LN ); } @@ -370,8 +341,7 @@ void genericsPrintf( const char *fmt, ... ) break; case 'r': - if ( _screenHandling ) - { + if ( _screenHandling ) { fprintf( stderr, CC_RES ); } @@ -399,10 +369,9 @@ void genericsReport( enum verbLevel l, const char *fmt, ... ) { static char op[MAX_STRLEN]; - static char *colours[V_MAX_VERBLEVEL] = {C_VERB_ERROR, C_VERB_WARN, C_VERB_INFO, C_VERB_DEBUG}; + static const char *colours[V_MAX_VERBLEVEL] = {C_VERB_ERROR, C_VERB_WARN, C_VERB_INFO, C_VERB_DEBUG}; - if ( l <= lstore ) - { + if ( l <= lstore ) { fflush( stdout ); genericsPrintf( colours[l] ); va_list va; diff --git a/Src/itmDecoder.c b/Src/itmDecoder.c index 2543a647..d50f2efd 100644 --- a/Src/itmDecoder.c +++ b/Src/itmDecoder.c @@ -73,19 +73,14 @@ void ITMDecoderForceSync( struct ITMDecoder *i, bool isSynced ) /* Force the decoder into a specific sync state */ { - if ( i->p == ITM_UNSYNCED ) - { - if ( isSynced ) - { + if ( i->p == ITM_UNSYNCED ) { + if ( isSynced ) { i->p = ITM_IDLE; i->stats.syncCount++; i->pk.len = 0; } - } - else - { - if ( !isSynced ) - { + } else { + if ( !isSynced ) { i->stats.lostSyncCount++; i->p = ITM_UNSYNCED; } @@ -98,8 +93,7 @@ bool ITMGetPacket( struct ITMDecoder *i, struct ITMPacket *p ) { /* This should have been reset in the call */ - if ( i->p != ITM_IDLE ) - { + if ( i->p != ITM_IDLE ) { return false; } @@ -132,25 +126,20 @@ enum ITMPumpEvent ITMPump( struct ITMDecoder *i, uint8_t c ) /* switched in, and hasn't been. */ i->syncStat = ( i->syncStat << 8 ) | c; - if ( ( ( i->syncStat )&TPIU_SYNCMASK ) == TPIU_SYNCPATTERN ) - { + if ( ( ( i->syncStat )&TPIU_SYNCMASK ) == TPIU_SYNCPATTERN ) { i->stats.tpiuSyncCount++; } - if ( ( ( i->syncStat )&SYNCMASK ) == SYNCPATTERN ) - { + if ( ( ( i->syncStat )&SYNCMASK ) == SYNCPATTERN ) { i->stats.syncCount++; /* Page register is reset on a sync */ i->pk.pageRegister = 0; retVal = ITM_EV_SYNCED; newState = ITM_IDLE; - } - else - { + } else { - switch ( i->p ) - { + switch ( i->p ) { // ----------------------------------------------------- case ITM_UNSYNCED: break; @@ -164,34 +153,28 @@ enum ITMPumpEvent ITMPump( struct ITMDecoder *i, uint8_t c ) // ************************************************* // ************** SYNC PACKET ********************** // ************************************************* - if ( c == 0b00000000 ) - { + if ( c == 0b00000000 ) { break; } // ************************************************* // ************** SOURCE PACKET ******************** // ************************************************* - if ( c & 0b00000011 ) - { + if ( c & 0b00000011 ) { i->targetCount = ( c & 0x03 ); - if ( i->targetCount == 3 ) - { + if ( i->targetCount == 3 ) { i->targetCount = 4; } i->pk.len = 0; i->pk.srcAddr = ( c & 0xF8 ) >> 3; - if ( !( c & 0x04 ) ) - { + if ( !( c & 0x04 ) ) { /* This is a Instrumentation (SW) packet */ i->stats.SWPkt++; newState = ITM_SW; - } - else - { + } else { /* This is a HW packet */ i->stats.HWPkt++; newState = ITM_HW; @@ -204,8 +187,7 @@ enum ITMPumpEvent ITMPump( struct ITMDecoder *i, uint8_t c ) // ************** PROTOCOL PACKET ****************** // ************************************************* - if ( c == 0b01110000 ) - { + if ( c == 0b01110000 ) { /* This is an overflow packet */ i->stats.overflow++; retVal = ITM_EV_OVERFLOW; @@ -213,20 +195,16 @@ enum ITMPumpEvent ITMPump( struct ITMDecoder *i, uint8_t c ) } // *********************************************** - if ( !( c & 0x0F ) ) - { + if ( !( c & 0x0F ) ) { i->pk.len = 1; /* The '1' is deliberate. */ /* This is a timestamp packet */ i->pk.d[0] = c; i->stats.TSPkt++; - if ( c & 0x80 ) - { + if ( c & 0x80 ) { /* This is TS packet format 1, so there's more to follow */ newState = ITM_TS; - } - else - { + } else { /* This is TS packet format 2, no more to come, and no change of state */ i->pk.type = ITM_PT_TS; retVal = ITM_EV_PACKET_RXED; @@ -236,15 +214,11 @@ enum ITMPumpEvent ITMPump( struct ITMDecoder *i, uint8_t c ) } // *********************************************** - if ( ( c & 0b11011111 ) == 0b10010100 ) - { + if ( ( c & 0b11011111 ) == 0b10010100 ) { /* This is a global timestamp packet */ - if ( ( c & 0b00100000 ) == 0 ) - { + if ( ( c & 0b00100000 ) == 0 ) { newState = ITM_GTS1; - } - else - { + } else { newState = ITM_GTS2; } @@ -252,8 +226,7 @@ enum ITMPumpEvent ITMPump( struct ITMDecoder *i, uint8_t c ) } // *********************************************** - if ( c == 0b00001000 ) - { + if ( c == 0b00001000 ) { /* This is a normal I-sync packet */ newState = ITM_NISYNC; i->pk.len = 0; @@ -262,22 +235,18 @@ enum ITMPumpEvent ITMPump( struct ITMDecoder *i, uint8_t c ) } // *********************************************** - if ( ( c & 0b00001000 ) == 0b00001000 ) - { + if ( ( c & 0b00001000 ) == 0b00001000 ) { /* Extension Packet */ i->pk.len = 1; /* The '1' is deliberate. */ i->stats.XTNPkt++; i->pk.d[0] = c; - if ( !( c & 0x84 ) ) - { + if ( !( c & 0x84 ) ) { /* This is the Stimulus Port Page Register setting ... deal with it here */ i->stats.PagePkt++; i->pk.pageRegister = ( c >> 4 ) & 0x07; - } - else - { + } else { newState = ITM_XTN; } @@ -286,22 +255,18 @@ enum ITMPumpEvent ITMPump( struct ITMDecoder *i, uint8_t c ) // *********************************************** if ( ( ( c & 0b11000100 ) == 0b11000100 ) || - ( ( c & 0b10000100 ) == 0b10000100 ) || - ( ( c & 0b11110000 ) == 0b11110000 ) || - ( ( c & 0b00000100 ) == 0b00000100 ) ) - { + ( ( c & 0b10000100 ) == 0b10000100 ) || + ( ( c & 0b11110000 ) == 0b11110000 ) || + ( ( c & 0b00000100 ) == 0b00000100 ) ) { /* Reserved packets - we have no idea what these are */ i->pk.len = 1; i->stats.ReservedPkt++; i->pk.d[0] = c; - if ( !( c & 0x80 ) ) - { + if ( !( c & 0x80 ) ) { i->pk.type = ITM_PT_RSRVD; retVal = ITM_EV_PACKET_RXED; - } - else - { + } else { /* According to protocol, this is multi-byte, so report it */ newState = ITM_RSVD; } @@ -327,8 +292,7 @@ enum ITMPumpEvent ITMPump( struct ITMDecoder *i, uint8_t c ) // ----------------------------------------------------- case ITM_GTS1: // Collecting GTS1 timestamp - wait for a zero continuation bit - if ( ( c & 0x80 ) == 0 ) - { + if ( ( c & 0x80 ) == 0 ) { newState = ITM_IDLE; } @@ -336,8 +300,7 @@ enum ITMPumpEvent ITMPump( struct ITMDecoder *i, uint8_t c ) // ----------------------------------------------------- case ITM_GTS2: // Collecting GTS2 timestamp - wait for a zero continuation bit - if ( ( c & 0x80 ) == 0 ) - { + if ( ( c & 0x80 ) == 0 ) { newState = ITM_IDLE; } @@ -347,8 +310,7 @@ enum ITMPumpEvent ITMPump( struct ITMDecoder *i, uint8_t c ) case ITM_SW: i->pk.d[i->pk.len++] = c; - if ( i->pk.len >= i->targetCount ) - { + if ( i->pk.len >= i->targetCount ) { newState = ITM_IDLE; i->pk.type = ITM_PT_SW; retVal = ITM_EV_PACKET_RXED; @@ -360,8 +322,7 @@ enum ITMPumpEvent ITMPump( struct ITMDecoder *i, uint8_t c ) case ITM_HW: i->pk.d[i->pk.len++] = c; - if ( i->pk.len >= i->targetCount ) - { + if ( i->pk.len >= i->targetCount ) { newState = ITM_IDLE; i->pk.type = ITM_PT_HW; retVal = ITM_EV_PACKET_RXED; @@ -373,8 +334,7 @@ enum ITMPumpEvent ITMPump( struct ITMDecoder *i, uint8_t c ) case ITM_TS: i->pk.d[i->pk.len++] = c; - if ( ( !( c & 0x80 ) ) || ( i->pk.len >= MAX_PACKET ) ) - { + if ( ( !( c & 0x80 ) ) || ( i->pk.len >= MAX_PACKET ) ) { /* We are done */ newState = ITM_IDLE; i->pk.type = ITM_PT_TS; @@ -387,8 +347,7 @@ enum ITMPumpEvent ITMPump( struct ITMDecoder *i, uint8_t c ) case ITM_RSVD: i->pk.d[i->pk.len++] = c; - if ( ( !( c & 0x80 ) ) || ( i->pk.len >= MAX_PACKET ) ) - { + if ( ( !( c & 0x80 ) ) || ( i->pk.len >= MAX_PACKET ) ) { /* We are done */ newState = ITM_IDLE; i->pk.type = ITM_PT_RSRVD; @@ -401,8 +360,7 @@ enum ITMPumpEvent ITMPump( struct ITMDecoder *i, uint8_t c ) case ITM_XTN: i->pk.d[i->pk.len++] = c; - if ( ( !( c & 0x80 ) ) || ( i->pk.len >= MAX_PACKET ) ) - { + if ( ( !( c & 0x80 ) ) || ( i->pk.len >= MAX_PACKET ) ) { /* We are done */ newState = ITM_IDLE; i->pk.type = ITM_PT_XTN; @@ -415,8 +373,7 @@ enum ITMPumpEvent ITMPump( struct ITMDecoder *i, uint8_t c ) case ITM_NISYNC: i->pk.d[i->pk.len++] = c; - if ( i->pk.len > i->targetCount ) - { + if ( i->pk.len > i->targetCount ) { newState = ITM_IDLE; i->pk.type = ITM_PT_NISYNC; retVal = ITM_EV_PACKET_RXED; @@ -427,8 +384,7 @@ enum ITMPumpEvent ITMPump( struct ITMDecoder *i, uint8_t c ) } } - if ( ( i->p != ITM_UNSYNCED ) || ( newState != ITM_UNSYNCED ) ) - { + if ( ( i->p != ITM_UNSYNCED ) || ( newState != ITM_UNSYNCED ) ) { genericsReport( V_DEBUG, "%02x %s --> %s(%d)%s", c, _protoNames[i->p], _protoNames[newState], i->targetCount, ( ( newState == ITM_IDLE ) ? EOL : " : " ) ); } diff --git a/Src/itmfifos.c b/Src/itmfifos.c index 9dada702..d81b9ef1 100644 --- a/Src/itmfifos.c +++ b/Src/itmfifos.c @@ -31,16 +31,14 @@ #define MAX_STRING_LENGTH (100) /* Maximum length that will be output from a fifo for a single event */ -struct runThreadParams /* Structure for parameters passed to a software task thread */ -{ +struct runThreadParams { /* Structure for parameters passed to a software task thread */ int portNo; int listenHandle; bool permafile; struct Channel *c; }; -struct Channel /* Information for an individual channel */ -{ +struct Channel { /* Information for an individual channel */ char *chanName; /* Filename to be used for the fifo */ char *presFormat; /* Format of data presentation to be used */ @@ -109,81 +107,65 @@ static void *_runFifo( void *arg ) /* Remove the file if it exists */ unlink( c->fifoName ); - if ( !params->permafile ) - { + if ( !params->permafile ) { /* This is a 'conventional' fifo, so it must be created */ - if ( mkfifo( c->fifoName, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH ) < 0 ) - { + if ( mkfifo( c->fifoName, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH ) < 0 ) { pthread_exit( NULL ); } } - do - { + do { /* Keep on opening the file (in case the fifo is opened/closed multiple times) */ /* We use RDWR to allow the open to proceed without a remote end */ - if ( !params->permafile ) - { + if ( !params->permafile ) { opfile = open( c->fifoName, O_RDWR | O_BINARY | O_NONBLOCK ); - } - else - { + } else { opfile = open( c->fifoName, O_WRONLY | O_CREAT | O_BINARY | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH ); } - do - { + do { /* ....get the packet. This will hang here until a packet arrives or the link closes */ readDataLen = read( params->listenHandle, &m, sizeof( struct swMsg ) ); - if ( readDataLen < 0 ) - { + if ( readDataLen < 0 ) { continue; } - if ( c->presFormat ) - { + if ( c->presFormat ) { // formatted output....start with specials - if ( strstr( c->presFormat, "%f" ) ) - { + if ( strstr( c->presFormat, "%f" ) ) { /* type punning on same host, after correctly building 32bit val * only unsafe on systems where u32/float have diff byte order */ float *nastycast = ( float * )&m.value; writeDataLen = snprintf( constructString, MAX_STRING_LENGTH, c->presFormat, *nastycast, *nastycast, *nastycast, *nastycast ); - } - else if ( strstr( c->presFormat, "%c" ) ) - { + } else if ( strstr( c->presFormat, "%c" ) ) { /* Format contains %c, so execute repeatedly for all characters in sent data */ writeDataLen = 0; - uint8_t op[4] = {m.value & 0xff, ( m.value >> 8 ) & 0xff, ( m.value >> 16 ) & 0xff, ( m.value >> 24 ) & 0xff}; + uint8_t op[4] = {( uint8_t )( m.value & 0xff ), + ( uint8_t )( ( m.value >> 8 ) & 0xff ), + ( uint8_t )( ( m.value >> 16 ) & 0xff ), + ( uint8_t )( ( m.value >> 24 ) & 0xff ) + }; uint32_t l = 0; - do - { + do { writeDataLen += snprintf( &constructString[writeDataLen], MAX_STRING_LENGTH - writeDataLen, c->presFormat, op[l], op[l], op[l], op[l] ); - } - while ( ++l < m.len ); - } - else - { + } while ( ++l < m.len ); + } else { writeDataLen = snprintf( constructString, MAX_STRING_LENGTH, c->presFormat, m.value, m.value, m.value, m.value ); } written = write( opfile, constructString, ( writeDataLen < MAX_STRING_LENGTH ) ? writeDataLen : MAX_STRING_LENGTH ); - } - else - { + } else { // raw output. written = write( opfile, &w, sizeof ( w ) ); } - } - while ( ( written > 0 ) && ( !c->ending ) ); + } while ( ( written > 0 ) && ( !c->ending ) ); /* Falling out on writen fail means we can re-open the fifo if it overflowed */ close( opfile ); - } - while ( !c->ending ); + } while ( !c->ending ); pthread_exit( NULL ); } @@ -202,43 +184,33 @@ static void *_runHWFifo( void *arg ) /* Remove the file if it exists */ unlink( c->fifoName ); - if ( !params->permafile ) - { + if ( !params->permafile ) { /* This is a 'conventional' fifo, so it must be created */ - if ( mkfifo( c->fifoName, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH ) < 0 ) - { + if ( mkfifo( c->fifoName, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH ) < 0 ) { pthread_exit( NULL ); } } - do - { - if ( !params->permafile ) - { + do { + if ( !params->permafile ) { /* We use RDWR to allow the open to proceed without a remote end */ opfile = open( c->fifoName, O_RDWR | O_BINARY | O_NONBLOCK ); - } - else - { + } else { opfile = open( c->fifoName, O_WRONLY | O_CREAT | O_BINARY | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH ); } - do - { + do { /* ....get the packet. We will hang here until a packet arrives or the link closes */ readDataLen = read( params->listenHandle, p, MAX_STRING_LENGTH ); - if ( readDataLen > 0 ) - { + if ( readDataLen > 0 ) { writeDataLen = write( opfile, p, readDataLen ); } - } - while ( ( writeDataLen > 0 ) && ( !c->ending ) ); + } while ( ( writeDataLen > 0 ) && ( !c->ending ) ); /* Falling out on writeDataLen fail means we can re-open the fifo if it overflowed */ close( opfile ); - } - while ( !c->ending ); + } while ( !c->ending ); pthread_exit( NULL ); } @@ -259,13 +231,10 @@ void _handleException( struct excMsg *m, struct itmfifosHandle *f ) f->lastHWExceptionTS = m->ts; - if ( m->exceptionNumber < 16 ) - { + if ( m->exceptionNumber < 16 ) { /* This is a system based exception */ opLen = snprintf( outputString, MAX_STRING_LENGTH, "%d,%" PRIu64 ",%s,%s" EOL, HWEVENT_EXCEPTION, eventdifftS, exEvent[m->eventType & 0x03], exNames[m->exceptionNumber & 0x0F] ); - } - else - { + } else { /* This is a CPU defined exception */ opLen = snprintf( outputString, MAX_STRING_LENGTH, "%d,%" PRIu64 ",%s,External,%d" EOL, HWEVENT_EXCEPTION, eventdifftS, exEvent[m->eventType & 0x03], m->exceptionNumber - 16 ); } @@ -286,19 +255,15 @@ void _handleDWTEvent( struct dwtMsg *m, struct itmfifosHandle *f ) f->lastHWExceptionTS = m->ts; opLen = snprintf( outputString, MAX_STRING_LENGTH, "%d,%" PRIu64, HWEVENT_DWT, eventdifftS ); - for ( uint32_t i = 0; i < NUM_EVENTS; i++ ) - { - if ( m->event & ( 1 << i ) ) - { + for ( uint32_t i = 0; i < NUM_EVENTS; i++ ) { + if ( m->event & ( 1 << i ) ) { // Copy this event into the output string outputString[opLen++] = ','; const char *u = evName[i]; - do - { + do { outputString[opLen++] = *u++; - } - while ( *u ); + } while ( *u ); } } @@ -317,13 +282,10 @@ void _handlePCSample( struct pcSampleMsg *m, struct itmfifosHandle *f ) f->lastHWExceptionTS = m->ts; - if ( m->sleep ) - { + if ( m->sleep ) { /* This is a sleep packet */ opLen = snprintf( outputString, ( MAX_STRING_LENGTH - 1 ), "%d,%" PRIu64 ",**SLEEP**" EOL, HWEVENT_PCSample, eventdifftS ); - } - else - { + } else { opLen = snprintf( outputString, ( MAX_STRING_LENGTH - 1 ), "%d,%" PRIu64 ",0x%08x" EOL, HWEVENT_PCSample, eventdifftS, m->pc ); } @@ -379,14 +341,10 @@ void _handleSW( struct swMsg *m, struct itmfifosHandle *f ) { /* Filter off filewriter packets and let the filewriter module deal with those */ - if ( ( m->srcAddr == FW_CHANNEL ) && ( f->filewriter ) ) - { + if ( ( m->srcAddr == FW_CHANNEL ) && ( f->filewriter ) ) { filewriterProcess( m ); - } - else - { - if ( ( m->srcAddr < NUM_CHANNELS ) && ( f->c[m->srcAddr].handle ) ) - { + } else { + if ( ( m->srcAddr < NUM_CHANNELS ) && ( f->c[m->srcAddr].handle ) ) { write( f->c[m->srcAddr].handle, m, sizeof( struct swMsg ) ); } } @@ -413,7 +371,7 @@ void _handleTS( struct TSMsg *m, struct itmfifosHandle *f ) int opLen; f->timeStamp += m->timeInc; - f->timeStatus = m->timeStatus; + f->timeStatus = ( enum timeDelay )m->timeStatus; opLen = snprintf( outputString, MAX_STRING_LENGTH, "%d,%d,%" PRIu32 EOL, HWEVENT_TS, m->timeStatus, m->timeInc ); write( f->c[HW_CHANNEL].handle, outputString, opLen ); @@ -429,8 +387,7 @@ void _itmPumpProcess( struct itmfifosHandle *f, char c ) typedef void ( *handlers )( void *decoded, struct itmfifosHandle * f ); /* Handlers for each complete message received */ - static const handlers h[MSG_NUM_MSGS] = - { + static const handlers h[MSG_NUM_MSGS] = { /* MSG_UNKNOWN */ NULL, /* MSG_RESERVED */ NULL, /* MSG_ERROR */ NULL, @@ -446,8 +403,7 @@ void _itmPumpProcess( struct itmfifosHandle *f, char c ) /* MSG_TS */ ( handlers )_handleTS }; - switch ( ITMPump( &f->i, c ) ) - { + switch ( ITMPump( &f->i, c ) ) { // ------------------------------------ case ITM_EV_NONE: break; @@ -478,8 +434,7 @@ void _itmPumpProcess( struct itmfifosHandle *f, char c ) /* See if we decoded a dispatchable match. genericMsg is just used to access */ /* the first two members of the decoded structs in a portable way. */ - if ( h[decoded.genericMsg.msgtype] ) - { + if ( h[decoded.genericMsg.msgtype] ) { ( h[decoded.genericMsg.msgtype] )( &decoded, f ); } @@ -492,8 +447,7 @@ void _itmPumpProcess( struct itmfifosHandle *f, char c ) static void _tpiuProtocolPump( struct itmfifosHandle *f, uint8_t c ) { - switch ( TPIUPump( &f->t, c ) ) - { + switch ( TPIUPump( &f->t, c ) ) { // ------------------------------------ case TPIU_EV_NEWSYNC: genericsReport( V_INFO, "TPIU In Sync (%d)" EOL, TPIUDecoderGetStats( &f->t )->syncCount ); @@ -517,22 +471,18 @@ static void _tpiuProtocolPump( struct itmfifosHandle *f, uint8_t c ) // ------------------------------------ case TPIU_EV_RXEDPACKET: - if ( !TPIUGetPacket( &f->t, &f->p ) ) - { + if ( !TPIUGetPacket( &f->t, &f->p ) ) { genericsReport( V_WARN, "TPIUGetPacket fell over" EOL ); } - for ( uint32_t g = 0; g < f->p.len; g++ ) - { - if ( f->p.packet[g].s == f->tpiuITMChannel ) - { + for ( uint32_t g = 0; g < f->p.len; g++ ) { + if ( f->p.packet[g].s == f->tpiuITMChannel ) { _itmPumpProcess( f, f->p.packet[g].d ); continue; } /* Its perfectly legal for TPIU channels to arrive that we aren't interested in */ - if ( ( f->p.packet[g].s != 0 ) && ( f->p.packet[g].s != 0x7f ) ) - { + if ( ( f->p.packet[g].s != 0 ) && ( f->p.packet[g].s != 0x7f ) ) { genericsReport( V_INFO, "Unhandled TPIU channel %02x" EOL, f->p.packet[g].s ); } } @@ -561,8 +511,7 @@ static void _tpiuProtocolPump( struct itmfifosHandle *f, uint8_t c ) void itmfifoSetChanPath( struct itmfifosHandle *f, char *s ) { - if ( f->chanPath ) - { + if ( f->chanPath ) { free( f->chanPath ); } @@ -581,13 +530,11 @@ void itmfifoSetChannel( struct itmfifosHandle *f, int chan, char *n, char *s ) { assert( chan <= NUM_CHANNELS ); - if ( f->c[chan].presFormat ) - { + if ( f->c[chan].presFormat ) { free( f->c[chan].presFormat ); } - if ( f->c[chan].chanName ) - { + if ( f->c[chan].chanName ) { free( f->c[chan].chanName ); } @@ -675,12 +622,9 @@ void itmfifoProtocolPump( struct itmfifosHandle *f, uint8_t c ) /* Top level protocol pump */ { - if ( f->useTPIU ) - { + if ( f->useTPIU ) { _tpiuProtocolPump( f, c ); - } - else - { + } else { /* There's no TPIU in use, so this goes straight to the ITM layer */ _itmPumpProcess( f, c ); } @@ -710,20 +654,15 @@ bool itmfifoCreate( struct itmfifosHandle *f ) ITMDecoderInit( &f->i, f->forceITMSync ); /* Cycle through channels and create a fifo for each one that is enabled */ - for ( int t = 0; t < ( NUM_CHANNELS + 1 ); t++ ) - { - if ( t < NUM_CHANNELS ) - { - if ( f->c[t].chanName ) - { + for ( int t = 0; t < ( NUM_CHANNELS + 1 ); t++ ) { + if ( t < NUM_CHANNELS ) { + if ( f->c[t].chanName ) { /* This is a live software channel fifo */ - if ( pipe( fd ) < 0 ) - { + if ( pipe( fd ) < 0 ) { return false; } - if ( !f->permafile ) - { + if ( !f->permafile ) { /* If this is not a permanent file then some data is allowed to get lost */ fcntl( fd[1], F_SETFL, O_NONBLOCK ); } @@ -738,30 +677,24 @@ bool itmfifoCreate( struct itmfifosHandle *f ) f->c[t].fifoName = ( char * )calloc( strlen( f->c[t].chanName ) + 2 + ( f->chanPath ? strlen( f->chanPath ) : 0 ), 1 ); - if ( f->chanPath ) - { + if ( f->chanPath ) { strcpy( f->c[t].fifoName, f->chanPath ); strcat( f->c[t].fifoName, "/" ); } strcat( f->c[t].fifoName, f->c[t].chanName ); - if ( pthread_create( &( f->c[t].thread ), NULL, &_runFifo, &( f->c[t].params ) ) ) - { + if ( pthread_create( &( f->c[t].thread ), NULL, &_runFifo, &( f->c[t].params ) ) ) { return false; } } - } - else - { + } else { /* This is the hardware fifo channel */ - if ( pipe( fd ) < 0 ) - { + if ( pipe( fd ) < 0 ) { return false; } - if ( !f->permafile ) - { + if ( !f->permafile ) { /* If this is not a permanent file then some data is allowed to get lost */ fcntl( fd[1], F_SETFL, O_NONBLOCK ); } @@ -775,16 +708,14 @@ bool itmfifoCreate( struct itmfifosHandle *f ) f->c[t].fifoName = ( char * )calloc( strlen( HWFIFO_NAME ) + 2 + ( ( f->chanPath ) ? strlen( f->chanPath ) : 0 ), 1 ); - if ( f->chanPath ) - { + if ( f->chanPath ) { strcpy( f->c[t].fifoName, f->chanPath ); strcat( f->c[t].fifoName, "/" ); } strcat( f->c[t].fifoName, HWFIFO_NAME ); - if ( pthread_create( &( f->c[t].thread ), NULL, &_runHWFifo, &( f->c[t].params ) ) ) - { + if ( pthread_create( &( f->c[t].thread ), NULL, &_runHWFifo, &( f->c[t].params ) ) ) { return false; } } @@ -798,41 +729,34 @@ void itmfifoShutdown( struct itmfifosHandle *f ) /* Destroy the per-port sub-processes. These will terminate when the fifos close */ { - if ( f->amEnding ) - { + if ( f->amEnding ) { return; } f->amEnding = true; /* Firstly go tell everything they're doomed */ - for ( int t = 0; t < NUM_CHANNELS + 1; t++ ) - { + for ( int t = 0; t < NUM_CHANNELS + 1; t++ ) { f->c[t].ending = true; - if ( f->c[t].handle > 0 ) - { + if ( f->c[t].handle > 0 ) { /* This will cause the read to end, thus terminating the pthread */ close( f->c[t].handle ); } } /* ...now clean up */ - for ( int t = 0; t < NUM_CHANNELS + 1; t++ ) - { - if ( f->c[t].handle > 0 ) - { + for ( int t = 0; t < NUM_CHANNELS + 1; t++ ) { + if ( f->c[t].handle > 0 ) { pthread_join( f->c[t].thread, NULL ); - if ( ! f->permafile ) - { + if ( ! f->permafile ) { unlink( f->c[t].fifoName ); } } /* Remove the name string too */ - if ( f->c[t].presFormat ) - { + if ( f->c[t].presFormat ) { free( f->c[t].presFormat ); } } @@ -844,8 +768,7 @@ void itmfifoFilewriter( struct itmfifosHandle *f, bool useFilewriter, char *work { f->filewriter = useFilewriter; - if ( f->filewriter ) - { + if ( f->filewriter ) { filewriterInit( workingPath ); } } diff --git a/Src/loadelf.c b/Src/loadelf.c index b74d2f6d..79d2db9a 100644 --- a/Src/loadelf.c +++ b/Src/loadelf.c @@ -31,13 +31,11 @@ static int _compareMem( const void *a, const void *b ) const symbolMemaddr as = ( ( struct symbolMemoryStore * )a )->start; const symbolMemaddr bs = ( ( struct symbolMemoryStore * )b )->start; - if ( as < bs ) - { + if ( as < bs ) { return -1; } - if ( as > bs ) - { + if ( as > bs ) { return 1; } @@ -51,13 +49,11 @@ static int _compareFunc( const void *a, const void *b ) const symbolMemaddr as = ( *( struct symbolFunctionStore ** )a )->lowaddr; const symbolMemaddr bs = ( *( struct symbolFunctionStore ** )b )->lowaddr; - if ( as < bs ) - { + if ( as < bs ) { return -1; } - if ( as > bs ) - { + if ( as > bs ) { return 1; } @@ -72,13 +68,11 @@ static int _matchFunc( const void *a, const void *b ) const symbolMemaddr as = ( *( struct symbolFunctionStore ** )b )->lowaddr; const symbolMemaddr ae = ( *( struct symbolFunctionStore ** )b )->highaddr; - if ( key < as ) - { + if ( key < as ) { return -1; } - if ( key > ae ) - { + if ( key > ae ) { return 1; } @@ -93,13 +87,11 @@ static int _compareLineMem( const void *a, const void *b ) const symbolMemaddr as = ( *( struct symbolLineStore ** )a )->lowaddr; const symbolMemaddr bs = ( *( struct symbolLineStore ** )b )->lowaddr; - if ( as < bs ) - { + if ( as < bs ) { return -1; } - if ( as > bs ) - { + if ( as > bs ) { return 1; } @@ -114,13 +106,11 @@ static int _matchLine( const void *a, const void *b ) const symbolMemaddr as = ( *( struct symbolLineStore ** )b )->lowaddr; const symbolMemaddr ae = ( *( struct symbolLineStore ** )b )->highaddr; - if ( key < as ) - { + if ( key < as ) { return -1; } - if ( key > ae ) - { + if ( key > ae ) { return 1; } @@ -137,49 +127,41 @@ static bool _readProg( struct symbol *p ) size_t shstrndx; char *name; - if ( elf_version( EV_CURRENT ) == EV_NONE ) - { + if ( elf_version( EV_CURRENT ) == EV_NONE ) { fprintf( stderr, "ELF library initialization failed : %s ", elf_errmsg ( -1 ) ); return p; } - if ( ( e = elf_begin( p->fd, ELF_C_READ, NULL ) ) == NULL ) - { + if ( ( e = elf_begin( p->fd, ELF_C_READ, NULL ) ) == NULL ) { fprintf( stderr, "ELF Begin failed\n" ); return false; } - if ( elf_getshdrstrndx( e, &shstrndx ) != 0 ) - { + if ( elf_getshdrstrndx( e, &shstrndx ) != 0 ) { fprintf( stderr, "elf_getshdrstrndx failed: %s\n", elf_errmsg( -1 ) ); return false; } /* Read this into memory by iterating over sections */ - while ( ( scn = elf_nextscn( e, scn ) ) != NULL ) - { + while ( ( scn = elf_nextscn( e, scn ) ) != NULL ) { - if ( gelf_getshdr( scn, &shdr ) != &shdr ) - { + if ( gelf_getshdr( scn, &shdr ) != &shdr ) { fprintf( stderr, "getshdr () failed : %s\n", elf_errmsg( -1 ) ); return false; } - if ( ( name = elf_strptr ( e, shstrndx, shdr.sh_name ) ) == NULL ) - { + if ( ( name = elf_strptr ( e, shstrndx, shdr.sh_name ) ) == NULL ) { fprintf( stderr, " elf_strptr () failed : %s\n", elf_errmsg ( -1 ) ); return false; } // fprintf(stderr, "%c ADDR=%08lx Type=%8x Flags=%04lx Size=%08lx Name=%s\n",((shdr.sh_flags & SHF_ALLOC) && (shdr.sh_type==SHT_PROGBITS))?'L':' ', shdr.sh_addr, shdr.sh_type, shdr.sh_flags, shdr.sh_size, name); - if ( ( shdr.sh_flags & SHF_ALLOC ) && ( shdr.sh_type == SHT_PROGBITS ) ) - { + if ( ( shdr.sh_flags & SHF_ALLOC ) && ( shdr.sh_type == SHT_PROGBITS ) ) { Elf_Data *data = NULL; /* This is program code or data; Allocate a new section */ - if ( ( data = elf_rawdata ( scn, data ) ) != NULL ) - { + if ( ( data = elf_rawdata ( scn, data ) ) != NULL ) { p->mem = ( struct symbolMemoryStore * )realloc( p->mem, ( p->nsect_mem + 1 ) * sizeof( struct symbolMemoryStore ) ); struct symbolMemoryStore *n = p->mem + p->nsect_mem; p->nsect_mem++; @@ -206,10 +188,8 @@ int _findOrAddString( const char *stringToFindorAdd, char ***table, unsigned int { /* Find the string in the specified table (and return its index) or create a new string record and return that index */ - for ( int i = 0; i < *elementCount; i++ ) - { - if ( !strcmp( ( *table )[i], stringToFindorAdd ) ) - { + for ( unsigned int i = 0; i < *elementCount; i++ ) { + if ( !strcmp( ( *table )[i], stringToFindorAdd ) ) { return i; } } @@ -232,20 +212,17 @@ static void _dump_die_attribs( Dwarf_Debug dbg, Dwarf_Die die ) Dwarf_Signed attr_count; const char *name; - if ( DW_DLV_OK != dwarf_attrlist( die, &attrs, &attr_count, 0 ) ) - { + if ( DW_DLV_OK != dwarf_attrlist( die, &attrs, &attr_count, 0 ) ) { fprintf( stderr, "Requesting attributes failed\n" ); return; } // Iterate through attributes - for ( int i = 0; i < attr_count; ++i ) - { + for ( int i = 0; i < attr_count; ++i ) { Dwarf_Half attr; Dwarf_Attribute attr_ptr = attrs[i]; - if ( DW_DLV_OK != dwarf_whatattr( attr_ptr, &attr, 0 ) ) - { + if ( DW_DLV_OK != dwarf_whatattr( attr_ptr, &attr, 0 ) ) { fprintf( stderr, "Failed to itentify attribute\n" ); goto terminate; } @@ -280,16 +257,14 @@ static void _getSourceLines( struct symbol *p, Dwarf_Debug dbg, Dwarf_Die die ) Dwarf_Bool isset; /* Now, for each source line, pull it into the line storage */ - if ( DW_DLV_OK == dwarf_srclines_b( die, &version, &tc, &linecontext, 0 ) ) - { + if ( DW_DLV_OK == dwarf_srclines_b( die, &version, &tc, &linecontext, 0 ) ) { dwarf_srclines_from_linecontext( linecontext, &linebuf, &linecount, 0 ); tracked_addr = 0; zero_start_dont_store = true; /* If a line address starts at zero, or is a direct continuation of a line that started at zero, then we dispose of it */ /* We consider any line that is within 16 bytes of the previous one to be a continuation, to allow for padding. */ - for ( int i = 0; i < linecount; ++i ) - { + for ( int i = 0; i < linecount; ++i ) { dwarf_line_is_addr_set( linebuf[i], &isset, 0 ); dwarf_lineaddr( linebuf[i], &line_addr, 0 ); dwarf_linebeginstatement( linebuf[i], &begin, 0 ); @@ -298,21 +273,17 @@ static void _getSourceLines( struct symbol *p, Dwarf_Debug dbg, Dwarf_Die die ) //if(isa) // fprintf(stderr,"\nDisc=%lld isa=%llx\n",disc,isa); - if ( ( isset ) && ( line_addr == 0 ) ) - { + if ( ( isset ) && ( line_addr == 0 ) ) { zero_start_dont_store = true; } //if (begin) // fprintf(stderr,"\nBEGIN(%08x):",(uint32_t)line_addr); - if ( ( zero_start_dont_store && ( ( !begin ) || ( !line_addr ) || ( ( line_addr - tracked_addr ) < 16 ) ) ) ) - { + if ( ( zero_start_dont_store && ( ( !begin ) || ( !line_addr ) || ( ( line_addr - tracked_addr ) < 16 ) ) ) ) { zero_start_dont_store = true; // sprintf(stderr,"!"); - } - else - { + } else { /* We are going to store this one */ // if (zero_start_dont_store) fprintf(stderr,"\n%08x: ",(uint32_t)line_addr); //else fprintf(stderr,"*"); @@ -357,7 +328,7 @@ void _dwarf_print( void *p, const char *line ) static void _processFunctionDie( struct symbol *p, Dwarf_Debug dbg, Dwarf_Die die, int filenameN, int producerN, Dwarf_Addr cu_base_addr ) { - char *name = ""; + char *name = ( char * )""; Dwarf_Addr h = 0; Dwarf_Addr l = 0; enum Dwarf_Form_Class formclass; @@ -369,16 +340,14 @@ static void _processFunctionDie( struct symbol *p, Dwarf_Debug dbg, Dwarf_Die di attr_tag = DW_AT_inline; - if ( dwarf_attr( die, attr_tag, &attr_data, 0 ) == DW_DLV_OK ) - { + if ( dwarf_attr( die, attr_tag, &attr_data, 0 ) == DW_DLV_OK ) { return; } /* See if this is an inline die usage */ attr_tag = DW_AT_abstract_origin; - if ( DW_DLV_OK == dwarf_attr( die, attr_tag, &attr_data, 0 ) ) - { + if ( DW_DLV_OK == dwarf_attr( die, attr_tag, &attr_data, 0 ) ) { /* It is, so track back to the real one */ Dwarf_Off abstract_origin_offset; Dwarf_Die abstract_origin_die; @@ -388,33 +357,26 @@ static void _processFunctionDie( struct symbol *p, Dwarf_Debug dbg, Dwarf_Die di dwarf_offdie_b( dbg, abstract_origin_offset, IS_INFO, &abstract_origin_die, 0 ); fprintf( stderr, "Instance at %08x...%08x\n\n\n", ( uint32_t )l, ( uint32_t )h ); isinline = true; - } - else - { + } else { dwarf_highpc_b ( die, &h, 0, &formclass, 0 ); dwarf_lowpc ( die, &l, 0 ); } - if ( formclass == DW_FORM_CLASS_CONSTANT ) - { + if ( formclass == DW_FORM_CLASS_CONSTANT ) { h += l; } - if ( l && ( l != h ) ) - { - if ( DW_DLV_OK != dwarf_diename( die, &name, 0 ) ) - { + if ( l && ( l != h ) ) { + if ( DW_DLV_OK != dwarf_diename( die, &name, 0 ) ) { /* Name will be hidden in a specification reference */ attr_tag = DW_AT_specification; - if ( dwarf_attr( die, attr_tag, &attr_data, 0 ) == DW_DLV_OK ) - { + if ( dwarf_attr( die, attr_tag, &attr_data, 0 ) == DW_DLV_OK ) { Dwarf_Off specification_offset; Dwarf_Die specification_die; dwarf_attr( die, attr_tag, &attr_data, 0 ); - if ( DW_DLV_OK == dwarf_global_formref( attr_data, &specification_offset, 0 ) ) - { + if ( DW_DLV_OK == dwarf_global_formref( attr_data, &specification_offset, 0 ) ) { dwarf_offdie_b( dbg, specification_offset, IS_INFO, &specification_die, 0 ); dwarf_diename( specification_die, &name, 0 ); } @@ -435,8 +397,7 @@ static void _processFunctionDie( struct symbol *p, Dwarf_Debug dbg, Dwarf_Die di /* Collect start of function line and column */ attr_tag = DW_AT_decl_line; - if ( dwarf_attr( die, attr_tag, &attr_data, 0 ) == DW_DLV_OK ) - { + if ( dwarf_attr( die, attr_tag, &attr_data, 0 ) == DW_DLV_OK ) { Dwarf_Unsigned no; dwarf_formudata( attr_data, &no, 0 ); newFunc->startline = no; @@ -444,8 +405,7 @@ static void _processFunctionDie( struct symbol *p, Dwarf_Debug dbg, Dwarf_Die di attr_tag = DW_AT_decl_column; - if ( dwarf_attr( die, attr_tag, &attr_data, 0 ) == DW_DLV_OK ) - { + if ( dwarf_attr( die, attr_tag, &attr_data, 0 ) == DW_DLV_OK ) { Dwarf_Unsigned no; dwarf_formudata( attr_data, &no, 0 ); newFunc->startcol = no; @@ -463,20 +423,17 @@ static void _processDie( struct symbol *p, Dwarf_Debug dbg, Dwarf_Die die, int l Dwarf_Die sib = die; - while ( DW_DLV_OK == dwarf_siblingof_b( dbg, sib, IS_INFO, &sib, 0 ) ) - { + while ( DW_DLV_OK == dwarf_siblingof_b( dbg, sib, IS_INFO, &sib, 0 ) ) { dwarf_tag( sib, &tag, 0 ); const char *n; dwarf_get_TAG_name( tag, &n ); - if ( ( tag == DW_TAG_subprogram ) || ( tag == DW_TAG_inlined_subroutine ) ) - { + if ( ( tag == DW_TAG_subprogram ) || ( tag == DW_TAG_inlined_subroutine ) ) { _processFunctionDie( p, dbg, sib, filenameN, producerN, cu_base_addr ); } } - if ( DW_DLV_OK == dwarf_child( die, &child, 0 ) ) - { + if ( DW_DLV_OK == dwarf_child( die, &child, 0 ) ) { _processDie( p, dbg, child, level + 1, filenameN, producerN, cu_base_addr ); dwarf_dealloc( dbg, child, DW_DLA_DIE ); } @@ -499,12 +456,9 @@ static bool _isAbsPath( const char *p ) static char *_joinPaths( const char *p1, const char *p2 ) { - if ( _isAbsPath( p2 ) ) - { + if ( _isAbsPath( p2 ) ) { return strdup( p2 ); - } - else - { + } else { char *res = ( char * )malloc( strlen( p1 ) + strlen( p2 ) + 2 ); strcpy( res, p1 ); strcat( res, "/" ); @@ -541,13 +495,11 @@ static bool _readLines( struct symbol *p ) unsigned int filenameN; unsigned int producerN; - if ( 0 != dwarf_init_b( p->fd, DW_GROUPNUMBER_ANY, NULL, NULL, &dbg, &err ) ) - { + if ( 0 != dwarf_init_b( p->fd, DW_GROUPNUMBER_ANY, NULL, NULL, &dbg, &err ) ) { return false; } - struct Dwarf_Printf_Callback_Info_s print_setup = - { + struct Dwarf_Printf_Callback_Info_s print_setup = { .dp_user_pointer = p, .dp_fptr = &_dwarf_print, .dp_buffer = _print_buffer, @@ -560,22 +512,19 @@ static bool _readLines( struct symbol *p ) dwarf_register_printf_callback( dbg, &print_setup ); /* Add an empty string to each string table, so the 0th element is the empty string in all cases */ - for ( enum symbolTables pt = 0; pt < PT_NUMTABLES; pt++ ) - { + for ( int pt = PT_PRODUCER; pt < PT_NUMTABLES; pt++ ) { _findOrAddString( "", &p->stringTable[pt], &p->tableLen[pt] ); } /* 1: Collect the functions and lines */ /* ---------------------------------- */ - while ( true ) - { + while ( true ) { memset( &dw_type_signature, 0, sizeof( dw_type_signature ) ); if ( DW_DLV_OK != dwarf_next_cu_header_d( dbg, true, &cu_header_length, &version_stamp, &abbrev_offset, &address_size, &dw_length_size, &dw_extension_size, &dw_type_signature, - &dw_typeoffset, &next_cu_header, &dw_header_cu_type, 0 ) ) - { + &dw_typeoffset, &next_cu_header, &dw_header_cu_type, 0 ) ) { break; } @@ -608,16 +557,13 @@ static bool _readLines( struct symbol *p ) qsort( p->func, p->nfunc, sizeof( struct symbolFunctionStore * ), _compareFunc ); /* Combine addresses in the lines table which have the same memory location...those aren't too useful for us */ - for ( int i = 1; i < p->nlines; i++ ) - { - while ( ( i < p->nlines ) && ( ( p->line[i]->filename == p->line[i - 1]->filename ) ) && ( ( p->line[i]->lowaddr == p->line[i - 1]->lowaddr ) ) ) - { + for ( unsigned int i = 1; i < p->nlines; i++ ) { + while ( ( i < p->nlines ) && ( ( p->line[i]->filename == p->line[i - 1]->filename ) ) && ( ( p->line[i]->lowaddr == p->line[i - 1]->lowaddr ) ) ) { /* This line needs to be freed in memory 'cos otherwise there is no reference to it anywhere */ free( p->line[i - 1] ); /* ...and move the following lines down */ - for ( int j = i; j < p->nlines; j++ ) - { + for ( unsigned int j = i; j < p->nlines; j++ ) { p->line[j - 1] = p->line[j]; } @@ -627,18 +573,15 @@ static bool _readLines( struct symbol *p ) /* Now do the same for lines with the same line number and file */ /* We can also set the high memory extent for each line here */ - for ( int i = 1; i < p->nlines; i++ ) - { + for ( unsigned int i = 1; i < p->nlines; i++ ) { while ( ( i < p->nlines ) && ( p->line[i]->startline == p->line[i - 1]->startline ) && - ( p->line[i]->filename == p->line[i - 1]->filename ) ) - { + ( p->line[i]->filename == p->line[i - 1]->filename ) ) { p->line[i]->lowaddr = p->line[i - 1]->lowaddr; free( p->line[i - 1] ); - for ( int j = i; j < p->nlines; j++ ) - { + for ( unsigned int j = i; j < p->nlines; j++ ) { p->line[j - 1] = p->line[j]; } @@ -648,24 +591,19 @@ static bool _readLines( struct symbol *p ) p->line[i - 1]->highaddr = p->line[i]->lowaddr - 1; } - if ( !p->nlines ) - { + if ( !p->nlines ) { fprintf( stderr, "No lines found in file\n" ); - } - else - { + } else { p->line[p->nlines - 1]->highaddr = p->line[p->nlines - 1]->lowaddr + 2; p->line[0]->lowaddr = p->line[0]->highaddr - 2; /* Allocate lines to functions ... these will be in address order 'cos the lines already are */ - for ( int i = 0; i < p->nlines; i++ ) - { + for ( unsigned int i = 0; i < p->nlines; i++ ) { struct symbolFunctionStore *f = symbolFunctionAt( p, p->line[i]->lowaddr ); p->line[i]->function = f; p->line[i]->isinline = false; - if ( f ) - { + if ( f ) { f->line = ( struct symbolLineStore ** )realloc( f->line, sizeof( struct symbolLineStore * ) * ( f->nlines + 1 ) ); f->line[f->nlines] = p->line[i]; f->nlines++; @@ -691,16 +629,14 @@ static bool _loadSource( struct symbol *p ) /* We need to aqquire source code for all of the files that we have an entry in the stringtable, so let's start by making room */ p->source = ( struct symbolSourcecodeStore ** )calloc( 1, sizeof( struct symbolSourcecodeStore * )*p->tableLen[PT_FILENAME] ); - for ( int i = 0; i < p->tableLen[PT_FILENAME]; i++ ) - { + for ( unsigned int i = 0; i < p->tableLen[PT_FILENAME]; i++ ) { r = readsourcefile( p->stringTable[PT_FILENAME][i], &l ); /* Create an entry for this file. It will remain zero (NULL) if there are no lines in it, because r was NULL */ struct symbolSourcecodeStore *store = p->source[i] = ( struct symbolSourcecodeStore * )calloc( 1, sizeof( struct symbolSourcecodeStore ) ); /* Lines in sio.c are demarked by \n, \r or \0 ... so we just need to find the indicies to one after each of those */ - while ( l ) - { + while ( l ) { /* Add this line to the storage. */ store->linetext = ( char ** )realloc( store->linetext, sizeof( char * ) * ( store->nlines + 1 ) ); store->linetext[store->nlines++] = r; @@ -728,12 +664,9 @@ const char *symbolSource( struct symbol *p, unsigned int fileNumber, unsigned in { assert( p ); - if ( ( fileNumber < p->tableLen[PT_FILENAME] ) && p->source && ( lineNumber < p->source[fileNumber]->nlines ) ) - { + if ( ( fileNumber < p->tableLen[PT_FILENAME] ) && p->source && ( lineNumber < p->source[fileNumber]->nlines ) ) { return ( const char * )p->source[fileNumber]->linetext[lineNumber]; - } - else - { + } else { return NULL; } } @@ -826,11 +759,9 @@ symbolMemptr symbolCodeAt( struct symbol *p, symbolMemaddr addr, unsigned int *l /* A speedup in case we're looking in the same region as previously */ if ( ( p->cachedSearchIndex != -1 ) && - ( p->mem[p->cachedSearchIndex].start < addr ) && - ( addr - p->mem[p->cachedSearchIndex].start < p->mem[p->cachedSearchIndex].len ) ) - { - if ( len ) - { + ( p->mem[p->cachedSearchIndex].start < addr ) && + ( addr - p->mem[p->cachedSearchIndex].start < p->mem[p->cachedSearchIndex].len ) ) { + if ( len ) { *len = p->mem[p->cachedSearchIndex].len - ( addr - p->mem[p->cachedSearchIndex].start ); } @@ -842,19 +773,15 @@ symbolMemptr symbolCodeAt( struct symbol *p, symbolMemaddr addr, unsigned int *l for ( i = p->nsect_mem - 1; i && p->mem[i].start > addr; i-- ); /* Are we within this code? */ - if ( addr - p->mem[i].start < p->mem[i].len ) - { + if ( addr - p->mem[i].start < p->mem[i].len ) { p->cachedSearchIndex = i; - if ( len ) - { + if ( len ) { *len = p->mem[i].len - ( addr - p->mem[i].start ); } return &( p->mem[i].data[addr - p->mem[i].start] ); - } - else - { + } else { p->cachedSearchIndex = -1; return NULL; } @@ -867,31 +794,24 @@ void symbolDelete( struct symbol *p ) /* Delete symbol set */ { - if ( p ) - { + if ( p ) { /* We are done with any elf that might have been open */ - if ( p->fd >= 0 ) - { + if ( p->fd >= 0 ) { /* There is no point in nulling p->fd cos we will delete p anyway */ close( p->fd ); } /* Close the disassembler if it's in use */ - if ( !p->caphandle ) - { + if ( !p->caphandle ) { cs_close( &p->caphandle ); } - if ( p->nsect_mem ) - { - for ( int i = p->nsect_mem - 1; i; i-- ) - { - if ( p->mem[i].name ) - { + if ( p->nsect_mem ) { + for ( int i = p->nsect_mem - 1; i; i-- ) { + if ( p->mem[i].name ) { free( p->mem[i].name ); - if ( p->mem[i].data ) - { + if ( p->mem[i].data ) { free( p->mem[i].data ); } } @@ -900,18 +820,15 @@ void symbolDelete( struct symbol *p ) free( p->mem ); } - while ( p->nfunc ) - { + while ( p->nfunc ) { struct symbolFunctionStore *f = p->func[--p->nfunc]; - if ( f->funcname ) - { + if ( f->funcname ) { /* Remove the functionName, assuming we have one */ free( f->funcname ); } - if ( f->line ) - { + if ( f->line ) { /* ...and any source code cross-references */ free( f->line ); } @@ -920,28 +837,23 @@ void symbolDelete( struct symbol *p ) } /* Flush the string tables */ - for ( enum symbolTables pt = 0; pt < PT_NUMTABLES; pt++ ) - { - while ( p->tableLen[pt] ) - { + for ( int pt = 0; pt < PT_NUMTABLES; pt++ ) { + while ( p->tableLen[pt] ) { free( p->stringTable[pt][--p->tableLen[pt]] ); } } /* Flush the source code line records */ - for ( int i = 0; i < p->nlines; i++ ) - { + for ( unsigned int i = 0; i < p->nlines; i++ ) { free( p->line[i] ); } - if ( p->line ) - { + if ( p->line ) { free( p->line ); } /* Remove any source code we might be holding */ - for ( int i = 0; i < p->tableLen[PT_FILENAME]; i++ ) - { + for ( unsigned int i = 0; i < p->tableLen[PT_FILENAME]; i++ ) { /* Text is all allocated in one block by readsource, so just deleting the firt element is enough */ free( p->source[i]->linetext[0] ); @@ -957,7 +869,7 @@ void symbolDelete( struct symbol *p ) // ==================================================================================================== -char *symbolDisassembleLine( struct symbol *p, enum instructionClass *ic, symbolMemaddr addr, symbolMemaddr *newaddr ) +char *symbolDisassembleLine( struct symbol *p, int *ic, symbolMemaddr addr, symbolMemaddr *newaddr ) /* Return assembly code representing this line */ @@ -966,18 +878,15 @@ char *symbolDisassembleLine( struct symbol *p, enum instructionClass *ic, symbol size_t count; static char op[255]; - if ( newaddr ) - { + if ( newaddr ) { *newaddr = NO_ADDRESS; } - *ic = 0; + *ic = LE_IC_NONE; - if ( !p->caphandle ) - { + if ( !p->caphandle ) { /* Disassembler isn't initialised yet */ - if ( cs_open( CS_ARCH_ARM, CS_MODE_THUMB + CS_MODE_LITTLE_ENDIAN, &p->caphandle ) != CS_ERR_OK ) - { + if ( cs_open( CS_ARCH_ARM, CS_MODE_THUMB, &p->caphandle ) != CS_ERR_OK ) { return NULL; } @@ -986,8 +895,7 @@ char *symbolDisassembleLine( struct symbol *p, enum instructionClass *ic, symbol symbolMemptr m = symbolCodeAt( p, addr, NULL ); - if ( !m ) - { + if ( !m ) { /* If we don't have memory then we can't decode */ return NULL; } @@ -996,15 +904,14 @@ char *symbolDisassembleLine( struct symbol *p, enum instructionClass *ic, symbol *ic = LE_IC_NONE; - if ( count > 0 ) - { + if ( count > 0 ) { /* Characterise the instruction using rules from F1.3 of ARM IHI0064H.a */ /* Check instruction size */ - *ic |= ( insn->size == 4 ) ? LE_IC_4BYTE : 0; + *ic |= ( insn->size == 4 ) ? LE_IC_4BYTE : LE_IC_NONE; /* Was it a subroutine call? */ - *ic |= ( ( insn->id == ARM_INS_BL ) || ( insn->id == ARM_INS_BLX ) ) ? LE_IC_JUMP | LE_IC_CALL : 0; + *ic |= ( ( insn->id == ARM_INS_BL ) || ( insn->id == ARM_INS_BLX ) ) ? LE_IC_JUMP | LE_IC_CALL : LE_IC_NONE; /* Was it a regular call? */ *ic |= ( ( insn->id == ARM_INS_B ) || ( insn->id == ARM_INS_BX ) || ( insn->id == ARM_INS_ISB ) || @@ -1024,29 +931,25 @@ char *symbolDisassembleLine( struct symbol *p, enum instructionClass *ic, symbol /* Add text describing instruction */ - if ( *ic & LE_IC_4BYTE ) - { - sprintf( op, "%8"PRIx64": %02x%02x %02x%02x %s %s", insn->address, insn->bytes[1], insn->bytes[0], insn->bytes[3], insn->bytes[2], insn->mnemonic, insn->op_str ); - } - else - { - sprintf( op, "%8"PRIx64": %02x%02x %s %s", insn->address, insn->bytes[1], insn->bytes[0], insn->mnemonic, insn->op_str ); + if ( *ic & LE_IC_4BYTE ) { + sprintf( op, "%8" PRIx64 ": %02x%02x %02x%02x %s %s", + insn->address, insn->bytes[1], insn->bytes[0], insn->bytes[3], insn->bytes[2], + insn->mnemonic, insn->op_str ); + } else { + sprintf( op, "%8" PRIx64 ": %02x%02x %s %s", insn->address, insn->bytes[1], + insn->bytes[0], insn->mnemonic, insn->op_str ); } /* Check to see if operands are immediate */ cs_detail *detail = insn->detail; - if ( detail->arm.op_count ) - { + if ( detail->arm.op_count ) { - for ( int n = 0; n < insn->detail->arm.op_count; n++ ) - { - if ( insn->detail->arm.operands[n].type == ARM_OP_IMM ) - { + for ( int n = 0; n < insn->detail->arm.op_count; n++ ) { + if ( insn->detail->arm.operands[n].type == ARM_OP_IMM ) { *ic |= LE_IC_IMMEDIATE; - if ( newaddr ) - { + if ( newaddr ) { *newaddr = detail->arm.operands[0].imm; } @@ -1061,9 +964,7 @@ char *symbolDisassembleLine( struct symbol *p, enum instructionClass *ic, symbol // { // fsprintf ( stderr, &op[strlen( op )], " ; %s%s%s%s", *ic & LE_IC_JUMP ? "JUMP " : "", *ic & LE_IC_CALL ? "CALL " : "", *ic & LE_IC_IMMEDIATE ? "IMM " : "", *ic & LE_IC_IRET ? "IRET " : "" ); // } - } - else - { + } else { sprintf( op, "No disassembly" ); } @@ -1083,15 +984,12 @@ bool symbolSetValid( struct symbol *p ) #define ELF_MAGIC (0x464c457f) uint32_t magicMatch; - if ( ( p ) && ( p->fd >= 0 ) ) - { + if ( ( p ) && ( p->fd >= 0 ) ) { /* See if we can read from this file */ lseek( p->fd, 0, SEEK_SET ); - if ( sizeof( magicMatch ) == read( p->fd, &magicMatch, sizeof( magicMatch ) ) ) - { - if ( ELF_MAGIC == magicMatch ) - { + if ( sizeof( magicMatch ) == read( p->fd, &magicMatch, sizeof( magicMatch ) ) ) { + if ( ELF_MAGIC == magicMatch ) { return true; } } @@ -1121,22 +1019,19 @@ struct symbol *symbolAquire( char *filename, bool loadlines, bool loadmem, bool } /* Load the memory image if this was requested...if it fails then we fail */ - if ( loadmem && ( !_readProg( p ) ) ) - { + if ( loadmem && ( !_readProg( p ) ) ) { symbolDelete( p ); return NULL; } /* Load the functions and source code line mappings if requested */ - if ( !_readLines( p ) ) - { + if ( !_readLines( p ) ) { symbolDelete( p ); return NULL; } /* ...finally, the source code if requested. This can only be done if mem or functions we requested */ - if ( ( loadsource && ( loadmem || loadlines ) ) && !_loadSource( p ) ) - { + if ( ( loadsource && ( loadmem || loadlines ) ) && !_loadSource( p ) ) { symbolDelete( p ); return NULL; } @@ -1163,8 +1058,7 @@ bool _listLines( struct symbol *p ) int index = 0; struct symbolLineStore *l; - while ( ( l = symbolLineIndex( p, index++ ) ) ) - { + while ( ( l = symbolLineIndex( p, index++ ) ) ) { fprintf( stderr, " " MEMADDRF "..." MEMADDRF " %4d ( %s )" EOL, l->lowaddr, l->highaddr, l->startline, symbolGetFilename( p, l->filename ) ); } } @@ -1178,20 +1072,16 @@ bool _listFunctions( struct symbol *p, bool includeLines ) struct symbolFunctionStore *f; struct symbolLineStore *l; - while ( f = symbolFunctionIndex( p, iter++ ) ) - { + while ( f = symbolFunctionIndex( p, iter++ ) ) { fprintf( stderr, MEMADDRF "..." MEMADDRF " %s ( %s %d,%d )" EOL, f->lowaddr, f->highaddr, f->funcname, symbolGetFilename( p, f->filename ), f->startline, f->startcol ); - if ( includeLines ) - { + if ( includeLines ) { int iter2 = 0; - while ( l = symbolFunctionLineIndex( f, iter2++ ) ) - { + while ( l = symbolFunctionLineIndex( f, iter2++ ) ) { fprintf( stderr, " " MEMADDRF "..." MEMADDRF " %4d ( %s )" EOL, l->lowaddr, l->highaddr, l->startline, symbolGetFilename( p, l->filename ) ); - if ( ( l->function != f ) || ( l->filename != f->filename ) ) - { + if ( ( l->function != f ) || ( l->filename != f->filename ) ) { fprintf( stderr, "*****DATA INCONSISTENCY" EOL ); } } @@ -1207,8 +1097,7 @@ bool _listFile( struct symbol *p, int fileNo ) const char *t; int i = 0; - while ( t = symbolSource( p, fileNo, i++ ) ) - { + while ( t = symbolSource( p, fileNo, i++ ) ) { fprintf( stderr, "%s", t ); } } @@ -1223,8 +1112,7 @@ bool _disassemble( struct symbol *p, symbolMemaddr a, unsigned int len ) symbolMemaddr addr; symbolMemaddr newaddr; - for ( addr = a; addr < a + len; addr += ic & LE_IC_4BYTE ? 4 : 2 ) - { + for ( addr = a; addr < a + len; addr += ic & LE_IC_4BYTE ? 4 : 2 ) { char *u = symbolDisassembleLine( p, &ic, addr, &newaddr ); fprintf( stderr, "%s\n", u ); } @@ -1239,8 +1127,7 @@ void main( int argc, char *argv[] ) enum instructionClass ic; struct symbol *p = symbolAquire( argv[1], true, true, true ); - if ( !p ) - { + if ( !p ) { fprintf( stderr, "Failed to aquire" EOL ); exit( -1 ); } @@ -1250,15 +1137,13 @@ void main( int argc, char *argv[] ) struct symbolLineStore *s; - for ( int i = 0; i < p->nlines; i++ ) - { + for ( int i = 0; i < p->nlines; i++ ) { s = symbolLineIndex( p, i ); fprintf( stderr, "\n%08x ... %08x %s %s", ( uint32_t )s->lowaddr, ( uint32_t )s->highaddr, s->isinline ? "INLINE" : "", symbolSource( p, s->filename, s->startline - 1 ) ); if ( ( s->lowaddr > 0x08000000 ) && ( s->highaddr != -1 ) ) - for ( symbolMemaddr b = s->lowaddr; b < s->highaddr; ) - { + for ( symbolMemaddr b = s->lowaddr; b < s->highaddr; ) { fprintf( stderr, " %s\n", symbolDisassembleLine( p, &ic, b, NULL ) ); b += ic & LE_IC_4BYTE ? 4 : 2; } diff --git a/Src/msgDecoder.c b/Src/msgDecoder.c index 1f982932..71e2f449 100644 --- a/Src/msgDecoder.c +++ b/Src/msgDecoder.c @@ -47,12 +47,9 @@ static bool _handlePCSample( struct ITMPacket *packet, struct pcSampleMsg *decod { decoded->msgtype = MSG_PC_SAMPLE; - if ( packet->len == 1 ) - { + if ( packet->len == 1 ) { decoded->sleep = true; - } - else - { + } else { decoded->sleep = false; decoded->pc = ( packet->d[3] << 24 ) | ( packet->d[2] << 16 ) | ( packet->d[1] << 8 ) | ( packet->d[0] ); } @@ -69,8 +66,7 @@ static bool _handleDataRWWP( struct ITMPacket *packet, struct watchMsg *decoded decoded->comp = ( packet->srcAddr >> 1 ) & 0x3; decoded->isWrite = ( ( packet->srcAddr & 0x01 ) != 0 ); - switch ( packet->len ) - { + switch ( packet->len ) { case 1: decoded->data = packet->d[0]; break; @@ -117,8 +113,7 @@ static bool _handleHW( struct ITMPacket *packet, struct msg *decoded ) bool wasDecoded = false; decoded->genericMsg.msgtype = MSG_NONE; - switch ( packet->srcAddr ) - { + switch ( packet->srcAddr ) { // -------------- case 0: /* DWT Event */ wasDecoded = _handleDWTEvent( packet, ( struct dwtMsg * )decoded ); @@ -136,16 +131,11 @@ static bool _handleHW( struct ITMPacket *packet, struct msg *decoded ) // -------------- default: - if ( ( ( packet->srcAddr & 0x19 ) == 0x10 ) || ( ( packet->srcAddr & 0x19 ) == 0x11 ) ) - { + if ( ( ( packet->srcAddr & 0x19 ) == 0x10 ) || ( ( packet->srcAddr & 0x19 ) == 0x11 ) ) { wasDecoded = _handleDataRWWP( packet, ( struct watchMsg * )decoded ); - } - else if ( ( packet->srcAddr & 0x19 ) == 0x08 ) - { + } else if ( ( packet->srcAddr & 0x19 ) == 0x08 ) { wasDecoded = _handleDataAccessWP( packet, ( struct wptMsg * )decoded ); - } - else if ( ( packet->srcAddr & 0x19 ) == 0x09 ) - { + } else if ( ( packet->srcAddr & 0x19 ) == 0x09 ) { wasDecoded = _handleDataOffsetWP( packet, ( struct oswMsg * )decoded ); } @@ -194,27 +184,21 @@ static bool _handleTS( struct ITMPacket *packet, struct TSMsg *decoded ) decoded->msgtype = MSG_TS; uint32_t stamp = 0; - if ( !( ( packet->d[0] ) & 0x80 ) ) - { + if ( !( ( packet->d[0] ) & 0x80 ) ) { /* This is packet format 2 ... just a simple increment */ stamp = packet->d[0] >> 4; - } - else - { + } else { /* This is packet format 1 ... full decode needed */ decoded->timeStatus = ( packet->d[0] & 0x30 ) >> 4; stamp = ( packet->d[1] ) & 0x7f; - if ( packet->len > 2 ) - { + if ( packet->len > 2 ) { stamp |= ( packet->d[2] ) << 7; - if ( packet->len > 3 ) - { + if ( packet->len > 3 ) { stamp |= ( packet->d[3] & 0x7F ) << 14; - if ( packet->len > 4 ) - { + if ( packet->len > 4 ) { stamp |= ( packet->d[4] & 0x7f ) << 21; } } @@ -238,8 +222,7 @@ bool msgDecoder( struct ITMPacket *packet, struct msg *decoded ) decoded->genericMsg.msgtype = MSG_NONE; decoded->genericMsg.ts = genericsTimestampuS(); /* Stamp as early as possible, even if its not real */ - switch ( packet->type ) - { + switch ( packet->type ) { case ITM_PT_NONE: decoded->genericMsg.msgtype = MSG_NONE; break; diff --git a/Src/msgSeq.c b/Src/msgSeq.c index 74509b0a..9b0265af 100644 --- a/Src/msgSeq.c +++ b/Src/msgSeq.c @@ -30,8 +30,7 @@ static bool _bufferPacket( struct MSGSeq *d ) struct msg p; - if ( !ITMGetDecodedPacket( d->i, &p ) ) - { + if ( !ITMGetDecodedPacket( d->i, &p ) ) { /* There wasn't a decodable message in there */ return false; } @@ -40,13 +39,10 @@ static bool _bufferPacket( struct MSGSeq *d ) memcpy( &d->pbuffer[d->wp], &p, sizeof( struct msg ) ); /* If this is a timestamp then we put it on the front to be released first */ - if ( d->pbuffer[d->wp].genericMsg.msgtype == MSG_TS ) - { + if ( d->pbuffer[d->wp].genericMsg.msgtype == MSG_TS ) { d->releaseTimeMsg = true; return true; - } - else - { + } else { d->wp = ( d->wp + 1 ) % d->pbl; assert( d->wp != d->rp ); @@ -70,7 +66,7 @@ void MSGSeqInit( struct MSGSeq *d, struct ITMDecoder *i, uint32_t maxEntries ) memset( d, 0, sizeof( struct MSGSeq ) ); d->i = i; d->pbl = maxEntries; - d->pbuffer = calloc( maxEntries, sizeof( struct msg ) ); + d->pbuffer = ( struct msg * )calloc( maxEntries, sizeof( struct msg ) ); } // ==================================================================================================== struct msg *MSGSeqGetPacket( struct MSGSeq *d ) @@ -79,14 +75,12 @@ struct msg *MSGSeqGetPacket( struct MSGSeq *d ) uint32_t trp = d->rp; /* Roll the timestamp off the front if it's present */ - if ( d->releaseTimeMsg ) - { + if ( d->releaseTimeMsg ) { d->releaseTimeMsg = false; return &d->pbuffer[d->wp]; } - if ( d->wp == d->rp ) - { + if ( d->wp == d->rp ) { return NULL; } @@ -103,8 +97,7 @@ bool MSGSeqPump( struct MSGSeq *d, uint8_t c ) { bool r = false; - switch ( ITMPump( d->i, c ) ) - { + switch ( ITMPump( d->i, c ) ) { // ------------------------------------ case ITM_EV_NONE: break; diff --git a/Src/nwclient.c b/Src/nwclient.c index 39a5a941..822a8059 100644 --- a/Src/nwclient.c +++ b/Src/nwclient.c @@ -83,10 +83,8 @@ static int _lock_with_timeout( pthread_mutex_t *mutex, const struct timespec *ts left = ts->tv_sec * 1000; /* how much waiting is left, in msec */ step = 10; /* msec to sleep at each trywait() failure */ - do - { - if ( ( ret = pthread_mutex_trylock( mutex ) ) != 0 ) - { + do { + if ( ( ret = pthread_mutex_trylock( mutex ) ) != 0 ) { struct timespec dly; dly.tv_sec = 0; @@ -95,8 +93,7 @@ static int _lock_with_timeout( pthread_mutex_t *mutex, const struct timespec *ts left -= step; } - } - while ( ret != 0 && left > 0 ); + } while ( ret != 0 && left > 0 ); return ret; } @@ -109,17 +106,13 @@ static void _clientRemove( volatile struct nwClient *c ) { close( c->portNo ); - if ( c->prevClient ) - { + if ( c->prevClient ) { c->prevClient->nextClient = c->nextClient; - } - else - { + } else { c->parent->firstClient = c->nextClient; } - if ( c->nextClient ) - { + if ( c->nextClient ) { c->nextClient->prevClient = c->prevClient; } @@ -145,12 +138,10 @@ static void *_listenTask( void *arg ) clilen = sizeof( cli_addr ); listen( h->sockfd, 5 ); - while ( !h->finish ) - { + while ( !h->finish ) { newsockfd = accept( h->sockfd, ( struct sockaddr * ) &cli_addr, &clilen ); - if ( h->finish ) - { + if ( h->finish ) { close( newsockfd ); break; } @@ -166,16 +157,14 @@ static void *_listenTask( void *arg ) client->portNo = newsockfd; /* Hook into linked list */ - if ( _lock_with_timeout( &h->clientList, &ts ) < 0 ) - { + if ( _lock_with_timeout( &h->clientList, &ts ) < 0 ) { genericsExit( -1, "Failed to acquire mutex" EOL ); } client->nextClient = h->firstClient; client->prevClient = NULL; - if ( client->nextClient ) - { + if ( client->nextClient ) { client->nextClient->prevClient = client; } @@ -200,16 +189,14 @@ void nwclientSend( struct nwclientsHandle *h, uint32_t len, uint8_t *ipbuffer, b ssize_t sent = 0; const struct timespec ts = {.tv_sec = 1, .tv_nsec = 0}; - if ( _lock_with_timeout( &h->clientList, &ts ) < 0 ) - { + if ( _lock_with_timeout( &h->clientList, &ts ) < 0 ) { genericsExit( -1, "Failed to acquire mutex" EOL ); } /* Now kick all the clients that new data arrived for them to distribute */ volatile struct nwClient *n = h->firstClient; - while ( n ) - { + while ( n ) { volatile struct nwClient *nextc = n->nextClient; uint32_t tosend = len; int8_t *p = ( int8_t * )ipbuffer; /* Cast is needed for Windows */ @@ -222,8 +209,7 @@ void nwclientSend( struct nwclientsHandle *h, uint32_t len, uint8_t *ipbuffer, b struct pollfd pfd = { n->portNo, POLLOUT | POLLHUP | POLLERR, 0 }; #endif - do - { + do { /* Need to ensure this port has room for more data */ #ifdef WIN32 if ( select( n->portNo + 1, NULL, &wfds, NULL, unlimWait ? NULL : &tv ) <= 0 ) @@ -236,17 +222,14 @@ void nwclientSend( struct nwclientsHandle *h, uint32_t len, uint8_t *ipbuffer, b sent = send( n->portNo, ( char * )p, len, MSG_NOSIGNAL ); - if ( sent > 0 ) - { + if ( sent > 0 ) { tosend -= sent; p += sent; } - } - while ( ( sent >= 0 ) && ( tosend ) ); + } while ( ( sent >= 0 ) && ( tosend ) ); /* If we didn't manage to send everthing then it's time to get rid of this client */ - if ( tosend ) - { + if ( tosend ) { genericsReport( V_WARN, EOL "Unresponsive client dropped" EOL ); _clientRemove( n ); } @@ -269,10 +252,9 @@ struct nwclientsHandle *nwclientStart( int port ) MEMCHECK( h, NULL ); h->sockfd = socket( AF_INET, SOCK_STREAM, 0 ); - setsockopt( h->sockfd, SOL_SOCKET, SO_REUSEPORT, ( const void * )&flag, sizeof( flag ) ); + setsockopt( h->sockfd, SOL_SOCKET, SO_REUSEPORT, ( const char * )&flag, sizeof( flag ) ); - if ( h->sockfd < 0 ) - { + if ( h->sockfd < 0 ) { genericsReport( V_ERROR, "Error opening socket" EOL ); goto free_and_return; } @@ -282,14 +264,12 @@ struct nwclientsHandle *nwclientStart( int port ) serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons( port ); - if ( setsockopt( h->sockfd, SOL_SOCKET, SO_REUSEADDR, ( const void * ) &flag, sizeof( flag ) ) < 0 ) - { + if ( setsockopt( h->sockfd, SOL_SOCKET, SO_REUSEADDR, ( const char * ) &flag, sizeof( flag ) ) < 0 ) { genericsReport( V_ERROR, "setsockopt(SO_REUSEADDR) failed" ); goto free_and_return; } - if ( bind( h->sockfd, ( struct sockaddr * ) &serv_addr, sizeof( serv_addr ) ) < 0 ) - { + if ( bind( h->sockfd, ( struct sockaddr * ) &serv_addr, sizeof( serv_addr ) ) < 0 ) { genericsReport( V_ERROR, "Error on binding" EOL ); goto free_and_return; } @@ -298,8 +278,7 @@ struct nwclientsHandle *nwclientStart( int port ) pthread_mutex_init( &h->clientList, NULL ); /* We have the listening socket - spawn a thread to handle it */ - if ( pthread_create( &( h->ipThread ), NULL, &_listenTask, h ) ) - { + if ( pthread_create( &( h->ipThread ), NULL, &_listenTask, h ) ) { genericsReport( V_ERROR, "Failed to create listening thread" EOL ); goto free_and_return; } @@ -316,24 +295,21 @@ void nwclientShutdown( struct nwclientsHandle *h ) { const struct timespec ts = {.tv_sec = 1, .tv_nsec = 0}; - if ( !h ) - { + if ( !h ) { return; } /* Flag that we're ending */ h->finish = true; - if ( _lock_with_timeout( &h->clientList, &ts ) < 0 ) - { + if ( _lock_with_timeout( &h->clientList, &ts ) < 0 ) { genericsExit( -1, "Failed to acquire mutex" EOL ); } /* Shut all the client connections */ volatile struct nwClient *c = h->firstClient; - while ( c ) - { + while ( c ) { volatile struct nwClient *nextc = c->nextClient; _clientRemove( c ); c = nextc; diff --git a/Src/orbcat.c b/Src/orbcat.c index f7897ed8..4ce2bd18 100644 --- a/Src/orbcat.c +++ b/Src/orbcat.c @@ -51,11 +51,10 @@ enum TSType { TSNone, TSAbsolute, TSRelative, TSDelta, TSStamp, TSStampDelta, TS const char *tsTypeString[TSNumTypes] = { "None", "Absolute", "Relative", "Delta", "System Timestamp", "System Timestamp Delta" }; // Record for options, either defaults or from command line -struct -{ +struct { /* Config information */ bool useTPIU; - uint32_t tpiuChannel; + uint8_t tpiuChannel; bool forceITMSync; uint64_t cps; /* Cycles per second for target CPU */ @@ -73,17 +72,15 @@ struct char *file; /* File host connection */ bool endTerminate; /* Terminate when file/socket "ends" */ -} options = -{ - .forceITMSync = true, +} options = { .tpiuChannel = 1, + .forceITMSync = true, + .tsTrigger = DEFAULT_TS_TRIGGER, .port = NWCLIENT_SERVER_PORT, - .server = "localhost", - .tsTrigger = DEFAULT_TS_TRIGGER + .server = ( char * )"localhost" }; -struct -{ +struct { /* The decoders and the packets from them */ struct ITMDecoder i; struct MSGSeq d; @@ -121,23 +118,20 @@ static void _outputTimestamp( void ) char opConstruct[MAX_STRING_LENGTH]; uint64_t res; struct tm tm; + uint64_t delta; time_t td; - switch ( options.tsType ) - { + switch ( options.tsType ) { case TSNone: // ----------------------------------------------------------------------- break; case TSRelative: // ------------------------------------------------------------------- - if ( !_r.gotte ) - { + if ( !_r.gotte ) { /* Get the starting time */ _r.oldte = _timestamp(); _r.gotte = true; fprintf( stdout, REL_FORMAT_INIT ); - } - else - { + } else { uint64_t now = _timestamp(); res = now - _r.oldte; fprintf( stdout, REL_FORMAT, res / ONE_SEC_IN_USEC, ( res / ( ONE_SEC_IN_USEC / 1000 ) ) % 1000 ); @@ -154,25 +148,19 @@ static void _outputTimestamp( void ) break; case TSDelta: // ---------------------------------------------------------------------- - if ( !_r.gotte ) - { + if ( !_r.gotte ) { /* Get the starting time */ _r.oldte = _timestamp(); _r.gotte = true; fprintf( stdout, DEL_FORMAT_INIT ); - } - else - { + } else { uint64_t t = _timestamp(); res = t - _r.oldte; _r.oldte = t; - if ( res / 1000 ) - { + if ( res / 1000 ) { fprintf( stdout, DEL_FORMAT, res / ONE_SEC_IN_USEC, ( res / 1000 ) % 1000 ); - } - else - { + } else { fprintf( stdout, DEL_FORMAT_CTD ); } } @@ -180,35 +168,28 @@ static void _outputTimestamp( void ) break; case TSStamp: // ----------------------------------------------------------------------- - if ( options.cps ) - { + if ( options.cps ) { uint64_t tms = ( _r.timeStamp * 1000000 ) / options.cps; fprintf( stdout, STAMP_FORMAT_MS, tms / 1000000, ( tms / 1000 ) % 1000, tms % 1000 ); - } - else - { + } else { fprintf( stdout, STAMP_FORMAT, _r.timeStamp ); } break; case TSStampDelta: // ------------------------------------------------------------------ - if ( !_r.gotte ) - { + if ( !_r.gotte ) { _r.lastTimeStamp = _r.timeStamp; _r.gotte = true; } - uint64_t delta = _r.timeStamp - _r.lastTimeStamp; + delta = _r.timeStamp - _r.lastTimeStamp; _r.lastTimeStamp = _r.timeStamp; - if ( options.cps ) - { + if ( options.cps ) { uint64_t tms = ( delta * 1000000 ) / options.cps; fprintf( stdout, STAMP_FORMAT_MS_DELTA, tms / 1000000, ( tms / 1000 ) % 1000, tms % 1000 ); - } - else - { + } else { fprintf( stdout, STAMP_FORMAT, delta ); } @@ -226,11 +207,9 @@ static void _outputText( char *p ) char *q; - while ( *p ) - { + while ( *p ) { /* If this is the first character in a new line, then we need to generate a timestamp */ - if ( !_r.inLine ) - { + if ( !_r.inLine ) { _outputTimestamp(); _r.inLine = true; } @@ -238,15 +217,12 @@ static void _outputText( char *p ) /* See if there is a trigger in these data...if so then output everything prior to it */ q = strchr( p, options.tsTrigger ); - if ( q ) - { + if ( q ) { *q = 0; fprintf( stdout, "%s" EOL, p ); /* Once we've output these data then we're not in a line any more */ _r.inLine = false; - } - else - { + } else { /* Just output the whole of the data we've got, then we're done */ fputs( p, stdout ); break; @@ -269,30 +245,26 @@ static void _handleSW( struct swMsg *m, struct ITMDecoder *i ) *p = 0; /* Print anything we want to output into the buffer */ - if ( ( m->srcAddr < NUM_CHANNELS ) && ( options.presFormat[m->srcAddr] ) ) - { + if ( ( m->srcAddr < NUM_CHANNELS ) && ( options.presFormat[m->srcAddr] ) ) { // formatted output....start with specials - if ( strstr( options.presFormat[m->srcAddr], "%f" ) ) - { + if ( strstr( options.presFormat[m->srcAddr], "%f" ) ) { /* type punning on same host, after correctly building 32bit val * only unsafe on systems where u32/float have diff byte order */ float *nastycast = ( float * )&m->value; p += snprintf( p, MAX_STRING_LENGTH - ( p - opConstruct ), options.presFormat[m->srcAddr], *nastycast, *nastycast, *nastycast, *nastycast ); - } - else if ( strstr( options.presFormat[m->srcAddr], "%c" ) ) - { + } else if ( strstr( options.presFormat[m->srcAddr], "%c" ) ) { /* Format contains %c, so execute repeatedly for all characters in sent data */ - uint8_t op[4] = {m->value & 0xff, ( m->value >> 8 ) & 0xff, ( m->value >> 16 ) & 0xff, ( m->value >> 24 ) & 0xff}; + uint8_t op[4] = { ( uint8_t )( m->value & 0xff ), + ( uint8_t )( ( m->value >> 8 ) & 0xff ), + ( uint8_t )( ( m->value >> 16 ) & 0xff ), + ( uint8_t )( ( m->value >> 24 ) & 0xff ) + }; uint32_t l = 0; - do - { + do { p += snprintf( p, MAX_STRING_LENGTH - ( p - opConstruct ), options.presFormat[m->srcAddr], op[l], op[l], op[l] ); - } - while ( ++l < m->len ); - } - else - { + } while ( ++l < m->len ); + } else { p += snprintf( p, MAX_STRING_LENGTH - ( p - opConstruct ), options.presFormat[m->srcAddr], m->value, m->value, m->value, m->value ); } } @@ -317,8 +289,7 @@ static void _itmPumpProcess( char c ) typedef void ( *handlers )( void *decoded, struct ITMDecoder * i ); /* Handlers for each complete message received */ - static const handlers h[MSG_NUM_MSGS] = - { + static const handlers h[MSG_NUM_MSGS] = { /* MSG_UNKNOWN */ NULL, /* MSG_RESERVED */ NULL, /* MSG_ERROR */ NULL, @@ -339,37 +310,28 @@ static void _itmPumpProcess( char c ) /* target-based timestamps we need to re-sequence the messages so that the timestamps are */ /* issued _before_ the data they apply to. These are the two cases. */ - if ( ( options.tsType != TSStamp ) && ( options.tsType != TSStampDelta ) ) - { - if ( ITM_EV_PACKET_RXED == ITMPump( &_r.i, c ) ) - { - if ( ITMGetDecodedPacket( &_r.i, &p ) ) - { + if ( ( options.tsType != TSStamp ) && ( options.tsType != TSStampDelta ) ) { + if ( ITM_EV_PACKET_RXED == ITMPump( &_r.i, c ) ) { + if ( ITMGetDecodedPacket( &_r.i, &p ) ) { assert( p.genericMsg.msgtype < MSG_NUM_MSGS ); - if ( h[p.genericMsg.msgtype] ) - { + if ( h[p.genericMsg.msgtype] ) { ( h[p.genericMsg.msgtype] )( &p, &_r.i ); } } } - } - else - { + } else { /* Pump messages into the store until we get a time message, then we can read them out */ - if ( !MSGSeqPump( &_r.d, c ) ) - { + if ( !MSGSeqPump( &_r.d, c ) ) { return; } /* We are synced timewise, so empty anything that has been waiting */ - while ( ( pp = MSGSeqGetPacket( &_r.d ) ) ) - { + while ( ( pp = MSGSeqGetPacket( &_r.d ) ) ) { assert( pp->genericMsg.msgtype < MSG_NUM_MSGS ); - if ( h[pp->genericMsg.msgtype] ) - { + if ( h[pp->genericMsg.msgtype] ) { ( h[pp->genericMsg.msgtype] )( pp, &_r.i ); } } @@ -385,10 +347,8 @@ static void _itmPumpProcess( char c ) static void _protocolPump( uint8_t c ) { - if ( options.useTPIU ) - { - switch ( TPIUPump( &_r.t, c ) ) - { + if ( options.useTPIU ) { + switch ( TPIUPump( &_r.t, c ) ) { case TPIU_EV_NEWSYNC: case TPIU_EV_SYNCED: ITMDecoderForceSync( &_r.i, true ); @@ -403,21 +363,17 @@ static void _protocolPump( uint8_t c ) break; case TPIU_EV_RXEDPACKET: - if ( !TPIUGetPacket( &_r.t, &_r.p ) ) - { + if ( !TPIUGetPacket( &_r.t, &_r.p ) ) { genericsReport( V_WARN, "TPIUGetPacket fell over" EOL ); } - for ( uint32_t g = 0; g < _r.p.len; g++ ) - { - if ( _r.p.packet[g].s == options.tpiuChannel ) - { + for ( uint32_t g = 0; g < _r.p.len; g++ ) { + if ( _r.p.packet[g].s == options.tpiuChannel ) { _itmPumpProcess( _r.p.packet[g].d ); continue; } - if ( _r.p.packet[g].s != 0 ) - { + if ( _r.p.packet[g].s != 0 ) { genericsReport( V_DEBUG, "Unknown TPIU channel %02x" EOL, _r.p.packet[g].s ); } } @@ -428,9 +384,7 @@ static void _protocolPump( uint8_t c ) genericsReport( V_WARN, "****ERROR****" EOL ); break; } - } - else - { + } else { _itmPumpProcess( c ); } } @@ -462,8 +416,7 @@ static void _printVersion( void ) genericsPrintf( "orbcat version " GIT_DESCRIBE EOL ); } // ==================================================================================================== -static struct option _longOptions[] = -{ +static struct option _longOptions[] = { {"channel", required_argument, NULL, 'c'}, {"cpufreq", required_argument, NULL, 'C'}, {"eof", no_argument, NULL, 'E'}, @@ -485,11 +438,12 @@ bool _processOptions( int argc, char *argv[] ) int c, optionIndex = 0; unsigned int chan; char *chanIndex; + char *a; + #define DELIMITER ',' while ( ( c = getopt_long ( argc, argv, "c:C:Ef:g:hVns:t:T:v:", _longOptions, &optionIndex ) ) != -1 ) - switch ( c ) - { + switch ( c ) { // ------------------------------------ case 'C': options.cps = atoi( optarg ) * 1000; @@ -531,21 +485,18 @@ bool _processOptions( int argc, char *argv[] ) options.server = optarg; // See if we have an optional port number too - char *a = optarg; + a = optarg; - while ( ( *a ) && ( *a != ':' ) ) - { + while ( ( *a ) && ( *a != ':' ) ) { a++; } - if ( *a == ':' ) - { + if ( *a == ':' ) { *a = 0; options.port = atoi( ++a ); } - if ( !options.port ) - { + if ( !options.port ) { options.port = NWCLIENT_SERVER_PORT; } @@ -559,8 +510,7 @@ bool _processOptions( int argc, char *argv[] ) // ------------------------------------ case 'T': - switch ( *optarg ) - { + switch ( *optarg ) { case 'a': options.tsType = TSAbsolute; break; @@ -590,13 +540,12 @@ bool _processOptions( int argc, char *argv[] ) // ------------------------------------ case 'v': - if ( !isdigit( *optarg ) ) - { + if ( !isdigit( *optarg ) ) { genericsReport( V_ERROR, "-v requires a numeric argument." EOL ); return false; } - genericsSetReportLevel( atoi( optarg ) ); + genericsSetReportLevel( ( enum verbLevel )atoi( optarg ) ); break; // ------------------------------------ @@ -606,15 +555,13 @@ bool _processOptions( int argc, char *argv[] ) chan = atoi( optarg ); - if ( chan >= NUM_CHANNELS ) - { + if ( chan >= NUM_CHANNELS ) { genericsReport( V_ERROR, "Channel index out of range" EOL ); return false; } /* Scan for format */ - while ( ( *chanIndex ) && ( *chanIndex != DELIMITER ) ) - { + while ( ( *chanIndex ) && ( *chanIndex != DELIMITER ) ) { chanIndex++; } @@ -622,13 +569,11 @@ bool _processOptions( int argc, char *argv[] ) chanIndex++; /* Scan past any whitespace */ - while ( ( *chanIndex ) && ( isspace( *chanIndex ) ) ) - { + while ( ( *chanIndex ) && ( isspace( *chanIndex ) ) ) { chanIndex++; } - if ( !*chanIndex ) - { + if ( !*chanIndex ) { genericsReport( V_ERROR, "No output format for channel %d (avoid spaces before the output spec)" EOL, chan ); return false; } @@ -639,12 +584,9 @@ bool _processOptions( int argc, char *argv[] ) // ------------------------------------ case '?': - if ( optopt == 'b' ) - { + if ( optopt == 'b' ) { genericsReport( V_ERROR, "Option '%c' requires an argument." EOL, optopt ); - } - else if ( !isprint ( optopt ) ) - { + } else if ( !isprint ( optopt ) ) { genericsReport( V_ERROR, "Unknown option character `\\x%x'." EOL, optopt ); } @@ -656,8 +598,7 @@ bool _processOptions( int argc, char *argv[] ) // ------------------------------------ } - if ( ( options.useTPIU ) && ( !options.tpiuChannel ) ) - { + if ( ( options.useTPIU ) && ( !options.tpiuChannel ) ) { genericsReport( V_ERROR, "TPIU set for use but no channel set for ITM output" EOL ); return false; } @@ -667,47 +608,36 @@ bool _processOptions( int argc, char *argv[] ) genericsReport( V_INFO, "ForceSync : %s" EOL, options.forceITMSync ? "true" : "false" ); genericsReport( V_INFO, "Timestamp : %s" EOL, tsTypeString[options.tsType] ); - if ( options.cps ) - { + if ( options.cps ) { genericsReport( V_INFO, "S-CPU Speed: %d KHz" EOL, options.cps ); } - if ( options.tsType != TSNone ) - { + if ( options.tsType != TSNone ) { char unesc[2] = {options.tsTrigger, 0}; genericsReport( V_INFO, "TriggerChr : '%s'" EOL, genericsEscape( unesc ) ); } - if ( options.file ) - { + if ( options.file ) { genericsReport( V_INFO, "Input File : %s", options.file ); - if ( options.endTerminate ) - { + if ( options.endTerminate ) { genericsReport( V_INFO, " (Terminate on exhaustion)" EOL ); - } - else - { + } else { genericsReport( V_INFO, " (Ongoing read)" EOL ); } } - if ( options.useTPIU ) - { + if ( options.useTPIU ) { genericsReport( V_INFO, "Using TPIU : true (ITM on channel %d)" EOL, options.tpiuChannel ); - } - else - { + } else { genericsReport( V_INFO, "Using TPIU : false" EOL ); } genericsReport( V_INFO, "Channels :" EOL ); - for ( int g = 0; g < NUM_CHANNELS; g++ ) - { - if ( options.presFormat[g] ) - { + for ( int g = 0; g < NUM_CHANNELS; g++ ) { + if ( options.presFormat[g] ) { genericsReport( V_INFO, " %02d [%s]" EOL, g, genericsEscape( options.presFormat[g] ) ); } } @@ -717,12 +647,9 @@ bool _processOptions( int argc, char *argv[] ) // ==================================================================================================== static struct Stream *_tryOpenStream() { - if ( options.file != NULL ) - { + if ( options.file != NULL ) { return streamCreateFile( options.file ); - } - else - { + } else { return streamCreateSocket( options.server, options.port ); } } @@ -732,30 +659,24 @@ static void _feedStream( struct Stream *stream ) struct timeval t; unsigned char cbw[TRANSFER_SIZE]; - while ( true ) - { + while ( true ) { size_t receivedSize; t.tv_sec = 0; t.tv_usec = 10000; enum ReceiveResult result = stream->receive( stream, cbw, TRANSFER_SIZE, &t, &receivedSize ); - if ( result != RECEIVE_RESULT_OK ) - { - if ( result == RECEIVE_RESULT_EOF && options.endTerminate ) - { + if ( result != RECEIVE_RESULT_OK ) { + if ( result == RECEIVE_RESULT_EOF && options.endTerminate ) { return; - } - else if ( result == RECEIVE_RESULT_ERROR ) - { + } else if ( result == RECEIVE_RESULT_ERROR ) { break; } } unsigned char *c = cbw; - while ( receivedSize-- ) - { + while ( receivedSize-- ) { _protocolPump( *c++ ); } @@ -769,8 +690,7 @@ int main( int argc, char *argv[] ) { bool alreadyReported = false; - if ( !_processOptions( argc, argv ) ) - { + if ( !_processOptions( argc, argv ) ) { exit( -1 ); } @@ -779,18 +699,14 @@ int main( int argc, char *argv[] ) ITMDecoderInit( &_r.i, options.forceITMSync ); MSGSeqInit( &_r.d, &_r.i, MSG_REORDER_BUFLEN ); - while ( true ) - { + while ( true ) { struct Stream *stream = NULL; - while ( true ) - { + while ( true ) { stream = _tryOpenStream(); - if ( stream != NULL ) - { - if ( alreadyReported ) - { + if ( stream != NULL ) { + if ( alreadyReported ) { genericsReport( V_INFO, "Connected" EOL ); alreadyReported = false; } @@ -798,14 +714,12 @@ int main( int argc, char *argv[] ) break; } - if ( !alreadyReported ) - { + if ( !alreadyReported ) { genericsReport( V_INFO, EOL "No connection" EOL ); alreadyReported = true; } - if ( options.endTerminate ) - { + if ( options.endTerminate ) { break; } @@ -813,16 +727,14 @@ int main( int argc, char *argv[] ) usleep( 10000 ); } - if ( stream != NULL ) - { + if ( stream != NULL ) { _feedStream( stream ); } stream->close( stream ); free( stream ); - if ( options.endTerminate ) - { + if ( options.endTerminate ) { break; } } diff --git a/Src/orbdump.c b/Src/orbdump.c index e1317d18..f968630b 100644 --- a/Src/orbdump.c +++ b/Src/orbdump.c @@ -23,17 +23,16 @@ #define MAX_STRING_LENGTH (256) /* Maximum length that will be output from a fifo for a single event */ -#define DEFAULT_OUTFILE "/dev/stdout" +#define DEFAULT_OUTFILE (char*)"/dev/stdout" #define DEFAULT_TIMELEN 10000 /* ---------- CONFIGURATION ----------------- */ -struct /* Record for options, either defaults or from command line */ -{ +struct { /* Record for options, either defaults or from command line */ /* Config information */ bool useTPIU; bool forceITMSync; - uint32_t tpiuITMChannel; + int8_t tpiuITMChannel; /* File to output dump to */ char *outfile; @@ -49,20 +48,18 @@ struct /* Record for options, either defaul /* Source information */ int port; char *server; -} options = -{ - .forceITMSync = true, +} options = { .useTPIU = false, + .forceITMSync = true, .tpiuITMChannel = 1, .outfile = DEFAULT_OUTFILE, .timelen = DEFAULT_TIMELEN, .port = NWCLIENT_SERVER_PORT, - .server = "localhost" + .server = ( char * )"localhost" }; /* ----------- LIVE STATE ----------------- */ -struct -{ +struct { /* The decoders and the packets from them */ struct ITMDecoder i; struct ITMPacket h; @@ -97,10 +94,8 @@ void _protocolPump( uint8_t c ) /* Top level protocol pump */ { - if ( options.useTPIU ) - { - switch ( TPIUPump( &_r.t, c ) ) - { + if ( options.useTPIU ) { + switch ( TPIUPump( &_r.t, c ) ) { // ------------------------------------ case TPIU_EV_NEWSYNC: case TPIU_EV_SYNCED: @@ -119,21 +114,17 @@ void _protocolPump( uint8_t c ) // ------------------------------------ case TPIU_EV_RXEDPACKET: - if ( !TPIUGetPacket( &_r.t, &_r.p ) ) - { + if ( !TPIUGetPacket( &_r.t, &_r.p ) ) { genericsReport( V_WARN, "TPIUGetPacket fell over" EOL ); } - for ( uint32_t g = 0; g < _r.p.len; g++ ) - { - if ( _r.p.packet[g].s == options.tpiuITMChannel ) - { + for ( uint32_t g = 0; g < _r.p.len; g++ ) { + if ( _r.p.packet[g].s == options.tpiuITMChannel ) { ITMPump( &_r.i, _r.p.packet[g].d ); continue; } - if ( _r.p.packet[g].s != 0 ) - { + if ( _r.p.packet[g].s != 0 ) { genericsReport( V_DEBUG, "Unknown TPIU channel %02x" EOL, _r.p.packet[g].s ); } } @@ -146,9 +137,7 @@ void _protocolPump( uint8_t c ) break; // ------------------------------------ } - } - else - { + } else { /* There's no TPIU in use, so this goes straight to the ITM layer */ ITMPump( &_r.i, c ); } @@ -177,8 +166,7 @@ void _printVersion( void ) genericsPrintf( "orbdump version " GIT_DESCRIBE EOL ); } // ==================================================================================================== -static struct option _longOptions[] = -{ +static struct option _longOptions[] = { {"help", no_argument, NULL, 'h'}, {"length", required_argument, NULL, 'l'}, {"itm-sync", no_argument, NULL, 'n'}, @@ -200,8 +188,7 @@ bool _processOptions( int argc, char *argv[] ) int c, optionIndex = 0; while ( ( c = getopt_long ( argc, argv, "hVl:Mno:p:s:t:v:w", _longOptions, &optionIndex ) ) != -1 ) - switch ( c ) - { + switch ( c ) { case 'o': options.outfile = optarg; break; @@ -223,13 +210,12 @@ bool _processOptions( int argc, char *argv[] ) break; case 'v': - if ( !isdigit( *optarg ) ) - { + if ( !isdigit( *optarg ) ) { genericsReport( V_ERROR, "-v requires a numeric argument." EOL ); return false; } - genericsSetReportLevel( atoi( optarg ) ); + genericsSetReportLevel( ( enum verbLevel )atoi( optarg ) ); break; case 't': @@ -256,12 +242,9 @@ bool _processOptions( int argc, char *argv[] ) return false; case '?': - if ( optopt == 'b' ) - { + if ( optopt == 'b' ) { genericsReport( V_ERROR, "Option '%c' requires an argument." EOL, optopt ); - } - else if ( !isprint ( optopt ) ) - { + } else if ( !isprint ( optopt ) ) { genericsReport( V_ERROR, "Unknown option character `\\x%x'." EOL, optopt ); } @@ -272,8 +255,7 @@ bool _processOptions( int argc, char *argv[] ) return false; } - if ( ( options.useTPIU ) && ( !options.tpiuITMChannel ) ) - { + if ( ( options.useTPIU ) && ( !options.tpiuITMChannel ) ) { genericsReport( V_ERROR, "TPIU set for use but no channel set for ITM output" EOL ); return false; } @@ -282,19 +264,15 @@ bool _processOptions( int argc, char *argv[] ) genericsReport( V_INFO, "Server : %s:%d" EOL, options.server, options.port ); genericsReport( V_INFO, "ForceSync : %s" EOL, options.forceITMSync ? "true" : "false" ); - if ( options.timelen ) - { + if ( options.timelen ) { genericsReport( V_INFO, "Rec Length: %dmS" EOL, options.timelen ); - } - else - { + } else { genericsReport( V_INFO, "Rec Length: Unlimited" EOL ); } genericsReport( V_INFO, "Sync Write: %s" EOL, options.writeSync ? "true" : "false" ); - if ( options.useTPIU ) - { + if ( options.useTPIU ) { genericsReport( V_INFO, "Using TPIU: true (ITM on channel %d)" EOL, options.tpiuITMChannel ); } @@ -321,8 +299,7 @@ int main( int argc, char *argv[] ) bool alreadyReported = false; struct Stream *stream; - if ( !_processOptions( argc, argv ) ) - { + if ( !_processOptions( argc, argv ) ) { exit( -1 ); } @@ -332,15 +309,12 @@ int main( int argc, char *argv[] ) TPIUDecoderInit( &_r.t ); ITMDecoderInit( &_r.i, options.forceITMSync ); - while ( true ) - { + while ( true ) { stream = _tryOpenStream(); - if ( stream != NULL ) - { - if ( alreadyReported ) - { + if ( stream != NULL ) { + if ( alreadyReported ) { genericsReport( V_INFO, "Connected" EOL ); alreadyReported = false; } @@ -348,8 +322,7 @@ int main( int argc, char *argv[] ) break; } - if ( !alreadyReported ) - { + if ( !alreadyReported ) { genericsReport( V_INFO, EOL "No connection" EOL ); alreadyReported = true; } @@ -363,8 +336,7 @@ int main( int argc, char *argv[] ) /* .... and the file to dump it into */ opFile = fopen( options.outfile, "wb" ); - if ( !opFile ) - { + if ( !opFile ) { genericsReport( V_ERROR, "Could not open output file for writing" EOL ); return -2; } @@ -372,26 +344,21 @@ int main( int argc, char *argv[] ) genericsReport( V_INFO, "Waiting for sync" EOL ); /* Start the process of collecting the data */ - while ( true ) - { + while ( true ) { enum ReceiveResult result = stream->receive( stream, cbw, TRANSFER_SIZE, NULL, &receivedSize ); - if ( result != RECEIVE_RESULT_OK ) - { - if ( result == RECEIVE_RESULT_EOF ) - { + if ( result != RECEIVE_RESULT_OK ) { + if ( result == RECEIVE_RESULT_EOF ) { break; } - if ( result == RECEIVE_RESULT_ERROR ) - { + if ( result == RECEIVE_RESULT_ERROR ) { genericsReport( V_ERROR, "Reading from connection failed" EOL ); return -2; } } - if ( ( options.timelen ) && ( ( firstTime != 0 ) && ( ( _timestamp() - firstTime ) > options.timelen ) ) ) - { + if ( ( options.timelen ) && ( ( firstTime != 0 ) && ( ( _timestamp() - firstTime ) > options.timelen ) ) ) { /* This packet arrived at the end of the window...finish the write process */ break; } @@ -400,23 +367,19 @@ int main( int argc, char *argv[] ) t = receivedSize; - while ( t-- ) - { + while ( t-- ) { _protocolPump( *c++ ); } /* Check to make sure there's not an unexpected TPIU in here */ - if ( ITMDecoderGetStats( &_r.i )->tpiuSyncCount ) - { + if ( ITMDecoderGetStats( &_r.i )->tpiuSyncCount ) { genericsReport( V_WARN, "Got a TPIU sync while decoding ITM...did you miss a -t option?" EOL ); break; } /* ... now check if we've acheived sync so can write frames */ - if ( !haveSynced ) - { - if ( !ITMDecoderIsSynced( &_r.i ) ) - { + if ( !haveSynced ) { + if ( !ITMDecoderIsSynced( &_r.i ) ) { continue; } @@ -429,13 +392,11 @@ int main( int argc, char *argv[] ) octetsRxed += fwrite( cbw, 1, receivedSize, opFile ); - if ( !ITMDecoderIsSynced( &_r.i ) ) - { + if ( !ITMDecoderIsSynced( &_r.i ) ) { genericsReport( V_WARN, "Warning:Sync lost while writing output" EOL ); } - if ( options.writeSync ) - { + if ( options.writeSync ) { #if defined(WIN32) _flushall(); #else @@ -448,8 +409,7 @@ int main( int argc, char *argv[] ) free( stream ); fclose( opFile ); - if ( receivedSize <= 0 ) - { + if ( receivedSize <= 0 ) { genericsReport( V_ERROR, "Network Read failed" EOL ); return -2; } diff --git a/Src/orbfifo.c b/Src/orbfifo.c index 6ecad2d9..0bc4688d 100644 --- a/Src/orbfifo.c +++ b/Src/orbfifo.c @@ -33,8 +33,7 @@ //#define DUMP_BLOCK /* Record for options, either defaults or from command line */ -struct -{ +struct { /* Config information */ bool filewriter; /* Supporting filewriter functionality */ char *fwbasedir; /* Base directory for filewriter output */ @@ -48,14 +47,12 @@ struct int port; /* Source information */ char *server; -} options = -{ +} options = { .port = NWCLIENT_SERVER_PORT, - .server = "localhost" + .server = ( char * )"localhost" }; -struct -{ +struct { struct itmfifosHandle *f; /* Link to the itmfifo subsystem */ bool ending; /* Flag indicating app is terminating */ } _r; @@ -92,8 +89,7 @@ void _printVersion( void ) genericsPrintf( "orbfifo version " GIT_DESCRIBE ); } // ==================================================================================================== -struct option _longOptions[] = -{ +struct option _longOptions[] = { {"basedir", required_argument, NULL, 'b'}, {"channel", required_argument, NULL, 'c'}, {"eof", no_argument, NULL, 'E'}, @@ -120,11 +116,10 @@ static bool _processOptions( int argc, char *argv[] ) char *chanName; uint chan; char *chanIndex; - + char *a; while ( ( c = getopt_long ( argc, argv, "b:c:Ef:hVn:Ps:t:v:w:", _longOptions, &optionIndex ) ) != -1 ) - switch ( c ) - { + switch ( c ) { // ------------------------------------ case 'b': @@ -174,21 +169,18 @@ static bool _processOptions( int argc, char *argv[] ) options.server = optarg; // See if we have an optional port number too - char *a = optarg; + a = optarg; - while ( ( *a ) && ( *a != ':' ) ) - { + while ( ( *a ) && ( *a != ':' ) ) { a++; } - if ( *a == ':' ) - { + if ( *a == ':' ) { *a = 0; options.port = atoi( ++a ); } - if ( !options.port ) - { + if ( !options.port ) { options.port = NWCLIENT_SERVER_PORT; } @@ -204,13 +196,12 @@ static bool _processOptions( int argc, char *argv[] ) // ------------------------------------ case 'v': - if ( !isdigit( *optarg ) ) - { + if ( !isdigit( *optarg ) ) { genericsReport( V_ERROR, "-v requires a numeric argument." EOL ); return false; } - genericsSetReportLevel( atoi( optarg ) ); + genericsSetReportLevel( ( enum verbLevel )atoi( optarg ) ); break; // ------------------------------------ @@ -226,29 +217,25 @@ static bool _processOptions( int argc, char *argv[] ) case 'c': chanIndex = chanConfig = strdup( optarg ); - if ( NULL == chanConfig ) - { + if ( NULL == chanConfig ) { genericsReport( V_ERROR, "Couldn't allocate memory at %s::%d" EOL, __FILE__, __LINE__ ); return false; } chan = atoi( optarg ); - if ( chan >= NUM_CHANNELS ) - { + if ( chan >= NUM_CHANNELS ) { genericsReport( V_ERROR, "Channel index out of range" EOL ); free( chanConfig ); return false; } /* Scan for start of filename */ - while ( ( *chanIndex ) && ( *chanIndex != DELIMITER ) ) - { + while ( ( *chanIndex ) && ( *chanIndex != DELIMITER ) ) { chanIndex++; } - if ( !*chanIndex ) - { + if ( !*chanIndex ) { genericsReport( V_ERROR, "No filename for channel %d" EOL, chan ); free( chanConfig ); return false; @@ -257,13 +244,11 @@ static bool _processOptions( int argc, char *argv[] ) chanName = ++chanIndex; /* Scan for format */ - while ( ( *chanIndex ) && ( *chanIndex != DELIMITER ) ) - { + while ( ( *chanIndex ) && ( *chanIndex != DELIMITER ) ) { chanIndex++; } - if ( !*chanIndex ) - { + if ( !*chanIndex ) { genericsReport( V_WARN, "No output format for channel %d, output raw!" EOL, chan ); itmfifoSetChannel( _r.f, chan, chanName, NULL ); break; @@ -276,12 +261,9 @@ static bool _processOptions( int argc, char *argv[] ) // ------------------------------------ case '?': - if ( optopt == 'b' ) - { + if ( optopt == 'b' ) { genericsReport( V_ERROR, "Option '%c' requires an argument." EOL, optopt ); - } - else if ( !isprint ( optopt ) ) - { + } else if ( !isprint ( optopt ) ) { genericsReport( V_ERROR, "Unknown option character `\\x%x'." EOL, optopt ); } @@ -298,36 +280,27 @@ static bool _processOptions( int argc, char *argv[] ) genericsReport( V_INFO, "orbfifo version " GIT_DESCRIBE EOL ); genericsReport( V_INFO, "Server : %s:%d" EOL, options.server, options.port ); - if ( itmfifoGetUseTPIU( _r.f ) ) - { + if ( itmfifoGetUseTPIU( _r.f ) ) { genericsReport( V_INFO, "Using TPIU : true (ITM on channel %d)" EOL, itmfifoGettpiuITMChannel( _r.f ) ); - } - else - { + } else { genericsReport( V_INFO, "Using TPIU : false" EOL ); } - if ( options.file ) - { + if ( options.file ) { genericsReport( V_INFO, "Input File : %s", options.file ); - if ( options.fileTerminate ) - { + if ( options.fileTerminate ) { genericsReport( V_INFO, " (Terminate on exhaustion)" EOL ); - } - else - { + } else { genericsReport( V_INFO, " (Ongoing read)" EOL ); } } genericsReport( V_INFO, "Channels :" EOL ); - for ( int g = 0; g < NUM_CHANNELS; g++ ) - { - if ( itmfifoGetChannelName( _r.f, g ) ) - { - genericsReport( V_INFO, " %02d [%s] [%s]" EOL, g, genericsEscape( itmfifoGetChannelFormat( _r.f, g ) ? : "RAW" ), itmfifoGetChannelName( _r.f, g ) ); + for ( int g = 0; g < NUM_CHANNELS; g++ ) { + if ( itmfifoGetChannelName( _r.f, g ) ) { + genericsReport( V_INFO, " %02d [%s] [%s]" EOL, g, genericsEscape( itmfifoGetChannelFormat( _r.f, g ) ? : ( char * )"RAW" ), itmfifoGetChannelName( _r.f, g ) ); } } @@ -343,28 +316,24 @@ static void _processBlock( int s, unsigned char *cbw ) { genericsReport( V_DEBUG, "RXED Packet of %d bytes" EOL, s ); - if ( s ) - { + if ( s ) { #ifdef DUMP_BLOCK uint8_t *c = cbw; uint32_t y = s; fprintf( stderr, EOL ); - while ( y-- ) - { + while ( y-- ) { fprintf( stderr, "%02X ", *c++ ); - if ( !( y % 16 ) ) - { + if ( !( y % 16 ) ) { fprintf( stderr, EOL ); } } #endif - while ( s-- ) - { + while ( s-- ) { itmfifoProtocolPump( _r.f, *cbw++ ); } } @@ -404,8 +373,7 @@ int main( int argc, char *argv[] ) _r.f = itmfifoInit( true, false, 1 ); assert( _r.f ); - if ( !_processOptions( argc, argv ) ) - { + if ( !_processOptions( argc, argv ) ) { /* processOptions generates its own error messages */ genericsExit( -1, "" EOL ); } @@ -421,39 +389,30 @@ int main( int argc, char *argv[] ) lastTime = genericsTimestampmS(); /* This ensures the atexit gets called */ - if ( SIG_ERR == signal( SIGINT, _intHandler ) ) - { + if ( SIG_ERR == signal( SIGINT, _intHandler ) ) { genericsExit( -1, "Failed to establish Int handler" EOL ); } /* Don't kill a sub-process when any reader or writer evaporates */ - if ( SIG_ERR == signal( SIGPIPE, SIG_IGN ) ) - { + if ( SIG_ERR == signal( SIGPIPE, SIG_IGN ) ) { genericsExit( -1, "Failed to ignore SIGPIPEs" EOL ); } - if ( ! ( itmfifoCreate( _r.f ) ) ) - { + if ( ! ( itmfifoCreate( _r.f ) ) ) { genericsExit( -1, "Failed to make channel devices" EOL ); } /* Start the filewriter */ itmfifoFilewriter( _r.f, options.filewriter, options.fwbasedir ); - while ( !_r.ending ) - { - if ( options.file != NULL ) - { + while ( !_r.ending ) { + if ( options.file != NULL ) { stream = streamCreateFile( options.file ); - } - else - { - while ( !_r.ending ) - { + } else { + while ( !_r.ending ) { stream = streamCreateSocket( options.server, options.port ); - if ( stream ) - { + if ( stream ) { break; } @@ -462,20 +421,17 @@ int main( int argc, char *argv[] ) } } - while ( !_r.ending ) - { + while ( !_r.ending ) { remainTime = ( ( lastTime + 1000000 - genericsTimestampuS() ) ); - if ( remainTime > 0 ) - { + if ( remainTime > 0 ) { tv.tv_sec = remainTime / 1000000; tv.tv_usec = remainTime % 1000000; } enum ReceiveResult result = stream->receive( stream, cbw, TRANSFER_SIZE, &tv, ( size_t * )&t ); - if ( ( result == RECEIVE_RESULT_EOF ) || ( result == RECEIVE_RESULT_ERROR ) ) - { + if ( ( result == RECEIVE_RESULT_EOF ) || ( result == RECEIVE_RESULT_ERROR ) ) { break; } @@ -483,15 +439,13 @@ int main( int argc, char *argv[] ) } - if ( stream ) - { + if ( stream ) { stream->close( stream ); free( stream ); stream = NULL; } - if ( options.fileTerminate ) - { + if ( options.fileTerminate ) { break; } } diff --git a/Src/orblcd.c b/Src/orblcd.c index 51c0e087..22192e55 100644 --- a/Src/orblcd.c +++ b/Src/orblcd.c @@ -31,17 +31,16 @@ /************** APPLICATION SPECIFIC ********************************************************************/ /* Target application specifics */ -struct TApp -{ +struct TApp { /* Application specific Options */ int chan; /* The channel we are listening on */ int sbcolour; /* Colour to be used for single bit renders */ /* Operational stuff */ - int x; /* Current X pos */ - int y; /* Current Y pos */ + unsigned int x; /* Current X pos */ + unsigned int y; /* Current Y pos */ float scale; /* Scale for output window */ - int modeDescriptor; /* Descriptor for source mode */ + unsigned int modeDescriptor; /* Descriptor for source mode */ char *windowTitle; /* Title for SDL output window */ /* SDL stuff */ @@ -54,19 +53,17 @@ struct TApp uint32_t map8to24bit[256]; /* Colour index table for 8 to 24 bit mapping */ int pwidth; /* Width of one line of pixel buffer */ -} _app = -{ +} _app = { .chan = LCD_DATA_CHANNEL, .sbcolour = 0x00ff00, .scale = 1.5f, - .windowTitle = "ORBLcd Output Window" + .windowTitle = ( char * )"ORBLcd Output Window" }; /************** APPLICATION SPECIFIC ENDS ***************************************************************/ /* Record for options, either defaults or from command line */ -struct Options -{ +struct Options { /* Source information */ int port; /* Source port, or zero if no port set */ char *server; /* Source server */ @@ -77,10 +74,13 @@ struct Options int tpiuChannel; /* TPIU channel to be used (for case TPIU present, 0 otherwise) */ bool forceITMSync; /* Do we need ITM syncs? */ -} _options = {.forceITMSync = true, .port = NWCLIENT_SERVER_PORT, .server = "localhost"}; +} _options = { + .port = NWCLIENT_SERVER_PORT, + .server = ( char * )"localhost", + .forceITMSync = true, +}; -struct RunTime -{ +struct RunTime { /* The decoders and the packets from them */ struct ITMDecoder i; struct ITMPacket h; @@ -94,8 +94,7 @@ struct RunTime struct Options *options; /* Command line options (reference to above) */ struct TApp *app; /* Data storage for target application */ -} _r = -{ +} _r = { .options = &_options, .app = &_app, }; @@ -111,21 +110,17 @@ static void _paintPixels( struct swMsg *m, struct RunTime *r ) int d = m->value; int y; - if ( !r->app->pixels ) - { + if ( !r->app->pixels ) { /* For whatever reason we aren't initialised yet */ return; } - for ( int b = ORBLCD_PIXELS_PER_WORD( r->app->modeDescriptor ) - 1; b >= 0; b-- ) - { - switch ( ORBLCD_DECODE_D( r->app->modeDescriptor ) ) - { + for ( int b = ORBLCD_PIXELS_PER_WORD( r->app->modeDescriptor ) - 1; b >= 0; b-- ) { + switch ( ORBLCD_DECODE_D( r->app->modeDescriptor ) ) { case ORBLCD_DEPTH_1: y = ( d & ( 1 << ( b % 8 ) ) ) ? r->app->sbcolour : 0; - if ( !( b % 8 ) ) - { + if ( !( b % 8 ) ) { d >>= 8; } @@ -153,13 +148,11 @@ static void _paintPixels( struct swMsg *m, struct RunTime *r ) /* Output bitdepth is always the same, so span calculation is too */ *( uint32_t * )&r->app->pixels[r->app->x * 4 + r->app->y * r->app->pwidth] = y | 0xff000000; - if ( ++r->app->x >= ORBLCD_DECODE_X( r->app->modeDescriptor ) ) - { + if ( ++r->app->x >= ORBLCD_DECODE_X( r->app->modeDescriptor ) ) { r->app->y++; r->app->x = 0; - if ( r->app->y == ORBLCD_DECODE_Y( r->app->modeDescriptor ) ) - { + if ( r->app->y == ORBLCD_DECODE_Y( r->app->modeDescriptor ) ) { r->app->y = 0; } @@ -174,11 +167,9 @@ static void _handleCommand( struct swMsg *m, struct RunTime *r ) { /* This is control data */ - switch ( ORBLCD_DECODE_C( m->value ) ) - { + switch ( ORBLCD_DECODE_C( m->value ) ) { case ORBLCD_CMD_INIT_LCD: // ------------------------------------------------------- - if ( ( !r->app->mainWindow ) || ( m->value != r->app->modeDescriptor ) ) - { + if ( ( !r->app->mainWindow ) || ( m->value != r->app->modeDescriptor ) ) { /* Create a new, or replacement, SDL window */ genericsReport( V_ERROR, "%s window %dx%d, depth %d" EOL, ( r->app->modeDescriptor ) ? "Replacement" : "New", @@ -186,18 +177,15 @@ static void _handleCommand( struct swMsg *m, struct RunTime *r ) r->app->modeDescriptor = m->value; /* If this is due to a resize activity then destroy the old stuff */ - if ( r->app->renderer ) - { + if ( r->app->renderer ) { SDL_DestroyRenderer( r->app->renderer ); } - if ( r->app->mainWindow ) - { + if ( r->app->mainWindow ) { SDL_DestroyWindow( r->app->mainWindow ); } - if ( r->app->pixels ) - { + if ( r->app->pixels ) { free( r->app->pixels ); } @@ -212,9 +200,7 @@ static void _handleCommand( struct swMsg *m, struct RunTime *r ) /* Create the memory for drawing the image */ r->app->pwidth = sizeof( uint32_t ) * ORBLCD_DECODE_X( r->app->modeDescriptor ); r->app->pixels = ( uint8_t * )calloc( ORBLCD_DECODE_Y( r->app->modeDescriptor ) * r->app->pwidth, 1 ); - } - else - { + } else { /* Repaint the SDL window */ SDL_UpdateTexture( r->app->texture, NULL, r->app->pixels, r->app->pwidth ); SDL_RenderCopy( r->app->renderer, r->app->texture, NULL, NULL ); @@ -225,21 +211,18 @@ static void _handleCommand( struct swMsg *m, struct RunTime *r ) break; case ORBLCD_CMD_CLEAR: // ------------------------------------------------------------- - if ( r->app->pixels ) - { + if ( r->app->pixels ) { memset( r->app->pixels, 0, ORBLCD_DECODE_Y( r->app->modeDescriptor ) * r->app->pwidth ); } break; case ORBLCD_CMD_GOTOXY: // ------------------------------------------------------------ - if ( ORBLCD_DECODE_X( m->value ) < ORBLCD_DECODE_X( r->app->modeDescriptor ) ) - { + if ( ORBLCD_DECODE_X( m->value ) < ORBLCD_DECODE_X( r->app->modeDescriptor ) ) { r->app->x = ORBLCD_DECODE_X( m->value ); } - if ( ORBLCD_DECODE_Y( m->value ) < ORBLCD_DECODE_Y( r->app->modeDescriptor ) ) - { + if ( ORBLCD_DECODE_Y( m->value ) < ORBLCD_DECODE_Y( r->app->modeDescriptor ) ) { r->app->y = ORBLCD_DECODE_Y( m->value ); } @@ -256,12 +239,9 @@ static void _handleCommand( struct swMsg *m, struct RunTime *r ) static void _handleSW( struct swMsg *m, struct RunTime *r ) { - if ( ( m->srcAddr == r->app->chan ) && ( r->app->pixels ) ) - { + if ( ( m->srcAddr == r->app->chan ) && ( r->app->pixels ) ) { _paintPixels( m, r ); - } - else if ( m->srcAddr == r->app->chan + 1 ) - { + } else if ( m->srcAddr == r->app->chan + 1 ) { _handleCommand( m, r ); } } @@ -278,8 +258,7 @@ void _itmPumpProcess( char c, struct RunTime *r ) { struct msg decoded; - switch ( ITMPump( &r->i, c ) ) - { + switch ( ITMPump( &r->i, c ) ) { case ITM_EV_NONE: break; @@ -304,8 +283,7 @@ void _itmPumpProcess( char c, struct RunTime *r ) /* See if we decoded a dispatchable match. genericMsg is just used to access */ /* the first two members of the decoded structs in a portable way. */ - if ( decoded.genericMsg.msgtype == MSG_SOFTWARE ) - { + if ( decoded.genericMsg.msgtype == MSG_SOFTWARE ) { _handleSW( ( struct swMsg * )&decoded, r ); } @@ -324,13 +302,10 @@ static void _TPIUpacketRxed( enum TPIUPumpEvent e, struct TPIUPacket *p, void *p { struct RunTime *r = ( struct RunTime * )param; - switch ( e ) - { + switch ( e ) { case TPIU_EV_RXEDPACKET: - for ( uint32_t g = 0; g < p->len; g++ ) - { - if ( 1 == p->packet[g].s ) - { + for ( uint32_t g = 0; g < p->len; g++ ) { + if ( 1 == p->packet[g].s ) { _itmPumpProcess( p->packet[g].d, r ); } } @@ -354,12 +329,9 @@ static void _TPIUpacketRxed( enum TPIUPumpEvent e, struct TPIUPacket *p, void *p static struct Stream *_tryOpenStream( struct RunTime *r ) { - if ( r->options->file != NULL ) - { + if ( r->options->file != NULL ) { return streamCreateFile( r->options->file ); - } - else - { + } else { return streamCreateSocket( r->options->server, r->options->port ); } } @@ -368,54 +340,40 @@ static struct Stream *_tryOpenStream( struct RunTime *r ) static bool _feedStream( struct Stream *stream, struct RunTime *r ) { unsigned char cbw[TRANSFER_SIZE]; - struct timeval t = - { + struct timeval t = { .tv_sec = 0, .tv_usec = 100000 }; SDL_Event e; - while ( true ) - { + while ( true ) { size_t receivedSize; enum ReceiveResult result = stream->receive( stream, cbw, TRANSFER_SIZE, &t, &receivedSize ); /* Check for SDL close */ - while ( SDL_PollEvent( &e ) != 0 ) - { - if ( e.type == SDL_QUIT ) - { + while ( SDL_PollEvent( &e ) != 0 ) { + if ( e.type == SDL_QUIT ) { return false; } } - if ( result != RECEIVE_RESULT_OK ) - { - if ( result == RECEIVE_RESULT_EOF && r->options->fileTerminate ) - { + if ( result != RECEIVE_RESULT_OK ) { + if ( result == RECEIVE_RESULT_EOF && r->options->fileTerminate ) { return true; - } - else if ( result == RECEIVE_RESULT_ERROR ) - { + } else if ( result == RECEIVE_RESULT_ERROR ) { break; - } - else - { + } else { usleep( 100000 ); } } unsigned char *c = cbw; - if ( _r.options->tpiuChannel ) - { + if ( _r.options->tpiuChannel ) { TPIUPump2( &r->t, cbw, receivedSize, _TPIUpacketRxed, r ); - } - else - { - while ( receivedSize-- ) - { + } else { + while ( receivedSize-- ) { _itmPumpProcess( *c++, r ); } } @@ -451,8 +409,7 @@ void _printVersion( void ) genericsPrintf( "orblcd version " GIT_DESCRIBE EOL ); } // ==================================================================================================== -static struct option _longOptions[] = -{ +static struct option _longOptions[] = { {"channel", required_argument, NULL, 'c'}, {"eof", no_argument, NULL, 'E'}, {"help", no_argument, NULL, 'h'}, @@ -473,10 +430,10 @@ bool _processOptions( int argc, char *argv[], struct RunTime *r ) { int c, optionIndex = 0; + char *a; while ( ( c = getopt_long ( argc, argv, "c:Ef:hns:S:t:v:Vw:z:", _longOptions, &optionIndex ) ) != -1 ) - switch ( c ) - { + switch ( c ) { // ------------------------------------ case 'c': r->app->chan = atoi( optarg ); @@ -513,21 +470,18 @@ bool _processOptions( int argc, char *argv[], struct RunTime *r ) r->options->server = optarg; // See if we have an optional port number too - char *a = optarg; + a = optarg; - while ( ( *a ) && ( *a != ':' ) ) - { + while ( ( *a ) && ( *a != ':' ) ) { a++; } - if ( *a == ':' ) - { + if ( *a == ':' ) { *a = 0; r->options->port = atoi( ++a ); } - if ( !r->options->port ) - { + if ( !r->options->port ) { r->options->port = NWCLIENT_SERVER_PORT; } @@ -545,13 +499,12 @@ bool _processOptions( int argc, char *argv[], struct RunTime *r ) // ------------------------------------ case 'v': - if ( !isdigit( *optarg ) ) - { + if ( !isdigit( *optarg ) ) { genericsReport( V_ERROR, "-v requires a numeric argument." EOL ); return false; } - genericsSetReportLevel( atoi( optarg ) ); + genericsSetReportLevel( ( enum verbLevel )atoi( optarg ) ); break; // ------------------------------------ @@ -566,12 +519,9 @@ bool _processOptions( int argc, char *argv[], struct RunTime *r ) // ------------------------------------ case '?': - if ( optopt == 'b' ) - { + if ( optopt == 'b' ) { genericsReport( V_ERROR, "Option '%c' requires an argument." EOL, optopt ); - } - else if ( !isprint ( optopt ) ) - { + } else if ( !isprint ( optopt ) ) { genericsReport( V_ERROR, "Unknown option character `\\x%x'." EOL, optopt ); } @@ -592,36 +542,27 @@ bool _processOptions( int argc, char *argv[], struct RunTime *r ) genericsReport( V_INFO, "Relative Scale : %1.2f:1" EOL, r->app->scale ); genericsReport( V_INFO, "Window Title : %s" EOL, r->app->windowTitle ); - if ( r->options->port ) - { + if ( r->options->port ) { genericsReport( V_INFO, "NW SERVER H&P : %s:%d" EOL, r->options->server, r->options->port ); } - if ( r->options->tpiuChannel ) - { + if ( r->options->tpiuChannel ) { genericsReport( V_INFO, "Use/Strip TPIU : True, channel %d" EOL, r->options->tpiuChannel ); - } - else - { + } else { genericsReport( V_INFO, "Use/Strip TPIU : False" EOL ); } - if ( r->options->file ) - { + if ( r->options->file ) { genericsReport( V_INFO, "Input File : %s", r->options->file ); - if ( r->options->fileTerminate ) - { + if ( r->options->fileTerminate ) { genericsReport( V_INFO, " (Terminate on exhaustion)" EOL ); - } - else - { + } else { genericsReport( V_INFO, " (Ongoing read)" EOL ); } } - if ( ( r->options->file ) && ( r->options->port ) ) - { + if ( ( r->options->file ) && ( r->options->port ) ) { genericsReport( V_ERROR, "Cannot specify file and port or NW Server at same time" EOL ); return false; } @@ -640,8 +581,7 @@ int main( int argc, char *argv[] ) { bool alreadyReported = false; - if ( !_processOptions( argc, argv, &_r ) ) - { + if ( !_processOptions( argc, argv, &_r ) ) { exit( -1 ); } @@ -649,29 +589,23 @@ int main( int argc, char *argv[] ) TPIUDecoderInit( &_r.t ); ITMDecoderInit( &_r.i, _r.options->forceITMSync ); - if ( SDL_Init( SDL_INIT_VIDEO ) < 0 ) - { + if ( SDL_Init( SDL_INIT_VIDEO ) < 0 ) { genericsExit( -1, "Could not initailise SDL" ); } /* Load up default colour index map R3G3B2 */ - for ( int i = 0; i < 256; i++ ) - { + for ( int i = 0; i < 256; i++ ) { _r.app->map8to24bit[i] = ( ( i & 0xE0 ) << 21 ) | ( ( i & 0x1c ) << 13 ) | ( i << 6 ); } - while ( true ) - { + while ( true ) { struct Stream *stream = NULL; - while ( true ) - { + while ( true ) { stream = _tryOpenStream( &_r ); - if ( stream != NULL ) - { - if ( alreadyReported ) - { + if ( stream != NULL ) { + if ( alreadyReported ) { genericsReport( V_INFO, "Connected" EOL ); alreadyReported = false; } @@ -679,14 +613,12 @@ int main( int argc, char *argv[] ) break; } - if ( !alreadyReported ) - { + if ( !alreadyReported ) { genericsReport( V_INFO, EOL "No connection" EOL ); alreadyReported = true; } - if ( _r.options->fileTerminate ) - { + if ( _r.options->fileTerminate ) { break; } @@ -694,10 +626,8 @@ int main( int argc, char *argv[] ) usleep( 10000 ); } - if ( stream != NULL ) - { - if ( !_feedStream( stream, &_r ) ) - { + if ( stream != NULL ) { + if ( !_feedStream( stream, &_r ) ) { break; } } @@ -705,8 +635,7 @@ int main( int argc, char *argv[] ) stream->close( stream ); free( stream ); - if ( _r.options->fileTerminate ) - { + if ( _r.options->fileTerminate ) { break; } } diff --git a/Src/orbmortem.c b/Src/orbmortem.c index 5df7d9d5..c57d5857 100644 --- a/Src/orbmortem.c +++ b/Src/orbmortem.c @@ -27,7 +27,7 @@ #include "sio.h" #include "stream.h" -#define REMOTE_SERVER "localhost" +#define REMOTE_SERVER (char*)"localhost" #define SCRATCH_STRING_LEN (65535) /* Max length for a string under construction */ //#define DUMP_BLOCK @@ -39,8 +39,7 @@ #define TICK_TIME_MS (100) /* Time intervals for screen updates and keypress check */ /* Record for options, either defaults or from command line */ -struct Options -{ +struct Options { /* Source information */ char *file; /* File host connection */ bool fileTerminate; /* Terminate when file read isn't successful */ @@ -61,26 +60,23 @@ struct Options char *openFileCL; /* Command line for opening refernced file */ bool withDebugText; /* Include debug text (hidden in) output...screws line numbering a bit */ -} _options = -{ +} _options = { + .demangle = true, + .buflen = DEFAULT_PM_BUFLEN_K * 1024, + .channel = 2, .port = NWCLIENT_SERVER_PORT, .server = REMOTE_SERVER, - .demangle = true, .protocol = TRACE_PROT_ETM35, - .channel = 2, - .buflen = DEFAULT_PM_BUFLEN_K * 1024 }; /* A block of received data */ -struct dataBlock -{ +struct dataBlock { ssize_t fillLevel; uint8_t buffer[TRANSFER_SIZE]; }; /* Materials required to be maintained across callbacks for output construction */ -struct opConstruct -{ +struct opConstruct { uint32_t currentFileindex; /* The filename we're currently in */ struct symbolFunctionStore *currentFunctionptr; /* The function we're currently in */ uint32_t currentLine; /* The line we're currently in */ @@ -90,8 +86,7 @@ struct opConstruct /* Maximum depth of call stack, defined Section 5.3 or ARM IHI0064H.a ID120820 */ #define MAX_CALL_STACK (15) -struct RunTime -{ +struct RunTime { struct TRACEDecoder i; struct TPIUDecoder t; @@ -178,9 +173,8 @@ static void _printHelp( const char *const progName ) genericsPrintf( " -O, --objdump-opts: Options to pass directly to objdump" EOL ); genericsPrintf( " -p, --trace-proto: { " ); - for ( int i = TRACE_PROT_LIST_START; i < TRACE_PROT_NUM; i++ ) - { - genericsPrintf( "%s ", TRACEDecodeGetProtocolName( i ) ); + for ( int i = TRACE_PROT_LIST_START; i < TRACE_PROT_NUM; i++ ) { + genericsPrintf( "%s ", TRACEDecodeGetProtocolName( ( enum TRACEprotocol )i ) ); } genericsPrintf( "} trace protocol to use, default is %s" EOL, TRACEDecodeGetProtocolName( TRACE_PROT_LIST_START ) ); @@ -200,8 +194,7 @@ void _printVersion( void ) genericsPrintf( "orbmortem version " GIT_DESCRIBE ); } // ==================================================================================================== -static struct option _longOptions[] = -{ +static struct option _longOptions[] = { {"alt-addr-enc", no_argument, NULL, 'A'}, {"buffer-len", required_argument, NULL, 'b'}, {"editor-cmd", required_argument, NULL, 'C'}, @@ -226,10 +219,10 @@ static bool _processOptions( int argc, char *argv[], struct RunTime *r ) { int c, optionIndex = 0; + char *a; while ( ( c = getopt_long ( argc, argv, "Ab:C:Dd:Ee:f:hVMO:p:s:t:v:w", _longOptions, &optionIndex ) ) != -1 ) - switch ( c ) - { + switch ( c ) { // ------------------------------------ case 'A': r->options->noAltAddr = true; @@ -298,11 +291,12 @@ static bool _processOptions( int argc, char *argv[], struct RunTime *r ) case 'p': /* Index through protocol strings looking for match or end of list */ - for ( r->options->protocol = TRACE_PROT_LIST_START; - ( ( r->options->protocol != TRACE_PROT_NUM ) && strcasecmp( optarg, TRACEDecodeGetProtocolName( r->options->protocol ) ) ); - r->options->protocol++ ) + for ( c = TRACE_PROT_LIST_START; + ( ( c != TRACE_PROT_NUM ) && strcasecmp( optarg, TRACEDecodeGetProtocolName( ( enum TRACEprotocol )c ) ) ); + c++ ) {} + r->options->protocol = ( enum TRACEprotocol )c; break; // ------------------------------------ @@ -311,21 +305,18 @@ static bool _processOptions( int argc, char *argv[], struct RunTime *r ) r->options->server = optarg; // See if we have an optional port number too - char *a = optarg; + a = optarg; - while ( ( *a ) && ( *a != ':' ) ) - { + while ( ( *a ) && ( *a != ':' ) ) { a++; } - if ( *a == ':' ) - { + if ( *a == ':' ) { *a = 0; r->options->port = atoi( ++a ); } - if ( !r->options->port ) - { + if ( !r->options->port ) { r->options->port = NWCLIENT_SERVER_PORT; } @@ -341,13 +332,12 @@ static bool _processOptions( int argc, char *argv[], struct RunTime *r ) // ------------------------------------ case 'v': - if ( !isdigit( *optarg ) ) - { + if ( !isdigit( *optarg ) ) { genericsReport( V_ERROR, "-v requires a numeric argument." EOL ); return false; } - genericsSetReportLevel( atoi( optarg ) ); + genericsSetReportLevel( ( enum verbLevel )atoi( optarg ) ); break; // ------------------------------------ @@ -359,12 +349,9 @@ static bool _processOptions( int argc, char *argv[], struct RunTime *r ) // ------------------------------------ case '?': - if ( optopt == 'b' ) - { + if ( optopt == 'b' ) { genericsReport( V_ERROR, "Option '%c' requires an argument." EOL, optopt ); - } - else if ( !isprint ( optopt ) ) - { + } else if ( !isprint ( optopt ) ) { genericsReport( V_ERROR, "Unknown option character `\\x%x'." EOL, optopt ); } @@ -380,32 +367,25 @@ static bool _processOptions( int argc, char *argv[], struct RunTime *r ) /* ... and dump the config if we're being verbose */ genericsReport( V_INFO, "orbmortem version " GIT_DESCRIBE EOL ); - if ( r->options->withDebugText ) - { + if ( r->options->withDebugText ) { genericsReport( V_INFO, "Incoporate debug text in output buffer" EOL ); } - if ( r->options->protocol >= TRACE_PROT_NONE ) - { + if ( r->options->protocol >= TRACE_PROT_NONE ) { genericsExit( V_ERROR, "Unrecognised decode protocol" EOL ); - } - else - { + } else { genericsReport( V_INFO, "Protocol %s" EOL, TRACEDecodeGetProtocolName( r->options->protocol ) ); } - if ( ( r->options->protocol == TRACE_PROT_MTB ) && ( !r->options->file ) ) - { + if ( ( r->options->protocol == TRACE_PROT_MTB ) && ( !r->options->file ) ) { genericsExit( V_ERROR, "MTB only makes sense when input is from a file" EOL ); } - if ( !r->options->elffile ) - { + if ( !r->options->elffile ) { genericsExit( V_ERROR, "Elf File not specified" EOL ); } - if ( !r->options->buflen ) - { + if ( !r->options->buflen ) { genericsExit( -1, "Illegal value for Post Mortem Buffer length" EOL ); } @@ -418,21 +398,18 @@ static void _processBlock( struct RunTime *r ) { uint8_t *c = r->rawBlock.buffer; - uint32_t y = r->rawBlock.fillLevel; + int32_t y = r->rawBlock.fillLevel; genericsReport( V_DEBUG, "RXED Packet of %d bytes" EOL, y ); - if ( y ) - { + if ( y ) { #ifdef DUMP_BLOCK fprintf( stderr, EOL ); - while ( y-- ) - { + while ( y-- ) { fprintf( stderr, "%02X ", *c++ ); - if ( !( y % 16 ) ) - { + if ( !( y % 16 ) ) { fprintf( stderr, EOL ); } } @@ -441,38 +418,26 @@ static void _processBlock( struct RunTime *r ) y = r->rawBlock.fillLevel; #endif - if ( r->options->useTPIU ) - { + if ( r->options->useTPIU ) { struct TPIUPacket p; - while ( y-- ) - { - if ( TPIU_EV_RXEDPACKET == TPIUPump( &r->t, *c++ ) ) - { - if ( !TPIUGetPacket( &r->t, &p ) ) - { + while ( y-- ) { + if ( TPIU_EV_RXEDPACKET == TPIUPump( &r->t, *c++ ) ) { + if ( !TPIUGetPacket( &r->t, &p ) ) { genericsReport( V_WARN, "TPIUGetPacket fell over" EOL ); - } - else - { + } else { /* Iterate through the packet, putting bytes for TRACE into the processing buffer */ - for ( uint32_t g = 0; g < p.len; g++ ) - { - if ( r->options->channel == p.packet[g].s ) - { + for ( int g = 0; g < p.len; g++ ) { + if ( r->options->channel == p.packet[g].s ) { r->pmBuffer[r->wp] = p.packet[g].d; r->newTotalBytes++; - uint32_t nwp = ( r->wp + 1 ) % r->options->buflen; + int32_t nwp = ( r->wp + 1 ) % r->options->buflen; - if ( nwp == r->rp ) - { - if ( r->singleShot ) - { + if ( nwp == r->rp ) { + if ( r->singleShot ) { r->held = true; return; - } - else - { + } else { r->rp = ( r->rp + 1 ) % r->options->buflen; } } @@ -483,25 +448,18 @@ static void _processBlock( struct RunTime *r ) } } } - } - else - { + } else { r->newTotalBytes += y; - while ( y-- ) - { + while ( y-- ) { r->pmBuffer[r->wp] = *c++; - uint32_t nwp = ( r->wp + 1 ) % r->options->buflen; + int32_t nwp = ( r->wp + 1 ) % r->options->buflen; - if ( nwp == r->rp ) - { - if ( r->singleShot ) - { + if ( nwp == r->rp ) { + if ( r->singleShot ) { r->held = true; return; - } - else - { + } else { r->rp = ( r->rp + 1 ) % r->options->buflen; } } @@ -521,10 +479,8 @@ static void _flushBuffer( struct RunTime *r ) SIOsetOutputBuffer( r->sio, 0, 0, NULL, false ); /* Remove all of the recorded lines */ - while ( r->numLines-- ) - { - if ( !r->opText[r->numLines].isRef ) - { + while ( r->numLines-- ) { + if ( !r->opText[r->numLines].isRef ) { free( r->opText[r->numLines].buffer ); } } @@ -598,8 +554,7 @@ static void _traceReport( enum verbLevel l, const char *fmt, ... ) /* Debug reporting stream */ { - if ( _r.options->withDebugText ) - { + if ( _r.options->withDebugText ) { static char op[SCRATCH_STRING_LEN]; va_list va; @@ -613,8 +568,7 @@ static void _traceReport( enum verbLevel l, const char *fmt, ... ) static void _addRetToStack( struct RunTime *r, symbolMemaddr p ) { - if ( r->stackDepth == MAX_CALL_STACK - 1 ) - { + if ( r->stackDepth == MAX_CALL_STACK - 1 ) { /* Stack is full, so make room for a new entry */ memmove( &r->callStack[0], &r->callStack[1], sizeof( symbolMemaddr ) * ( MAX_CALL_STACK - 1 ) ); } @@ -622,8 +576,7 @@ static void _addRetToStack( struct RunTime *r, symbolMemaddr p ) r->callStack[r->stackDepth] = p; _traceReport( V_DEBUG, "Pushed %08x to return stack", r->callStack[r->stackDepth] ); - if ( r->stackDepth < MAX_CALL_STACK - 1 ) - { + if ( r->stackDepth < MAX_CALL_STACK - 1 ) { /* We aren't at max depth, so go ahead and remove this entry */ r->stackDepth++; } @@ -634,96 +587,75 @@ static void _reportNonflowEvents( struct RunTime *r ) { struct TRACECPUState *cpu = TRACECPUState( &r->i ); - if ( TRACEStateChanged( &r->i, EV_CH_TRACESTART ) ) - { - if ( !r->traceRunning ) - { + if ( TRACEStateChanged( &r->i, EV_CH_TRACESTART ) ) { + if ( !r->traceRunning ) { _appendRefToOPBuffer( r, NULL, r->op.currentLine, LT_EVENT, "========== TRACE START EVENT ==========" ); r->traceRunning = true; } } - if ( TRACEStateChanged( &r->i, EV_CH_VMID ) ) - { + if ( TRACEStateChanged( &r->i, EV_CH_VMID ) ) { _appendToOPBuffer( r, NULL, r->op.currentLine, LT_EVENT, "*** VMID Set to %d", cpu->vmid ); } - if ( TRACEStateChanged( &r->i, EV_CH_EX_EXIT ) ) - { + if ( TRACEStateChanged( &r->i, EV_CH_EX_EXIT ) ) { _appendRefToOPBuffer( r, NULL, r->op.currentLine, LT_EVENT, "========== Exception Exit ==========" ); } - if ( TRACEStateChanged( &r->i, EV_CH_TSTAMP ) ) - { - if ( cpu->ts ) - { - if ( cpu->ts != COUNT_UNKNOWN ) - { + if ( TRACEStateChanged( &r->i, EV_CH_TSTAMP ) ) { + if ( cpu->ts ) { + if ( cpu->ts != COUNT_UNKNOWN ) { _appendToOPBuffer( r, NULL, r->op.currentLine, LT_EVENT, "*** Timestamp %ld", cpu->ts ); - } - else - { + } else { _appendToOPBuffer( r, NULL, r->op.currentLine, LT_EVENT, "*** Timestamp unknown" ); } } } - if ( TRACEStateChanged( &r->i, EV_CH_TRIGGER ) ) - { + if ( TRACEStateChanged( &r->i, EV_CH_TRIGGER ) ) { _appendRefToOPBuffer( r, NULL, r->op.currentLine, LT_EVENT, "*** Trigger" ); } - if ( TRACEStateChanged( &r->i, EV_CH_CLOCKSPEED ) ) - { + if ( TRACEStateChanged( &r->i, EV_CH_CLOCKSPEED ) ) { _appendRefToOPBuffer( r, NULL, r->op.currentLine, LT_EVENT, "*** Change Clockspeed" ); } - if ( TRACEStateChanged( &r->i, EV_CH_ISLSIP ) ) - { + if ( TRACEStateChanged( &r->i, EV_CH_ISLSIP ) ) { _appendRefToOPBuffer( r, NULL, r->op.currentLine, LT_EVENT, "*** ISLSIP Triggered" ); } - if ( TRACEStateChanged( &r->i, EV_CH_CYCLECOUNT ) ) - { + if ( TRACEStateChanged( &r->i, EV_CH_CYCLECOUNT ) ) { _appendToOPBuffer( r, NULL, r->op.currentLine, LT_EVENT, "(Cycle Count %d)", cpu->cycleCount ); } - if ( TRACEStateChanged( &r->i, EV_CH_VMID ) ) - { + if ( TRACEStateChanged( &r->i, EV_CH_VMID ) ) { _appendToOPBuffer( r, NULL, r->op.currentLine, LT_EVENT, "(VMID is now %d)", cpu->vmid ); } - if ( TRACEStateChanged( &r->i, EV_CH_CONTEXTID ) ) - { - if ( r->context != cpu->contextID ) - { + if ( TRACEStateChanged( &r->i, EV_CH_CONTEXTID ) ) { + if ( r->context != cpu->contextID ) { _appendToOPBuffer( r, NULL, r->op.currentLine, LT_EVENT, "(Context ID is now %d)", cpu->contextID ); r->context = cpu->contextID; } } - if ( TRACEStateChanged( &r->i, EV_CH_SECURE ) ) - { + if ( TRACEStateChanged( &r->i, EV_CH_SECURE ) ) { _appendToOPBuffer( r, NULL, r->op.currentLine, LT_EVENT, "(Non-Secure State is now %s)", cpu->nonSecure ? "True" : "False" ); } - if ( TRACEStateChanged( &r->i, EV_CH_ALTISA ) ) - { + if ( TRACEStateChanged( &r->i, EV_CH_ALTISA ) ) { _appendToOPBuffer( r, NULL, r->op.currentLine, LT_EVENT, "(Using AltISA is now %s)", cpu->altISA ? "True" : "False" ); } - if ( TRACEStateChanged( &r->i, EV_CH_HYP ) ) - { + if ( TRACEStateChanged( &r->i, EV_CH_HYP ) ) { _appendToOPBuffer( r, NULL, r->op.currentLine, LT_EVENT, "(Using Hypervisor is now %s)", cpu->hyp ? "True" : "False" ); } - if ( TRACEStateChanged( &r->i, EV_CH_JAZELLE ) ) - { + if ( TRACEStateChanged( &r->i, EV_CH_JAZELLE ) ) { _appendToOPBuffer( r, NULL, r->op.currentLine, LT_EVENT, "(Using Jazelle is now %s)", cpu->jazelle ? "True" : "False" ); } - if ( TRACEStateChanged( &r->i, EV_CH_THUMB ) ) - { + if ( TRACEStateChanged( &r->i, EV_CH_THUMB ) ) { _appendToOPBuffer( r, NULL, r->op.currentLine, LT_EVENT, "(Using Thumb is now %s)", cpu->thumb ? "True" : "False" ); } } @@ -740,7 +672,7 @@ static void _traceCB( void *d ) uint32_t disposition; uint32_t targetAddr = 0; /* Just to avoid unitialised variable warning */ bool linearRun = false; - enum instructionClass ic; + int ic; symbolMemaddr newaddr; /* 1: Report anything that doesn't affect the flow */ @@ -749,10 +681,8 @@ static void _traceCB( void *d ) /* 2: Deal with exception entry */ /* ============================ */ - if ( TRACEStateChanged( &r->i, EV_CH_EX_ENTRY ) ) - { - switch ( r->options->protocol ) - { + if ( TRACEStateChanged( &r->i, EV_CH_EX_ENTRY ) ) { + switch ( r->options->protocol ) { case TRACE_PROT_ETM35: _appendToOPBuffer( r, NULL, r->op.currentLine, LT_EVENT, "========== Exception Entry%s (%d (%s) at 0x%08x) ==========", TRACEStateChanged( &r->i, EV_CH_CANCELLED ) ? ", Last Instruction Cancelled" : "", cpu->exception, TRACEExceptionName( cpu->exception ), cpu->addr ); @@ -768,12 +698,9 @@ static void _traceCB( void *d ) /* For the ETM4 case we get a new address with the exception indication. This address is the preferred _return_ address, */ /* there will be a further address packet, which is the jump destination, along shortly. Note that _this_ address */ /* change indication will be consumed here, and won't hit the test below (which is correct behaviour. */ - if ( !TRACEStateChanged( &r->i, EV_CH_ADDRESS ) ) - { + if ( !TRACEStateChanged( &r->i, EV_CH_ADDRESS ) ) { _traceReport( V_DEBUG, "Exception occured without return address specification" ); - } - else - { + } else { _appendToOPBuffer( r, NULL, r->op.currentLine, LT_EVENT, "========== Exception Entry (%d (%s) at 0x%08x return to %08x ) ==========", cpu->exception, TRACEExceptionName( cpu->exception ), r->op.workingAddr, cpu->addr ); _addRetToStack( r, cpu->addr ); @@ -790,33 +717,27 @@ static void _traceCB( void *d ) /* 3: Collect flow affecting changes introduced by this event */ /* ========================================================== */ - if ( TRACEStateChanged( &r->i, EV_CH_ADDRESS ) ) - { + if ( TRACEStateChanged( &r->i, EV_CH_ADDRESS ) ) { /* Make debug report if calculated and reported addresses differ. This is most useful for testing when exhaustive */ /* address reporting is switched on. It will give 'false positives' for uncalculable instructions (e.g. bx lr) but */ /* it's a decent safety net to be sure the jump decoder is working correctly. */ - if ( r->options->protocol != TRACE_PROT_MTB ) - { + if ( r->options->protocol != TRACE_PROT_MTB ) { _traceReport( V_DEBUG, "%sCommanded CPU Address change (Was:0x%08x Commanded:0x%08x)" EOL, ( r->op.workingAddr == cpu->addr ) ? "" : "***INCONSISTENT*** ", r->op.workingAddr, cpu->addr ); } /* Return Stack: If we had a stack deletion pending because of a candidate match, it wasn't, so abort */ - if ( r->stackDelPending ) - { + if ( r->stackDelPending ) { _traceReport( V_DEBUG, "Stack delete aborted" ); } r->stackDelPending = false; /* Whatever the state was, this is an explicit setting of an address, so we need to respect it */ r->op.workingAddr = cpu->addr; - } - else - { + } else { /* Return Stack: If we had a stack deletion pending because of a candidate match, the match was good, so commit */ - if ( ( r->stackDelPending == true ) && ( r->stackDepth ) ) - { + if ( ( r->stackDelPending == true ) && ( r->stackDepth ) ) { r->stackDepth--; _traceReport( V_DEBUG, "Stack delete comitted" ); } @@ -824,8 +745,7 @@ static void _traceCB( void *d ) r->stackDelPending = false; } - if ( TRACEStateChanged( &r->i, EV_CH_LINEAR ) ) - { + if ( TRACEStateChanged( &r->i, EV_CH_LINEAR ) ) { /* MTB-Specific mechanism: Execute instructions from the marked starting location to the indicated finishing one */ /* Disposition is all 1's because every instruction is executed. */ r->op.workingAddr = cpu->addr; @@ -835,8 +755,7 @@ static void _traceCB( void *d ) _traceReport( V_DEBUG, "Linear run 0x%08x to 0x%08x" EOL, cpu->addr, cpu->toAddr ); } - if ( TRACEStateChanged( &r->i, EV_CH_ENATOMS ) ) - { + if ( TRACEStateChanged( &r->i, EV_CH_ENATOMS ) ) { /* Atoms represent instruction steps...some of which will have been executed, some stepped over. The number of steps is the */ /* total of the eatoms (executed) and natoms (not executed) and the disposition bitfield shows if each individual instruction */ /* was executed or not. For ETM3 each 'run' of instructions is a single instruction with the disposition bit telling you if */ @@ -848,30 +767,23 @@ static void _traceCB( void *d ) /* 4: Execute the flow instructions */ /* ================================ */ - while ( ( incAddr && !linearRun ) || ( ( r->op.workingAddr <= targetAddr ) && linearRun ) ) - { + while ( ( incAddr && !linearRun ) || ( ( r->op.workingAddr <= targetAddr ) && linearRun ) ) { /* Firstly, lets get the source code line...*/ struct symbolLineStore *l = symbolLineAt( r->s, r->op.workingAddr ); - if ( l ) - { + if ( l ) { /* If we have changed file or function put a header line in */ - if ( l->function ) - { + if ( l->function ) { /* There is a valid function tag recognised here. If it's a change highlight it in the output. */ - if ( ( l->function->filename != r->op.currentFileindex ) || ( l->function != r->op.currentFunctionptr ) ) - { + if ( ( l->function->filename != r->op.currentFileindex ) || ( l->function != r->op.currentFunctionptr ) ) { _appendToOPBuffer( r, l, r->op.currentLine, LT_FILE, "%s::%s", symbolGetFilename( r->s, l->function->filename ), l->function->funcname ); r->op.currentFileindex = l->function->filename; r->op.currentFunctionptr = l->function; r->op.currentLine = NO_LINE; } - } - else - { + } else { /* We didn't find a valid function, but we might have some information to work with.... */ - if ( ( NO_FILE != r->op.currentFileindex ) || ( NULL != r->op.currentFunctionptr ) ) - { + if ( ( NO_FILE != r->op.currentFileindex ) || ( NULL != r->op.currentFunctionptr ) ) { _appendToOPBuffer( r, l, r->op.currentLine, LT_FILE, "Unknown function" ); r->op.currentFileindex = NO_FILE; r->op.currentFunctionptr = NULL; @@ -881,8 +793,7 @@ static void _traceCB( void *d ) } /* If we have changed line then output the new one */ - if ( l && ( ( l->startline != r->op.currentLine ) ) ) - { + if ( l && ( ( l->startline != r->op.currentLine ) ) ) { const char *v = symbolSource( r->s, l->filename, l->startline - 1 ); r->op.currentLine = l->startline; _appendRefToOPBuffer( r, l, r->op.currentLine, LT_SOURCE, v ); @@ -891,8 +802,7 @@ static void _traceCB( void *d ) /* Now output the matching assembly, and location updates */ char *a = symbolDisassembleLine( r->s, &ic, r->op.workingAddr, &newaddr ); - if ( a ) - { + if ( a ) { /* Calculate if this instruction was executed. This is slightly hairy depending on which protocol we're using; */ /* * ETM3.5: Instructions are executed based on disposition bit (LSB in disposition word) */ /* * ETM4 : ETM4 everything up to a branch is executed...decision about that branch is based on disposition bit */ @@ -913,10 +823,8 @@ static void _traceCB( void *d ) /* Move addressing along */ - if ( ( r->i.protocol != TRACE_PROT_ETM4 ) || ( ic & LE_IC_JUMP ) ) - { - if ( r->i.protocol == TRACE_PROT_ETM4 ) - { + if ( ( r->i.protocol != TRACE_PROT_ETM4 ) || ( ic & LE_IC_JUMP ) ) { + if ( r->i.protocol == TRACE_PROT_ETM4 ) { _traceReport( V_DEBUG, "Consumed, %sexecuted (%d left)", insExecuted ? "" : "not ", incAddr - 1 ); } @@ -924,60 +832,43 @@ static void _traceCB( void *d ) incAddr--; } - if ( ic & LE_IC_CALL ) - { - if ( insExecuted ) - { + if ( ic & LE_IC_CALL ) { + if ( insExecuted ) { /* Push the instruction after this if it's a subroutine or ISR */ _traceReport( V_DEBUG, "Call to %08x", newaddr ); _addRetToStack( r, r->op.workingAddr + ( ( ic & LE_IC_4BYTE ) ? 4 : 2 ) ); } r->op.workingAddr = insExecuted ? newaddr : r->op.workingAddr + ( ( ic & LE_IC_4BYTE ) ? 4 : 2 ); - } - else if ( ic & LE_IC_JUMP ) - { + } else if ( ic & LE_IC_JUMP ) { _traceReport( V_DEBUG, "%sTAKEN JUMP", insExecuted ? "" : "NOT " ); - if ( insExecuted ) - { + if ( insExecuted ) { /* Update working address according to if jump was taken */ - if ( ic & LE_IC_IMMEDIATE ) - { + if ( ic & LE_IC_IMMEDIATE ) { /* We have a good address, so update with it */ r->op.workingAddr = newaddr; - } - else - { + } else { /* We didn't get the address, so need to park the call stack address if we've got one. Either we won't */ /* get an address (in which case this one was correct), or we wont (in which case, don't unstack this one). */ - if ( r->stackDepth ) - { + if ( r->stackDepth ) { r->op.workingAddr = r->callStack[r->stackDepth - 1]; _traceReport( V_DEBUG, "Return with stacked candidate to %08x", r->op.workingAddr ); - } - else - { + } else { _traceReport( V_DEBUG, "Return with no stacked candidate" ); } r->stackDelPending = true; } - } - else - { + } else { /* The branch wasn't taken, so just move along */ r->op.workingAddr += ( ic & LE_IC_4BYTE ) ? 4 : 2; } - } - else - { + } else { /* Just a regular instruction, so just move along */ r->op.workingAddr += ( ic & LE_IC_4BYTE ) ? 4 : 2; } - } - else - { + } else { _appendRefToOPBuffer( r, l, r->op.currentLine, LT_ASSEMBLY, "\t\tASSEMBLY NOT FOUND" EOL ); r->op.workingAddr += 2; disposition >>= 1; @@ -994,12 +885,10 @@ static bool _dumpBuffer( struct RunTime *r ) { _flushBuffer( r ); - if ( !symbolSetValid( r->s ) ) - { + if ( !symbolSetValid( r->s ) ) { symbolDelete( r->s ); - if ( !( r->s = symbolAquire( r->options->elffile, true, true, true ) ) ) - { + if ( !( r->s = symbolAquire( r->options->elffile, true, true, true ) ) ) { genericsReport( V_ERROR, "Elf file or symbols in it not found" EOL ); return false; } @@ -1011,8 +900,7 @@ static bool _dumpBuffer( struct RunTime *r ) int bytesAvailable = ( ( r->wp + r->options->buflen ) - r->rp ) % r->options->buflen; /* If we started wrapping (i.e. the rx ring buffer got full) then any guesses about sync status are invalid */ - if ( ( bytesAvailable == r->options->buflen - 1 ) && ( !r->singleShot ) ) - { + if ( ( bytesAvailable == r->options->buflen - 1 ) && ( !r->singleShot ) ) { TRACEDecoderForceSync( &r->i, false ); } @@ -1028,25 +916,22 @@ static bool _dumpBuffer( struct RunTime *r ) return true; } // ==================================================================================================== -static struct symbolLineStore *_fileAndLine( struct RunTime *r, uint32_t i ) +static struct symbolLineStore *_fileAndLine( struct RunTime *r, int32_t i ) { /* Search backwards from current position in buffer until we find a line a line record attached */ /* (b) a filename which contains this line. */ while ( ( i ) && - ( ( ( ( r->opText[i].lt != LT_SOURCE ) && ( r->opText[i].lt != LT_ASSEMBLY ) ) || r->opText[i].dat == NULL ) ) ) - { + ( ( ( ( r->opText[i].lt != LT_SOURCE ) && ( r->opText[i].lt != LT_ASSEMBLY ) ) || r->opText[i].dat == NULL ) ) ) { i--; } - if ( !i || !r->opText[i].dat ) - { + if ( !i || !r->opText[i].dat ) { i = SIOgetCurrentLineno( r->sio ); while ( ( i ) && - ( ( ( ( r->opText[i].lt != LT_SOURCE ) && ( r->opText[i].lt != LT_ASSEMBLY ) ) || r->opText[i].dat == NULL ) ) ) - { + ( ( ( ( r->opText[i].lt != LT_SOURCE ) && ( r->opText[i].lt != LT_ASSEMBLY ) ) || r->opText[i].dat == NULL ) ) ) { i++; } } @@ -1067,8 +952,7 @@ static void _mapFileBuffer( struct RunTime *r, int lineno, int filenameIndex ) r->filenumLines = 0; - while ( ( c = symbolSource( r->s, filenameIndex, index++ ) ) ) - { + while ( ( c = symbolSource( r->s, filenameIndex, index++ ) ) ) { r->fileopText = ( struct sioline * )realloc( r->fileopText, ( sizeof( struct sioline ) ) * ( r->filenumLines + 1 ) ); /* This line removes the 'const', but we know to not mess with this line */ @@ -1091,8 +975,7 @@ static void _doFileDive( struct RunTime *r ) { static struct symbolLineStore *l; - if ( ( r->diving ) || ( !r->numLines ) || ( !r->held ) ) - { + if ( ( r->diving ) || ( !r->numLines ) || ( !r->held ) ) { return; } @@ -1100,8 +983,7 @@ static void _doFileDive( struct RunTime *r ) assert( !r->fileopText ); assert( !r->filenumLines ); - if ( !( l = _fileAndLine( r, SIOgetCurrentLineno( r->sio ) ) ) ) - { + if ( !( l = _fileAndLine( r, SIOgetCurrentLineno( r->sio ) ) ) ) { SIOalert( r->sio, "Couldn't get filename/line" ); return; } @@ -1117,8 +999,7 @@ static void _doFilesurface( struct RunTime *r ) /* Come back out of a file we're diving into */ { - if ( !r->diving ) - { + if ( !r->diving ) { return; } @@ -1139,22 +1020,20 @@ static void _doSave( struct RunTime *r, bool includeDebug ) { FILE *f; char fn[SCRATCH_STRING_LEN]; - uint32_t w; + int32_t w; char *p; snprintf( fn, SCRATCH_STRING_LEN, "%s.trace", SIOgetSaveFilename( r->sio ) ); f = fopen( fn, "wb" ); - if ( !f ) - { + if ( !f ) { SIOalert( r->sio, "Save Trace Failed" ); return; } w = r->rp; - while ( w != r->wp ) - { + while ( w != r->wp ) { fwrite( &r->pmBuffer[w], 1, 1, f ); w = ( w + 1 ) % r->options->buflen; } @@ -1164,46 +1043,39 @@ static void _doSave( struct RunTime *r, bool includeDebug ) snprintf( fn, SCRATCH_STRING_LEN, "%s.report", SIOgetSaveFilename( r->sio ) ); f = fopen( fn, "wb" ); - if ( !f ) - { + if ( !f ) { SIOalert( r->sio, "Save Report Failed" ); return; } w = 0; - while ( w != r->numLines ) - { + while ( w != r->numLines ) { p = r->opText[w].buffer; /* Skip debug lines unless specifically told to include them */ - if ( ( r->opText[w].lt == LT_DEBUG ) && ( !includeDebug ) ) - { + if ( ( r->opText[w].lt == LT_DEBUG ) && ( !includeDebug ) ) { continue; } - if ( ( r->opText[w].lt == LT_SOURCE ) || ( r->opText[w].lt == LT_MU_SOURCE ) ) - { + if ( ( r->opText[w].lt == LT_SOURCE ) || ( r->opText[w].lt == LT_MU_SOURCE ) ) { /* Need a line number on this */ fwrite( fn, sprintf( fn, "%5d ", r->opText[w].line ), 1, f ); } - if ( r->opText[w].lt == LT_NASSEMBLY ) - { + if ( r->opText[w].lt == LT_NASSEMBLY ) { /* This is an _unexecuted_ assembly line, need to mark it */ fwrite( "(**", 3, 1, f ); } /* Search forward for a NL or 0, both are EOL for this purpose */ - while ( ( *p ) && ( *p != '\n' ) && ( *p != '\r' ) ) - { + while ( ( *p ) && ( *p != '\n' ) && ( *p != '\r' ) ) { p++; } fwrite( r->opText[w].buffer, p - r->opText[w].buffer, 1, f ); - if ( r->opText[w].lt == LT_NASSEMBLY ) - { + if ( r->opText[w].lt == LT_NASSEMBLY ) { /* This is an _unexecuted_ assembly line, need to mark it */ fwrite( " **)", 4, 1, f ); } @@ -1249,8 +1121,7 @@ int main( int argc, char *argv[] ) /* This is set here to avoid huge .data section in startup image */ _r.options = &_options; - if ( !_processOptions( argc, argv, &_r ) ) - { + if ( !_processOptions( argc, argv, &_r ) ) { /* processOptions generates its own error messages */ genericsExit( -1, "" EOL ); } @@ -1260,10 +1131,8 @@ int main( int argc, char *argv[] ) /* Make sure the fifos get removed at the end */ atexit( _doExit ); - if ( _r.options->file != NULL ) - { - if ( NULL == ( stream = streamCreateFile( _r.options->file ) ) ) - { + if ( _r.options->file != NULL ) { + if ( NULL == ( stream = streamCreateFile( _r.options->file ) ) ) { genericsExit( V_ERROR, "File not found" EOL ); _r.ending = true; } @@ -1272,8 +1141,7 @@ int main( int argc, char *argv[] ) /* Check we've got _some_ symbols to start from */ _r.s = symbolAquire( _r.options->elffile, true, true, true ); - if ( !_r.s ) - { + if ( !_r.s ) { genericsReport( V_ERROR, "Elf file or symbols in it not found" EOL ); return -1; } @@ -1281,8 +1149,7 @@ int main( int argc, char *argv[] ) genericsReport( V_DEBUG, "Loaded %s" EOL, _r.options->elffile ); /* This ensures the atexit gets called */ - if ( SIG_ERR == signal( SIGINT, _intHandler ) ) - { + if ( SIG_ERR == signal( SIGINT, _intHandler ) ) { genericsExit( -1, "Failed to establish Int handler" EOL ); } @@ -1293,8 +1160,7 @@ int main( int argc, char *argv[] ) #if !defined( WIN32 ) /* Don't kill a sub-process when any reader or writer evaporates */ - if ( SIG_ERR == signal( SIGPIPE, SIG_IGN ) ) - { + if ( SIG_ERR == signal( SIGPIPE, SIG_IGN ) ) { genericsExit( -1, "Failed to ignore SIGPIPEs" EOL ); } @@ -1305,8 +1171,7 @@ int main( int argc, char *argv[] ) TRACEDecoderInit( &_r.i, _r.options->protocol, !( _r.options->noAltAddr ), _traceReport ); - if ( _r.options->useTPIU ) - { + if ( _r.options->useTPIU ) { TPIUDecoderInit( &_r.t ); } @@ -1316,25 +1181,20 @@ int main( int argc, char *argv[] ) /* Put a record of the protocol in use on screen */ SIOtagText( _r.sio, TRACEDecodeGetProtocolName( _r.options->protocol ) ); - while ( !_r.ending ) - { - if ( NULL == _r.options->file ) - { + while ( !_r.ending ) { + if ( NULL == _r.options->file ) { /* Keep trying to open a network connection at half second intervals */ - while ( 1 ) - { + while ( 1 ) { stream = streamCreateSocket( _r.options->server, _r.options->port + ( _r.options->useTPIU ? 0 : 1 ) ); - if ( stream ) - { + if ( stream ) { break; } /* This can happen when the feeder has gone missing... */ SIOalert( _r.sio, "No connection" ); - if ( SIOHandler( _r.sio, true, 0, _r.options->withDebugText ) == SIO_EV_QUIT ) - { + if ( SIOHandler( _r.sio, true, 0, _r.options->withDebugText ) == SIO_EV_QUIT ) { _r.ending = true; break; } @@ -1346,58 +1206,47 @@ int main( int argc, char *argv[] ) /* ----------------------------------------------------------------------------- */ /* This is the main active loop...only break out of this when ending or on error */ /* ----------------------------------------------------------------------------- */ - while ( !_r.ending ) - { + while ( !_r.ending ) { tv.tv_sec = 0; tv.tv_usec = 10000; - if ( stream ) - { + if ( stream ) { /* We always read the data, even if we're held, to keep the socket alive */ enum ReceiveResult result = stream->receive( stream, _r.rawBlock.buffer, TRANSFER_SIZE, &tv, ( size_t * )&_r.rawBlock.fillLevel ); /* Try to re-establish socket if there was an error */ - if ( result == RECEIVE_RESULT_ERROR ) - { + if ( result == RECEIVE_RESULT_ERROR ) { break; } - if ( ( ( result == RECEIVE_RESULT_EOF ) || ( _r.rawBlock.fillLevel <= 0 ) ) && _r.options->file ) - { + if ( ( ( result == RECEIVE_RESULT_EOF ) || ( _r.rawBlock.fillLevel <= 0 ) ) && _r.options->file ) { /* Read from file is complete, remove it */ stream->close( stream ); free( stream ); stream = NULL; } - } - else - { + } else { /* No point in checking for keypresses _too_ often! */ usleep( TICK_TIME_MS * 100 ); } - if ( !_r.held ) - { + if ( !_r.held ) { /* Pump all of the data through the protocol handler */ _processBlock( &_r ); } /* Update the outputs and deal with any keys that made it up this high */ /* =================================================================== */ - switch ( ( s = SIOHandler( _r.sio, ( genericsTimestampmS() - lastTTime ) > TICK_TIME_MS, _r.oldTotalIntervalBytes, _r.options->withDebugText ) ) ) - { + switch ( ( s = SIOHandler( _r.sio, ( genericsTimestampmS() - lastTTime ) > TICK_TIME_MS, _r.oldTotalIntervalBytes, _r.options->withDebugText ) ) ) { case SIO_EV_HOLD: // ----------------- Request for Hold Start/Stop ------------------------------------- - if ( !_r.options->file ) - { + if ( !_r.options->file ) { _r.held = !_r.held; - if ( !_r.held ) - { + if ( !_r.held ) { _r.wp = _r.rp = 0; - if ( _r.diving ) - { + if ( _r.diving ) { _doFilesurface( &_r ); } @@ -1412,70 +1261,52 @@ int main( int argc, char *argv[] ) case SIO_EV_PREV: case SIO_EV_NEXT: // ----------------- Request for next/prev execution line ----------------------------- - if ( !_r.diving ) - { + if ( !_r.diving ) { int32_t l = SIOgetCurrentLineno( _r.sio ); - if ( ( ( s == SIO_EV_PREV ) && ( !l ) ) || ( ( s == SIO_EV_NEXT ) && ( l >= _r.numLines - 1 ) ) ) - { + if ( ( ( s == SIO_EV_PREV ) && ( !l ) ) || ( ( s == SIO_EV_NEXT ) && ( l >= _r.numLines - 1 ) ) ) { break; } /* In a regular window, scroll back looking for an earlier assembly instruction */ - do - { + do { l += s == SIO_EV_PREV ? -1 : 1; - } - while ( l && ( l < _r.numLines - 1 ) && ( ( _r.opText[l].lt != LT_ASSEMBLY ) ) ); + } while ( l && ( l < _r.numLines - 1 ) && ( ( _r.opText[l].lt != LT_ASSEMBLY ) ) ); - if ( l ) - { + if ( l ) { SIOsetCurrentLineno( _r.sio, l ); SIOrequestRefresh( _r.sio ); - } - else - { + } else { SIObeep(); } - } - else - { + } else { /* In a diving window, situation is slightly more complicated */ int32_t l = _r.lineNum; struct symbolLineStore *oldLine = _fileAndLine( &_r, l ); - if ( ( ( s == SIO_EV_PREV ) && ( !l ) ) || ( ( s == SIO_EV_NEXT ) && ( l >= _r.numLines - 1 ) ) ) - { + if ( ( ( s == SIO_EV_PREV ) && ( !l ) ) || ( ( s == SIO_EV_NEXT ) && ( l >= _r.numLines - 1 ) ) ) { break; } /* Search for different _source_line_ to the one we started from */ - do - { + do { l += s == SIO_EV_PREV ? -1 : 1; - } - while ( l && ( l < _r.numLines - 1 ) && ( ( _r.opText[l].lt != LT_SOURCE ) ) ); + } while ( l && ( l < _r.numLines - 1 ) && ( ( _r.opText[l].lt != LT_SOURCE ) ) ); - if ( l ) - { - if ( oldLine->filename == _fileAndLine( &_r, l )->filename ) - { + if ( l ) { + if ( oldLine->filename == _fileAndLine( &_r, l )->filename ) { /* We are still in the same file, so only the line number to change */ _r.lineNum = l; SIOsetCurrentLineno( _r.sio, _fileAndLine( &_r, l )->startline - 1 ); SIOrequestRefresh( _r.sio ); - } - else - { + } else { /* We have changed diving file, surface and enter the new one */ _r.lineNum = l; _doFilesurface( &_r ); _doFileDive( &_r ); SIOrequestRefresh( _r.sio ); } - } - else - { + } else { SIObeep(); } @@ -1484,8 +1315,7 @@ int main( int argc, char *argv[] ) break; case SIO_EV_SAVE: // ------------------ Request for file save ------------------------------------------- - if ( _r.options->file ) - { + if ( _r.options->file ) { _doSave( &_r, false ); } @@ -1496,8 +1326,7 @@ int main( int argc, char *argv[] ) break; case SIO_EV_FOPEN: // ------------------- Request for file open ----------------------------------------- - if ( _r.options->openFileCL ) - { + if ( _r.options->openFileCL ) { // _doFileOpen( &_r, false ); } @@ -1517,40 +1346,33 @@ int main( int argc, char *argv[] ) /* Deal with possible timeout on sampling, or if this is a read-from-file that is finished */ if ( ( !_r.numLines ) && - ( - ( _r.options->file && !stream ) || - ( ( ( genericsTimestampmS() - lastHTime ) > HANG_TIME_MS ) && - ( _r.newTotalBytes - _r.oldTotalHangBytes == 0 ) && - ( _r.wp != _r.rp ) ) - ) - ) - { - if ( !_dumpBuffer( &_r ) ) - { + ( + ( _r.options->file && !stream ) || + ( ( ( genericsTimestampmS() - lastHTime ) > HANG_TIME_MS ) && + ( _r.newTotalBytes - _r.oldTotalHangBytes == 0 ) && + ( _r.wp != _r.rp ) ) + ) + ) { + if ( !_dumpBuffer( &_r ) ) { /* Dumping the buffer failed, so give up */ _r.ending = true; - } - else - { + } else { _r.held = true; SIOheld( _r.sio, _r.held ); } } /* Update the intervals */ - if ( ( genericsTimestampmS() - lastHTime ) > HANG_TIME_MS ) - { + if ( ( genericsTimestampmS() - lastHTime ) > HANG_TIME_MS ) { _r.oldTotalHangBytes = _r.newTotalBytes; lastHTime = genericsTimestampmS(); } - if ( ( genericsTimestampmS() - lastTTime ) > TICK_TIME_MS ) - { + if ( ( genericsTimestampmS() - lastTTime ) > TICK_TIME_MS ) { lastTTime = genericsTimestampmS(); } - if ( ( genericsTimestampmS() - lastTSTime ) > INTERVAL_TIME_MS ) - { + if ( ( genericsTimestampmS() - lastTSTime ) > INTERVAL_TIME_MS ) { _r.oldTotalIntervalBytes = _r.newTotalBytes - _r.oldTotalBytes; _r.oldTotalBytes = _r.newTotalBytes; lastTSTime = genericsTimestampmS(); @@ -1561,22 +1383,19 @@ int main( int argc, char *argv[] ) /* End of main loop ... we get here because something forced us out */ /* ----------------------------------------------------------------------------- */ - if ( stream ) - { + if ( stream ) { stream->close( stream ); free( stream ); stream = NULL; } - if ( _r.options->file ) - { + if ( _r.options->file ) { /* Don't keep re-reading the file if it is a file! */ _r.held = true; } - if ( _r.options->fileTerminate ) - { + if ( _r.options->fileTerminate ) { _r.ending = true; } } diff --git a/Src/orbprofile.c b/Src/orbprofile.c index 7e66f5db..66a8ee36 100644 --- a/Src/orbprofile.c +++ b/Src/orbprofile.c @@ -37,16 +37,14 @@ #define DBG_OUT(...) fprintf(stderr,__VA_ARGS__) //#define DBG_OUT(...) -struct _subcallAccount -{ +struct _subcallAccount { struct subcallSig sig; uint64_t inTicks; }; /* ---------- CONFIGURATION ----------------- */ -struct Options /* Record for options, either defaults or from command line */ -{ +struct Options { /* Record for options, either defaults or from command line */ bool demangle; /* Demangle C++ names */ char *file; /* File host connection */ bool fileTerminate; /* Terminate when file read isn't successful */ @@ -59,7 +57,7 @@ struct Options /* Record for options, either defaults char *dotfile; /* File to output dot information */ char *profile; /* File to output profile information */ - int sampleDuration; /* How long we are going to sample for */ + unsigned int sampleDuration; /* How long we are going to sample for */ bool mono; /* Supress colour in output */ bool noaltAddr; /* Dont use alternate addressing */ bool useTPIU; /* Are we using TPIU, and stripping TPIU frames? */ @@ -69,18 +67,16 @@ struct Options /* Record for options, either defaults int port; /* Source information for where to connect to */ char *server; -} _options = -{ +} _options = { .demangle = true, .sampleDuration = DEFAULT_DURATION_MS, - .port = NWCLIENT_SERVER_PORT, .protocol = TRACE_PROT_ETM35, - .server = "localhost" + .port = NWCLIENT_SERVER_PORT, + .server = ( char * )"localhost" }; /* State of routine tracking, maintained across TRACE callbacks to reconstruct program flow */ -struct opConstruct -{ +struct opConstruct { struct execEntryHash *h; /* The exec entry we were in last (file, function, line, addr etc) */ struct execEntryHash *oldh; /* The exec entry we're currently in (file, function, line, addr etc) */ struct execEntryHash *inth; /* Fake exec entry for an interrupt source */ @@ -96,15 +92,13 @@ struct opConstruct }; /* A block of received data */ -struct dataBlock -{ +struct dataBlock { ssize_t fillLevel; uint8_t buffer[TRANSFER_SIZE]; }; /* ----------- LIVE STATE ----------------- */ -struct RunTime -{ +struct RunTime { /* Information about the program */ const char *progName; /* Name by which this program was called */ @@ -179,8 +173,7 @@ static void _callEvent( struct RunTime *r, uint32_t retAddr, uint32_t to ) /* Find a record for this source/dest pair */ HASH_FIND( hh, r->subhead, &r->substack[r->substacklen].sig, sizeof( struct subcallSig ), s ); - if ( !s ) - { + if ( !s ) { /* This call entry doesn't exist (i.e. it's the first time this from/to pair have been seen...let's create it */ s = ( struct subcall * )calloc( 1, sizeof( struct subcall ) ); MEMCHECK( s, ); @@ -190,8 +183,7 @@ static void _callEvent( struct RunTime *r, uint32_t retAddr, uint32_t to ) r->substacklen++; - for ( uint32_t g = 0; g < r->substacklen; g++ ) - { + for ( uint32_t g = 0; g < r->substacklen; g++ ) { putchar( ' ' ); } @@ -208,16 +200,13 @@ static void _returnEvent( struct RunTime *r, uint32_t to ) uint32_t orig = r->substacklen; /* Cover the startup case that we happen to hit a return before a call */ - if ( !r->substack ) - { + if ( !r->substack ) { return; } /* Check we've got a valid stack entry to match to */ - do - { - if ( !r->substacklen ) - { + do { + if ( !r->substacklen ) { DBG_OUT( "OUT OUT OF STACK ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" EOL ); break; } @@ -225,8 +214,7 @@ static void _returnEvent( struct RunTime *r, uint32_t to ) /* The -1th entry was the last written, so see if that is back far enough */ r->substacklen--; - for ( uint32_t g = 0; g < r->substacklen + 1; g++ ) - { + for ( uint32_t g = 0; g < r->substacklen + 1; g++ ) { putchar( ' ' ); } @@ -237,14 +225,11 @@ static void _returnEvent( struct RunTime *r, uint32_t to ) /* We don't bother deallocating memory here cos it'll be done the next time we make a call */ s->myCost += cpu->instCount - r->substack[r->substacklen].inTicks; s->count++; - } - while ( to != r->substack[r->substacklen].sig.src ); + } while ( to != r->substack[r->substacklen].sig.src ); /* Check function we popped back to matches where we think we should be */ - if ( to != r->substack[r->substacklen].sig.src ) - { - for ( uint32_t ty = 0; ty < orig; ty++ ) - { + if ( to != r->substack[r->substacklen].sig.src ) { + for ( uint32_t ty = 0; ty < orig; ty++ ) { DBG_OUT( "%d:%08X ", ty, r->substack[ty].sig.src ); } @@ -258,17 +243,14 @@ static void _hashFindOrCreate( struct RunTime *r, uint32_t addr, struct execEntr HASH_FIND_INT( r->insthead, &addr, *h ); - if ( !( *h ) ) - { + if ( !( *h ) ) { /* We don't have this address captured yet, do it now */ - if ( SymbolLookup( r->s, r->op.workingAddr, &n ) ) - { - if ( n.assyLine == ASSY_NOT_FOUND ) - { + if ( SymbolLookup( r->s, r->op.workingAddr, &n ) ) { + if ( n.assyLine == ASSY_NOT_FOUND ) { genericsExit( -1, "No assembly for function at address %08x, %s" EOL, r->op.workingAddr, SymbolFunction( r->s, n.functionindex ) ); } - *h = calloc( 1, sizeof( struct execEntryHash ) ); + *h = ( struct execEntryHash * )calloc( 1, sizeof( struct execEntryHash ) ); MEMCHECK( *h, ); ( *h )->addr = r->op.workingAddr; @@ -282,9 +264,7 @@ static void _hashFindOrCreate( struct RunTime *r, uint32_t addr, struct execEntr ( *h )->is4Byte = n.assy[n.assyLine].is4Byte; ( *h )->codes = n.assy[n.assyLine].codes; ( *h )->assyText = n.assy[n.assyLine].lineText; - } - else - { + } else { genericsExit( -1, "No symbol for address %08x" EOL, r->op.workingAddr ); } @@ -311,19 +291,15 @@ static void _handleInstruction( struct RunTime *r, bool actioned ) r->op.h->count++; /* If source postion changed then update source code line visitation counts too */ - if ( ( r->op.oldh ) && ( ( r->op.h->line != r->op.oldh->line ) || ( r->op.h->functionindex != r->op.oldh->functionindex ) ) ) - { + if ( ( r->op.oldh ) && ( ( r->op.h->line != r->op.oldh->line ) || ( r->op.h->functionindex != r->op.oldh->functionindex ) ) ) { r->op.h->scount++; } /* If this is a computable destination then action it */ - if ( ( actioned ) && ( ( r->op.h->isJump ) || ( r->op.h->isSubCall ) ) ) - { + if ( ( actioned ) && ( ( r->op.h->isJump ) || ( r->op.h->isSubCall ) ) ) { /* Take this call ... note that the jumpdest may not be known at this point */ r->op.workingAddr = r->op.h->jumpdest; - } - else - { + } else { /* If it wasn't a jump or subroutine then increment the address */ r->op.workingAddr += ( r->op.h->is4Byte ) ? 4 : 2; } @@ -333,16 +309,13 @@ static void _handleInstruction( struct RunTime *r, bool actioned ) static void _checkJumps( struct RunTime *r ) { - if ( r->op.h ) - { + if ( r->op.h ) { - if ( ( TRACEStateChanged( &r->i, EV_CH_EX_EXIT ) ) || ( r->op.h->isReturn ) ) - { + if ( ( TRACEStateChanged( &r->i, EV_CH_EX_EXIT ) ) || ( r->op.h->isReturn ) ) { _returnEvent( r, r->op.workingAddr ); } - if ( r->op.h->isSubCall ) - { + if ( r->op.h->isSubCall ) { _callEvent( r, r->op.h->addr + ( ( r->op.h->is4Byte ) ? 4 : 2 ), r->op.workingAddr ); } } @@ -358,32 +331,29 @@ static void _traceCB( void *d ) static uint32_t incAddr = 0; static uint32_t disposition = 0; - if ( TRACEStateChanged( &r->i, EV_CH_ADDRESS ) ) - { + if ( TRACEStateChanged( &r->i, EV_CH_ADDRESS ) ) { printf( EOL "Address 0x%08lx" EOL, r->i.cpu.addr ); } - TRACEStateChanged( &r->i, 0xffffffff ); + TRACEStateChanged( &r->i, ( enum TRACEchanges )0xffffffff ); return; /* This routine gets called when valid data are available */ /* if these are the first data, then reset counters etc. */ - if ( !r->sampling ) - { + if ( !r->sampling ) { r->op.firsttstamp = cpu->instCount; genericsReport( V_INFO, "Sampling" EOL ); /* Fill in a time to start from */ r->starttime = genericsTimestampmS(); - if ( TRACEStateChanged( &r->i, EV_CH_ADDRESS ) ) - { + if ( TRACEStateChanged( &r->i, EV_CH_ADDRESS ) ) { r->op.workingAddr = cpu->addr; DBG_OUT( "Got initial address %08x" EOL, r->op.workingAddr ); r->sampling = true; } /* Create false entry for an interrupt source */ - r->op.inth = calloc( 1, sizeof( struct execEntryHash ) ); + r->op.inth = ( struct execEntryHash * )calloc( 1, sizeof( struct execEntryHash ) ); MEMCHECK( r->op.inth, ); r->op.inth->addr = INTERRUPT; @@ -398,25 +368,18 @@ static void _traceCB( void *d ) /* Pull changes introduced by this event ============================== */ - if ( TRACEStateChanged( &r->i, EV_CH_ENATOMS ) ) - { + if ( TRACEStateChanged( &r->i, EV_CH_ENATOMS ) ) { /* We are going to execute some instructions. Check if the last of the old batch of */ /* instructions was cancelled and, if it wasn't and it's still outstanding, action it. */ - if ( TRACEStateChanged( &r->i, EV_CH_CANCELLED ) ) - { + if ( TRACEStateChanged( &r->i, EV_CH_CANCELLED ) ) { DBG_OUT( "CANCELLED" EOL ); - } - else - { - if ( incAddr ) - { + } else { + if ( incAddr ) { DBG_OUT( "***" EOL ); _handleInstruction( r, disposition & 1 ); - if ( ( r->op.h->isJump ) || ( r->op.h->isSubCall ) || ( r->op.h->isReturn ) ) - { - if ( TRACEStateChanged( &r->i, EV_CH_ADDRESS ) ) - { + if ( ( r->op.h->isJump ) || ( r->op.h->isSubCall ) || ( r->op.h->isReturn ) ) { + if ( TRACEStateChanged( &r->i, EV_CH_ADDRESS ) ) { DBG_OUT( "New addr %08lx" EOL, cpu->addr ); r->op.workingAddr = cpu->addr; } @@ -426,10 +389,8 @@ static void _traceCB( void *d ) } } - if ( TRACEStateChanged( &r->i, EV_CH_ADDRESS ) ) - { - if ( TRACEStateChanged( &r->i, EV_CH_EX_ENTRY ) ) - { + if ( TRACEStateChanged( &r->i, EV_CH_ADDRESS ) ) { + if ( TRACEStateChanged( &r->i, EV_CH_EX_ENTRY ) ) { DBG_OUT( "INTERRUPT!!" EOL ); _callEvent( r, r->op.workingAddr, cpu->addr ); } @@ -446,8 +407,7 @@ static void _traceCB( void *d ) DBG_OUT( "E:%d N:%d" EOL, cpu->eatoms, cpu->natoms ); /* Action those changes, except the last one */ - while ( incAddr > 1 ) - { + while ( incAddr > 1 ) { incAddr--; _handleInstruction( r, disposition & 1 ); _checkJumps( r ); @@ -473,9 +433,8 @@ static void _printHelp( const char *const progName ) genericsPrintf( " -O, --objdump-opts: Options to pass directly to objdump" EOL ); genericsPrintf( " -p, --trace-proto: { " ); - for ( int i = TRACE_PROT_LIST_START; i < TRACE_PROT_NUM; i++ ) - { - genericsPrintf( "%s ", TRACEDecodeGetProtocolName( i ) ); + for ( int i = TRACE_PROT_LIST_START; i < TRACE_PROT_NUM; i++ ) { + genericsPrintf( "%s ", TRACEDecodeGetProtocolName( ( enum TRACEprotocol )i ) ); } genericsPrintf( "} trace protocol to use, default is %s" EOL, TRACEDecodeGetProtocolName( TRACE_PROT_LIST_START ) ); @@ -495,8 +454,7 @@ void _printVersion( void ) genericsPrintf( "orbprofile version " GIT_DESCRIBE ); } // ==================================================================================================== -static struct option _longOptions[] = -{ +static struct option _longOptions[] = { {"alt-addr-enc", no_argument, NULL, 'A'}, {"no-demangle", required_argument, NULL, 'D'}, {"del-prefix", required_argument, NULL, 'd'}, @@ -523,11 +481,11 @@ static bool _processOptions( int argc, char *argv[], struct RunTime *r ) { int c, optionIndex = 0; + char *a; while ( ( c = getopt_long ( argc, argv, "ADd:e:Ef:hVI:MO:p:s:Tt:v:y:z:", _longOptions, &optionIndex ) ) != -1 ) - switch ( c ) - { + switch ( c ) { // ------------------------------------ case 'A': r->options->noaltAddr = true; @@ -590,11 +548,12 @@ static bool _processOptions( int argc, char *argv[], struct RunTime *r ) case 'p': /* Index through protocol strings looking for match or end of list */ - for ( r->options->protocol = TRACE_PROT_LIST_START; - ( ( r->options->protocol != TRACE_PROT_NUM ) && strcasecmp( optarg, TRACEDecodeGetProtocolName( r->options->protocol ) ) ); - r->options->protocol++ ) + for ( c = TRACE_PROT_LIST_START; + ( ( c != TRACE_PROT_NUM ) && strcasecmp( optarg, TRACEDecodeGetProtocolName( ( enum TRACEprotocol )c ) ) ); + c++ ) {} + r->options->protocol = ( enum TRACEprotocol )c; break; // ------------------------------------ @@ -602,21 +561,18 @@ static bool _processOptions( int argc, char *argv[], struct RunTime *r ) r->options->server = optarg; // See if we have an optional port number too - char *a = optarg; + a = optarg; - while ( ( *a ) && ( *a != ':' ) ) - { + while ( ( *a ) && ( *a != ':' ) ) { a++; } - if ( *a == ':' ) - { + if ( *a == ':' ) { *a = 0; r->options->port = atoi( ++a ); } - if ( !r->options->port ) - { + if ( !r->options->port ) { r->options->port = NWCLIENT_SERVER_PORT; } @@ -636,13 +592,12 @@ static bool _processOptions( int argc, char *argv[], struct RunTime *r ) // ------------------------------------ case 'v': - if ( !isdigit( *optarg ) ) - { + if ( !isdigit( *optarg ) ) { genericsReport( V_ERROR, "-v requires a numeric argument." EOL ); return false; } - genericsSetReportLevel( atoi( optarg ) ); + genericsSetReportLevel( ( enum verbLevel )atoi( optarg ) ); break; // ------------------------------------ @@ -657,12 +612,9 @@ static bool _processOptions( int argc, char *argv[], struct RunTime *r ) // ------------------------------------ case '?': - if ( optopt == 'b' ) - { + if ( optopt == 'b' ) { genericsReport( V_ERROR, "Option '%c' requires an argument." EOL, optopt ); - } - else if ( !isprint ( optopt ) ) - { + } else if ( !isprint ( optopt ) ) { genericsReport( V_ERROR, "Unknown option character `\\x%x'." EOL, optopt ); } @@ -675,18 +627,15 @@ static bool _processOptions( int argc, char *argv[], struct RunTime *r ) // ------------------------------------ } - if ( !r->options->elffile ) - { + if ( !r->options->elffile ) { genericsExit( -2, "Elf File not specified" EOL ); } - if ( !r->options->sampleDuration ) - { + if ( !r->options->sampleDuration ) { genericsExit( -2, "Illegal sample duration" EOL ); } - if ( r->options->protocol >= TRACE_PROT_NONE ) - { + if ( r->options->protocol >= TRACE_PROT_NONE ) { genericsExit( V_ERROR, "Unrecognised decode protocol" EOL ); } @@ -732,17 +681,14 @@ static void *_processBlocks( void *params ) { struct RunTime *r = ( struct RunTime * )params; - while ( true ) - { + while ( true ) { pthread_cond_wait( &r->dataForClients, &r->dataForClients_m ); - if ( r->rp != ( volatile int )r->wp ) - { + if ( r->rp != ( volatile int )r->wp ) { genericsReport( V_DEBUG, "RXED Packet of %d bytes" EOL, r->rawBlock[r->rp].fillLevel ); /* Check to see if we've finished (a zero length packet */ - if ( !r->rawBlock[r->rp].fillLevel ) - { + if ( !r->rawBlock[r->rp].fillLevel ) { break; } @@ -752,40 +698,30 @@ static void *_processBlocks( void *params ) DBG_OUT( EOL ); - while ( y-- ) - { + while ( y-- ) { DBG_OUT( "%02X ", *c++ ); - if ( !( y % 16 ) ) - { + if ( !( y % 16 ) ) { DBG_OUT( EOL ); } } #endif - if ( r->options->useTPIU ) - { + if ( r->options->useTPIU ) { struct TPIUPacket p; int j = 0; - for ( int i = 0; i < r->rawBlock[r->rp].fillLevel; i++ ) - { + for ( int i = 0; i < r->rawBlock[r->rp].fillLevel; i++ ) { /* Strip the TPIU formatting from the block. It can go back into the same block 'cos it will always take less room */ - if ( TPIU_EV_RXEDPACKET == TPIUPump( &r->t, r->rawBlock[r->rp].buffer[i] ) ) - { - if ( !TPIUGetPacket( &r->t, &p ) ) - { + if ( TPIU_EV_RXEDPACKET == TPIUPump( &r->t, r->rawBlock[r->rp].buffer[i] ) ) { + if ( !TPIUGetPacket( &r->t, &p ) ) { genericsReport( V_WARN, "TPIUGetPacket fell over" EOL ); - } - else - { + } else { /* Iterate through the packet, putting bytes for TRACE into the processing buffer */ - for ( uint32_t g = 0; g < p.len; g++ ) - { - if ( r->options->channel == p.packet[g].s ) - { + for ( uint32_t g = 0; g < p.len; g++ ) { + if ( r->options->channel == p.packet[g].s ) { r->rawBlock[r->rp].buffer[j++] = p.packet[g].d; } } @@ -793,13 +729,10 @@ static void *_processBlocks( void *params ) } } - if ( j > 0 ) - { + if ( j > 0 ) { TRACEDecoderPump( &r->i, r->rawBlock[r->rp].buffer, j, _traceCB, &_r ); } - } - else - { + } else { /* Pump all of the data through the protocol handler */ TRACEDecoderPump( &r->i, r->rawBlock[r->rp].buffer, r->rawBlock[r->rp].fillLevel, _traceCB, &_r ); @@ -825,18 +758,15 @@ int main( int argc, char *argv[] ) _r.progName = genericsBasename( argv[0] ); _r.options = &_options; - if ( pthread_mutex_init( &_r.dataForClients_m, NULL ) != 0 ) - { + if ( pthread_mutex_init( &_r.dataForClients_m, NULL ) != 0 ) { genericsExit( -1, "Failed to establish mutex for condition variablee" EOL ); } - if ( pthread_cond_init( &_r.dataForClients, NULL ) != 0 ) - { + if ( pthread_cond_init( &_r.dataForClients, NULL ) != 0 ) { genericsExit( -1, "Failed to establish condition variablee" EOL ); } - if ( !_processOptions( argc, argv, &_r ) ) - { + if ( !_processOptions( argc, argv, &_r ) ) { /* processOptions generates its own error messages */ genericsExit( -1, "" EOL ); } @@ -847,16 +777,14 @@ int main( int argc, char *argv[] ) atexit( _doExit ); /* This ensures the atexit gets called */ - if ( SIG_ERR == signal( SIGINT, _intHandler ) ) - { + if ( SIG_ERR == signal( SIGINT, _intHandler ) ) { genericsExit( -1, "Failed to establish Int handler" EOL ); } #if !defined(WIN32) /* Don't kill a sub-process when any reader or writer evaporates */ - if ( SIG_ERR == signal( SIGPIPE, SIG_IGN ) ) - { + if ( SIG_ERR == signal( SIGPIPE, SIG_IGN ) ) { genericsExit( -1, "Failed to ignore SIGPIPEs" EOL ); } @@ -864,25 +792,18 @@ int main( int argc, char *argv[] ) TRACEDecoderInit( &_r.i, _r.options->protocol, !_r.options->noaltAddr, genericsReport ); - if ( _r.options->useTPIU ) - { + if ( _r.options->useTPIU ) { TPIUDecoderInit( &_r.t ); } - while ( !_r.ending ) - { - if ( _r.options->file != NULL ) - { + while ( !_r.ending ) { + if ( _r.options->file != NULL ) { stream = streamCreateFile( _r.options->file ); - } - else - { - while ( 1 ) - { + } else { + while ( 1 ) { stream = streamCreateSocket( _r.options->server, _r.options->port ); - if ( !stream ) - { + if ( !stream ) { break; } @@ -893,12 +814,10 @@ int main( int argc, char *argv[] ) /* We need symbols constantly while running ... lets get them */ - if ( !SymbolSetValid( &_r.s, _r.options->elffile ) ) - { + if ( !SymbolSetValid( &_r.s, _r.options->elffile ) ) { r = SymbolSetCreate( &_r.s, _r.options->elffile, _r.options->deleteMaterial, _r.options->demangle, true, true, _r.options->odoptions ); - switch ( r ) - { + switch ( r ) { case SYMBOL_NOELF: genericsExit( -1, "Elf file or symbols in it not found" EOL ); break; @@ -927,8 +846,7 @@ int main( int argc, char *argv[] ) /* This is the main active loop...only break out of this when ending or on error */ /* ----------------------------------------------------------------------------- */ - while ( !_r.ending ) - { + while ( !_r.ending ) { /* Each time segment is restricted */ tv.tv_sec = 0; tv.tv_usec = TICK_TIME_MS * 1000; @@ -938,13 +856,11 @@ int main( int argc, char *argv[] ) enum ReceiveResult result = stream->receive( stream, rxBlock->buffer, TRANSFER_SIZE, &tv, ( size_t * )&rxBlock->fillLevel ); - if ( ( result == RECEIVE_RESULT_EOF ) || ( result == RECEIVE_RESULT_ERROR ) ) - { + if ( ( result == RECEIVE_RESULT_EOF ) || ( result == RECEIVE_RESULT_ERROR ) ) { break; } - if ( rxBlock->fillLevel <= 0 ) - { + if ( rxBlock->fillLevel <= 0 ) { /* We are at EOF (Probably the descriptor closed) */ break; } @@ -954,8 +870,7 @@ int main( int argc, char *argv[] ) int nwp = ( _r.wp + 1 ) % NUM_RAW_BLOCKS; - if ( nwp == ( volatile int )_r.rp ) - { + if ( nwp == ( volatile int )_r.rp ) { genericsExit( -1, "Overflow" EOL ); } @@ -963,15 +878,13 @@ int main( int argc, char *argv[] ) pthread_cond_signal( &_r.dataForClients ); /* Update the intervals */ - if ( ( ( volatile bool ) _r.sampling ) && ( ( genericsTimestampmS() - ( volatile uint32_t )_r.starttime ) > _r.options->sampleDuration ) ) - { + if ( ( ( volatile bool ) _r.sampling ) && ( ( genericsTimestampmS() - ( volatile uint32_t )_r.starttime ) > _r.options->sampleDuration ) ) { _r.ending = true; /* Post an empty data packet to flag to packet processor that it's done */ int nwp = ( _r.wp + 1 ) % NUM_RAW_BLOCKS; - if ( nwp == ( volatile int )_r.rp ) - { + if ( nwp == ( volatile int )_r.rp ) { genericsExit( -1, "Overflow" EOL ); } @@ -992,16 +905,11 @@ int main( int argc, char *argv[] ) genericsReport( V_INFO, "Received %d raw sample bytes, %ld function changes, %ld distinct addresses" EOL, _r.intervalBytes, HASH_COUNT( _r.subhead ), HASH_COUNT( _r.insthead ) ); - if ( HASH_COUNT( _r.subhead ) ) - { - if ( ext_ff_outputDot( _r.options->dotfile, _r.subhead, _r.s ) ) - { + if ( HASH_COUNT( _r.subhead ) ) { + if ( ext_ff_outputDot( _r.options->dotfile, _r.subhead, _r.s ) ) { genericsReport( V_INFO, "Output DOT" EOL ); - } - else - { - if ( _r.options->dotfile ) - { + } else { + if ( _r.options->dotfile ) { genericsExit( -1, "Failed to output DOT" EOL ); } } @@ -1012,14 +920,10 @@ int main( int argc, char *argv[] ) _r.op.lasttstamp - _r.op.firsttstamp, _r.insthead, _r.subhead, - _r.s ) ) - { + _r.s ) ) { genericsReport( V_INFO, "Output Profile" EOL ); - } - else - { - if ( _r.options->profile ) - { + } else { + if ( _r.options->profile ) { genericsExit( -1, "Failed to output profile" EOL ); } } diff --git a/Src/orbstat.c b/Src/orbstat.c index 7f2328d4..2d9209f9 100644 --- a/Src/orbstat.c +++ b/Src/orbstat.c @@ -41,8 +41,7 @@ enum CDState { CD_waitinout, CD_waitsrc, CD_waitdst }; /* ---------- CONFIGURATION ----------------- */ -struct Options /* Record for options, either defaults or from command line */ -{ +struct Options { /* Record for options, either defaults or from command line */ bool demangle; /* Demangle C++ names */ char *file; /* File host connection */ bool fileTerminate; /* Terminate when file read isn't successful */ @@ -63,32 +62,29 @@ struct Options /* Record for options, either defaults bool mono; /* Supress colour in output */ bool useTPIU; /* Are we using TPIU, and stripping TPIU frames? */ - uint32_t tpiuITMChannel; /* Which TPIU channel to use for ITM */ + int8_t tpiuITMChannel; /* Which TPIU channel to use for ITM */ int port; /* Source information for where to connect to */ char *server; -} _options = -{ +} _options = { .demangle = true, - .sampleDuration = DEFAULT_DURATION_MS, - .port = NWCLIENT_SERVER_PORT, .traceChannel = DEFAULT_TRACE_CHANNEL, .fileChannel = DEFAULT_FILE_CHANNEL, + .sampleDuration = DEFAULT_DURATION_MS, .forceITMSync = true, - .server = "localhost" + .port = NWCLIENT_SERVER_PORT, + .server = ( char * )"localhost" }; /* A block of received data */ -struct dataBlock -{ +struct dataBlock { ssize_t fillLevel; uint8_t buffer[TRANSFER_SIZE]; }; /* ----------- LIVE STATE ----------------- */ -struct RunTime -{ +struct RunTime { struct ITMDecoder i; /* The decoders and the packets from them */ struct ITMPacket h; struct TPIUDecoder t; @@ -151,31 +147,25 @@ static void _handleSW( struct RunTime *r ) struct swMsg *m = ( struct swMsg * )&r->m; - if ( m->srcAddr == r->options->traceChannel ) - { - switch ( r->CDState ) - { + if ( m->srcAddr == r->options->traceChannel ) { + switch ( r->CDState ) { // -------------------- Reporting the time stamp and if it's an In or Out event case CD_waitinout: - if ( ( m->value & COMMS_MASK ) == IN_EVENT ) - { + if ( ( m->value & COMMS_MASK ) == IN_EVENT ) { isIn = true; r->CDState = CD_waitsrc; } - if ( ( m->value & COMMS_MASK ) == OUT_EVENT ) - { + if ( ( m->value & COMMS_MASK ) == OUT_EVENT ) { isIn = false; r->CDState = CD_waitsrc; } - if ( r->CDState != CD_waitinout ) - { + if ( r->CDState != CD_waitinout ) { /* Time is encoded in lowest three octets ...accomodate rollover */ uint32_t t = m->value & 0xFFFFFF; - if ( t < _r.oldt ) - { + if ( t < _r.oldt ) { r->highOrdert++; } @@ -183,8 +173,7 @@ static void _handleSW( struct RunTime *r ) r->tcount = ( _r.highOrdert << 24 ) | t; /* Finally, if we're not sampling, then start sampling */ - if ( !r->sampling ) - { + if ( !r->sampling ) { genericsReport( V_WARN, "Sampling" EOL ); /* Fill in a time to start from */ r->starttime = genericsTimestampmS(); @@ -203,14 +192,11 @@ static void _handleSW( struct RunTime *r ) r->CDState = CD_waitdst; HASH_FIND_INT( r->insthead, &addr, r->from ); - if ( !r->from ) - { - if ( SymbolLookup( r->s, addr, &n ) ) - { - r->from = calloc( 1, sizeof( struct execEntryHash ) ); + if ( !r->from ) { + if ( SymbolLookup( r->s, addr, &n ) ) { + r->from = ( struct execEntryHash * )calloc( 1, sizeof( struct execEntryHash ) ); - if ( !r->from ) - { + if ( !r->from ) { genericsExit( ENOMEM, "Memory allocation failure at %s::%d", __FILE__, __LINE__ ); } @@ -218,9 +204,7 @@ static void _handleSW( struct RunTime *r ) r->from->fileindex = n.fileindex; r->from->line = n.line; r->from->functionindex = n.functionindex; - } - else - { + } else { genericsReport( V_ERROR, "No symbol for address %08x" EOL, addr ); r->CDState = CD_waitinout; return; @@ -239,14 +223,11 @@ static void _handleSW( struct RunTime *r ) HASH_FIND_INT( r->insthead, &addr, r->to ); - if ( !r->to ) - { - if ( SymbolLookup( r->s, addr, &n ) ) - { - r->to = calloc( 1, sizeof( struct execEntryHash ) ); + if ( !r->to ) { + if ( SymbolLookup( r->s, addr, &n ) ) { + r->to = ( struct execEntryHash * )calloc( 1, sizeof( struct execEntryHash ) ); - if ( !r->to ) - { + if ( !r->to ) { genericsExit( ENOMEM, "Memory allocation failure at %s::%d", __FILE__, __LINE__ ); } @@ -254,9 +235,7 @@ static void _handleSW( struct RunTime *r ) r->to->fileindex = n.fileindex; r->to->line = n.line; r->to->functionindex = n.functionindex; - } - else - { + } else { genericsReport( V_ERROR, "No symbol for address %08x" EOL, addr ); r->CDState = CD_waitinout; return; @@ -270,8 +249,7 @@ static void _handleSW( struct RunTime *r ) /* ----------------------------------------------------------------------------------------------------------*/ /* We have everything. Record calls between functions. These are flagged via isIn true/false for call/return */ /* ----------------------------------------------------------------------------------------------------------*/ - if ( isIn ) - { + if ( isIn ) { /* Now make calling record */ sig.src = r->from->addr; sig.dst = r->to->addr; @@ -279,13 +257,11 @@ static void _handleSW( struct RunTime *r ) /* Find, or create, the call record */ HASH_FIND( hh, r->subhead, &sig, sizeof( struct subcallSig ), s ); - if ( !s ) - { + if ( !s ) { /* This entry doesn't exist...let's create it */ s = ( struct subcall * )calloc( 1, sizeof( struct subcall ) ); - if ( !s ) - { + if ( !s ) { genericsExit( ENOMEM, "Memory allocation failure at %s::%d", __FILE__, __LINE__ ); } @@ -304,17 +280,13 @@ static void _handleSW( struct RunTime *r ) /* ...and add it to the call stack */ r->substack = ( struct subcall ** )realloc( r->substack, ( r->substacklen + 1 ) * sizeof( struct subcall * ) ); r->substack[r->substacklen++] = s; - } - else - { + } else { /* We've come out */ - if ( r->substacklen ) - { + if ( r->substacklen ) { /* We don't bother deallocating memory here cos it'll be done on the next isSubCall */ s = r->substack[--r->substacklen]; - if ( ( s->sig.src != r->from->addr ) || ( s->sig.dst != r->to->addr ) ) - { + if ( ( s->sig.src != r->from->addr ) || ( s->sig.dst != r->to->addr ) ) { genericsReport( V_WARN, "Address mismatch" EOL ); } @@ -338,8 +310,7 @@ void _itmPumpProcess( struct RunTime *r, char c ) typedef void ( *handlers )( struct RunTime * r ); /* Handlers for each complete message received */ - static const handlers h[MSG_NUM_MSGS] = - { + static const handlers h[MSG_NUM_MSGS] = { /* MSG_UNKNOWN */ NULL, /* MSG_RESERVED */ NULL, /* MSG_ERROR */ NULL, @@ -355,8 +326,7 @@ void _itmPumpProcess( struct RunTime *r, char c ) /* MSG_TS */ NULL }; - switch ( ITMPump( &r->i, c ) ) - { + switch ( ITMPump( &r->i, c ) ) { // ------------------------------------ case ITM_EV_NONE: break; @@ -387,8 +357,7 @@ void _itmPumpProcess( struct RunTime *r, char c ) /* See if we decoded a dispatchable match. genericMsg is just used to access */ /* the first two members of the decoded structs in a portable way. */ - if ( h[r->m.genericMsg.msgtype] ) - { + if ( h[r->m.genericMsg.msgtype] ) { ( h[r->m.genericMsg.msgtype] )( r ); } @@ -403,10 +372,8 @@ void _protocolPump( struct RunTime *r, uint8_t c ) /* Top level protocol pump */ { - if ( r->options->useTPIU ) - { - switch ( TPIUPump( &r->t, c ) ) - { + if ( r->options->useTPIU ) { + switch ( TPIUPump( &r->t, c ) ) { // ------------------------------------ case TPIU_EV_NEWSYNC: genericsReport( V_INFO, "TPIU In Sync (%d)" EOL, TPIUDecoderGetStats( &r->t )->syncCount ); @@ -428,21 +395,17 @@ void _protocolPump( struct RunTime *r, uint8_t c ) // ------------------------------------ case TPIU_EV_RXEDPACKET: - if ( !TPIUGetPacket( &r->t, &r->p ) ) - { + if ( !TPIUGetPacket( &r->t, &r->p ) ) { genericsReport( V_WARN, "TPIUGetPacket fell over" EOL ); } - for ( uint32_t g = 0; g < r->p.len; g++ ) - { - if ( r->p.packet[g].s == r->options->tpiuITMChannel ) - { + for ( uint32_t g = 0; g < r->p.len; g++ ) { + if ( r->p.packet[g].s == r->options->tpiuITMChannel ) { _itmPumpProcess( r, r->p.packet[g].d ); continue; } - if ( r->p.packet[g].s != 0 ) - { + if ( r->p.packet[g].s != 0 ) { genericsReport( V_DEBUG, "Unknown TPIU channel %02x" EOL, r->p.packet[g].s ); } } @@ -455,9 +418,7 @@ void _protocolPump( struct RunTime *r, uint8_t c ) break; // ------------------------------------ } - } - else - { + } else { /* There's no TPIU in use, so this goes straight to the ITM layer */ _itmPumpProcess( r, c ); } @@ -495,8 +456,7 @@ void _printVersion( void ) genericsPrintf( "orbstat version " GIT_DESCRIBE ); } // ==================================================================================================== -static struct option _longOptions[] = -{ +static struct option _longOptions[] = { {"no-demangle", no_argument, NULL, 'D'}, {"del-prefix", required_argument, NULL, 'd'}, {"elf-file", required_argument, NULL, 'e'}, @@ -523,10 +483,10 @@ static bool _processOptions( int argc, char *argv[], struct RunTime *r ) { int c, optionIndex = 0; + char *a; while ( ( c = getopt_long ( argc, argv, "Dd:e:Ef:g:hI:nO:s:t:Tv:Vy:z:", _longOptions, &optionIndex ) ) != -1 ) - switch ( c ) - { + switch ( c ) { // ------------------------------------ case 'd': r->options->deleteMaterial = optarg; @@ -593,21 +553,18 @@ static bool _processOptions( int argc, char *argv[], struct RunTime *r ) r->options->server = optarg; // See if we have an optional port number too - char *a = optarg; + a = optarg; - while ( ( *a ) && ( *a != ':' ) ) - { + while ( ( *a ) && ( *a != ':' ) ) { a++; } - if ( *a == ':' ) - { + if ( *a == ':' ) { *a = 0; r->options->port = atoi( ++a ); } - if ( !r->options->port ) - { + if ( !r->options->port ) { r->options->port = NWCLIENT_SERVER_PORT; } @@ -626,13 +583,12 @@ static bool _processOptions( int argc, char *argv[], struct RunTime *r ) // ------------------------------------ case 'v': - if ( !isdigit( *optarg ) ) - { + if ( !isdigit( *optarg ) ) { genericsReport( V_ERROR, "-v requires a numeric argument." EOL ); return false; } - genericsSetReportLevel( atoi( optarg ) ); + genericsSetReportLevel( ( enum verbLevel )atoi( optarg ) ); break; // ------------------------------------ @@ -647,12 +603,9 @@ static bool _processOptions( int argc, char *argv[], struct RunTime *r ) // ------------------------------------ case '?': - if ( optopt == 'b' ) - { + if ( optopt == 'b' ) { genericsReport( V_ERROR, "Option '%c' requires an argument." EOL, optopt ); - } - else if ( !isprint ( optopt ) ) - { + } else if ( !isprint ( optopt ) ) { genericsReport( V_ERROR, "Unknown option character `\\x%x'." EOL, optopt ); } @@ -665,14 +618,12 @@ static bool _processOptions( int argc, char *argv[], struct RunTime *r ) // ------------------------------------ } - if ( !r->options->elffile ) - { + if ( !r->options->elffile ) { genericsReport( V_ERROR, "Elf File not specified" EOL ); exit( -2 ); } - if ( !r->options->sampleDuration ) - { + if ( !r->options->sampleDuration ) { genericsReport( V_ERROR, "Illegal sample duration" EOL ); exit( -2 ); } @@ -721,8 +672,7 @@ int main( int argc, char *argv[] ) /* This is set here to avoid huge .data section in startup image */ _r.options = &_options; - if ( !_processOptions( argc, argv, &_r ) ) - { + if ( !_processOptions( argc, argv, &_r ) ) { /* processOptions generates its own error messages */ genericsExit( -1, "" EOL ); } @@ -733,16 +683,14 @@ int main( int argc, char *argv[] ) atexit( _doExit ); /* This ensures the atexit gets called */ - if ( SIG_ERR == signal( SIGINT, _intHandler ) ) - { + if ( SIG_ERR == signal( SIGINT, _intHandler ) ) { genericsExit( -1, "Failed to establish Int handler" EOL ); } #if !defined(WIN32) /* Don't kill a sub-process when any reader or writer evaporates */ - if ( SIG_ERR == signal( SIGPIPE, SIG_IGN ) ) - { + if ( SIG_ERR == signal( SIGPIPE, SIG_IGN ) ) { genericsExit( -1, "Failed to ignore SIGPIPEs" EOL ); } @@ -752,20 +700,14 @@ int main( int argc, char *argv[] ) TPIUDecoderInit( &_r.t ); ITMDecoderInit( &_r.i, _r.options->forceITMSync ); - while ( !_r.ending ) - { - if ( _r.options->file != NULL ) - { + while ( !_r.ending ) { + if ( _r.options->file != NULL ) { stream = streamCreateFile( _r.options->file ); - } - else - { - while ( 1 ) - { + } else { + while ( 1 ) { stream = streamCreateSocket( _r.options->server, _r.options->port ); - if ( stream ) - { + if ( stream ) { break; } @@ -776,12 +718,10 @@ int main( int argc, char *argv[] ) /* We need symbols constantly while running ... check they are current */ /* We need symbols constantly while running ... lets get them */ - if ( !SymbolSetValid( &_r.s, _r.options->elffile ) ) - { + if ( !SymbolSetValid( &_r.s, _r.options->elffile ) ) { r = SymbolSetCreate( &_r.s, _r.options->elffile, _r.options->deleteMaterial, _r.options->demangle, true, true, _r.options->odoptions ); - switch ( r ) - { + switch ( r ) { case SYMBOL_NOELF: genericsExit( -1, "Elf file or symbols in it not found" EOL ); break; @@ -804,26 +744,19 @@ int main( int argc, char *argv[] ) /* ----------------------------------------------------------------------------- */ /* This is the main active loop...only break out of this when ending or on error */ /* ----------------------------------------------------------------------------- */ - while ( !_r.ending ) - { + while ( !_r.ending ) { /* Each time segment is restricted */ tv.tv_sec = 0; tv.tv_usec = TICK_TIME_MS * 1000; enum ReceiveResult result = stream->receive( stream, _r.rawBlock.buffer, TRANSFER_SIZE, &tv, ( size_t * )&_r.rawBlock.fillLevel ); - if ( result != RECEIVE_RESULT_OK ) - { - if ( result == RECEIVE_RESULT_EOF && _r.options->fileTerminate ) - { + if ( result != RECEIVE_RESULT_OK ) { + if ( result == RECEIVE_RESULT_EOF && _r.options->fileTerminate ) { _r.ending = true; - } - else if ( result == RECEIVE_RESULT_ERROR ) - { + } else if ( result == RECEIVE_RESULT_ERROR ) { break; - } - else - { + } else { usleep( 100000 ); } } @@ -834,21 +767,18 @@ int main( int argc, char *argv[] ) /* Pump all of the data through the protocol handler */ uint8_t *c = _r.rawBlock.buffer; - while ( _r.rawBlock.fillLevel > 0 ) - { + while ( _r.rawBlock.fillLevel > 0 ) { _protocolPump( &_r, *c++ ); _r.rawBlock.fillLevel--; } /* Check to make sure there's not an unexpected TPIU in here */ - if ( ITMDecoderGetStats( &_r.i )->tpiuSyncCount ) - { + if ( ITMDecoderGetStats( &_r.i )->tpiuSyncCount ) { genericsReport( V_WARN, "Got a TPIU sync while decoding ITM...did you miss a -t option?" EOL ); } /* Update the intervals */ - if ( ( _r.sampling ) && ( ( genericsTimestampmS() - _r.starttime ) > _r.options->sampleDuration ) ) - { + if ( ( _r.sampling ) && ( ( genericsTimestampmS() - _r.starttime ) > _r.options->sampleDuration ) ) { _r.ending = true; } } @@ -860,16 +790,13 @@ int main( int argc, char *argv[] ) /* Data are collected, now process and report */ genericsReport( V_WARN, "Received %d raw sample bytes, %ld function changes, %ld distinct addresses" EOL, _r.intervalBytes, HASH_COUNT( _r.subhead ), HASH_COUNT( _r.insthead ) ); - if ( HASH_COUNT( _r.subhead ) ) - { - if ( ext_ff_outputDot( _r.options->dotfile, _r.subhead, _r.s ) ) - { + if ( HASH_COUNT( _r.subhead ) ) { + if ( ext_ff_outputDot( _r.options->dotfile, _r.subhead, _r.s ) ) { genericsReport( V_WARN, "Output DOT" EOL ); } if ( ext_ff_outputProfile( _r.options->profile, _r.options->elffile, _r.options->truncateDeleteMaterial ? _r.options->deleteMaterial : NULL, false, - _r.tcount - _r.starttcount, _r.insthead, _r.subhead, _r.s ) ) - { + _r.tcount - _r.starttcount, _r.insthead, _r.subhead, _r.s ) ) { genericsReport( V_WARN, "Output Profile" EOL ); } } diff --git a/Src/orbtop.c b/Src/orbtop.c index 11485be8..6210ab72 100644 --- a/Src/orbtop.c +++ b/Src/orbtop.c @@ -37,8 +37,7 @@ #define MSG_REORDER_BUFLEN (10) /* Maximum number of samples to re-order for timekeeping */ -struct visitedAddr /* Structure for Hashmap of visited/observed addresses */ -{ +struct visitedAddr { /* Structure for Hashmap of visited/observed addresses */ uint64_t visits; struct nameEntry *n; @@ -71,12 +70,11 @@ struct exceptionRecord /* Record of exception activity */ /* ---------- CONFIGURATION ----------------- */ -struct /* Record for options, either defaults or from command line */ -{ +struct { /* Record for options, either defaults or from command line */ bool useTPIU; /* Are we decoding via the TPIU? */ bool reportFilenames; /* Report filenames for each routine? */ bool outputExceptions; /* Set to include exceptions in output flow */ - uint32_t tpiuITMChannel; /* What channel? */ + int8_t tpiuITMChannel; /* What channel? */ bool forceITMSync; /* Must ITM start synced? */ char *file; /* File host connection */ @@ -100,24 +98,19 @@ struct /* Record for options, either defau int port; /* Source information */ char *server; -} options = -{ - .forceITMSync = true, +} options = { .useTPIU = false, .tpiuITMChannel = 1, - .outfile = NULL, - .logfile = NULL, - .lineDisaggregation = false, + .forceITMSync = true, .maxRoutines = 8, .demangle = true, .displayInterval = TOP_UPDATE_INTERVAL * 1000, .port = NWCLIENT_SERVER_PORT, - .server = "localhost" + .server = ( char * )"localhost" }; /* ----------- LIVE STATE ----------------- */ -struct -{ +struct { struct ITMDecoder i; /* The decoders and the packets from them */ struct MSGSeq d; /* Message (re-)sequencer */ struct ITMPacket h; @@ -168,13 +161,11 @@ int64_t _timestamp( void ) int _addresses_sort_fn( void *a, void *b ) { - if ( ( ( ( struct visitedAddr * )a )->n->addr ) < ( ( ( struct visitedAddr * )b )->n->addr ) ) - { + if ( ( ( ( struct visitedAddr * )a )->n->addr ) < ( ( ( struct visitedAddr * )b )->n->addr ) ) { return -1; } - if ( ( ( ( struct visitedAddr * )a )->n->addr ) > ( ( ( struct visitedAddr * )b )->n->addr ) ) - { + if ( ( ( ( struct visitedAddr * )a )->n->addr ) > ( ( ( struct visitedAddr * )b )->n->addr ) ) { return 1; } @@ -186,20 +177,17 @@ int _routines_sort_fn( void *a, void *b ) { int r; - if ( ( options.reportFilenames ) && ( ( ( ( struct visitedAddr * )a )->n->fileindex ) && ( ( ( struct visitedAddr * )b )->n->fileindex ) ) ) - { + if ( ( options.reportFilenames ) && ( ( ( ( struct visitedAddr * )a )->n->fileindex ) && ( ( ( struct visitedAddr * )b )->n->fileindex ) ) ) { r = ( ( int )( ( struct visitedAddr * )a )->n->fileindex ) - ( ( int )( ( struct visitedAddr * )b )->n->fileindex ); - if ( r ) - { + if ( r ) { return r; } } r = ( ( int )( ( struct visitedAddr * )a )->n->functionindex ) - ( ( int )( ( struct visitedAddr * )b )->n->functionindex ); - if ( r ) - { + if ( r ) { return r; } @@ -221,8 +209,7 @@ int _report_sort_fn( const void *a, const void *b ) void _exitEx( int64_t ts ) { - if ( _r.currentException == NO_EXCEPTION ) - { + if ( _r.currentException == NO_EXCEPTION ) { /* This can happen under startup and overflow conditions */ return; } @@ -239,39 +226,33 @@ void _exitEx( int64_t ts ) _r.er[_r.currentException].entryTime = 0; /* ...and account for this time */ - if ( ( !_r.er[_r.currentException].minTime ) || ( _r.er[_r.currentException].thisTime < _r.er[_r.currentException].minTime ) ) - { + if ( ( !_r.er[_r.currentException].minTime ) || ( _r.er[_r.currentException].thisTime < _r.er[_r.currentException].minTime ) ) { _r.er[_r.currentException].minTime = _r.er[_r.currentException].thisTime; } - if ( _r.er[_r.currentException].thisTime > _r.er[_r.currentException].maxTime ) - { + if ( _r.er[_r.currentException].thisTime > _r.er[_r.currentException].maxTime ) { _r.er[_r.currentException].maxTime = _r.er[_r.currentException].thisTime; } const int64_t walltime = _r.er[_r.currentException].thisTime + _r.er[_r.currentException].stealTime; - if ( walltime > _r.er[_r.currentException].maxWallTime ) - { + if ( walltime > _r.er[_r.currentException].maxWallTime ) { _r.er[_r.currentException].maxWallTime = walltime; } - if ( _r.erDepth > _r.er[_r.currentException].maxDepth ) - { + if ( _r.erDepth > _r.er[_r.currentException].maxDepth ) { _r.er[_r.currentException].maxDepth = _r.erDepth; } /* Step out of this exception */ _r.currentException = _r.er[_r.currentException].prev; - if ( _r.erDepth ) - { + if ( _r.erDepth ) { _r.erDepth--; } /* If we are still in an exception then carry on accounting */ - if ( _r.currentException != NO_EXCEPTION ) - { + if ( _r.currentException != NO_EXCEPTION ) { _r.er[_r.currentException].entryTime = ts; _r.er[_r.currentException].stealTime += thisTime + thisStealTime; } @@ -282,7 +263,7 @@ void _handleTS( struct TSMsg *m, struct ITMDecoder *i ) { assert( m->msgtype == MSG_TS ); - _r.timeStatus = m->timeStatus; + _r.timeStatus = ( enum timeDelay )m->timeStatus; _r.timeStamp += m->timeInc; } // ==================================================================================================== @@ -292,11 +273,9 @@ void _handleException( struct excMsg *m, struct ITMDecoder *i ) assert( m->msgtype == MSG_EXCEPTION ); assert( m->exceptionNumber < MAX_EXCEPTIONS ); - switch ( m->eventType ) - { + switch ( m->eventType ) { case EXEVENT_ENTER: - if ( _r.er[m->exceptionNumber].entryTime != 0 ) - { + if ( _r.er[m->exceptionNumber].entryTime != 0 ) { /* We beleive we are already in this exception. This can happen when we've lost * messages due to ITM overflow. Don't process the enter. Everything will get * fixed up in the next EXEXIT_RESUME which will reset everything. @@ -304,8 +283,7 @@ void _handleException( struct excMsg *m, struct ITMDecoder *i ) break; } - if ( _r.currentException != NO_EXCEPTION ) - { + if ( _r.currentException != NO_EXCEPTION ) { /* Already in an exception ... account for time until now */ _r.er[_r.currentException].thisTime += _r.timeStamp - _r.er[_r.currentException].entryTime; } @@ -322,8 +300,7 @@ void _handleException( struct excMsg *m, struct ITMDecoder *i ) break; case EXEVENT_RESUME: /* Unwind all levels of exception (deals with tail chaining) */ - while ( ( _r.currentException != m->exceptionNumber ) && ( _r.erDepth ) ) - { + while ( ( _r.currentException != m->exceptionNumber ) && ( _r.erDepth ) ) { _exitEx( _r.timeStamp ); } @@ -371,18 +348,15 @@ uint32_t _consolodateReport( struct reportLine **returnReport, uint32_t *returnR HASH_SORT( _r.addresses, _routines_sort_fn ); /* Now merge them together */ - for ( a = _r.addresses; a != NULL; a = a->hh.next ) - { - if ( !a->visits ) - { + for ( a = _r.addresses; a != NULL; a = ( struct visitedAddr * )a->hh.next ) { + if ( !a->visits ) { continue; } if ( ( reportLines == 0 ) || - ( ( options.reportFilenames ) && ( report[reportLines - 1].n->fileindex != a->n->fileindex ) ) || - ( report[reportLines - 1].n->functionindex != a->n->functionindex ) || - ( ( report[reportLines - 1].n->line != a->n->line ) && ( options.lineDisaggregation ) ) ) - { + ( ( options.reportFilenames ) && ( report[reportLines - 1].n->fileindex != a->n->fileindex ) ) || + ( report[reportLines - 1].n->functionindex != a->n->functionindex ) || + ( ( report[reportLines - 1].n->line != a->n->line ) && ( options.lineDisaggregation ) ) ) { /* Make room for a report line */ reportLines++; report = ( struct reportLine * )realloc( report, sizeof( struct reportLine ) * ( reportLines ) ); @@ -402,12 +376,9 @@ uint32_t _consolodateReport( struct reportLine **returnReport, uint32_t *returnR uint32_t addr = FN_SLEEPING; HASH_FIND_INT( _r.addresses, &addr, a ); - if ( a ) - { + if ( a ) { n = a->n; - } - else - { + } else { n = ( struct nameEntry * )malloc( sizeof( struct nameEntry ) ); } @@ -483,10 +454,8 @@ static void _outputJson( FILE *f, uint32_t total, uint32_t reportLines, struct r assert( jsonTopTable ); cJSON_AddItemToObject( jsonStore, "toptable", jsonTopTable ); - for ( uint32_t n = 0; n < reportLines; n++ ) - { - if ( report[n].count ) - { + for ( uint32_t n = 0; n < reportLines; n++ ) { + if ( report[n].count ) { char *d = NULL; /* Output in JSON Format */ @@ -504,8 +473,7 @@ static void _outputJson( FILE *f, uint32_t total, uint32_t reportLines, struct r assert( jsonElement ); cJSON_AddItemToObject( jsonTableEntry, "function", jsonElement ); - if ( options.lineDisaggregation ) - { + if ( options.lineDisaggregation ) { jsonElement = cJSON_CreateNumber( report[n].n->line ? report[n].n->line : 0 ); assert( jsonElement ); cJSON_AddItemToObject( jsonTableEntry, "line", jsonElement ); @@ -520,10 +488,8 @@ static void _outputJson( FILE *f, uint32_t total, uint32_t reportLines, struct r assert( jsonIntTable ); cJSON_AddItemToObject( jsonStore, "exceptions", jsonIntTable ); - for ( uint32_t e = 0; e < MAX_EXCEPTIONS; e++ ) - { - if ( _r.er[e].visits ) - { + for ( uint32_t e = 0; e < MAX_EXCEPTIONS; e++ ) { + if ( _r.er[e].visits ) { jsonTableEntry = cJSON_CreateObject(); assert( jsonTableEntry ); cJSON_AddItemToObject( jsonIntTable, "exceptions", jsonTableEntry ); @@ -560,8 +526,7 @@ static void _outputJson( FILE *f, uint32_t total, uint32_t reportLines, struct r free( opString ); } -static const char *ExceptionNames[] = -{ +static const char *ExceptionNames[] = { [0] = "None", [1] = "Reset", [2] = "NMI", @@ -596,49 +561,39 @@ static void _outputTop( uint32_t total, uint32_t reportLines, struct reportLine uint32_t printed = 0; /* This is the file retaining the current samples */ - if ( options.outfile ) - { + if ( options.outfile ) { p = fopen( options.outfile, "w" ); } /* This is the file containing the historic samples */ - if ( options.logfile ) - { + if ( options.logfile ) { q = fopen( options.logfile, "a" ); } genericsPrintf( CLEAR_SCREEN ); - if ( total ) - { - for ( uint32_t n = 0; n < reportLines; n++ ) - { + if ( total ) { + for ( uint32_t n = 0; n < reportLines; n++ ) { percentage = ( report[n].count * 10000 ) / total; samples += report[n].count; - if ( report[n].count ) - { + if ( report[n].count ) { char *d = NULL; - if ( ( percentage >= CUTOFF ) && ( ( !options.cutscreen ) || ( n < options.cutscreen ) ) ) - { + if ( ( percentage >= CUTOFF ) && ( ( !options.cutscreen ) || ( n < options.cutscreen ) ) ) { dispSamples += report[n].count; totPercent += percentage; genericsPrintf( C_DATA "%3d.%02d%% " C_SUPPORT " %7" PRIu64 " ", percentage / 100, percentage % 100, report[n].count ); - if ( ( options.reportFilenames ) && ( report[n].n->fileindex != NO_FILE ) ) - { + if ( ( options.reportFilenames ) && ( report[n].n->fileindex != NO_FILE ) ) { genericsPrintf( C_CONTEXT "%s" C_RESET "::", SymbolFilename( _r.s, report[n].n->fileindex ) ); } - if ( ( options.lineDisaggregation ) && ( report[n].n->line ) ) - { + if ( ( options.lineDisaggregation ) && ( report[n].n->line ) ) { genericsPrintf( C_SUPPORT2 "%s" C_RESET "::" C_CONTEXT "%d" EOL, d ? d : SymbolFunction( _r.s, report[n].n->functionindex ), report[n].n->line ); - } - else - { + } else { genericsPrintf( C_SUPPORT2 "%s" C_RESET EOL, d ? d : SymbolFunction( _r.s, report[n].n->functionindex ) ); } @@ -646,29 +601,21 @@ static void _outputTop( uint32_t total, uint32_t reportLines, struct reportLine } /* Write to current and historical data files if appropriate */ - if ( percentage >= CUTOFF ) - { - if ( !options.lineDisaggregation ) - { - if ( ( p ) && ( n < options.maxRoutines ) ) - { + if ( percentage >= CUTOFF ) { + if ( !options.lineDisaggregation ) { + if ( ( p ) && ( n < options.maxRoutines ) ) { fprintf( p, "%s,%3d.%02d" EOL, d ? d : SymbolFunction( _r.s, report[n].n->functionindex ), percentage / 100, percentage % 100 ); } - if ( q ) - { + if ( q ) { fprintf( q, "%s,%3d.%02d" EOL, d ? d : SymbolFunction( _r.s, report[n].n->functionindex ), percentage / 100, percentage % 100 ); } - } - else - { - if ( ( p ) && ( n < options.maxRoutines ) ) - { + } else { + if ( ( p ) && ( n < options.maxRoutines ) ) { fprintf( p, "%s::%d,%3d.%02d" EOL, d ? d : SymbolFunction( _r.s, report[n].n->functionindex ), report[n].n->line, percentage / 100, percentage % 100 ); } - if ( q ) - { + if ( q ) { fprintf( q, "%s::%d,%3d.%02d" EOL, d ? d : SymbolFunction( _r.s, report[n].n->functionindex ), report[n].n->line, percentage / 100, percentage % 100 ); } } @@ -681,52 +628,45 @@ static void _outputTop( uint32_t total, uint32_t reportLines, struct reportLine genericsPrintf( C_RESET "-----------------" EOL ); - genericsPrintf( C_DATA "%3d.%02d%% " C_SUPPORT " %7" PRIu64 " " C_RESET "of "C_DATA" %" PRIu64 " "C_RESET" Samples" EOL, totPercent / 100, totPercent % 100, dispSamples, samples ); + genericsPrintf( C_DATA "%3d.%02d%% " C_SUPPORT " %7" PRIu64 " " C_RESET "of " C_DATA " %" PRIu64 " " C_RESET " Samples" EOL, totPercent / 100, totPercent % 100, dispSamples, samples ); - if ( p ) - { + if ( p ) { fclose( p ); } - if ( q ) - { + if ( q ) { fprintf( q, "===================================" EOL ); fclose( q ); } - if ( options.outputExceptions ) - { + if ( options.outputExceptions ) { /* Tidy up screen output */ - while ( printed++ <= options.cutscreen ) - { + while ( printed++ <= options.cutscreen ) { genericsPrintf( EOL ); } genericsPrintf( EOL " Exception | Count | MaxD | TotalTicks | %% | AveTicks | minTicks | maxTicks | maxWall " EOL ); genericsPrintf( /**/"-------------------+----------+-------+-------------+-------+------------+------------+------------+----------" EOL ); - for ( uint32_t e = 0; e < MAX_EXCEPTIONS; e++ ) - { + for ( uint32_t e = 0; e < MAX_EXCEPTIONS; e++ ) { - if ( _r.er[e].visits ) - { + if ( _r.er[e].visits ) { char exceptionName[30] = { 0 }; - if ( e < 16 ) - { + if ( e < 16 ) { snprintf( exceptionName, sizeof( exceptionName ), "(%s)", ExceptionNames[e] ); - } - else - { + } else { snprintf( exceptionName, sizeof( exceptionName ), "(IRQ %d)", e - 16 ); } const float util_percent = ( float )_r.er[e].totalTime / ( _r.timeStamp - _r.lastReportTicks ) * 100.0f; genericsPrintf( C_DATA "%3" PRId32 " %-14s" C_RESET " | " C_DATA "%8" PRIu64 C_RESET " |" C_DATA " %5" - PRIu32 C_RESET " | "C_DATA " %9" PRIu64 C_RESET " |" C_DATA "%6.1f" C_RESET " | " C_DATA "%9" PRIu64 C_RESET " | " C_DATA "%9" PRIu64 C_RESET " | " C_DATA" %9" PRIu64 C_RESET " | " C_DATA "%9" - PRIu64 C_RESET EOL, - e, exceptionName, _r.er[e].visits, _r.er[e].maxDepth, _r.er[e].totalTime, util_percent, _r.er[e].totalTime / _r.er[e].visits, _r.er[e].minTime, _r.er[e].maxTime, _r.er[e].maxWallTime ); + PRIu32 C_RESET " | " C_DATA " %9" PRIu64 C_RESET " |" C_DATA "%6.1f" C_RESET " | " C_DATA + "%9" PRIu64 C_RESET " | " C_DATA "%9" PRIu64 C_RESET " | " C_DATA " %9" PRIu64 C_RESET + " | " C_DATA "%9" PRIu64 C_RESET EOL, + e, exceptionName, _r.er[e].visits, _r.er[e].maxDepth, _r.er[e].totalTime, util_percent, + _r.er[e].totalTime / _r.er[e].visits, _r.er[e].minTime, _r.er[e].maxTime, _r.er[e].maxWallTime ); } } } @@ -738,11 +678,13 @@ static void _outputTop( uint32_t total, uint32_t reportLines, struct reportLine ( _r.HWPkt != ITMDecoderGetStats( &_r.i )->HWPkt ) ? C_HW_IND "H" : C_RESET "-" ); if ( ( _r.lastReportTicks ) && ( lastTime != _r.lastReportus ) ) - genericsPrintf( "Interval = " C_DATA "%" PRIu64 "ms " C_RESET "/ "C_DATA "%" PRIu64 C_RESET " (~" C_DATA "%" PRIu64 C_RESET " Ticks/ms)" EOL, - ( ( lastTime - _r.lastReportus ) + 500 ) / 1000, _r.timeStamp - _r.lastReportTicks, ( ( _r.timeStamp - _r.lastReportTicks ) * 1000 ) / ( lastTime - _r.lastReportus ) ); - else - { - genericsPrintf( C_RESET "Interval = " C_DATA "%" PRIu64 C_RESET "ms" EOL, ( ( lastTime - _r.lastReportus ) + 500 ) / 1000 ); + genericsPrintf( "Interval = " C_DATA "%" PRIu64 "ms " C_RESET "/ " C_DATA "%" PRIu64 C_RESET " (~" + C_DATA "%" PRIu64 C_RESET " Ticks/ms)" EOL, + ( ( lastTime - _r.lastReportus ) + 500 ) / 1000, _r.timeStamp - _r.lastReportTicks, + ( ( _r.timeStamp - _r.lastReportTicks ) * 1000 ) / ( lastTime - _r.lastReportus ) ); + else { + genericsPrintf( C_RESET "Interval = " C_DATA "%" PRIu64 C_RESET "ms" EOL, + ( ( lastTime - _r.lastReportus ) + 500 ) / 1000 ); } genericsReport( V_INFO, " Ovf=%3d ITMSync=%3d TPIUSync=%3d ITMErrors=%3d" EOL, @@ -761,21 +703,15 @@ void _handlePCSample( struct pcSampleMsg *m, struct ITMDecoder *i ) struct visitedAddr *a; - if ( m->sleep ) - { + if ( m->sleep ) { /* This is a sleep packet */ _r.sleeps++; - } - else - { + } else { HASH_FIND_INT( _r.addresses, &m->pc, a ); - if ( a ) - { + if ( a ) { a->visits++; - } - else - { + } else { struct nameEntry n; /* Find a matching name record if there is one */ @@ -801,8 +737,7 @@ void _flushHash( void ) struct visitedAddr *a; UT_hash_handle hh; - for ( a = _r.addresses; a != NULL; a = hh.next ) - { + for ( a = _r.addresses; a != NULL; a = ( struct visitedAddr * )hh.next ) { hh = a->hh; free( a ); } @@ -818,8 +753,7 @@ void _itmPumpProcess( uint8_t c ) typedef void ( *handlers )( void *decoded, struct ITMDecoder * i ); /* Handlers for each complete message received */ - static const handlers h[MSG_NUM_MSGS] = - { + static const handlers h[MSG_NUM_MSGS] = { /* MSG_UNKNOWN */ NULL, /* MSG_RESERVED */ NULL, /* MSG_ERROR */ NULL, @@ -837,26 +771,22 @@ void _itmPumpProcess( uint8_t c ) struct msg *p; - if ( !MSGSeqPump( &_r.d, c ) ) - { + if ( !MSGSeqPump( &_r.d, c ) ) { return; } /* We are synced timewise, so empty anything that has been waiting */ - while ( 1 ) - { + while ( 1 ) { p = MSGSeqGetPacket( &_r.d ); - if ( !p ) - { + if ( !p ) { /* all read */ break; } assert( p->genericMsg.msgtype < MSG_NUM_MSGS ); - if ( h[p->genericMsg.msgtype] ) - { + if ( h[p->genericMsg.msgtype] ) { ( h[p->genericMsg.msgtype] )( p, &_r.i ); } } @@ -873,10 +803,8 @@ void _protocolPump( uint8_t c ) /* Top level protocol pump */ { - if ( options.useTPIU ) - { - switch ( TPIUPump( &_r.t, c ) ) - { + if ( options.useTPIU ) { + switch ( TPIUPump( &_r.t, c ) ) { // ------------------------------------ case TPIU_EV_NEWSYNC: genericsReport( V_INFO, "TPIU In Sync (%d)" EOL, TPIUDecoderGetStats( &_r.t )->syncCount ); @@ -898,21 +826,17 @@ void _protocolPump( uint8_t c ) // ------------------------------------ case TPIU_EV_RXEDPACKET: - if ( !TPIUGetPacket( &_r.t, &_r.p ) ) - { + if ( !TPIUGetPacket( &_r.t, &_r.p ) ) { genericsReport( V_WARN, "TPIUGetPacket fell over" EOL ); } - for ( uint32_t g = 0; g < _r.p.len; g++ ) - { - if ( _r.p.packet[g].s == options.tpiuITMChannel ) - { + for ( uint32_t g = 0; g < _r.p.len; g++ ) { + if ( _r.p.packet[g].s == options.tpiuITMChannel ) { _itmPumpProcess( _r.p.packet[g].d ); continue; } - if ( _r.p.packet[g].s != 0 ) - { + if ( _r.p.packet[g].s != 0 ) { genericsReport( V_DEBUG, "Unknown TPIU channel %02x" EOL, _r.p.packet[g].s ); } } @@ -925,9 +849,7 @@ void _protocolPump( uint8_t c ) break; // ------------------------------------ } - } - else - { + } else { /* There's no TPIU in use, so this goes straight to the ITM layer */ _itmPumpProcess( c ); } @@ -968,8 +890,7 @@ void _printVersion( void ) genericsPrintf( "orbtop version " GIT_DESCRIBE EOL ); } // ==================================================================================================== -static struct option _longOptions[] = -{ +static struct option _longOptions[] = { {"cut-after", required_argument, NULL, 'c'}, {"no-demangle", required_argument, NULL, 'D'}, {"del-prefix", required_argument, NULL, 'd'}, @@ -999,10 +920,10 @@ bool _processOptions( int argc, char *argv[] ) { int c, optionIndex = 0; + char *a; while ( ( c = getopt_long ( argc, argv, "c:d:DEe:f:g:hVI:j:lMnO:o:r:Rs:t:v:", _longOptions, &optionIndex ) ) != -1 ) - switch ( c ) - { + switch ( c ) { // ------------------------------------ case 'c': options.cutscreen = atoi( optarg ); @@ -1083,13 +1004,12 @@ bool _processOptions( int argc, char *argv[] ) // ------------------------------------ case 'v': - if ( !isdigit( *optarg ) ) - { + if ( !isdigit( *optarg ) ) { genericsReport( V_ERROR, "-v requires a numeric argument." EOL ); return false; } - genericsSetReportLevel( atoi( optarg ) ); + genericsSetReportLevel( ( enum verbLevel )atoi( optarg ) ); break; // ------------------------------------ @@ -1108,21 +1028,18 @@ bool _processOptions( int argc, char *argv[] ) options.server = optarg; // See if we have an optional port number too - char *a = optarg; + a = optarg; - while ( ( *a ) && ( *a != ':' ) ) - { + while ( ( *a ) && ( *a != ':' ) ) { a++; } - if ( *a == ':' ) - { + if ( *a == ':' ) { *a = 0; options.port = atoi( ++a ); } - if ( !options.port ) - { + if ( !options.port ) { options.port = NWCLIENT_SERVER_PORT; } @@ -1140,12 +1057,9 @@ bool _processOptions( int argc, char *argv[] ) // ------------------------------------ case '?': - if ( optopt == 'b' ) - { + if ( optopt == 'b' ) { genericsReport( V_ERROR, "Option '%c' requires an argument." EOL, optopt ); - } - else if ( !isprint ( optopt ) ) - { + } else if ( !isprint ( optopt ) ) { genericsReport( V_ERROR, "Unknown option character `\\x%x'." EOL, optopt ); } @@ -1158,26 +1072,21 @@ bool _processOptions( int argc, char *argv[] ) // ------------------------------------ } - if ( ( options.useTPIU ) && ( !options.tpiuITMChannel ) ) - { + if ( ( options.useTPIU ) && ( !options.tpiuITMChannel ) ) { genericsReport( V_ERROR, "TPIU set for use but no channel set for ITM output" EOL ); return -EINVAL; } - if ( !options.elffile ) - { + if ( !options.elffile ) { genericsReport( V_ERROR, "Elf File not specified" EOL ); exit( -EBADF ); } genericsReport( V_INFO, "orbtop version " GIT_DESCRIBE EOL ); - if ( options.file ) - { + if ( options.file ) { genericsReport( V_INFO, "Input File : %s", options.file ); - } - else - { + } else { genericsReport( V_INFO, "Server : %s:%d" EOL, options.server, options.port ); } @@ -1189,12 +1098,9 @@ bool _processOptions( int argc, char *argv[] ) genericsReport( V_INFO, "Log File : %s" EOL, options.logfile ? options.logfile : "None" ); genericsReport( V_INFO, "Objdump options : %s" EOL, options.odoptions ? options.odoptions : "None" ); - if ( options.useTPIU ) - { + if ( options.useTPIU ) { genericsReport( V_INFO, "Using TPIU : true (ITM on channel %d)" EOL, options.tpiuITMChannel ); - } - else - { + } else { genericsReport( V_INFO, "Using TPIU : false" EOL ); } @@ -1204,12 +1110,9 @@ bool _processOptions( int argc, char *argv[] ) static struct Stream *_openStream() { - if ( options.file != NULL ) - { + if ( options.file != NULL ) { return streamCreateFile( options.file ); - } - else - { + } else { return streamCreateSocket( options.server, options.port ); } } @@ -1239,8 +1142,7 @@ int main( int argc, char *argv[] ) size_t receivedSize = 0; enum symbolErr r; - if ( OK != _processOptions( argc, argv ) ) - { + if ( OK != _processOptions( argc, argv ) ) { exit( -EINVAL ); } @@ -1249,8 +1151,7 @@ int main( int argc, char *argv[] ) /* Check we've got _some_ symbols to start from */ r = SymbolSetCreate( &_r.s, options.elffile, options.deleteMaterial, options.demangle, true, true, options.odoptions ); - switch ( r ) - { + switch ( r ) { case SYMBOL_NOELF: genericsExit( -1, "Elf file or symbols in it not found" EOL ); break; @@ -1279,32 +1180,24 @@ int main( int argc, char *argv[] ) _r.currentException = NO_EXCEPTION; /* Open file for JSON output if we have one */ - if ( options.json ) - { - if ( options.json[0] == '-' ) - { + if ( options.json ) { + if ( options.json[0] == '-' ) { _r.jsonfile = stdout; - } - else - { + } else { _r.jsonfile = fopen( options.json, "w" ); - if ( !_r.jsonfile ) - { + if ( !_r.jsonfile ) { perror( "Couldn't open json output file" ); return -ENOENT; } } } - while ( 1 ) - { + while ( 1 ) { struct Stream *stream = _openStream(); - if ( stream == NULL ) - { - if ( !alreadyReported ) - { + if ( stream == NULL ) { + if ( !alreadyReported ) { genericsReport( V_ERROR, "No connection" EOL ); alreadyReported = true; } @@ -1315,8 +1208,7 @@ int main( int argc, char *argv[] ) alreadyReported = false; - if ( ( !options.json ) || ( options.json[0] != '-' ) ) - { + if ( ( !options.json ) || ( options.json[0] != '-' ) ) { genericsPrintf( CLEAR_SCREEN "Connected..." EOL ); } @@ -1325,44 +1217,36 @@ int main( int argc, char *argv[] ) _r.lastReportus = _timestamp(); - while ( 1 ) - { + while ( 1 ) { thisTime = _timestamp(); remainTime = ( ( _r.lastReportus + options.displayInterval - thisTime ) ) + 500; - if ( remainTime > 0 ) - { + if ( remainTime > 0 ) { tv.tv_sec = remainTime / 1000000; tv.tv_usec = remainTime % 1000000; receiveResult = stream->receive( stream, cbw, TRANSFER_SIZE, &tv, &receivedSize ); - } - else - { + } else { receiveResult = RECEIVE_RESULT_OK; receivedSize = 0; } - if ( receiveResult == RECEIVE_RESULT_ERROR ) - { + if ( receiveResult == RECEIVE_RESULT_ERROR ) { /* Something went wrong in the receive */ break; } - if ( receiveResult == RECEIVE_RESULT_EOF ) - { + if ( receiveResult == RECEIVE_RESULT_EOF ) { /* We are at EOF, hopefully next loop will get more data. */ } /* Check to make sure our symbols are still appropriate */ - if ( !SymbolSetValid( &_r.s, options.elffile ) ) - { + if ( !SymbolSetValid( &_r.s, options.elffile ) ) { /* Make sure old references are invalidated */ _flushHash(); r = SymbolSetCreate( &_r.s, options.elffile, options.deleteMaterial, options.demangle, true, true, options.odoptions ); - switch ( r ) - { + switch ( r ) { case SYMBOL_NOELF: genericsReport( V_WARN, "Elf file or symbols in it not found" EOL ); break; @@ -1379,8 +1263,7 @@ int main( int argc, char *argv[] ) break; } - if ( SYMBOL_NOELF == r ) - { + if ( SYMBOL_NOELF == r ) { usleep( 1000000L ); continue; } @@ -1391,25 +1274,21 @@ int main( int argc, char *argv[] ) /* Pump all of the data through the protocol handler */ uint8_t *c = cbw; - while ( receivedSize > 0 ) - { + while ( receivedSize > 0 ) { _protocolPump( *c++ ); receivedSize--; } /* See if its time to post-process it */ - if ( receiveResult == RECEIVE_RESULT_TIMEOUT || remainTime <= 0 ) - { + if ( receiveResult == RECEIVE_RESULT_TIMEOUT || remainTime <= 0 ) { /* Create the report that we will output */ total = _consolodateReport( &report, &reportLines ); - if ( options.json ) - { + if ( options.json ) { _outputJson( _r.jsonfile, total, reportLines, report, thisTime ); } - if ( ( !options.json ) || ( options.json[0] != '-' ) ) - { + if ( ( !options.json ) || ( options.json[0] != '-' ) ) { _outputTop( total, reportLines, report, thisTime ); } @@ -1417,15 +1296,13 @@ int main( int argc, char *argv[] ) free( report ); /* ...and zero the exception records */ - for ( uint32_t e = 0; e < MAX_EXCEPTIONS; e++ ) - { + for ( uint32_t e = 0; e < MAX_EXCEPTIONS; e++ ) { _r.er[e].visits = _r.er[e].maxDepth = _r.er[e].totalTime = _r.er[e].minTime = _r.er[e].maxTime = _r.er[e].maxWallTime = 0; } /* It's safe to update these here because the ticks won't be updated until more * records arrive. */ - if ( _r.ITMoverflows != ITMDecoderGetStats( &_r.i )->overflow ) - { + if ( _r.ITMoverflows != ITMDecoderGetStats( &_r.i )->overflow ) { /* We had an overflow, so can't safely track max depth ... reset it */ _r.erDepth = 0; } @@ -1438,8 +1315,7 @@ int main( int argc, char *argv[] ) _r.lastReportTicks = _r.timeStamp; /* Check to make sure there's not an unexpected TPIU in here */ - if ( ITMDecoderGetStats( &_r.i )->tpiuSyncCount ) - { + if ( ITMDecoderGetStats( &_r.i )->tpiuSyncCount ) { genericsReport( V_WARN, "Got a TPIU sync while decoding ITM...did you miss a -t option?" EOL ); ITMDecoderGetStats( &_r.i )->tpiuSyncCount = 0; } @@ -1450,8 +1326,7 @@ int main( int argc, char *argv[] ) free( stream ); } - if ( ( !ITMDecoderGetStats( &_r.i )->tpiuSyncCount ) ) - { + if ( ( !ITMDecoderGetStats( &_r.i )->tpiuSyncCount ) ) { genericsReport( V_ERROR, "Read failed" EOL ); } diff --git a/Src/orbtrace.c b/Src/orbtrace.c index 6d3609f0..fbc54a06 100644 --- a/Src/orbtrace.c +++ b/Src/orbtrace.c @@ -24,8 +24,7 @@ #define MAX(a,b) (((a)>(b))?(a):(b)) /* Record for options, either defaults or from command line */ -struct Options -{ +struct Options { /* Probe config */ char *sn; /* Any part of serial number to differentiate probe */ char *nick; /* Nickname for device */ @@ -54,16 +53,14 @@ enum Actions { ACTION_BRIGHTNESS, ACTION_ENCHANGE_VTREF, ACTION_ENCHANGE_VTPWR, ACTION_ENCHANGE_ALL }; -struct RunTime -{ +struct RunTime { struct OrbtraceIf *dev; /* Link to the connected Orbtrace device */ bool ending; /* Flag indicating app is terminating */ int ndevices; /* Number of devices found connected that match search spec */ uint64_t actions; /* Actions to be performed */ struct Options *options; /* Runtime command line options */ -} _r = -{ +} _r = { .options = &_options }; @@ -103,12 +100,9 @@ static bool _tcl_action( struct RunTime *r, int x ) /* Query and then clear an action flag */ { - if ( !_tst_action( r, x ) ) - { + if ( !_tst_action( r, x ) ) { return false; - } - else - { + } else { _clr_action( r, x ); return true; } @@ -165,8 +159,7 @@ void _printVersion( void ) genericsPrintf( "Orbtrace version " GIT_DESCRIBE ); } // ==================================================================================================== -static struct option _longOptions[] = -{ +static struct option _longOptions[] = { {"serial-speed", required_argument, NULL, 'a'}, {"power", required_argument, NULL, 'e'}, {"help", no_argument, NULL, 'h'}, @@ -187,14 +180,12 @@ static bool _checkVoltages( struct RunTime *r ) /* Check that voltages, if requested, are sensible */ { - if ( _tst_action( r, ACTION_VCHANGE_VTREF ) && ( 0 == OrbtraceIfValidateVoltage( r->dev, r->options->TRefmv ) ) ) - { + if ( _tst_action( r, ACTION_VCHANGE_VTREF ) && ( 0 == OrbtraceIfValidateVoltage( r->dev, r->options->TRefmv ) ) ) { genericsReport( V_ERROR, "Illegal voltage specified for TRef (%d.%03dV)" EOL, r->options->TRefmv / 1000, r->options->TRefmv % 1000 ); return false; } - if ( _tst_action( r, ACTION_VCHANGE_VTPWR ) && ( 0 == OrbtraceIfValidateVoltage( r->dev, r->options->TPwrmv ) ) ) - { + if ( _tst_action( r, ACTION_VCHANGE_VTPWR ) && ( 0 == OrbtraceIfValidateVoltage( r->dev, r->options->TPwrmv ) ) ) { genericsReport( V_ERROR, "Illegal voltage specified for TPwr (%d.%03dV)" EOL, r->options->TPwrmv / 1000, r->options->TPwrmv % 1000 ); return false; } @@ -215,8 +206,7 @@ static int _processOptions( struct RunTime *r, int argc, char *argv[] ) char *a; while ( ( c = getopt_long ( argc, argv, "a:e:hlp:Mn:T:v:V", _longOptions, &optionIndex ) ) != -1 ) - switch ( c ) - { + switch ( c ) { // ------------------------------------ case 'a': /* Serial Speed */ r->options->serial_speed = atoi( optarg ); @@ -234,34 +224,28 @@ static int _processOptions( struct RunTime *r, int argc, char *argv[] ) channel = OrbtraceIfNameToChannel( optarg ); a = optarg; - while ( ( *a ) && ( *a != ',' ) ) - { + while ( ( *a ) && ( *a != ',' ) ) { a++; } - if ( ( *a == ',' ) || ( channel != CH_NONE ) ) - { + if ( ( *a == ',' ) || ( channel != CH_NONE ) ) { a++; action = ( ( *a == '1' ) || ( !strcasecmp( "on", a ) ) ); - if ( action || ( *a == '0' ) || ( !strcasecmp( "off", a ) ) ) - { - if ( channel == CH_VTREF ) - { + if ( action || ( *a == '0' ) || ( !strcasecmp( "off", a ) ) ) { + if ( channel == CH_VTREF ) { r->options->TRefEN = action; _set_action( r, ACTION_ENCHANGE_VTREF ); break; } - if ( channel == CH_VTPWR ) - { + if ( channel == CH_VTPWR ) { r->options->TPwrEN = action; _set_action( r, ACTION_ENCHANGE_VTPWR ); break; } - if ( channel == CH_ALL ) - { + if ( channel == CH_ALL ) { r->options->TPwrEN = r->options->TRefEN = action; _set_action( r, ACTION_ENCHANGE_ALL ); break; @@ -312,16 +296,11 @@ static int _processOptions( struct RunTime *r, int argc, char *argv[] ) case 'T': /* Set tracewidth */ r->options->traceWidth = 0; - if ( ( *optarg == 'u' ) && ( !*( optarg + 1 ) ) ) - { + if ( ( *optarg == 'u' ) && ( !*( optarg + 1 ) ) ) { r->options->swoUART = true; - } - else if ( ( *optarg == 'm' ) && ( !*( optarg + 1 ) ) ) - { + } else if ( ( *optarg == 'm' ) && ( !*( optarg + 1 ) ) ) { r->options->swoMANCH = true; - } - else - { + } else { r->options->traceWidth = atoi( optarg ); } @@ -333,25 +312,21 @@ static int _processOptions( struct RunTime *r, int argc, char *argv[] ) channel = OrbtraceIfNameToChannel( optarg ); a = optarg; - while ( ( *a ) && ( *a != ',' ) ) - { + while ( ( *a ) && ( *a != ',' ) ) { a++; } - if ( ( *a == ',' ) && ( channel != CH_NONE ) ) - { + if ( ( *a == ',' ) && ( channel != CH_NONE ) ) { a++; voltage = atof( a ); - if ( channel == CH_VTREF ) - { + if ( channel == CH_VTREF ) { r->options->TRefmv = ( int )( ( voltage + 0.0005F ) * 1000 ); _set_action( r, ACTION_VCHANGE_VTREF ); break; } - if ( channel == CH_VTPWR ) - { + if ( channel == CH_VTPWR ) { r->options->TPwrmv = ( int )( ( voltage + 0.0005F ) * 1000 ); _set_action( r, ACTION_VCHANGE_VTPWR ); break; @@ -375,13 +350,12 @@ static int _processOptions( struct RunTime *r, int argc, char *argv[] ) // ------------------------------------ case 'v': - if ( !isdigit( *optarg ) ) - { + if ( !isdigit( *optarg ) ) { genericsReport( V_ERROR, "-v requires a numeric argument." EOL ); return false; } - genericsSetReportLevel( atoi( optarg ) ); + genericsSetReportLevel( ( enum verbLevel )atoi( optarg ) ); break; // ------------------------------------ @@ -404,12 +378,9 @@ static int _processOptions( struct RunTime *r, int argc, char *argv[] ) // ------------------------------------ case '?': - if ( optopt == 'b' ) - { + if ( optopt == 'b' ) { genericsReport( V_ERROR, "Option '%c' requires an argument." EOL, optopt ); - } - else if ( !isprint ( optopt ) ) - { + } else if ( !isprint ( optopt ) ) { genericsReport( V_ERROR, "Unknown option character `\\x%x'." EOL, optopt ); } @@ -423,29 +394,25 @@ static int _processOptions( struct RunTime *r, int argc, char *argv[] ) } /* Test parameters for sanity */ - if ( _tst_action( r, ACTION_RESET_PARAMS ) && ( _num_actions( r ) > 1 ) ) - { + if ( _tst_action( r, ACTION_RESET_PARAMS ) && ( _num_actions( r ) > 1 ) ) { genericsReport( V_ERROR, "Resetting parameters is an exclusive operation" EOL ); return false; } if ( ( ( r->options->serial_speed ) && ( !r->options->swoUART ) ) && - ( ( !r->options->serial_speed ) && ( r->options->swoUART ) ) ) - { + ( ( !r->options->serial_speed ) && ( r->options->swoUART ) ) ) { genericsReport( V_ERROR, "For SWO/UART both baudrate and mode need to be set" EOL ); return false; } if ( ( _tst_action( r, ACTION_SET_TRACE ) ) && - ( ( ( r->options->traceWidth ) && ( ( r->options->swoUART ) || ( r->options->swoMANCH ) ) ) || - ( ( r->options->swoUART ) && ( r->options->swoMANCH ) ) ) ) - { + ( ( ( r->options->traceWidth ) && ( ( r->options->swoUART ) || ( r->options->swoMANCH ) ) ) || + ( ( r->options->swoUART ) && ( r->options->swoMANCH ) ) ) ) { genericsReport( V_ERROR, "Only one trace configuration can be set at the same time" EOL ); return false; } - if ( _tst_action( r, ACTION_LIST_DEVICES ) && ( ( _num_actions( r ) > 1 ) ) ) - { + if ( _tst_action( r, ACTION_LIST_DEVICES ) && ( ( _num_actions( r ) > 1 ) ) ) { genericsReport( V_ERROR, "Listing devices is an exclusive operation" EOL ); return false; } @@ -453,14 +420,12 @@ static int _processOptions( struct RunTime *r, int argc, char *argv[] ) if ( ( r->options->traceWidth != 0 ) && ( r->options->traceWidth != 1 ) && ( r->options->traceWidth != 2 ) && - ( r->options->traceWidth != 4 ) ) - { + ( r->options->traceWidth != 4 ) ) { genericsReport( V_ERROR, "Orbtrace interface illegal port width" EOL ); return false; } - if ( _tst_action( r, ACTION_BRIGHTNESS ) && ( ( r->options->brightness < 0 ) || ( r->options->brightness > 255 ) ) ) - { + if ( _tst_action( r, ACTION_BRIGHTNESS ) && ( ( r->options->brightness < 0 ) || ( r->options->brightness > 255 ) ) ) { genericsReport( V_ERROR, "Brightness setting out of range" EOL ); return false; } @@ -488,158 +453,118 @@ static int _performActions( struct RunTime *r ) /* Beware, there is a logic to the order of actions...think before you change them or insert new ones */ // ----------------------------------------------------------------------------------- - if ( _tst_action( r, ACTION_UNLOCK ) ) - { + if ( _tst_action( r, ACTION_UNLOCK ) ) { } // ----------------------------------------------------------------------------------- - if ( _tst_action( r, ACTION_RESET_PARAMS ) ) - { + if ( _tst_action( r, ACTION_RESET_PARAMS ) ) { } // ----------------------------------------------------------------------------------- - if ( _tcl_action( r, ACTION_VCHANGE_VTREF ) ) - { + if ( _tcl_action( r, ACTION_VCHANGE_VTREF ) ) { genericsReport( V_INFO, "Setting VTRef %d.%03dV : ", r->options->TRefmv / 1000, r->options->TRefmv % 1000 ); - if ( OrbtraceIfVoltage( r->dev, CH_VTREF, r->options->TRefmv ) ) - { + if ( OrbtraceIfVoltage( r->dev, CH_VTREF, r->options->TRefmv ) ) { genericsReport( V_INFO, "OK" EOL ); - } - else - { + } else { genericsReport( V_ERROR, "Setting VTRef failed" EOL ); retVal |= -1; } } // ----------------------------------------------------------------------------------- - if ( _tcl_action( r, ACTION_VCHANGE_VTPWR ) ) - { + if ( _tcl_action( r, ACTION_VCHANGE_VTPWR ) ) { genericsReport( V_INFO, "Setting VTPwr %d.%03dV : ", r->options->TPwrmv / 1000, r->options->TPwrmv % 1000 ); - if ( OrbtraceIfVoltage( r->dev, CH_VTPWR, r->options->TPwrmv ) ) - { + if ( OrbtraceIfVoltage( r->dev, CH_VTPWR, r->options->TPwrmv ) ) { genericsReport( V_INFO, "OK" EOL ); - } - else - { + } else { genericsReport( V_ERROR, "Setting VTPwr failed" EOL ); retVal |= -1; } } // ----------------------------------------------------------------------------------- - if ( _tcl_action( r, ACTION_ENCHANGE_VTREF ) ) - { + if ( _tcl_action( r, ACTION_ENCHANGE_VTREF ) ) { genericsReport( V_INFO, "VTRef %s : ", r->options->TRefEN ? "On" : "Off" ); - if ( OrbtraceIfSetVoltageEn( r->dev, CH_VTREF, r->options->TRefEN ) ) - { + if ( OrbtraceIfSetVoltageEn( r->dev, CH_VTREF, r->options->TRefEN ) ) { genericsReport( V_INFO, "OK" EOL ); - } - else - { + } else { genericsReport( V_ERROR, "Changing VTRef state failed" EOL ); retVal |= -1; } } // ----------------------------------------------------------------------------------- - if ( _tcl_action( r, ACTION_ENCHANGE_ALL ) ) - { + if ( _tcl_action( r, ACTION_ENCHANGE_ALL ) ) { genericsReport( V_INFO, "All Channels %s : ", r->options->TRefEN ? "On" : "Off" ); - if ( OrbtraceIfSetVoltageEn( r->dev, CH_ALL, r->options->TRefEN ) ) - { + if ( OrbtraceIfSetVoltageEn( r->dev, CH_ALL, r->options->TRefEN ) ) { genericsReport( V_INFO, "OK" EOL ); - } - else - { + } else { genericsReport( V_ERROR, "Changing all power channel states failed" EOL ); retVal |= -1; } } // ----------------------------------------------------------------------------------- - if ( _tcl_action( r, ACTION_ENCHANGE_VTPWR ) ) - { + if ( _tcl_action( r, ACTION_ENCHANGE_VTPWR ) ) { genericsReport( V_INFO, "VTPwr %s : ", r->options->TPwrEN ? "On" : "Off" ); - if ( OrbtraceIfSetVoltageEn( r->dev, CH_VTPWR, r->options->TPwrEN ) ) - { + if ( OrbtraceIfSetVoltageEn( r->dev, CH_VTPWR, r->options->TPwrEN ) ) { genericsReport( V_INFO, "OK" EOL ); - } - else - { + } else { genericsReport( V_ERROR, "Changing VTPwr state failed" EOL ); retVal |= -1; } } // ----------------------------------------------------------------------------------- - if ( _tst_action( r, ACTION_BRIGHTNESS ) ) - { + if ( _tst_action( r, ACTION_BRIGHTNESS ) ) { } // ----------------------------------------------------------------------------------- - if ( _tst_action( r, ACTION_SN ) ) - { + if ( _tst_action( r, ACTION_SN ) ) { } // ----------------------------------------------------------------------------------- - if ( _tst_action( r, ACTION_READ_PARAMS ) ) - { + if ( _tst_action( r, ACTION_READ_PARAMS ) ) { } // ----------------------------------------------------------------------------------- - if ( _tst_action( r, ACTION_SETNICK ) ) - { + if ( _tst_action( r, ACTION_SETNICK ) ) { } // ----------------------------------------------------------------------------------- - if ( _tcl_action( r, ACTION_SERIAL_SPEED ) ) - { + if ( _tcl_action( r, ACTION_SERIAL_SPEED ) ) { genericsReport( V_INFO, "Setting baudrate to %d bps" EOL, r->options->serial_speed ); - if ( OrbtraceIfSetSWOBaudrate( r->dev, r->options->serial_speed ) ) - { + if ( OrbtraceIfSetSWOBaudrate( r->dev, r->options->serial_speed ) ) { genericsReport( V_INFO, "OK" EOL ); - } - else - { + } else { genericsReport( V_ERROR, "Setting serial speed failed" EOL ); retVal |= -1; } } // ----------------------------------------------------------------------------------- - if ( _tcl_action( r, ACTION_SET_TRACE ) ) - { - if ( r->options->traceWidth ) - { + if ( _tcl_action( r, ACTION_SET_TRACE ) ) { + if ( r->options->traceWidth ) { genericsReport( V_INFO, "Setting port width to %d" EOL, r->options->traceWidth ); - if ( OrbtraceIfSetTraceWidth( r->dev, r->options->traceWidth ) ) - { + if ( OrbtraceIfSetTraceWidth( r->dev, r->options->traceWidth ) ) { genericsReport( V_INFO, "OK" EOL ); - } - else - { + } else { genericsReport( V_ERROR, "Setting port width failed" EOL ); retVal |= -1; } - } - else if ( ( r->options->swoMANCH ) || ( r->options->swoUART ) ) - { + } else if ( ( r->options->swoMANCH ) || ( r->options->swoUART ) ) { genericsReport( V_INFO, "Setting SWO with %s encoding" EOL, r->options->swoMANCH ? "Manchester" : "UART" ); - if ( OrbtraceIfSetTraceSWO( r->dev, r->options->swoMANCH ) ) - { + if ( OrbtraceIfSetTraceSWO( r->dev, r->options->swoMANCH ) ) { genericsReport( V_INFO, "OK" EOL ); - } - else - { + } else { genericsReport( V_ERROR, "Setting SWO encoding failed" EOL ); retVal |= -1; } @@ -647,13 +572,11 @@ static int _performActions( struct RunTime *r ) } // ----------------------------------------------------------------------------------- - if ( _tst_action( r, ACTION_WRITE_PARAMS ) ) - { + if ( _tst_action( r, ACTION_WRITE_PARAMS ) ) { } // ----------------------------------------------------------------------------------- - if ( _tst_action( r, ACTION_LOCKDEVICE ) ) - { + if ( _tst_action( r, ACTION_LOCKDEVICE ) ) { } return retVal; @@ -665,8 +588,7 @@ int main( int argc, char *argv[] ) int selection = 0; int retVal = 0; - if ( !_processOptions( &_r, argc, argv ) ) - { + if ( !_processOptions( &_r, argc, argv ) ) { /* processOptions generates its own error messages */ genericsExit( -1, "" EOL ); } @@ -677,8 +599,7 @@ int main( int argc, char *argv[] ) atexit( _doExit ); /* This ensures the atexit gets called */ - if ( SIG_ERR == signal( SIGINT, _intHandler ) ) - { + if ( SIG_ERR == signal( SIGINT, _intHandler ) ) { genericsExit( -1, "Failed to establish Int handler" EOL ); } @@ -688,36 +609,27 @@ int main( int argc, char *argv[] ) _r.ndevices = OrbtraceIfGetDeviceList( _r.dev, _r.options->sn, DEVTYPE( DEVICE_ORBTRACE_MINI ) ); - if ( !_r.ndevices ) - { + if ( !_r.ndevices ) { genericsReport( V_ERROR, "No devices found" EOL ); - } - else - { + } else { /* Allow option to choose between devices if there's more than one found */ - if ( _tcl_action ( &_r, ACTION_LIST_DEVICES ) ) - { + if ( _tcl_action ( &_r, ACTION_LIST_DEVICES ) ) { OrbtraceIfListDevices( _r.dev ); - } - else - { + } else { selection = OrbtraceIfSelectDevice( _r.dev ); - if ( _num_actions( &_r ) ) - { + if ( _num_actions( &_r ) ) { genericsReport( V_INFO, "Got device [%s %s, S/N %s]" EOL, OrbtraceIfGetManufacturer( _r.dev, selection ), OrbtraceIfGetProduct( _r.dev, selection ), OrbtraceIfGetSN( _r.dev, selection ) ); - if ( !OrbtraceIfOpenDevice( _r.dev, selection ) ) - { + if ( !OrbtraceIfOpenDevice( _r.dev, selection ) ) { genericsExit( -1, "Couldn't open device" EOL ); } /* Check voltages now we know what interface we're connected to */ - if ( !_checkVoltages( &_r ) ) - { + if ( !_checkVoltages( &_r ) ) { genericsExit( -2, "Specified interface voltage check failed" EOL ); } diff --git a/Src/orbtraceIf.c b/Src/orbtraceIf.c index d24a1961..8bed4c2f 100644 --- a/Src/orbtraceIf.c +++ b/Src/orbtraceIf.c @@ -15,8 +15,7 @@ #include "generics.h" /* List of device VID/PID pairs this library works with */ -static const struct OrbtraceInterfaceType _validDevices[DEVICE_NUM_DEVICES] = -{ +static const struct OrbtraceInterfaceType _validDevices[DEVICE_NUM_DEVICES] = { { 0x1209, 0x3443, DEVICE_ORBTRACE_MINI }, { 0x1d50, 0x6018, DEVICE_BMP}, { 0, 0 } @@ -48,12 +47,10 @@ static const struct OrbtraceInterfaceType _validDevices[DEVICE_NUM_DEVICES] = /* String on front of version number to remove */ #define VERSION_FRONTMATTER "Version: " -static const struct -{ +static const struct { const char *name; const int num; -} _powerNames[] = -{ +} _powerNames[] = { POWERNAMES }; @@ -66,31 +63,25 @@ static void _flushDeviceList( struct OrbtraceIf *o ) /* Flush out any old device records */ { - for ( size_t i = 0; i < o->numDevices; i++ ) - { - if ( o->devices[i].sn ) - { + for ( size_t i = 0; i < o->numDevices; i++ ) { + if ( o->devices[i].sn ) { free( o->devices[i].sn ); } - if ( o->devices[i].manufacturer ) - { + if ( o->devices[i].manufacturer ) { free( o->devices[i].manufacturer ); } - if ( o->devices[i].product ) - { + if ( o->devices[i].product ) { free( o->devices[i].product ); } - if ( o->devices[i].version ) - { + if ( o->devices[i].version ) { free( o->devices[i].version ); } } - if ( o->devices ) - { + if ( o->devices ) { free( o->devices ); } @@ -103,13 +94,11 @@ static int _strcmpint( char *s1, char *s2 ) /* Version of strcmp that accomodates NULLs */ { - if ( ( s1 ) && ( !s2 ) ) - { + if ( ( s1 ) && ( !s2 ) ) { return -1; } - if ( ( !s1 ) && ( s2 ) ) - { + if ( ( !s1 ) && ( s2 ) ) { return 1; } @@ -125,23 +114,19 @@ static int _compareFunc( const void *vd1, const void *vd2 ) const struct OrbtraceIfDevice *d2 = ( const struct OrbtraceIfDevice * )vd2; int r = 0; - if ( ( r = _strcmpint( d1->manufacturer, d2->manufacturer ) ) ) - { + if ( ( r = _strcmpint( d1->manufacturer, d2->manufacturer ) ) ) { return r; } - if ( ( r = _strcmpint( d1->product, d2->product ) ) ) - { + if ( ( r = _strcmpint( d1->product, d2->product ) ) ) { return r; } - if ( ( r = strcmp( d1->sn, d2->sn ) ) ) - { + if ( ( r = strcmp( d1->sn, d2->sn ) ) ) { return r; } - if ( ( r = d1->vid - d2->vid ) ) - { + if ( ( r = d1->vid - d2->vid ) ) { return r; } @@ -154,18 +139,14 @@ uint16_t _getInterface( struct OrbtraceIf *o, char intType, int *nameIndex ) struct libusb_config_descriptor *config; int iface = NO_INTERFACE; - if ( ( libusb_get_active_config_descriptor( o->dev, &config ) ) >= 0 ) - { - for ( int if_num = 0; if_num < config->bNumInterfaces; if_num++ ) - { + if ( ( libusb_get_active_config_descriptor( o->dev, &config ) ) >= 0 ) { + for ( int if_num = 0; if_num < config->bNumInterfaces; if_num++ ) { const struct libusb_interface_descriptor *i = &config->interface[if_num].altsetting[0]; - if ( ( i->bInterfaceClass == 0xff ) && ( i->bInterfaceSubClass == intType ) ) - { + if ( ( i->bInterfaceClass == 0xff ) && ( i->bInterfaceSubClass == intType ) ) { iface = i->bInterfaceNumber; - if ( nameIndex != NULL ) - { + if ( nameIndex != NULL ) { /* Return the name index of this interface too */ *nameIndex = i->iInterface; } @@ -182,20 +163,17 @@ uint16_t _getInterface( struct OrbtraceIf *o, char intType, int *nameIndex ) static bool _doInterfaceControlTransfer( struct OrbtraceIf *o, uint8_t interface, uint16_t request, uint16_t value, uint8_t indexUpperHalf, uint8_t dlen, void *data ) { - if ( !o->handle ) - { + if ( !o->handle ) { return false; } - if ( interface == ( uint8_t )NO_INTERFACE ) - { + if ( interface == ( uint8_t )NO_INTERFACE ) { return false; } #ifdef WIN32 - if ( libusb_claim_interface( o->handle, interface ) != 0 ) - { + if ( libusb_claim_interface( o->handle, interface ) != 0 ) { return false; } @@ -207,15 +185,14 @@ static bool _doInterfaceControlTransfer( struct OrbtraceIf *o, uint8_t interface request, value, ( indexUpperHalf << 8 ) | interface, - data, + ( unsigned char * )data, dlen, 0 ) >= 0; #ifdef WIN32 - if ( libusb_release_interface( o->handle, interface ) != 0 ) - { + if ( libusb_release_interface( o->handle, interface ) != 0 ) { return false; } @@ -240,13 +217,10 @@ struct OrbtraceIf *OrbtraceIfCreateContext( void ) { struct OrbtraceIf *o = ( struct OrbtraceIf * )calloc( 1, sizeof( struct OrbtraceIf ) ); - if ( libusb_init( &o->context ) < 0 ) - { + if ( libusb_init( &o->context ) < 0 ) { free( o ); return NULL; - } - else - { + } else { // libusb_set_debug(o->context, LIBUSB_LOG_LEVEL_DEBUG); return o; } @@ -256,8 +230,7 @@ struct OrbtraceIf *OrbtraceIfCreateContext( void ) void OrbtraceIfDestroyContext( struct OrbtraceIf *o ) { - if ( o ) - { + if ( o ) { libusb_exit( o->context ); } } @@ -280,15 +253,13 @@ int OrbtraceIfGetDeviceList( struct OrbtraceIf *o, char *sn, uint32_t devmask ) /* Flush out any old scans we might be holding */ _flushDeviceList( o ); - if ( o->list ) - { + if ( o->list ) { libusb_free_device_list( o->list, true ); } int count = libusb_get_device_list( o->context, &o->list ); - for ( size_t i = 0; i < count; i++ ) - { + for ( int i = 0; i < count; i++ ) { o->dev = o->list[i]; struct libusb_device_descriptor desc = { 0 }; libusb_get_device_descriptor( o->dev, &desc ); @@ -298,45 +269,38 @@ int OrbtraceIfGetDeviceList( struct OrbtraceIf *o, char *sn, uint32_t devmask ) ( ( _validDevices[y].vid != desc.idVendor ) || ( _validDevices[y].pid != desc.idProduct ) ) ); y++ ); /* If it's one we're interested in then process further */ - if ( _validDevices[y].vid ) - { + if ( _validDevices[y].vid ) { /* We'll store this match for access later */ - o->devices = realloc( o->devices, ( o->numDevices + 1 ) * sizeof( struct OrbtraceIfDevice ) ); + o->devices = ( struct OrbtraceIfDevice * )realloc( o->devices, ( o->numDevices + 1 ) * sizeof( struct OrbtraceIfDevice ) ); d = &o->devices[o->numDevices]; memset( d, 0, sizeof( struct OrbtraceIfDevice ) ); d->devtype = _validDevices[y].devtype; - if ( !libusb_open( o->list[i], &o->handle ) ) - { - if ( desc.iSerialNumber ) - { + if ( !libusb_open( o->list[i], &o->handle ) ) { + if ( desc.iSerialNumber ) { libusb_get_string_descriptor_ascii( o->handle, desc.iSerialNumber, ( unsigned char * )tfrString, MAX_USB_DESC_LEN ); } /* This is a match if no S/N match was requested or if there is a S/N and they part-match, and it's a matching devtype */ - if ( ( devmask & ( 1 << d->devtype ) ) && ( ( !sn ) || ( ( desc.iSerialNumber ) && ( strstr( tfrString, sn ) ) ) ) ) - { + if ( ( devmask & ( 1 << d->devtype ) ) && ( ( !sn ) || ( ( desc.iSerialNumber ) && ( strstr( tfrString, sn ) ) ) ) ) { /* We will keep this one! */ o->numDevices++; d->sn = strdup( desc.iSerialNumber ? tfrString : "" ); - if ( desc.iManufacturer ) - { + if ( desc.iManufacturer ) { libusb_get_string_descriptor_ascii( o->handle, desc.iManufacturer, ( unsigned char * )tfrString, MAX_USB_DESC_LEN ); } d->manufacturer = strdup( desc.iManufacturer ? tfrString : "" ); - if ( desc.iProduct ) - { + if ( desc.iProduct ) { libusb_get_string_descriptor_ascii( o->handle, desc.iProduct, ( unsigned char * )tfrString, MAX_USB_DESC_LEN ); } d->product = strdup( desc.iProduct ? tfrString : "" ); d->devIndex = i; - switch ( d->devtype ) - { + switch ( d->devtype ) { case DEVICE_ORBTRACE_MINI: d->powerIf = _getInterface( o, 'P', NULL ); d->traceIf = _getInterface( o, 'T', NULL ); @@ -344,14 +308,11 @@ int OrbtraceIfGetDeviceList( struct OrbtraceIf *o, char *sn, uint32_t devmask ) /* Collect the probe version from the version interface */ d->versionIf = _getInterface( o, 'V', &versionIndex ); - if ( versionIndex ) - { + if ( versionIndex ) { libusb_get_string_descriptor_ascii( o->handle, versionIndex, ( unsigned char * )tfrString, MAX_USB_DESC_LEN ); /* If string contains 'Version: ' at the start then remove it */ d->version = strdup( ( strstr( tfrString, VERSION_FRONTMATTER ) ) ? &tfrString[strlen( VERSION_FRONTMATTER )] : "" ); - } - else - { + } else { d->version = strdup( "" ); } @@ -361,8 +322,7 @@ int OrbtraceIfGetDeviceList( struct OrbtraceIf *o, char *sn, uint32_t devmask ) /* On BMP version and serial are merged, so let's unmerge them by making the last word of the product the version */ d->version = &d->product[strlen( d->product ) - 1]; - while ( ( !isspace( *d->version ) ) && ( d->version != d->product ) ) - { + while ( ( !isspace( *d->version ) ) && ( d->version != d->product ) ) { d->version--; } @@ -395,10 +355,10 @@ void OrbtraceIfListDevices( struct OrbtraceIf *o ) genericsPrintf( C_RESET " Id | Description | Serial | Version" EOL ); genericsPrintf( " ---+------------------------------------------+------------------+----------------------------" EOL ); - for ( int i = 0; i < o->numDevices; i++ ) - { + for ( unsigned int i = 0; i < o->numDevices; i++ ) { snprintf( printConstruct, SCRATCH_STRINGLEN, "%s %s", OrbtraceIfGetManufacturer( o, i ), OrbtraceIfGetProduct( o, i ) ) ; - genericsPrintf( C_SEL " %2d " C_RESET "|"C_ELEMENT" %-40s "C_RESET"|"C_ELEMENT" %16s "C_RESET"|"C_ELEMENT" %s" C_RESET EOL, + genericsPrintf( C_SEL " %2d " C_RESET "|" C_ELEMENT " %-40s " C_RESET "|" + C_ELEMENT " %16s " C_RESET "|" C_ELEMENT " %s" C_RESET EOL, i + 1, printConstruct, OrbtraceIfGetSN( o, i ), OrbtraceIfGetVersion( o, i ) ); } } @@ -407,16 +367,14 @@ void OrbtraceIfListDevices( struct OrbtraceIf *o ) int OrbtraceIfSelectDevice( struct OrbtraceIf *o ) { - int selection = o->numDevices; + unsigned int selection = o->numDevices; - if ( o->numDevices > 1 ) - { + if ( o->numDevices > 1 ) { OrbtraceIfListDevices( o ); selection = 0; - while ( ( selection < 1 ) || ( selection > o->numDevices ) ) - { + while ( ( selection < 1 ) || ( selection > o->numDevices ) ) { genericsPrintf( EOL C_SEL "Selection>" C_RESET ); scanf( "%d", &selection ); } @@ -425,18 +383,16 @@ int OrbtraceIfSelectDevice( struct OrbtraceIf *o ) return selection - 1; } // ==================================================================================================== -bool OrbtraceIfOpenDevice( struct OrbtraceIf *o, int entry ) +bool OrbtraceIfOpenDevice( struct OrbtraceIf *o, unsigned int entry ) { - if ( ( entry < 0 ) || ( entry >= o->numDevices ) ) - { + if ( ( entry < 0 ) || ( entry >= o->numDevices ) ) { return false; } o->dev = o->list[ o->devices[entry].devIndex]; - if ( libusb_open( o->dev, &o->handle ) ) - { + if ( libusb_open( o->dev, &o->handle ) ) { o->dev = NULL; o->handle = NULL; return false; @@ -453,14 +409,12 @@ bool OrbtraceGetIfandEP( struct OrbtraceIf *o ) uint8_t num_altsetting = 0; int32_t err; - if ( ( !o->dev ) || ( !o->handle ) ) - { + if ( ( !o->dev ) || ( !o->handle ) ) { return false; } /* For the BMP case we can quickly return the correct values */ - switch ( o->devices[o->activeDevice].devtype ) - { + switch ( o->devices[o->activeDevice].devtype ) { default: // ------------------------------------------------------------------------------------- return false; @@ -473,8 +427,7 @@ bool OrbtraceGetIfandEP( struct OrbtraceIf *o ) genericsReport( V_DEBUG, "Searching for trace interface" EOL ); struct libusb_config_descriptor *config; - if ( ( err = libusb_get_active_config_descriptor( o->dev, &config ) ) < 0 ) - { + if ( ( err = libusb_get_active_config_descriptor( o->dev, &config ) ) < 0 ) { genericsReport( V_WARN, "Failed to get config descriptor (%d)" EOL, err ); return false; } @@ -482,18 +435,15 @@ bool OrbtraceGetIfandEP( struct OrbtraceIf *o ) /* Loop through the interfaces looking for ours */ bool interface_found = false; - for ( int if_num = 0; if_num < config->bNumInterfaces && !interface_found; if_num++ ) - { - for ( int alt_num = 0; alt_num < config->interface[if_num].num_altsetting && !interface_found; alt_num++ ) - { + for ( int if_num = 0; if_num < config->bNumInterfaces && !interface_found; if_num++ ) { + for ( int alt_num = 0; alt_num < config->interface[if_num].num_altsetting && !interface_found; alt_num++ ) { const struct libusb_interface_descriptor *i = &config->interface[if_num].altsetting[alt_num]; if ( i->bInterfaceClass != 0xff || i->bInterfaceSubClass != 0x54 || ( i->bInterfaceProtocol != 0x00 && i->bInterfaceProtocol != 0x01 ) || - i->bNumEndpoints != 0x01 ) - { + i->bNumEndpoints != 0x01 ) { /* Not the interface we're looking for */ continue; } @@ -511,8 +461,7 @@ bool OrbtraceGetIfandEP( struct OrbtraceIf *o ) libusb_free_config_descriptor( config ); - if ( !interface_found ) - { + if ( !interface_found ) { genericsReport( V_DEBUG, "No supported interfaces found" EOL ); return false; } @@ -520,14 +469,12 @@ bool OrbtraceGetIfandEP( struct OrbtraceIf *o ) break; } - if ( ( err = libusb_claim_interface ( o->handle, o->iface ) ) < 0 ) - { + if ( ( err = libusb_claim_interface ( o->handle, o->iface ) ) < 0 ) { genericsReport( V_DEBUG, "Failed to claim interface (%d)" EOL, err ); return false; } - if ( num_altsetting > 1 && ( err = libusb_set_interface_alt_setting ( o->handle, o->iface, altsetting ) ) < 0 ) - { + if ( num_altsetting > 1 && ( err = libusb_set_interface_alt_setting ( o->handle, o->iface, altsetting ) ) < 0 ) { genericsReport( V_WARN, "Failed to set altsetting (%d)" EOL, err ); return false; } @@ -546,11 +493,9 @@ bool OrbtraceIfSetupTransfers( struct OrbtraceIf *o, bool hiresTime, struct data o->numBlocks = numBlocks; o->d = d; - for ( uint32_t t = 0; t < o->numBlocks ; t++ ) - { + for ( int t = 0; t < o->numBlocks ; t++ ) { /* Allocate memory */ - if ( !o->d[t].usbtfr ) - { + if ( !o->d[t].usbtfr ) { o->d[t].usbtfr = libusb_alloc_transfer( 0 ); } @@ -562,8 +507,7 @@ bool OrbtraceIfSetupTransfers( struct OrbtraceIf *o, bool hiresTime, struct data hiresTime ? 1 : 0 /* Use timeout if hires mode */ ); - if ( libusb_submit_transfer( o->d[t].usbtfr ) ) - { + if ( libusb_submit_transfer( o->d[t].usbtfr ) ) { genericsReport( V_INFO, "Error submitting USB requests" EOL ); return false; } @@ -585,10 +529,8 @@ int OrbtraceIfHandleEvents( struct OrbtraceIf *o ) void OrbtraceIfCloseTransfers( struct OrbtraceIf *o ) { - for ( uint32_t t = 0; t < o->numBlocks; t++ ) - { - if ( o->d[t].usbtfr ) - { + for ( int32_t t = 0; t < o->numBlocks; t++ ) { + if ( o->d[t].usbtfr ) { libusb_cancel_transfer( o->d[t].usbtfr ); libusb_free_transfer( o->d[t].usbtfr ); o->d[t].usbtfr = 0; @@ -608,8 +550,7 @@ bool OrbtraceIfSetTraceWidth( struct OrbtraceIf *o, int width ) { uint16_t d = ( width != 4 ) ? width : 3; - if ( ( d < 1 ) || ( d > 3 ) ) - { + if ( ( d < 1 ) || ( d > 3 ) ) { return false; } @@ -641,7 +582,11 @@ bool OrbtraceIfSetTraceSWO( struct OrbtraceIf *o, bool isMANCH ) bool OrbtraceIfSetSWOBaudrate( struct OrbtraceIf *o, uint32_t speed ) { - uint8_t speed_le[4] = { ( speed & 0xff ), ( speed >> 8 ) & 0xff, ( speed >> 16 ) & 0xff, ( speed >> 24 ) & 0xff }; + uint8_t speed_le[4] = { ( uint8_t )( speed & 0xff ), + ( uint8_t )( ( speed >> 8 ) & 0xff ), + ( uint8_t )( ( speed >> 16 ) & 0xff ), + ( uint8_t )( ( speed >> 24 ) & 0xff ) + }; return _doInterfaceControlTransfer( o, @@ -661,15 +606,13 @@ enum Channel OrbtraceIfNameToChannel( char *x ) { int j; - for ( int i = 0; _powerNames[i].name; i++ ) - { + for ( int i = 0; _powerNames[i].name; i++ ) { char *y = x; for ( j = 0; _powerNames[i].name[j] && _powerNames[i].name[j] == tolower( *y++ ); j++ ); - if ( ( ( !*y ) || ( *y == ',' ) ) && ( !_powerNames[i].name[j] ) ) - { - return _powerNames[i].num; + if ( ( ( !*y ) || ( *y == ',' ) ) && ( !_powerNames[i].name[j] ) ) { + return ( enum Channel )_powerNames[i].num; } } @@ -679,8 +622,7 @@ enum Channel OrbtraceIfNameToChannel( char *x ) bool OrbtraceIfVoltage( struct OrbtraceIf *o, enum Channel ch, int voltage ) { - if ( ( ch >= CH_MAX ) || !OrbtraceIfValidateVoltage( o, voltage ) ) - { + if ( ( ch >= CH_MAX ) || !OrbtraceIfValidateVoltage( o, voltage ) ) { return false; } @@ -699,8 +641,7 @@ bool OrbtraceIfVoltage( struct OrbtraceIf *o, enum Channel ch, int voltage ) bool OrbtraceIfSetVoltageEn( struct OrbtraceIf *o, enum Channel ch, bool isOn ) { - if ( ( ch >= CH_MAX ) && ( ch != CH_ALL ) ) - { + if ( ( ch >= CH_MAX ) && ( ch != CH_ALL ) ) { return false; } @@ -718,8 +659,7 @@ bool OrbtraceIfSetVoltageEn( struct OrbtraceIf *o, enum Channel ch, bool isOn ) void OrbtraceIfCloseDevice( struct OrbtraceIf *o ) { - if ( o->handle ) - { + if ( o->handle ) { libusb_close( o->handle ); } diff --git a/Src/orbuculum.c b/Src/orbuculum.c index 43f0b5f8..b35b4f08 100644 --- a/Src/orbuculum.c +++ b/Src/orbuculum.c @@ -11,6 +11,8 @@ #include #include #include +#include +#include <../toml.hpp> #ifdef WIN32 #include #else @@ -34,14 +36,8 @@ #if defined LINUX #include #include - #if defined TCGETS2 - #include - /* Manual declaration to avoid conflict. */ - extern int ioctl ( int __fd, unsigned long int __request, ... ) ; - #else - #include - #include - #endif + #include + #include #elif defined WIN32 #include #else @@ -68,43 +64,44 @@ #define ORBTRACE "orbtrace" #define ORBTRACEENVNAME "ORBTRACE" +#define CONFIG_FILENAME ".orbcfg.toml" + /* Record for options, either defaults or from command line */ -struct Options -{ +struct Options { /* Config information */ bool nwserver; /* Using a nw server source */ /* Source information */ - char *nwserverHost; /* NW Server host connection */ + const char *nwserverHost; /* NW Server host connection */ int32_t nwserverPort; /* ...and port */ - char *port; /* Serial host connection */ - int speed; /* Speed of serial link */ - bool useTPIU; /* Are we using TPIU, and stripping TPIU frames? */ + const char *serialPort; /* Serial host connection */ + int serialSpeed; /* Speed of serial link */ uint32_t dataSpeed; /* Effective data speed (can be less than link speed!) */ - char *file; /* File host connection */ + const char *file; /* File host connection */ bool fileTerminate; /* Terminate when file read isn't successful */ - char *outfile; /* Output file for raw data dumping */ + const char *outfile; /* Output file for raw data dumping */ + bool run_orbtrace; /* Should we explictly run orbtrace on start */ char *otcl; /* Orbtrace command line options */ uint32_t intervalReportTime; /* If we want interval reports about performance */ bool mono; /* Supress colour in output */ int paceDelay; /* Delay between blocks of data transmission in file readout */ char *channelList; /* List of TPIU channels to be serviced */ bool hiresTime; /* Use hiresolution time (shorter timeouts...more accurate but higher load */ - char *sn; /* Any part serial number for identifying a specific device */ + const char *sn; /* Any part serial number for identifying a specific device */ + char *config; /* File containing base config, or NULL if there isn't one */ + /* Network link */ int listenPort; /* Listening port for network */ }; -struct handlers -{ +struct handlers { int channel; /* Channel number for this handler */ uint64_t intervalBytes; /* Number of depacketised bytes output on this channel */ struct dataBlock *strippedBlock; /* Processed buffers for output to clients */ struct nwclientsHandle *n; /* Link to the network client subsystem */ }; -struct RunTime -{ +struct RunTime { struct TPIUDecoder t; /* TPIU decoder instance, in case we need it */ struct OrbtraceIf *o; /* For accessing ORBTrace devices + BMPs */ @@ -139,7 +136,7 @@ struct RunTime #define SO_REUSEPORT SO_REUSEADDR #endif -#define NWSERVER_HOST "localhost" /* Address to connect to NW Server */ +#define NWSERVER_HOST "localhost" /* Address to connect to NW Server */ #define NWSERVER_PORT (2332) #define NUM_TPIU_CHANNELS 0x80 @@ -151,12 +148,8 @@ struct RunTime //#define DUMP_BLOCK -struct Options _options = -{ - .listenPort = NWCLIENT_SERVER_PORT, - .nwserverHost = NWSERVER_HOST, -}; - +/* Any non-null options will be set in the setup routine */ +struct Options _options; struct RunTime _r; // ==================================================================================================== @@ -178,8 +171,7 @@ static int _setSerialConfig ( int f, speed_t speed ) struct termios2 settings; int ret = ioctl( f, TCGETS2, &settings ); - if ( ret < 0 ) - { + if ( ret < 0 ) { return ( -3 ); } @@ -198,8 +190,7 @@ static int _setSerialConfig ( int f, speed_t speed ) ret = ioctl( f, TCSETS2, &settings ); - if ( ret < 0 ) - { + if ( ret < 0 ) { genericsReport( V_ERROR, "Unsupported baudrate" EOL ); return ( -3 ); } @@ -207,13 +198,11 @@ static int _setSerialConfig ( int f, speed_t speed ) // Check configuration is ok. ret = ioctl( f, TCGETS2, &settings ); - if ( ret < 0 ) - { + if ( ret < 0 ) { return ( -3 ); } - if ( ( settings.c_ispeed != speed ) || ( settings.c_ospeed != speed ) ) - { + if ( ( settings.c_ispeed != speed ) || ( settings.c_ospeed != speed ) ) { genericsReport( V_ERROR, "Failed to set baudrate" EOL ); return -4; } @@ -235,8 +224,7 @@ static bool _setSerialSpeed( HANDLE handle, int speed ) dcb.DCBlength = sizeof( DCB ); BOOL ok = GetCommState( handle, &dcb ); - if ( !ok ) - { + if ( !ok ) { return false; } @@ -247,8 +235,7 @@ static bool _setSerialSpeed( HANDLE handle, int speed ) ok = SetCommState( handle, &dcb ); - if ( !ok ) - { + if ( !ok ) { return false; } @@ -256,8 +243,7 @@ static bool _setSerialSpeed( HANDLE handle, int speed ) COMMTIMEOUTS timeouts; ok = GetCommTimeouts( handle, &timeouts ); - if ( !ok ) - { + if ( !ok ) { return false; } @@ -266,8 +252,7 @@ static bool _setSerialSpeed( HANDLE handle, int speed ) timeouts.ReadTotalTimeoutMultiplier = 0; ok = SetCommTimeouts( handle, &timeouts ); - if ( !ok ) - { + if ( !ok ) { return false; } @@ -283,14 +268,12 @@ static int _setSerialConfig ( int f, speed_t speed ) { struct termios settings; - if ( tcgetattr( f, &settings ) < 0 ) - { + if ( tcgetattr( f, &settings ) < 0 ) { perror( "tcgetattr" ); return ( -3 ); } - if ( cfsetspeed( &settings, speed ) < 0 ) - { + if ( cfsetspeed( &settings, speed ) < 0 ) { genericsReport( V_ERROR, "Error Setting input speed" EOL ); return ( -3 ); } @@ -303,8 +286,7 @@ static int _setSerialConfig ( int f, speed_t speed ) settings.c_cflag |= CS8 | CLOCAL; /* 8 bits */ settings.c_oflag &= ~OPOST; /* raw output */ - if ( tcsetattr( f, TCSANOW, &settings ) < 0 ) - { + if ( tcsetattr( f, TCSANOW, &settings ) < 0 ) { genericsReport( V_ERROR, "Unsupported baudrate" EOL ); return ( -3 ); } @@ -324,8 +306,7 @@ static void _doExit( void ) /* Give them a bit of time, then we're leaving anyway */ usleep( INTERVAL_100MS ); - if ( _r.opFileHandle ) - { + if ( _r.opFileHandle ) { close( _r.opFileHandle ); _r.opFileHandle = 0; } @@ -346,6 +327,7 @@ void _printHelp( const char *const progName ) { genericsPrintf( "Usage: %s [options]" EOL, progName ); genericsPrintf( " -a, --serial-speed: to use" EOL ); + genericsPrintf( " -C, --configuration: to use. Defaults to " CONFIG_FILENAME " (Set to - to avoid loading.)" EOL ); genericsPrintf( " -E, --eof: When reading from file, terminate at end of file" EOL ); genericsPrintf( " -f, --input-file: Take input from specified file" EOL ); genericsPrintf( " -h, --help: This help" EOL ); @@ -371,9 +353,9 @@ void _printVersion( void ) genericsPrintf( "orbuculum version " GIT_DESCRIBE ); } // ==================================================================================================== -static struct option _longOptions[] = -{ +static struct option _longOptions[] = { {"serial-speed", required_argument, NULL, 'a'}, + {"configuration", required_argument, NULL, 'C'}, {"eof", no_argument, NULL, 'E'}, {"input-file", required_argument, NULL, 'f'}, {"help", no_argument, NULL, 'h'}, @@ -393,30 +375,161 @@ static struct option _longOptions[] = {"version", no_argument, NULL, 'V'}, {NULL, no_argument, NULL, 0} }; + +// ==================================================================================================== +bool _getBaseConfig( int argc, char *argv[], struct RunTime *r ) + +{ +#define SHORTFORM "-C" +#define LONGFORM "--configuration=" + toml::table cfg; + + for ( int i = 0; i < argc; i++ ) { + if ( ( !strncmp( SHORTFORM, argv[i], strlen( SHORTFORM ) ) ) || ( !strncmp( LONGFORM, argv[i], strlen( LONGFORM ) ) ) ) { + if ( i < argc ) { + if ( !strncmp( SHORTFORM, argv[i], strlen( SHORTFORM ) ) ) { + r->options->config = ( argv[i][strlen( SHORTFORM )] ) ? ( &argv[i][strlen( SHORTFORM )] ) : argv[i + 1]; + } else { + r->options->config = &argv[i][strlen( LONGFORM )]; + } + } + + break; + } + } + + if ( !r->options->config ) { + r->options->config = ( char * )CONFIG_FILENAME; + } + + /* Deal with case of a space after the = in the longform, just indicate */ + if ( !r->options->config[0] ) { + r->options->config = ( char * )"-"; + } + + if ( !strncmp( "-", r->options->config, 1 ) ) { + return true; + } + + try { + cfg = toml::parse_file( r->options->config ); + } catch ( toml::parse_error &e ) { + genericsReport( V_ERROR, "%s: %s" EOL, r->options->config, e.what() ); + + if ( e.source().begin ) { + genericsReport( V_ERROR, "at line %d column %d" EOL, e.source().begin.line, e.source().begin.column ); + } + + return false; + } + + // ------------------ Source parameters ------------------------------ + r->options->serialSpeed = cfg["orbuculum"]["source"]["serial"]["speed"].value_or( 0 ); + { + auto s = cfg["orbuculum"]["source"]["serial"]["port"].value(); + r->options->serialPort = s ? strdup( s->c_str() ) : nullptr; + } + r->options->nwserverPort = cfg["orbuculum"]["source"]["server"]["port"].value_or( NWSERVER_PORT ); + { + auto s = cfg["orbuculum"]["source"]["server"]["name"].value(); + r->options->nwserverHost = strdup( s ? s->c_str() : NWSERVER_HOST ); + } + { + auto s = cfg["orbuculum"]["source"]["serial_number"].value(); + r->options->sn = s ? strdup( s->c_str() ) : NULL; + } + { + auto s = cfg["orbuculum"]["source"]["file"].value(); + r->options->file = s ? strdup( s->c_str() ) : NULL; + } + r->options->fileTerminate = cfg["orbuculum"]["source"]["exit_at_eof"].value_or( false ); + + // ------------------ Processing parameters ------------------------------ + r->options->hiresTime = cfg["orbuculum"]["processing"]["hires"].value_or( false ); + + { + auto chan = cfg.at_path( "orbuculum.processing.tpiu_channels" ); + std::string a; + + if ( chan.is_array() ) { + auto *s = chan.as_array(); + + for ( auto &&n : *s ) { + a += "," + std::to_string( n.value_or( 0 ) ); + } + + a.erase( a.begin() ); + } else if ( chan.is_integer() ) { + a = std::to_string( chan.as_integer()->value_or( 0 ) ); + } + + if ( a.length() ) { + r->options->channelList = strdup( a.c_str() ); + } + } + + // ------------------ Presentation parameters ------------------------------ + r->options->intervalReportTime = cfg["orbuculum"]["presentation"]["monitor_interval"].value_or( 0 ); + r->options->dataSpeed = cfg["orbuculum"]["presentation"]["data_speed"].value_or( 0 ); + r->options->mono = !cfg["orbuculum"]["presentation"]["colour"].value_or( true ); + genericsSetReportLevel( ( enum verbLevel )cfg["orbuculum"]["presentation"]["verbose"].value_or( 1 ) ); + r->options->run_orbtrace = cfg["orbuculum"]["presentation"]["run_orbtrace"].value_or( false ); + + // ------------------ Output parameters ------------------------------ + r->options->listenPort = cfg["orbuculum"]["output"]["port"].value_or( NWCLIENT_SERVER_PORT ); + { + auto s = cfg["orbuculum"]["output"]["file"].value(); + r->options->outfile = s ? strdup( s->c_str() ) : NULL; + } + r->options->paceDelay = cfg["orbuculum"]["output"]["pace_delay"].value_or( 0 ); + + /* We can make data Speed implicit if it's not explicitly stated */ + if ( !r->options->dataSpeed ) { + r->options->dataSpeed = r->options->serialSpeed; + } + + return true; +} + // ==================================================================================================== bool _processOptions( int argc, char *argv[], struct RunTime *r ) { int c, optionIndex = 0; + char *a; #define DELIMITER ',' - while ( ( c = getopt_long ( argc, argv, "a:Ef:hHVl:m:Mn:o:O:p:P:s:t:v:", _longOptions, &optionIndex ) ) != -1 ) - switch ( c ) - { + /* Read any file based config before command line */ + if ( !_getBaseConfig( argc, argv, &_r ) ) { + return false; + } + + optind = opterr = 0; + + while ( ( c = getopt_long ( argc, argv, ":a:C:Ef:hHVl:m:Mn:o:O:p:P:s:t:v:", _longOptions, &optionIndex ) ) != -1 ) + switch ( c ) { // ------------------------------------ case 'a': - r->options->speed = atoi( optarg ); - r->options->dataSpeed = r->options->speed; + r->options->serialSpeed = atoi( optarg ); + r->options->dataSpeed = r->options->serialSpeed; break; // ------------------------------------ + case 'C': + /* This is dealt with seperately in _getBaseConfig above, but shouldn't create an error */ + break; + // ------------------------------------ case 'E': r->options->fileTerminate = true; break; // ------------------------------------ case 'f': + if ( r->options->file ) { + free( (void*)r->options->file ); + } + r->options->file = optarg; break; @@ -436,74 +549,84 @@ bool _processOptions( int argc, char *argv[], struct RunTime *r ) return false; // ------------------------------------ - case 'l': r->options->listenPort = atoi( optarg ); break; // ------------------------------------ - case 'm': r->options->intervalReportTime = atoi( optarg ); break; // ------------------------------------ - case 'M': r->options->mono = true; break; // ------------------------------------ - case 'n': + if ( r->options->sn ) { + free( (void*)r->options->sn ); + } + r->options->sn = optarg; break; // ------------------------------------ - case 'o': + if ( r->options->outfile ) { + free( (void*)r->options->outfile ); + } + r->options->outfile = optarg; break; // ------------------------------------ - case 'O': + r->options->run_orbtrace = true; + + if ( r->options->otcl ) { + free( r->options->otcl ); + } + r->options->otcl = optarg; break; // ------------------------------------ - case 'p': - r->options->port = optarg; + if ( r->options->serialPort ) { + free( (void*)r->options->serialPort ); + } + + r->options->serialPort = optarg; break; // ------------------------------------ - case 'P': r->options->paceDelay = atoi( optarg ); break; // ------------------------------------ - case 's': + if ( r->options->nwserverHost ) { + free( (void*)r->options->nwserverHost ); + } + r->options->nwserverHost = optarg; // See if we have an optional port number too - char *a = optarg; + a = optarg; - while ( ( *a ) && ( *a != ':' ) ) - { + while ( ( *a ) && ( *a != ':' ) ) { a++; } - if ( *a == ':' ) - { + if ( *a == ':' ) { *a = 0; r->options->nwserverPort = atoi( ++a ); } - if ( !r->options->nwserverPort ) - { + if ( !r->options->nwserverPort ) { r->options->nwserverPort = NWSERVER_PORT; } @@ -511,33 +634,31 @@ bool _processOptions( int argc, char *argv[], struct RunTime *r ) // ------------------------------------ case 't': - r->options->useTPIU = true; + if ( r->options->channelList ) { + free( r->options->channelList ); + } + r->options->channelList = optarg; break; // ------------------------------------ case 'v': - if ( !isdigit( *optarg ) ) - { + if ( !isdigit( *optarg ) ) { genericsReport( V_ERROR, "-v requires a numeric argument." EOL ); return false; } - genericsSetReportLevel( atoi( optarg ) ); + genericsSetReportLevel( ( enum verbLevel )atoi( optarg ) ); break; // ------------------------------------ + case ':': + genericsReport( V_ERROR, "Option '%c' requires an argument." EOL, optopt ); + return false; + // ------------------------------------ case '?': - if ( optopt == 'b' ) - { - genericsReport( V_ERROR, "Option '%c' requires an argument." EOL, optopt ); - } - else if ( !isprint ( optopt ) ) - { - genericsReport( V_ERROR, "Unknown option character `\\x%x'." EOL, optopt ); - } - + genericsReport( V_ERROR, "Unknown option character %c." EOL, optopt ); return false; // ------------------------------------ @@ -550,91 +671,78 @@ bool _processOptions( int argc, char *argv[], struct RunTime *r ) /* ... and dump the config if we're being verbose */ genericsReport( V_INFO, "orbuculum version " GIT_DESCRIBE EOL ); - if ( r->options->intervalReportTime ) - { + genericsReport( V_INFO, "Base config in : %s" EOL, r->options->config ); + + if ( r->options->intervalReportTime ) { genericsReport( V_INFO, "Report Intv : %d mS" EOL, r->options->intervalReportTime ); } - if ( r->options->port ) - { - genericsReport( V_INFO, "Serial Port : %s" EOL, r->options->port ); + if ( r->options->serialPort ) { + genericsReport( V_INFO, "Serial Port : %s" EOL, r->options->serialPort ); } - if ( r->options->speed ) - { - genericsReport( V_INFO, "Serial Speed : %d baud" EOL, r->options->speed ); + if ( r->options->serialSpeed ) { + genericsReport( V_INFO, "Serial Speed : %d baud" EOL, r->options->serialSpeed ); } - if ( r->options->sn ) - { + if ( r->options->sn ) { genericsReport( V_INFO, "Serial Nummber : %s" EOL, r->options->sn ); } - if ( r->options->dataSpeed ) - { + if ( r->options->dataSpeed ) { genericsReport( V_INFO, "Max Data Rt : %d bps" EOL, r->options->dataSpeed ); } - if ( r->options->outfile ) - { + if ( r->options->outfile ) { genericsReport( V_INFO, "Raw Output file: %s" EOL, r->options->outfile ); } - if ( r->options->nwserverPort ) - { + if ( r->options->nwserverPort ) { genericsReport( V_INFO, "NW SERVER H&P : %s:%d" EOL, r->options->nwserverHost, r->options->nwserverPort ); } - if ( r->options->useTPIU ) - { + if ( r->options->channelList ) { genericsReport( V_INFO, "Use/Strip TPIU : True (Channel List %s)" EOL, r->options->channelList ); - } - else - { + } else { genericsReport( V_INFO, "Use/Strip TPIU : False" EOL ); } - if ( r->options->otcl ) - { - genericsReport( V_INFO, "Orbtrace CL : %s" EOL, r->options->otcl ); + if ( r->options->run_orbtrace ) { + genericsReport( V_INFO, "Run Orbtrace" EOL ); + + if ( r->options->otcl ) { + genericsReport( V_INFO, "Orbtrace CL : %s" EOL, r->options->otcl ); + } } - if ( r->options->hiresTime ) - { + if ( r->options->hiresTime ) { genericsReport( V_INFO, "High Res Time" EOL ); } - if ( r->options->file ) - { + if ( r->options->file ) { genericsReport( V_INFO, "Input File : %s" EOL, r->options->file ); genericsReport( V_INFO, "Pace Delay : %dus" EOL, r->options->paceDelay ); - if ( r->options->fileTerminate ) - { + if ( r->options->fileTerminate ) { genericsReport( V_INFO, " (Terminate on exhaustion)" EOL ); - } - else - { + } else { genericsReport( V_INFO, " (Ongoing read)" EOL ); } } - if ( ( r->options->file ) && ( ( r->options->port ) || ( r->options->nwserverPort ) ) ) - { - genericsReport( V_ERROR, "Cannot specify file and port or NW Server at same time" EOL ); + if ( ( r->options->file ) && ( ( r->options->serialPort ) || ( r->options->nwserverPort ) ) ) { + genericsReport( V_ERROR, "Cannot specify file and serial port or NW Server at same time" EOL ); return false; } - if ( ( r->options->paceDelay ) && ( !r->options->file ) ) - { + if ( ( r->options->paceDelay ) && ( !r->options->file ) ) { genericsReport( V_ERROR, "Pace Delay only makes sense when input is from a file" EOL ); return false; } - if ( ( r->options->port ) && ( r->options->nwserverPort ) ) - { - genericsReport( V_ERROR, "Cannot specify port and NW Server at same time" EOL ); + if ( ( r->options->serialPort ) && ( r->options->nwserverPort ) ) { + genericsReport( V_ERROR, "Cannot specify serial port and NW Server at same time" EOL ); return false; } @@ -650,8 +758,7 @@ void *_checkInterval( void *params ) uint64_t snapInterval; struct handlers *h; - while ( !r->ending ) - { + while ( !r->ending ) { usleep( r->options->intervalReportTime * INTERVAL_1MS ); /* Grab the interval and scale to 1 second */ @@ -659,30 +766,22 @@ void *_checkInterval( void *params ) snapInterval *= 8; - if ( r->conn ) - { + if ( r->conn ) { genericsPrintf( C_PREV_LN C_CLR_LN C_DATA ); - if ( snapInterval / 1000000 ) - { + if ( snapInterval / 1000000 ) { genericsPrintf( "%4d.%d " C_RESET "MBits/sec ", snapInterval / 1000000, ( snapInterval * 1 / 100000 ) % 10 ); - } - else if ( snapInterval / 1000 ) - { + } else if ( snapInterval / 1000 ) { genericsPrintf( "%4d.%d " C_RESET "KBits/sec ", snapInterval / 1000, ( snapInterval / 100 ) % 10 ); - } - else - { + } else { genericsPrintf( " %4d " C_RESET " Bits/sec ", snapInterval ); } h = r->handler; uint64_t totalDat = 0; - if ( ( r->intervalBytes ) && ( r->options->useTPIU ) ) - { - for ( int chIndex = 0; chIndex < r->numHandlers; chIndex++ ) - { + if ( ( r->intervalBytes ) && ( r->options->channelList ) ) { + for ( int chIndex = 0; chIndex < r->numHandlers; chIndex++ ) { genericsPrintf( " %d:%3d%% ", h->channel, ( h->intervalBytes * 100 ) / r->intervalBytes ); totalDat += h->intervalBytes; /* TODO: This needs a mutex */ @@ -696,8 +795,7 @@ void *_checkInterval( void *params ) r->intervalBytes = 0; - if ( r->options->dataSpeed > 100 ) - { + if ( r->options->dataSpeed > 100 ) { /* Conversion to percentage done as a division to avoid overflow */ uint32_t fullPercent = ( snapInterval * 100 ) / r->options->dataSpeed; genericsPrintf( "(" C_DATA " %3d%% " C_RESET "full)", ( fullPercent > 100 ) ? 100 : fullPercent ); @@ -715,15 +813,12 @@ static void _purgeBlock( struct RunTime *r ) { /* Now send any packets to clients who want it */ - if ( r->options->useTPIU ) - { + if ( r->options->channelList ) { struct handlers *h = r->handler; int i = r->numHandlers; - while ( i-- ) - { - if ( h->strippedBlock->fillLevel ) - { + while ( i-- ) { + if ( h->strippedBlock->fillLevel ) { nwclientSend( h->n, h->strippedBlock->fillLevel, h->strippedBlock->buffer, ( r->options->file != NULL ) ); h->intervalBytes += h->strippedBlock->fillLevel; h->strippedBlock->fillLevel = 0; @@ -745,25 +840,20 @@ static void _TPIUpacketRxed( enum TPIUPumpEvent e, struct TPIUPacket *p, void *p int cachedChannel = -1; int chIndex = 0; - switch ( e ) - { + switch ( e ) { case TPIU_EV_RXEDPACKET: /* Iterate through the packet, putting it into the correct output buffers */ - for ( uint32_t g = 0; g < p->len; g++ ) - { - if ( cachedChannel != p->packet[g].s ) - { + for ( uint32_t g = 0; g < p->len; g++ ) { + if ( cachedChannel != p->packet[g].s ) { /* Whatever happens, cache this result */ cachedChannel = p->packet[g].s; /* Search for channel */ h = r->handler; - for ( chIndex = 0; chIndex < r->numHandlers; chIndex++ ) - { - if ( h->channel == p->packet[g].s ) - { + for ( chIndex = 0; chIndex < r->numHandlers; chIndex++ ) { + if ( h->channel == p->packet[g].s ) { break; } @@ -771,13 +861,10 @@ static void _TPIUpacketRxed( enum TPIUPumpEvent e, struct TPIUPacket *p, void *p } } - if ( ( chIndex != r->numHandlers ) && ( h ) ) - { + if ( ( chIndex != r->numHandlers ) && ( h ) ) { /* We must have found a match for this at some point, so add it to the queue */ h->strippedBlock->buffer[h->strippedBlock->fillLevel++] = p->packet[g].d; - } - else - { + } else { genericsReport( V_WARN, "No handler for %d" EOL, p->packet[g].s ); } } @@ -804,8 +891,7 @@ static void _processBlock( struct RunTime *r, ssize_t fillLevel, uint8_t *buffer { genericsReport( V_DEBUG, "RXED Packet of %d bytes%s" EOL, fillLevel, ( r->options->intervalReportTime ) ? EOL : "" ); - if ( fillLevel ) - { + if ( fillLevel ) { /* Account for this reception */ r->intervalBytes += fillLevel; @@ -815,34 +901,27 @@ static void _processBlock( struct RunTime *r, ssize_t fillLevel, uint8_t *buffer genericsPrintf( EOL ); - while ( y-- ) - { + while ( y-- ) { genericsPrintf( "%02X ", *c++ ); - if ( !( y % 16 ) ) - { + if ( !( y % 16 ) ) { genericsPrinttf( EOL ); } } #endif - if ( r->opFileHandle ) - { - if ( write( r->opFileHandle, buffer, fillLevel ) < 0 ) - { + if ( r->opFileHandle ) { + if ( write( r->opFileHandle, buffer, fillLevel ) < 0 ) { genericsExit( -3, "Writing to file failed" EOL ); } } - if ( r-> options->useTPIU ) - { + if ( r-> options->channelList ) { /* Strip the TPIU framing from this input */ TPIUPump2( &r->t, r->rawBlock[r->rp].buffer, r->rawBlock[r->rp].fillLevel, _TPIUpacketRxed, r ); _purgeBlock( r ); - } - else - { + } else { /* Do it the old fashioned way and send out the unfettered block */ nwclientSend( _r.n, r->rawBlock[r->rp].fillLevel, r->rawBlock[r->rp].buffer, ( r->options->file != NULL ) ); } @@ -857,12 +936,10 @@ static void *_processBlocksQueue( void *params ) { struct RunTime *r = ( struct RunTime * )params; - while ( !r->ending ) - { + while ( !r->ending ) { pthread_cond_wait( &r->dataForClients, &r->dataForClients_m ); - while ( r->rp != r->wp ) - { + while ( r->rp != r->wp ) { _processBlock( r, r->rawBlock[r->rp].fillLevel, r->rawBlock[r->rp].buffer ); r->rp = ( r->rp + 1 ) % NUM_RAW_BLOCKS; } @@ -884,14 +961,11 @@ static void _usb_callback( struct libusb_transfer *t ) { /* Whatever the status that comes back, there may be data... */ - if ( t->actual_length > 0 ) - { + if ( t->actual_length > 0 ) { _r.intervalBytes += t->actual_length; - if ( _r.opFileHandle ) - { - if ( write( _r.opFileHandle, t->buffer, t->actual_length ) < 0 ) - { + if ( _r.opFileHandle ) { + if ( write( _r.opFileHandle, t->buffer, t->actual_length ) < 0 ) { genericsExit( -4, "Writing to file failed (%s)" EOL, strerror( errno ) ); } } @@ -902,47 +976,37 @@ static void _usb_callback( struct libusb_transfer *t ) genericsPrintf( stderr, EOL ); - while ( y-- ) - { + while ( y-- ) { genericsPrintf( stderr, "%02X ", *c++ ); - if ( !( y % 16 ) ) - { + if ( !( y % 16 ) ) { genericsPrintf( stderr, EOL ); } } #endif - if ( _r.options->useTPIU ) - { + if ( _r.options->channelList ) { /* Strip the TPIU framing from this input */ TPIUPump2( &_r.t, t->buffer, t->actual_length, _TPIUpacketRxed, &_r ); _purgeBlock( &_r ); - } - else - { + } else { /* Do it the old fashioned way and send out the unfettered block */ nwclientSend( _r.n, t->actual_length, t->buffer, false ); } } if ( ( t->status != LIBUSB_TRANSFER_COMPLETED ) && - ( t->status != LIBUSB_TRANSFER_TIMED_OUT ) && - ( t->status != LIBUSB_TRANSFER_CANCELLED ) - ) - { - if ( !_r.errored ) - { + ( t->status != LIBUSB_TRANSFER_TIMED_OUT ) && + ( t->status != LIBUSB_TRANSFER_CANCELLED ) + ) { + if ( !_r.errored ) { genericsReport( V_WARN, "Errored out with status %d (%s)" EOL, t->status, libusb_error_name( t->status ) ); } _r.errored = true; - } - else - { - if ( t->status != LIBUSB_TRANSFER_CANCELLED ) - { + } else { + if ( t->status != LIBUSB_TRANSFER_CANCELLED ) { libusb_submit_transfer( t ); } } @@ -955,29 +1019,23 @@ void _actionOrbtraceCommand( struct RunTime *r, char *sn, enum ORBTraceDevice d char commandLine[MAX_LINE_LEN]; /* If we have any configuration to do on this device, go ahead */ - if ( r->options->otcl ) - { - if ( getenv( ORBTRACEENVNAME ) ) - { - snprintf( commandLine, MAX_LINE_LEN, "%s %s %s %s", getenv( ORBTRACEENVNAME ), r->options->otcl, sn ? ( ( d == DEVICE_ORBTRACE_MINI ) ? "-n " : "-s " ) : "", sn ? sn : "" ); - } - else - { + if ( r->options->run_orbtrace ) { + if ( getenv( ORBTRACEENVNAME ) ) { + snprintf( commandLine, MAX_LINE_LEN, "%s %s %s %s", getenv( ORBTRACEENVNAME ), r->options->otcl ? r->options->otcl : "", sn ? ( ( d == DEVICE_ORBTRACE_MINI ) ? "-n " : "-s " ) : "", sn ? sn : "" ); + } else { char *baseDirectory = genericsGetBaseDirectory( ); - if ( !baseDirectory ) - { + if ( !baseDirectory ) { genericsExit( -1, "Failed to establish base directory" EOL ); } - snprintf( commandLine, MAX_LINE_LEN, "%s" ORBTRACE " %s %s %s", baseDirectory, r->options->otcl, sn ? ( ( d == DEVICE_ORBTRACE_MINI ) ? "-n " : "-s " ) : "", sn ? sn : "" ); + snprintf( commandLine, MAX_LINE_LEN, "%s" ORBTRACE " %s %s %s", baseDirectory, r->options->otcl ? r->options->otcl : "", sn ? ( ( d == DEVICE_ORBTRACE_MINI ) ? "-n " : "-s " ) : "", sn ? sn : "" ); free( baseDirectory ); } genericsReport( V_INFO, "%s" EOL, commandLine ); - if ( system( commandLine ) ) - { + if ( system( commandLine ) ) { genericsReport( V_ERROR, "Invoking orbtrace failed" EOL ); } } @@ -990,13 +1048,11 @@ static int _usbFeeder( struct RunTime *r ) int workingDev; /* Copy any part serial number across */ - if ( r->options->sn ) - { + if ( r->options->sn ) { r->sn = strdup( r->options->sn ); } - while ( !r->ending ) - { + while ( !r->ending ) { r->errored = false; /* ...just in case we had a context */ @@ -1004,23 +1060,20 @@ static int _usbFeeder( struct RunTime *r ) r->o = OrbtraceIfCreateContext(); assert( r->o ); - while ( 0 == OrbtraceIfGetDeviceList( r->o, r->sn, DEVTYPE_ALL ) ) - { + while ( 0 == OrbtraceIfGetDeviceList( r->o, r->sn, DEVTYPE_ALL ) ) { usleep( INTERVAL_1S ); } genericsReport( V_INFO, "Found device" EOL ); workingDev = OrbtraceIfSelectDevice( r->o ); - if ( !OrbtraceIfOpenDevice( r->o, workingDev ) ) - { + if ( !OrbtraceIfOpenDevice( r->o, workingDev ) ) { genericsReport( V_INFO, "Couldn't open device" EOL ); break; } /* Take a record of what device we're using...we'll use that next time around to re-connect */ - if ( r->sn ) - { + if ( r->sn ) { free( r->sn ); } @@ -1029,8 +1082,7 @@ static int _usbFeeder( struct RunTime *r ) /* Before we open, perform any orbtrace configuration that is needed */ _actionOrbtraceCommand( r, r->sn, OrbtraceIfGetDevtype( r->o, workingDev ) ); - if ( !OrbtraceGetIfandEP( r->o ) ) - { + if ( !OrbtraceGetIfandEP( r->o ) ) { genericsReport( V_INFO, "Couldn't get IF and EP" EOL ); break; } @@ -1041,12 +1093,10 @@ static int _usbFeeder( struct RunTime *r ) r->errored = !( r->conn = OrbtraceIfSetupTransfers( r->o, r->options->hiresTime, r->rawBlock, NUM_RAW_BLOCKS, _usb_callback ) ); /* =========================== The main dispatch loop ======================================= */ - while ( ( !r->ending ) && ( !r->errored ) ) - { + while ( ( !r->ending ) && ( !r->errored ) ) { int ret = OrbtraceIfHandleEvents( r->o ); - if ( ( ret ) && ( ret != LIBUSB_ERROR_INTERRUPTED ) ) - { + if ( ( ret ) && ( ret != LIBUSB_ERROR_INTERRUPTED ) ) { genericsReport( V_ERROR, "Error waiting for USB requests to complete %d" EOL, ret ); } } @@ -1058,8 +1108,7 @@ static int _usbFeeder( struct RunTime *r ) /* Remove transfers from list and release the memory */ OrbtraceIfCloseTransfers( r->o ); - if ( !r->ending ) - { + if ( !r->ending ) { genericsReport( V_INFO, "USB connection lost" EOL ); } @@ -1071,12 +1120,10 @@ static int _usbFeeder( struct RunTime *r ) // ==================================================================================================== static int _nwserverFeeder( struct RunTime *r ) { - while ( true ) - { + while ( true ) { struct Stream *stream = streamCreateSocket( r->options->nwserverHost, r->options->nwserverPort ); - if ( stream == NULL ) - { + if ( stream == NULL ) { continue; } @@ -1084,15 +1131,13 @@ static int _nwserverFeeder( struct RunTime *r ) r->conn = true; - while ( !r->ending ) - { + while ( !r->ending ) { struct dataBlock *rxBlock = &r->rawBlock[r->wp]; size_t receivedSize; enum ReceiveResult result = stream->receive( stream, rxBlock->buffer, USB_TRANSFER_SIZE, NULL, &receivedSize ); - if ( result != RECEIVE_RESULT_OK ) - { + if ( result != RECEIVE_RESULT_OK ) { break; } @@ -1101,8 +1146,7 @@ static int _nwserverFeeder( struct RunTime *r ) _dataAvailable( r ); } - if ( !r->ending ) - { + if ( !r->ending ) { genericsReport( V_INFO, "Lost NW Server Link" EOL ); } @@ -1123,10 +1167,9 @@ static int _nwserverFeeder( struct RunTime *r ) static int _serialFeeder( struct RunTime *r ) { char portPath[MAX_PATH] = { 0 }; - snprintf( portPath, sizeof( portPath ), "\\\\.\\%s", r->options->port ); + snprintf( portPath, sizeof( portPath ), "\\\\.\\%s", r->options->serialPort ); - while ( !r->ending ) - { + while ( !r->ending ) { HANDLE portHandle = CreateFile( portPath, GENERIC_READ, 0, // must be opened with exclusive-access @@ -1135,15 +1178,13 @@ static int _serialFeeder( struct RunTime *r ) 0, // not overlapped I/O NULL ); // hTemplate must be NULL for comm devices - if ( portHandle == INVALID_HANDLE_VALUE ) - { + if ( portHandle == INVALID_HANDLE_VALUE ) { genericsExit( 1, "Can't open serial port" EOL ); } genericsReport( V_INFO, "Port opened" EOL ); - if ( !_setSerialSpeed( portHandle, r->options->speed ) ) - { + if ( !_setSerialSpeed( portHandle, r->options->serialSpeed ) ) { genericsExit( 2, "setSerialConfig failed" EOL ); } @@ -1153,16 +1194,14 @@ static int _serialFeeder( struct RunTime *r ) r->conn = true; - while ( !r->ending ) - { + while ( !r->ending ) { DWORD eventMask = 0; WaitCommEvent( portHandle, &eventMask, NULL ); DWORD unused; COMSTAT stats; ClearCommError( portHandle, &unused, &stats ); - if ( stats.cbInQue == 0 ) - { + if ( stats.cbInQue == 0 ) { continue; } @@ -1170,8 +1209,7 @@ static int _serialFeeder( struct RunTime *r ) DWORD transferSize = stats.cbInQue; - if ( transferSize > USB_TRANSFER_SIZE ) - { + if ( transferSize > USB_TRANSFER_SIZE ) { transferSize = USB_TRANSFER_SIZE; } @@ -1180,8 +1218,7 @@ static int _serialFeeder( struct RunTime *r ) rxBlock->fillLevel = readBytes; - if ( rxBlock->fillLevel <= 0 ) - { + if ( rxBlock->fillLevel <= 0 ) { break; } @@ -1191,8 +1228,7 @@ static int _serialFeeder( struct RunTime *r ) r->conn = false; - if ( ! r->ending ) - { + if ( ! r->ending ) { genericsReport( V_INFO, "Read failed" EOL ); } @@ -1211,52 +1247,46 @@ static int _serialFeeder( struct RunTime *r ) { int ret; - while ( !r->ending ) - { + while ( !r->ending ) { #ifdef OSX int flags; - while ( !r->ending && ( r->f = open( r->options->port, O_RDONLY | O_NONBLOCK ) ) < 0 ) + while ( !r->ending && ( r->f = open( r->options->serialPort, O_RDONLY | O_NONBLOCK ) ) < 0 ) #else - while ( !r->ending && ( r->f = open( r->options->port, O_RDONLY ) ) < 0 ) + while ( !r->ending && ( r->f = open( r->options->serialPort, O_RDONLY ) ) < 0 ) #endif { genericsReport( V_WARN, "Can't open serial port" EOL ); usleep( INTERVAL_100MS ); } - genericsReport( V_INFO, "Port opened" EOL ); + genericsReport( V_INFO, "Serial Port opened" EOL ); #ifdef OSX /* Remove the O_NONBLOCK flag now the port is open (OSX Only) */ - if ( ( flags = fcntl( r->f, F_GETFL, NULL ) ) < 0 ) - { + if ( ( flags = fcntl( r->f, F_GETFL, NULL ) ) < 0 ) { genericsExit( -3, "F_GETFL failed" EOL ); } flags &= ~O_NONBLOCK; - if ( ( flags = fcntl( r->f, F_SETFL, flags ) ) < 0 ) - { + if ( ( flags = fcntl( r->f, F_SETFL, flags ) ) < 0 ) { genericsExit( -3, "F_SETFL failed" EOL ); } #endif - if ( ( ret = _setSerialConfig ( r->f, r->options->speed ) ) < 0 ) - { + if ( ( ret = _setSerialConfig ( r->f, r->options->serialSpeed ) ) < 0 ) { genericsExit( ret, "setSerialConfig failed" EOL ); } r->conn = true; - while ( !r->ending ) - { + while ( !r->ending ) { struct dataBlock *rxBlock = &r->rawBlock[r->wp]; - if ( ( rxBlock->fillLevel = read( r->f, rxBlock->buffer, USB_TRANSFER_SIZE ) ) <= 0 ) - { + if ( ( rxBlock->fillLevel = read( r->f, rxBlock->buffer, USB_TRANSFER_SIZE ) ) <= 0 ) { break; } @@ -1266,8 +1296,7 @@ static int _serialFeeder( struct RunTime *r ) r->conn = false; - if ( ! r->ending ) - { + if ( ! r->ending ) { genericsReport( V_INFO, "Read failed" EOL ); } @@ -1282,8 +1311,7 @@ static int _serialFeeder( struct RunTime *r ) static int _fileFeeder( struct RunTime *r ) { - if ( ( r->f = open( r->options->file, O_RDONLY | O_BINARY ) ) < 0 ) - { + if ( ( r->f = open( r->options->file, O_RDONLY | O_BINARY ) ) < 0 ) { genericsExit( -4, "Can't open file %s" EOL, r->options->file ); } @@ -1292,8 +1320,7 @@ static int _fileFeeder( struct RunTime *r ) /* We will read from the file very quickly, so let's give a chance for clients to connect before we do */ usleep( INTERVAL_1S ); - while ( !r->ending ) - { + while ( !r->ending ) { struct dataBlock *rxBlock = &r->rawBlock[r->wp]; rxBlock->fillLevel = read( r->f, rxBlock->buffer, USB_TRANSFER_SIZE ); @@ -1301,27 +1328,21 @@ static int _fileFeeder( struct RunTime *r ) _dataAvailable( r ); int nwp = ( r->wp + 1 ) % NUM_RAW_BLOCKS; - if ( r->options->paceDelay ) - { + if ( r->options->paceDelay ) { usleep( r->options->paceDelay ); } /* Spin waiting for buffer space to become available */ - while ( nwp == r->rp ) - { + while ( nwp == r->rp ) { usleep( INTERVAL_1MS ); } r->wp = nwp; - if ( !rxBlock->fillLevel ) - { - if ( r->options->fileTerminate ) - { + if ( !rxBlock->fillLevel ) { + if ( r->options->fileTerminate ) { break; - } - else - { + } else { // Just spin for a while to avoid clogging the CPU usleep( INTERVAL_100MS ); continue; @@ -1331,8 +1352,7 @@ static int _fileFeeder( struct RunTime *r ) r->conn = false; - if ( !r->options->fileTerminate ) - { + if ( !r->options->fileTerminate ) { genericsReport( V_INFO, "File read error" EOL ); } @@ -1362,18 +1382,15 @@ int main( int argc, char *argv[] ) /* Setup TPIU in case we call it into service later */ TPIUDecoderInit( &_r.t ); - if ( pthread_mutex_init( &_r.dataForClients_m, NULL ) != 0 ) - { + if ( pthread_mutex_init( &_r.dataForClients_m, NULL ) != 0 ) { genericsExit( -1, "Failed to establish mutex for condition variablee" EOL ); } - if ( pthread_cond_init( &_r.dataForClients, NULL ) != 0 ) - { - genericsExit( -1, "Failed to establish condition variablee" EOL ); + if ( pthread_cond_init( &_r.dataForClients, NULL ) != 0 ) { + genericsExit( -1, "Failed to establish condition variable" EOL ); } - if ( !_processOptions( argc, argv, &_r ) ) - { + if ( !_processOptions( argc, argv, &_r ) ) { /* processOptions generates its own error messages */ genericsExit( -1, "" EOL ); } @@ -1384,48 +1401,39 @@ int main( int argc, char *argv[] ) atexit( _doExit ); /* This ensures the atexit gets called */ - if ( SIG_ERR == signal( SIGINT, _intHandler ) ) - { + if ( SIG_ERR == signal( SIGINT, _intHandler ) ) { genericsExit( -1, "Failed to establish Int handler" EOL ); } /* Don't kill a sub-process when any reader or writer evaporates */ #if !defined WIN32 - if ( SIG_ERR == signal( SIGPIPE, SIG_IGN ) ) - { + if ( SIG_ERR == signal( SIGPIPE, SIG_IGN ) ) { genericsExit( -1, "Failed to ignore SIGPIPEs" EOL ); } #endif - if ( _r.options->useTPIU ) - { + if ( _r.options->channelList ) { char *c = _r.options->channelList; int x = 0; - while ( *c ) - { - while ( *c == ',' ) - { + while ( *c ) { + while ( *c == ',' ) { c++; } - while ( isdigit( *c ) ) - { + while ( isdigit( *c ) ) { x = x * 10 + ( *c++ -'0' ); } - if ( ( *c ) && ( *c != ',' ) ) - { + if ( ( *c ) && ( *c != ',' ) ) { genericsExit( -1, "Illegal character in channel list (%c)" EOL, *c ); } - if ( x ) - { + if ( x ) { /* This is a good number, so open */ - if ( ( x < 0 ) || ( x >= NUM_TPIU_CHANNELS ) ) - { + if ( ( x < 0 ) || ( x >= NUM_TPIU_CHANNELS ) ) { genericsExit( -1, "Channel number out of range" EOL ); } @@ -1441,52 +1449,41 @@ int main( int argc, char *argv[] ) } /* ...a blank line so this doesn't get erased by monitoring reports */ - if ( _r.options->intervalReportTime ) - { + if ( _r.options->intervalReportTime ) { genericsReport( V_WARN, EOL ); } - } - else - { - if ( !( _r.n = nwclientStart( _r.options->listenPort ) ) ) - { + } else { + if ( !( _r.n = nwclientStart( _r.options->listenPort ) ) ) { genericsExit( -1, "Failed to make network server" EOL ); } } - if ( _r.options->intervalReportTime ) - { + if ( _r.options->intervalReportTime ) { pthread_create( &_r.intervalThread, NULL, &_checkInterval, &_r ); } - if ( _r.options->outfile ) - { + if ( _r.options->outfile ) { _r.opFileHandle = open( _r.options->outfile, O_CREAT | O_TRUNC | O_WRONLY | O_BINARY, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH ); - if ( _r.opFileHandle < 0 ) - { + if ( _r.opFileHandle < 0 ) { genericsReport( V_ERROR, "Could not open output file for writing" EOL ); return -2; } } - if ( ( _r.options->nwserverPort ) || ( _r.options->port ) || ( _r.options->file ) ) - { + if ( ( _r.options->nwserverPort ) || ( _r.options->serialPort ) || ( _r.options->file ) ) { /* Start the distribution task */ pthread_create( &_r.processThread, NULL, &_processBlocksQueue, &_r ); - if ( _r.options->nwserverPort ) - { + if ( _r.options->nwserverPort ) { exit( _nwserverFeeder( &_r ) ); } - if ( _r.options->port ) - { + if ( _r.options->serialPort ) { exit( _serialFeeder( &_r ) ); } - if ( _r.options->file ) - { + if ( _r.options->file ) { exit( _fileFeeder( &_r ) ); } } diff --git a/Src/orbzmq.c b/Src/orbzmq.c index 7f67addd..abf134fa 100644 --- a/Src/orbzmq.c +++ b/Src/orbzmq.c @@ -22,21 +22,19 @@ #define HWFIFO_NAME "hwevent" #define MAX_STRING_LENGTH (100) /* Maximum length that will be output for a single event */ -#define DEFAULT_ZMQ_BIND_URL "tcp://*:3442" /* by default bind to all source interfaces */ +#define DEFAULT_ZMQ_BIND_URL (char*)"tcp://*:3442" /* by default bind to all source interfaces */ // Record for options, either defaults or from command line -struct Channel -{ +struct Channel { char *topic; char *format; }; -struct -{ +struct { /* Config information */ bool useTPIU; - uint32_t tpiuChannel; + int8_t tpiuChannel; bool forceITMSync; uint32_t hwOutputs; @@ -52,17 +50,15 @@ struct char *file; /* File host connection */ bool endTerminate; /* Terminate when file/socket "ends" */ -} options = -{ - .forceITMSync = true, +} options = { .tpiuChannel = 1, + .forceITMSync = true, .bindUrl = DEFAULT_ZMQ_BIND_URL, .port = NWCLIENT_SERVER_PORT, - .server = "localhost" + .server = ( char * )"localhost" }; -struct -{ +struct { /* The decoders and the packets from them */ struct ITMDecoder i; struct ITMPacket h; @@ -85,8 +81,7 @@ void _publishMessage( const char *topic, void *payload, size_t size ) zmq_send( _r.zmqSocket, payload, size, 0 ); } -static const char *hwEventNames[] = -{ +static const char *hwEventNames[] = { [HWEVENT_TS] = HWFIFO_NAME "TS", [HWEVENT_EXCEPTION] = HWFIFO_NAME "EXCP", [HWEVENT_PCSample] = HWFIFO_NAME "PC", @@ -106,39 +101,33 @@ void _handleSW( struct swMsg *m, struct ITMDecoder *i ) { assert( m->msgtype == MSG_SOFTWARE ); - if ( ( m->srcAddr < NUM_CHANNELS ) && ( options.channel[m->srcAddr].topic ) ) - { + if ( ( m->srcAddr < NUM_CHANNELS ) && ( options.channel[m->srcAddr].topic ) ) { struct Channel *channel = &options.channel[m->srcAddr]; char formatted[30]; size_t size = 0; // formatted output....start with specials - if ( channel->format == NULL ) - { + if ( channel->format == NULL ) { memcpy( formatted, &m->value, m->len ); size = m->len; - } - else if ( strstr( channel->format, "%f" ) ) - { + } else if ( strstr( channel->format, "%f" ) ) { /* type punning on same host, after correctly building 32bit val * only unsafe on systems where u32/float have diff byte order */ float *nastycast = ( float * )&m->value; size = snprintf( formatted, sizeof( formatted ), channel->format, *nastycast, *nastycast, *nastycast, *nastycast ); - } - else if ( strstr( channel->format, "%c" ) ) - { + } else if ( strstr( channel->format, "%c" ) ) { /* Format contains %c, so execute repeatedly for all characters in sent data */ - uint8_t op[4] = {m->value & 0xff, ( m->value >> 8 ) & 0xff, ( m->value >> 16 ) & 0xff, ( m->value >> 24 ) & 0xff}; + uint8_t op[4] = {( uint8_t )( m->value & 0xff ), + ( uint8_t )( ( m->value >> 8 ) & 0xff ), + ( uint8_t )( ( m->value >> 16 ) & 0xff ), + ( uint8_t )( ( m->value >> 24 ) & 0xff ) + }; uint32_t l = 0; - do - { + do { size += snprintf( formatted + size, sizeof( formatted ) - size, channel->format, op[l], op[l], op[l] ); - } - while ( ++l < m->len ); - } - else - { + } while ( ++l < m->len ); + } else { size = snprintf( formatted, sizeof( formatted ), channel->format, m->value, m->value, m->value, m->value ); } @@ -150,8 +139,7 @@ void _handleException( struct excMsg *m ) { assert( m->msgtype == MSG_EXCEPTION ); - if ( !( options.hwOutputs & ( 1 << HWEVENT_EXCEPTION ) ) ) - { + if ( !( options.hwOutputs & ( 1 << HWEVENT_EXCEPTION ) ) ) { return; } @@ -166,13 +154,10 @@ void _handleException( struct excMsg *m ) _r.lastHWExceptionTS = m->ts; - if ( m->exceptionNumber < 16 ) - { + if ( m->exceptionNumber < 16 ) { /* This is a system based exception */ opLen = snprintf( outputString, MAX_STRING_LENGTH, "%" PRIu64 ",%s,%s", eventdifftS, exEvent[m->eventType & 0x03], exNames[m->exceptionNumber & 0x0F] ); - } - else - { + } else { /* This is a CPU defined exception */ opLen = snprintf( outputString, MAX_STRING_LENGTH, "%" PRIu64 ",%s,External,%d", eventdifftS, exEvent[m->eventType & 0x03], m->exceptionNumber - 16 ); } @@ -185,8 +170,7 @@ void _handleDWTEvent( struct dwtMsg *m ) { assert( m->msgtype == MSG_DWT_EVENT ); - if ( !( options.hwOutputs & ( 1 << HWEVENT_DWT ) ) ) - { + if ( !( options.hwOutputs & ( 1 << HWEVENT_DWT ) ) ) { return; } @@ -200,19 +184,15 @@ void _handleDWTEvent( struct dwtMsg *m ) _r.lastHWExceptionTS = m->ts; opLen = snprintf( outputString, MAX_STRING_LENGTH, "%" PRIu64, eventdifftS ); - for ( uint32_t i = 0; i < NUM_EVENTS; i++ ) - { - if ( m->event & ( 1 << i ) ) - { + for ( uint32_t i = 0; i < NUM_EVENTS; i++ ) { + if ( m->event & ( 1 << i ) ) { // Copy this event into the output string outputString[opLen++] = ','; const char *u = evName[i]; - do - { + do { outputString[opLen++] = *u++; - } - while ( *u ); + } while ( *u ); } } @@ -226,8 +206,7 @@ void _handlePCSample( struct pcSampleMsg *m ) { assert( m->msgtype == MSG_PC_SAMPLE ); - if ( !( options.hwOutputs & ( 1 << HWEVENT_PCSample ) ) ) - { + if ( !( options.hwOutputs & ( 1 << HWEVENT_PCSample ) ) ) { return; } @@ -237,13 +216,10 @@ void _handlePCSample( struct pcSampleMsg *m ) _r.lastHWExceptionTS = m->ts; - if ( m->sleep ) - { + if ( m->sleep ) { /* This is a sleep packet */ opLen = snprintf( outputString, ( MAX_STRING_LENGTH - 1 ), "%" PRIu64 ",**SLEEP**", eventdifftS ); - } - else - { + } else { opLen = snprintf( outputString, ( MAX_STRING_LENGTH - 1 ), "%" PRIu64 ",0x%08x", eventdifftS, m->pc ); } @@ -257,8 +233,7 @@ void _handleDataRWWP( struct watchMsg *m ) { assert( m->msgtype == MSG_DATA_RWWP ); - if ( !( options.hwOutputs & ( 1 << HWEVENT_RWWT ) ) ) - { + if ( !( options.hwOutputs & ( 1 << HWEVENT_RWWT ) ) ) { return; } @@ -279,8 +254,7 @@ void _handleDataAccessWP( struct wptMsg *m ) { assert( m->msgtype == MSG_DATA_ACCESS_WP ); - if ( !( options.hwOutputs & ( 1 << HWEVENT_AWP ) ) ) - { + if ( !( options.hwOutputs & ( 1 << HWEVENT_AWP ) ) ) { return; } @@ -301,8 +275,7 @@ void _handleDataOffsetWP( struct oswMsg *m ) { assert( m->msgtype == MSG_OSW ); - if ( !( options.hwOutputs & ( 1 << HWEVENT_OFS ) ) ) - { + if ( !( options.hwOutputs & ( 1 << HWEVENT_OFS ) ) ) { return; } @@ -322,8 +295,7 @@ void _handleTS( struct TSMsg *m ) { assert( m->msgtype == MSG_TS ); - if ( !( options.hwOutputs & ( 1 << HWEVENT_TS ) ) ) - { + if ( !( options.hwOutputs & ( 1 << HWEVENT_TS ) ) ) { return; } @@ -332,7 +304,7 @@ void _handleTS( struct TSMsg *m ) int opLen; _r.timeStamp += m->timeInc; - _r.timeStatus = m->timeStatus; + _r.timeStatus = ( enum timeDelay )m->timeStatus; opLen = snprintf( outputString, MAX_STRING_LENGTH, "%d,%" PRIu32, m->timeStatus, m->timeInc ); _publishMessage( hwEventNames[HWEVENT_TS], outputString, opLen ); @@ -345,8 +317,7 @@ void _itmPumpProcess( char c ) typedef void ( *handlers )( void *decoded, struct ITMDecoder * i ); /* Handlers for each complete message received */ - static const handlers h[MSG_NUM_MSGS] = - { + static const handlers h[MSG_NUM_MSGS] = { /* MSG_UNKNOWN */ NULL, /* MSG_RESERVED */ NULL, /* MSG_ERROR */ NULL, @@ -362,8 +333,7 @@ void _itmPumpProcess( char c ) /* MSG_TS */ ( handlers )_handleTS }; - switch ( ITMPump( &_r.i, c ) ) - { + switch ( ITMPump( &_r.i, c ) ) { case ITM_EV_NONE: break; @@ -388,8 +358,7 @@ void _itmPumpProcess( char c ) /* See if we decoded a dispatchable match. genericMsg is just used to access */ /* the first two members of the decoded structs in a portable way. */ - if ( h[decoded.genericMsg.msgtype] ) - { + if ( h[decoded.genericMsg.msgtype] ) { ( h[decoded.genericMsg.msgtype] )( &decoded, &_r.i ); } @@ -408,10 +377,8 @@ void _itmPumpProcess( char c ) // ==================================================================================================== void _protocolPump( uint8_t c ) { - if ( options.useTPIU ) - { - switch ( TPIUPump( &_r.t, c ) ) - { + if ( options.useTPIU ) { + switch ( TPIUPump( &_r.t, c ) ) { case TPIU_EV_NEWSYNC: case TPIU_EV_SYNCED: ITMDecoderForceSync( &_r.i, true ); @@ -426,21 +393,17 @@ void _protocolPump( uint8_t c ) break; case TPIU_EV_RXEDPACKET: - if ( !TPIUGetPacket( &_r.t, &_r.p ) ) - { + if ( !TPIUGetPacket( &_r.t, &_r.p ) ) { genericsReport( V_WARN, "TPIUGetPacket fell over" EOL ); } - for ( uint32_t g = 0; g < _r.p.len; g++ ) - { - if ( _r.p.packet[g].s == options.tpiuChannel ) - { + for ( uint32_t g = 0; g < _r.p.len; g++ ) { + if ( _r.p.packet[g].s == options.tpiuChannel ) { _itmPumpProcess( _r.p.packet[g].d ); continue; } - if ( _r.p.packet[g].s != 0 ) - { + if ( _r.p.packet[g].s != 0 ) { genericsReport( V_DEBUG, "Unknown TPIU channel %02x" EOL, _r.p.packet[g].s ); } } @@ -451,9 +414,7 @@ void _protocolPump( uint8_t c ) genericsReport( V_WARN, "****ERROR****" EOL ); break; } - } - else - { + } else { _itmPumpProcess( c ); } } @@ -490,8 +451,7 @@ void _printVersion( void ) static int32_t _parseHWEventsArg( char *s ) { - if ( strcasecmp( s, "all" ) == 0 ) - { + if ( strcasecmp( s, "all" ) == 0 ) { return 0xFF; } @@ -499,38 +459,22 @@ static int32_t _parseHWEventsArg( char *s ) char *token = strtok( s, "," ); - while ( token ) - { - if ( strcasecmp( token, "TS" ) == 0 ) - { + while ( token ) { + if ( strcasecmp( token, "TS" ) == 0 ) { result |= 1 << HWEVENT_TS; - } - else if ( strcasecmp( token, "EXCP" ) == 0 ) - { + } else if ( strcasecmp( token, "EXCP" ) == 0 ) { result |= 1 << HWEVENT_EXCEPTION; - } - else if ( strcasecmp( token, "PC" ) == 0 ) - { + } else if ( strcasecmp( token, "PC" ) == 0 ) { result |= 1 << HWEVENT_PCSample; - } - else if ( strcasecmp( token, "DWT" ) == 0 ) - { + } else if ( strcasecmp( token, "DWT" ) == 0 ) { result |= 1 << HWEVENT_DWT; - } - else if ( strcasecmp( token, "RWWT" ) == 0 ) - { + } else if ( strcasecmp( token, "RWWT" ) == 0 ) { result |= 1 << HWEVENT_RWWT; - } - else if ( strcasecmp( token, "AWP" ) == 0 ) - { + } else if ( strcasecmp( token, "AWP" ) == 0 ) { result |= 1 << HWEVENT_AWP; - } - else if ( strcasecmp( token, "OFS" ) == 0 ) - { + } else if ( strcasecmp( token, "OFS" ) == 0 ) { result |= 1 << HWEVENT_OFS; - } - else - { + } else { genericsReport( V_ERROR, "Unrecognied hardware event '%s'" EOL, token ); return -1; } @@ -542,8 +486,7 @@ static int32_t _parseHWEventsArg( char *s ) } // ==================================================================================================== -static struct option _longOptions[] = -{ +static struct option _longOptions[] = { {"zbind", required_argument, NULL, 'z'}, {"channel", required_argument, NULL, 'c'}, {"hwevent", required_argument, NULL, 'e'}, @@ -570,16 +513,14 @@ bool _processOptions( int argc, char *argv[] ) unsigned int chan; char *chanIndex; int32_t hwOutputs; + char *a; - for ( int g = 0; g < NUM_CHANNELS; g++ ) - { + for ( int g = 0; g < NUM_CHANNELS; g++ ) { options.channel[g].topic = NULL; } - while ( ( c = getopt_long ( argc, argv, "c:e:Ef:hns:t:v:Vz:", _longOptions, &optionIndex ) ) != -1 ) - { - switch ( c ) - { + while ( ( c = getopt_long ( argc, argv, "c:e:Ef:hns:t:v:Vz:", _longOptions, &optionIndex ) ) != -1 ) { + switch ( c ) { // ------------------------------------ case 'h': _printHelp( argv[0] ); @@ -615,21 +556,18 @@ bool _processOptions( int argc, char *argv[] ) options.server = optarg; // See if we have an optional port number too - char *a = optarg; + a = optarg; - while ( ( *a ) && ( *a != ':' ) ) - { + while ( ( *a ) && ( *a != ':' ) ) { a++; } - if ( *a == ':' ) - { + if ( *a == ':' ) { *a = 0; options.port = atoi( ++a ); } - if ( !options.port ) - { + if ( !options.port ) { options.port = NWCLIENT_SERVER_PORT; } @@ -643,13 +581,12 @@ bool _processOptions( int argc, char *argv[] ) // ------------------------------------ case 'v': - if ( !isdigit( *optarg ) ) - { + if ( !isdigit( *optarg ) ) { genericsReport( V_ERROR, "-v requires a numeric argument." EOL ); return false; } - genericsSetReportLevel( atoi( optarg ) ); + genericsSetReportLevel( ( enum verbLevel )atoi( optarg ) ); break; // ------------------------------------ @@ -657,29 +594,25 @@ bool _processOptions( int argc, char *argv[] ) case 'c': chanIndex = chanConfig = strdup( optarg ); - if ( NULL == chanConfig ) - { + if ( NULL == chanConfig ) { genericsReport( V_ERROR, "Couldn't allocate memory at %s::%d" EOL, __FILE__, __LINE__ ); return false; } chan = atoi( optarg ); - if ( chan >= NUM_CHANNELS ) - { + if ( chan >= NUM_CHANNELS ) { genericsReport( V_ERROR, "Channel index out of range" EOL ); free( chanConfig ); return false; } /* Scan for start of topic */ - while ( ( *chanIndex ) && ( *chanIndex != DELIMITER ) ) - { + while ( ( *chanIndex ) && ( *chanIndex != DELIMITER ) ) { chanIndex++; } - if ( !*chanIndex ) - { + if ( !*chanIndex ) { genericsReport( V_ERROR, "No filename for channel %d" EOL, chan ); free( chanConfig ); return false; @@ -688,13 +621,11 @@ bool _processOptions( int argc, char *argv[] ) chanName = ++chanIndex; /* Scan for format */ - while ( ( *chanIndex ) && ( *chanIndex != DELIMITER ) ) - { + while ( ( *chanIndex ) && ( *chanIndex != DELIMITER ) ) { chanIndex++; } - if ( !*chanIndex ) - { + if ( !*chanIndex ) { genericsReport( V_WARN, "No output format for channel %d, output raw!" EOL, chan ); break; } @@ -702,8 +633,7 @@ bool _processOptions( int argc, char *argv[] ) *chanIndex++ = 0; options.channel[chan].topic = strdup( chanName ); - if ( strcmp( chanIndex, "" ) != 0 ) - { + if ( strcmp( chanIndex, "" ) != 0 ) { options.channel[chan].format = strdup( genericsUnescape( chanIndex ) ); } @@ -712,8 +642,7 @@ bool _processOptions( int argc, char *argv[] ) case 'e': hwOutputs = _parseHWEventsArg( optarg ); - if ( hwOutputs == -1 ) - { + if ( hwOutputs == -1 ) { return false; } @@ -721,12 +650,9 @@ bool _processOptions( int argc, char *argv[] ) break; case '?': - if ( optopt == 'b' ) - { + if ( optopt == 'b' ) { genericsReport( V_ERROR, "Option '%c' requires an argument." EOL, optopt ); - } - else if ( !isprint ( optopt ) ) - { + } else if ( !isprint ( optopt ) ) { genericsReport( V_ERROR, "Unknown option character `\\x%x'." EOL, optopt ); } @@ -745,8 +671,7 @@ bool _processOptions( int argc, char *argv[] ) } } - if ( ( options.useTPIU ) && ( !options.tpiuChannel ) ) - { + if ( ( options.useTPIU ) && ( !options.tpiuChannel ) ) { genericsReport( V_ERROR, "TPIU set for use but no channel set for ITM output" EOL ); return false; } @@ -755,52 +680,40 @@ bool _processOptions( int argc, char *argv[] ) genericsReport( V_INFO, "Server : %s:%d" EOL, options.server, options.port ); genericsReport( V_INFO, "ForceSync : %s" EOL, options.forceITMSync ? "true" : "false" ); - if ( options.file ) - { + if ( options.file ) { genericsReport( V_INFO, "Input File : %s", options.file ); - if ( options.endTerminate ) - { + if ( options.endTerminate ) { genericsReport( V_INFO, " (Terminate on exhaustion)" EOL ); - } - else - { + } else { genericsReport( V_INFO, " (Ongoing read)" EOL ); } } - if ( options.useTPIU ) - { + if ( options.useTPIU ) { genericsReport( V_INFO, "Using TPIU : true (ITM on channel %d)" EOL, options.tpiuChannel ); - } - else - { + } else { genericsReport( V_INFO, "Using TPIU : false" EOL ); } genericsReport( V_INFO, "ZeroMQ bind : %s" EOL, options.bindUrl ); genericsReport( V_INFO, "Channels :" EOL ); - for ( int g = 0; g < NUM_CHANNELS; g++ ) - { + for ( int g = 0; g < NUM_CHANNELS; g++ ) { struct Channel *channel = &options.channel[g]; - if ( channel->topic ) - { - genericsReport( V_INFO, " %02d [%s] [%s]" EOL, g, genericsEscape( channel->format ? : "RAW" ), channel->topic ); + if ( channel->topic ) { + genericsReport( V_INFO, " %02d [%s] [%s]" EOL, g, genericsEscape( channel->format ? : ( char * )"RAW" ), channel->topic ); } } - for ( int g = 0; g < ( sizeof( hwEventNames ) / sizeof( *hwEventNames ) ); g++ ) - { - if ( hwEventNames[g] == NULL ) - { + for ( unsigned int g = 0; g < ( sizeof( hwEventNames ) / sizeof( *hwEventNames ) ); g++ ) { + if ( hwEventNames[g] == NULL ) { continue; } - if ( ( options.hwOutputs & ( 1 << g ) ) == 0 ) - { + if ( ( options.hwOutputs & ( 1 << g ) ) == 0 ) { continue;; } @@ -814,12 +727,9 @@ bool _processOptions( int argc, char *argv[] ) static struct Stream *_tryOpenStream() { - if ( options.file != NULL ) - { + if ( options.file != NULL ) { return streamCreateFile( options.file ); - } - else - { + } else { return streamCreateSocket( options.server, options.port ); } } @@ -828,31 +738,23 @@ static void _feedStream( struct Stream *stream ) { unsigned char cbw[TRANSFER_SIZE]; - while ( true ) - { + while ( true ) { size_t receivedSize; enum ReceiveResult result = stream->receive( stream, cbw, TRANSFER_SIZE, NULL, &receivedSize ); - if ( result != RECEIVE_RESULT_OK ) - { - if ( result == RECEIVE_RESULT_EOF && options.endTerminate ) - { + if ( result != RECEIVE_RESULT_OK ) { + if ( result == RECEIVE_RESULT_EOF && options.endTerminate ) { return; - } - else if ( result == RECEIVE_RESULT_ERROR ) - { + } else if ( result == RECEIVE_RESULT_ERROR ) { break; - } - else - { + } else { usleep( 100000 ); } } unsigned char *c = cbw; - while ( receivedSize-- ) - { + while ( receivedSize-- ) { _protocolPump( *c++ ); } @@ -865,8 +767,7 @@ int main( int argc, char *argv[] ) { bool alreadyReported = false; - if ( !_processOptions( argc, argv ) ) - { + if ( !_processOptions( argc, argv ) ) { exit( -1 ); } @@ -880,18 +781,14 @@ int main( int argc, char *argv[] ) TPIUDecoderInit( &_r.t ); ITMDecoderInit( &_r.i, options.forceITMSync ); - while ( true ) - { + while ( true ) { struct Stream *stream = NULL; - while ( true ) - { + while ( true ) { stream = _tryOpenStream(); - if ( stream != NULL ) - { - if ( alreadyReported ) - { + if ( stream != NULL ) { + if ( alreadyReported ) { genericsReport( V_INFO, "Connected" EOL ); alreadyReported = false; } @@ -899,14 +796,12 @@ int main( int argc, char *argv[] ) break; } - if ( !alreadyReported ) - { + if ( !alreadyReported ) { genericsReport( V_INFO, EOL "No connection" EOL ); alreadyReported = true; } - if ( options.endTerminate ) - { + if ( options.endTerminate ) { break; } @@ -914,16 +809,14 @@ int main( int argc, char *argv[] ) usleep( 10000 ); } - if ( stream != NULL ) - { + if ( stream != NULL ) { _feedStream( stream ); } stream->close( stream ); free( stream ); - if ( options.endTerminate ) - { + if ( options.endTerminate ) { break; } } diff --git a/Src/readsource.c b/Src/readsource.c index ca9b7adb..309cee6d 100644 --- a/Src/readsource.c +++ b/Src/readsource.c @@ -2,6 +2,7 @@ #include #include #include +#include "readsource.h" #define BLOCKSIZE (65536) #define MAX_LINE_LEN (4095) @@ -21,8 +22,7 @@ char *readsourcefile( char *path, size_t *l ) *l = 0; FILE *f = fopen( path, "r" ); - if ( f == NULL ) - { + if ( f == NULL ) { return NULL; } @@ -31,8 +31,7 @@ char *readsourcefile( char *path, size_t *l ) size_t insize = fread( retBuffer, 1, BLOCKSIZE, f ); *l = insize; - while ( !feof( f ) ) - { + while ( !feof( f ) ) { retBuffer = ( char * )realloc( retBuffer, *l + BLOCKSIZE ); insize = fread( &retBuffer[*l], 1, BLOCKSIZE, f ); *l += insize; @@ -62,13 +61,10 @@ char *readsourcefile( char *path, size_t *l ) size_t insize; /* Try and grab the file via a prettyprinter. If that doesn't work, grab it via cat */ - if ( getenv( "ORB_PRETTYPRINTER" ) ) - { + if ( getenv( "ORB_PRETTYPRINTER" ) ) { /* We have an environment variable containing the prettyprinter...lets use that */ snprintf( commandLine, MAX_LINE_LEN, "%s %s", getenv( "ORB_PRETTYPRINTER" ), path ); - } - else - { + } else { /* No environment variable, use the default */ snprintf( commandLine, MAX_LINE_LEN, "source-highlight -f esc -o STDOUT -i %s 2>/dev/null", path ); } @@ -79,13 +75,11 @@ char *readsourcefile( char *path, size_t *l ) retBuffer = ( char * )malloc( BLOCKSIZE ); insize = fread( retBuffer, 1, BLOCKSIZE, fd ); - if ( !insize ) - { + if ( !insize ) { pclose( fd ); isProcess = false; - if ( ( fd = fopen( path, "r" ) ) ) - { + if ( ( fd = fopen( path, "r" ) ) ) { insize = fread( retBuffer, 1, BLOCKSIZE, fd ); } } @@ -94,8 +88,7 @@ char *readsourcefile( char *path, size_t *l ) *l = insize; /* There may be more file to read...if so, then let's do it */ - while ( insize == BLOCKSIZE ) - { + while ( insize == BLOCKSIZE ) { /* Make another block available */ retBuffer = ( char * )realloc( retBuffer, *l + BLOCKSIZE ); insize = fread( &retBuffer[*l], 1, BLOCKSIZE, fd ); @@ -103,18 +96,14 @@ char *readsourcefile( char *path, size_t *l ) } /* Close the process or file, depending on what it was that actually got opened */ - if ( fd ) - { + if ( fd ) { isProcess ? pclose( fd ) : fclose( fd ); } /* Resize the memory to what was actually read in */ - if ( *l ) - { + if ( *l ) { retBuffer = ( char * )realloc( retBuffer, *l ); - } - else - { + } else { free( retBuffer ); retBuffer = NULL; } diff --git a/Src/sio.c b/Src/sio.c index 640e707b..3f4a3c29 100644 --- a/Src/sio.c +++ b/Src/sio.c @@ -22,8 +22,7 @@ #include "sio.h" /* Colours for output */ -enum CP -{ +enum CP { /* These initial pairs are set to match the ANSI foreground colors */ CP_FG_BLACK, CP_FG_DARK_RED, @@ -52,8 +51,7 @@ enum SRCH { SRCH_OFF, SRCH_FORWARDS, SRCH_BACKWARDS }; /* Display modes */ enum DISP { DISP_BOTH, DISP_SRC, DISP_ASSY, DISP_MAX_OPTIONS }; -struct SIOInstance -{ +struct SIOInstance { /* Materials for window handling */ WINDOW *outputWindow; /* Output window (main one) */ WINDOW *statusWindow; /* Status window (interaction one) */ @@ -121,8 +119,7 @@ static void _deleteTags( struct SIOInstance *sio ) /* reset the tag records */ { - for ( uint32_t t = 0; t < MAX_TAGS; t++ ) - { + for ( uint32_t t = 0; t < MAX_TAGS; t++ ) { sio->tag[t] = 0; } } @@ -132,8 +129,7 @@ static enum SIOEvent _processSaveFilename( struct SIOInstance *sio ) { enum SIOEvent op = SIO_EV_NONE; - switch ( sio->Key ) - { + switch ( sio->Key ) { case ERR: op = SIO_EV_CONSUMED; break; @@ -147,8 +143,7 @@ static enum SIOEvent _processSaveFilename( struct SIOInstance *sio ) case 263: /* --------------------------- Del Remove char from save string ----------------- */ /* Delete last character in save string */ - if ( strlen( sio->saveFilename ) ) - { + if ( strlen( sio->saveFilename ) ) { sio->saveFilename[strlen( sio->saveFilename ) - 1] = 0; } @@ -163,8 +158,7 @@ static enum SIOEvent _processSaveFilename( struct SIOInstance *sio ) break; default: /* ---------------------------- Add valid chars to save string ------------------ */ - if ( ( sio->Key > 31 ) && ( sio->Key < 255 ) ) - { + if ( ( sio->Key > 31 ) && ( sio->Key < 255 ) ) { sio->saveFilename = ( char * )realloc( sio->saveFilename, strlen( sio->saveFilename ) + 2 ); sio->saveFilename[strlen( sio->saveFilename ) + 1] = 0; sio->saveFilename[strlen( sio->saveFilename )] = sio->Key; @@ -234,12 +228,10 @@ static void _moveCursor( struct SIOInstance *sio, int lines ) { int dir = ( lines < 0 ) ? -1 : 1; - while ( lines && ( ( ( dir == -1 ) && ( sio->opTextRline ) ) || ( ( dir == 1 ) && ( sio->opTextRline < sio->opTextWline - 1 ) ) ) ) - { + while ( lines && ( ( ( dir == -1 ) && ( sio->opTextRline ) ) || ( ( dir == 1 ) && ( sio->opTextRline < sio->opTextWline - 1 ) ) ) ) { sio->opTextRline += dir; - if ( _onDisplay( sio, sio->opTextRline ) ) - { + if ( _onDisplay( sio, sio->opTextRline ) ) { lines -= dir; } } @@ -252,8 +244,7 @@ static enum SIOEvent _processRegularKeys( struct SIOInstance *sio ) { enum SIOEvent op = SIO_EV_NONE; - switch ( sio->Key ) - { + switch ( sio->Key ) { case ERR: op = SIO_EV_CONSUMED; break; @@ -287,9 +278,8 @@ static enum SIOEvent _processRegularKeys( struct SIOInstance *sio ) break; case 'd': /* ---------------------------- Display Mode ----------------------------------- */ - if ( !sio->amDiving ) - { - sio->displayMode = ( sio->displayMode + 1 ) % DISP_MAX_OPTIONS; + if ( !sio->amDiving ) { + sio->displayMode = ( enum DISP )( ( sio->displayMode + 1 ) % DISP_MAX_OPTIONS ); op = SIO_EV_CONSUMED; SIOrequestRefresh( sio ); } @@ -298,8 +288,7 @@ static enum SIOEvent _processRegularKeys( struct SIOInstance *sio ) case 'm': case 'M': /* ---------------------------- Enter Mark ------------------------------------- */ - if ( !sio->amDiving ) - { + if ( !sio->amDiving ) { sio->enteringMark = !sio->enteringMark; op = SIO_EV_CONSUMED; } @@ -308,15 +297,12 @@ static enum SIOEvent _processRegularKeys( struct SIOInstance *sio ) case 's': case 'S': /* ---------------------------- Enter save filename ---------------------------- */ - if ( ( sio->opTextWline ) && ( !sio->amDiving ) ) - { + if ( ( sio->opTextWline ) && ( !sio->amDiving ) ) { sio->saveFilename = ( char * )realloc( sio->saveFilename, 1 ); *sio->saveFilename = 0; curs_set( 1 ); sio->enteringSaveFilename = true; - } - else - { + } else { SIObeep(); } @@ -324,25 +310,16 @@ static enum SIOEvent _processRegularKeys( struct SIOInstance *sio ) break; case '0' ... '0'+MAX_TAGS: /* ----------- Tagged Location -------------------------------- */ - if ( sio->amDiving ) - { + if ( sio->amDiving ) { SIObeep(); - } - else - { - if ( sio->enteringMark ) - { + } else { + if ( sio->enteringMark ) { sio->tag[sio->Key - '0'] = sio->opTextRline + 1; sio->enteringMark = false; - } - else - { - if ( ( sio->tag[sio->Key - '0'] ) && ( sio->tag[sio->Key - '0'] < sio->opTextWline ) ) - { + } else { + if ( ( sio->tag[sio->Key - '0'] ) && ( sio->tag[sio->Key - '0'] < sio->opTextWline ) ) { sio->opTextRline = sio->tag[sio->Key - '0'] - 1; - } - else - { + } else { SIObeep(); } } @@ -408,11 +385,9 @@ static bool _updateSearch( struct SIOInstance *sio ) { for ( int32_t l = sio->opTextRline; - ( sio->searchMode == SRCH_FORWARDS ) ? ( l < sio->opTextWline - 1 ) : ( l > 0 ); - ( sio->searchMode == SRCH_FORWARDS ) ? l++ : l-- ) - { - if ( ( ( *sio->opText )[l].buffer ) && strstr( ( *sio->opText )[l].buffer, sio->searchString ) ) - { + ( sio->searchMode == SRCH_FORWARDS ) ? ( l < sio->opTextWline - 1 ) : ( l > 0 ); + ( sio->searchMode == SRCH_FORWARDS ) ? l++ : l-- ) { + if ( ( ( *sio->opText )[l].buffer ) && strstr( ( *sio->opText )[l].buffer, sio->searchString ) ) { /* This is a match */ sio->opTextRline = l; sio->searchOK = true; @@ -433,8 +408,7 @@ static enum SIOEvent _processSearchKeys( struct SIOInstance *sio ) { enum SIOEvent op = SIO_EV_NONE; - switch ( sio->Key ) - { + switch ( sio->Key ) { case ERR: op = SIO_EV_CONSUMED; break; @@ -461,8 +435,7 @@ static enum SIOEvent _processSearchKeys( struct SIOInstance *sio ) break; case 6: /* ----------------------------- CTRL-F Search Forwards ------------------------- */ - if ( !*sio->searchString ) - { + if ( !*sio->searchString ) { /* Try to re-instate old search */ *sio->searchString = sio->storedFirstSearch; } @@ -470,8 +443,7 @@ static enum SIOEvent _processSearchKeys( struct SIOInstance *sio ) sio->searchMode = SRCH_FORWARDS; /* Find next match */ - if ( ( sio->searchOK ) && ( sio->opTextRline < sio->opTextWline - 1 ) ) - { + if ( ( sio->searchOK ) && ( sio->opTextRline < sio->opTextWline - 1 ) ) { sio->opTextRline++; } @@ -481,8 +453,7 @@ static enum SIOEvent _processSearchKeys( struct SIOInstance *sio ) break; case 18: /* ---------------------------- CTRL-R Search Backwards ------------------------- */ - if ( !*sio->searchString ) - { + if ( !*sio->searchString ) { /* Try to re-instate old search */ *sio->searchString = sio->storedFirstSearch; } @@ -490,8 +461,7 @@ static enum SIOEvent _processSearchKeys( struct SIOInstance *sio ) /* Find prev match */ sio->searchMode = SRCH_BACKWARDS; - if ( ( sio->searchOK ) && ( sio->opTextRline > 0 ) ) - { + if ( ( sio->searchOK ) && ( sio->opTextRline > 0 ) ) { sio->opTextRline--; } @@ -503,8 +473,7 @@ static enum SIOEvent _processSearchKeys( struct SIOInstance *sio ) case 263: /* --------------------------- Del Remove char from search string -------------- */ /* Delete last character in search string */ - if ( strlen( sio->searchString ) ) - { + if ( strlen( sio->searchString ) ) { sio->searchString[strlen( sio->searchString ) - 1] = 0; } @@ -514,8 +483,7 @@ static enum SIOEvent _processSearchKeys( struct SIOInstance *sio ) break; default: /* ---------------------------- Add valid chars to search string ---------------- */ - if ( ( sio->Key > 31 ) && ( sio->Key < 255 ) ) - { + if ( ( sio->Key > 31 ) && ( sio->Key < 255 ) ) { sio->searchString = ( char * )realloc( sio->searchString, strlen( sio->searchString ) + 1 ); sio->searchString[strlen( sio->searchString ) + 1] = 0; sio->searchString[strlen( sio->searchString )] = sio->Key; @@ -540,14 +508,12 @@ static bool _displayLine( struct SIOInstance *sio, int32_t lineNum, int32_t scre char *u; /* Make sure this line is valid */ - if ( ( lineNum < 0 ) || ( lineNum >= sio->opTextWline ) ) - { + if ( ( lineNum < 0 ) || ( lineNum >= sio->opTextWline ) ) { return true; } /* ...and only display it if it fits the current mode */ - if ( !_onDisplay( sio, lineNum ) ) - { + if ( !_onDisplay( sio, lineNum ) ) { return false; } @@ -556,8 +522,7 @@ static bool _displayLine( struct SIOInstance *sio, int32_t lineNum, int32_t scre wmove( sio->outputWindow, screenline, 0 ); - switch ( ( *sio->opText )[lineNum].lt ) - { + switch ( ( *sio->opText )[lineNum].lt ) { case LT_EVENT: wattrset( sio->outputWindow, ( highlight ? A_STANDOUT : 0 ) | A_BOLD | COLOR_PAIR( CP_EVENT ) ); break; @@ -597,42 +562,33 @@ static bool _displayLine( struct SIOInstance *sio, int32_t lineNum, int32_t scre getyx( sio->outputWindow, y, x ); ( void )y; - while ( u && ( *u ) && ( *u != '\n' ) && ( *u != '\r' ) && ( x < OUTPUT_WINDOW_W ) ) - { + while ( u && ( *u ) && ( *u != '\n' ) && ( *u != '\r' ) && ( x < OUTPUT_WINDOW_W ) ) { /* Colour matches if we're in search mode, but whatever is happening, output the characters */ - if ( ( sio->searchMode != SRCH_OFF ) && ( *sio->searchString ) && ( !strncmp( u, ssp, strlen( ssp ) ) ) ) - { + if ( ( sio->searchMode != SRCH_OFF ) && ( *sio->searchString ) && ( !strncmp( u, ssp, strlen( ssp ) ) ) ) { wattrset( sio->outputWindow, A_BOLD | COLOR_PAIR( CP_SEARCH ) ); ssp++; - if ( !*ssp ) - { + if ( !*ssp ) { ssp = sio->searchString; } - } - else - { + } else { /* If the output string contains embedded escape colours then extract and respect them */ - while ( *u == 27 ) - { + while ( *u == 27 ) { u++; - if ( !strncmp( u, "[m", 2 ) ) - { + if ( !strncmp( u, "[m", 2 ) ) { u += 2; wattrset( sio->outputWindow, ( highlight ? A_BOLD | A_STANDOUT | COLOR_PAIR( CP_SOURCEHL ) : COLOR_PAIR( 15 ) ) ); continue; } - if ( !strncmp( u, "[3", 2 ) ) - { + if ( !strncmp( u, "[3", 2 ) ) { wattrset( sio->outputWindow, ( highlight ? A_BOLD | A_STANDOUT | COLOR_PAIR( CP_SOURCEHL ) : COLOR_PAIR( ( *( u + 2 ) ) - '0' ) ) ); u += 4; continue; } - if ( !strncmp( u, "[01;3", 5 ) ) - { + if ( !strncmp( u, "[01;3", 5 ) ) { wattrset( sio->outputWindow, ( highlight ? A_BOLD | A_STANDOUT | COLOR_PAIR( CP_SOURCEHL ) : COLOR_PAIR( ( *( u + 5 ) ) - '0' ) ) ); u += 7; continue; @@ -640,15 +596,11 @@ static bool _displayLine( struct SIOInstance *sio, int32_t lineNum, int32_t scre } } - if ( *u && ( *u != '\n' ) && ( *u != '\r' ) ) - { - if ( x == OUTPUT_WINDOW_W - 1 ) - { + if ( *u && ( *u != '\n' ) && ( *u != '\r' ) ) { + if ( x == OUTPUT_WINDOW_W - 1 ) { waddch( sio->outputWindow, '>' ); break; - } - else - { + } else { waddch( sio->outputWindow, *u++ ); } } @@ -660,10 +612,8 @@ static bool _displayLine( struct SIOInstance *sio, int32_t lineNum, int32_t scre wattr_set( sio->outputWindow, attr, pair, NULL ); /* Now pad out the rest of this line with spaces */ - if ( highlight ) - { - while ( x < OUTPUT_WINDOW_W ) - { + if ( highlight ) { + while ( x < OUTPUT_WINDOW_W ) { waddch( sio->outputWindow, ' ' ); x++; } @@ -684,10 +634,8 @@ static void _outputOutput( struct SIOInstance *sio ) cl = ( OUTPUT_WINDOW_L / 2 ); /* Firstly go forwards filling in each line of the screen */ - while ( ( cl < OUTPUT_WINDOW_L ) && ( cp < sio->opTextWline ) ) - { - if ( _displayLine( sio, cp++, cl, ( cl == ( OUTPUT_WINDOW_L / 2 ) ) ) ) - { + while ( ( cl < OUTPUT_WINDOW_L ) && ( cp < sio->opTextWline ) ) { + if ( _displayLine( sio, cp++, cl, ( cl == ( OUTPUT_WINDOW_L / 2 ) ) ) ) { cl++; } } @@ -696,10 +644,8 @@ static void _outputOutput( struct SIOInstance *sio ) cp = sio->opTextRline - 1; cl = ( OUTPUT_WINDOW_L / 2 ) - 1; - while ( ( cl >= 0 ) && ( cp >= 0 ) ) - { - if ( _displayLine( sio, cp--, cl, false ) ) - { + while ( ( cl >= 0 ) && ( cp >= 0 ) ) { + if ( _displayLine( sio, cp--, cl, false ) ) { cl--; } } @@ -714,10 +660,8 @@ static void _outputStatus( struct SIOInstance *sio, uint64_t oldintervalBytes ) mvwprintw( sio->statusWindow, 0, COLS - 4 - ( strlen( sio->progName ) + strlen( genericsBasename( sio->elffile ) ) ), " %s:%s ", sio->progName, genericsBasename( sio->elffile ) ); - if ( sio->warnTimeout ) - { - if ( sio->warnTimeout > genericsTimestampmS() ) - { + if ( sio->warnTimeout ) { + if ( sio->warnTimeout > genericsTimestampmS() ) { wattrset( sio->statusWindow, A_BOLD | COLOR_PAIR( CP_PROBLEM ) ); mvwprintw( sio->statusWindow, 1, 1, " %s ", sio->warnText ); } @@ -725,47 +669,33 @@ static void _outputStatus( struct SIOInstance *sio, uint64_t oldintervalBytes ) wattrset( sio->statusWindow, A_BOLD | COLOR_PAIR( CP_BASELINE ) ); - if ( sio->opTextWline ) - { + if ( sio->opTextWline ) { /* We have some opData stored, indicate where we are in it */ mvwprintw( sio->statusWindow, 0, 2, " %d%% (%d/%d) ", ( sio->opTextRline * 100 ) / ( sio->opTextWline - 1 ), sio->opTextRline + 1, sio->opTextWline ); } - if ( !sio->amDiving ) - { - mvwprintw( sio->statusWindow, 0, 44, " %s%s", ( char *[] ) - {"Mixed", "Source", "Assembly" + if ( !sio->amDiving ) { + mvwprintw( sio->statusWindow, 0, 44, " %s%s", ( char *[] ) { + ( char * )"Mixed", ( char * )"Source", ( char * )"Assembly" }[sio->displayMode], sio->outputDebug ? "+Debug " : " " ); - } - else - { + } else { mvwprintw( sio->statusWindow, 0, 30, " Diving Buffer " ); } wattrset( sio->statusWindow, A_BOLD | COLOR_PAIR( CP_BASELINETEXT ) ); - if ( sio->isFile ) - { + if ( sio->isFile ) { mvwprintw( sio->statusWindow, 1, COLS - 13 - ( ( sio->ttext ) ? strlen( sio->ttext ) : 0 ), "%s From file", ( sio->ttext ) ? sio->ttext : "" ); - } - else - { - if ( !sio->held ) - { + } else { + if ( !sio->held ) { uint64_t oldintervalBits = oldintervalBytes * 8; - if ( oldintervalBytes ) - { - if ( oldintervalBits < 9999 ) - { + if ( oldintervalBytes ) { + if ( oldintervalBits < 9999 ) { mvwprintw( sio->statusWindow, 1, COLS - 45, "%" PRIu64 " bps (~%" PRIu64 " Ips)", oldintervalBits, oldintervalBits / 11 ); - } - else if ( oldintervalBytes < 9999999 ) - { + } else if ( oldintervalBytes < 9999999 ) { mvwprintw( sio->statusWindow, 1, COLS - 45, "%" PRIu64 " Kbps (~%" PRIu64 " KIps)", oldintervalBits / 1000, oldintervalBits / 1120 ); - } - else - { + } else { mvwprintw( sio->statusWindow, 1, COLS - 45, "%" PRIu64 " Mbps (~%" PRIu64 " MIps)", oldintervalBits / 1000000, oldintervalBits / 1120000 ); } } @@ -773,61 +703,49 @@ static void _outputStatus( struct SIOInstance *sio, uint64_t oldintervalBytes ) mvwprintw( sio->statusWindow, 1, COLS - 11 - ( ( sio->ttext ) ? strlen( sio->ttext ) : 0 ), "%s %s", ( sio->ttext ) ? sio->ttext : "", oldintervalBytes ? "Capturing" : " Waiting" ); - } - else - { + } else { mvwprintw( sio->statusWindow, 1, COLS - 6 - ( ( sio->ttext ) ? strlen( sio->ttext ) : 0 ), "%s Hold", ( ( sio->ttext ) ? sio->ttext : "" ) ); } } /* We only output the tags while not in a diving buffer */ - if ( ! sio->amDiving ) - { + if ( ! sio->amDiving ) { mvwprintw( sio->statusWindow, 0, 30, " " ); - for ( uint32_t t = 0; t < MAX_TAGS; t++ ) - { - if ( sio->tag[t] ) - { + for ( uint32_t t = 0; t < MAX_TAGS; t++ ) { + if ( sio->tag[t] ) { wattrset( sio->statusWindow, A_BOLD | COLOR_PAIR( CP_BASELINETEXT ) ); if ( ( sio->tag[t] >= ( sio->opTextRline - OUTPUT_WINDOW_L / 2 ) ) && - ( sio->tag[t] <= ( sio->opTextRline + ( OUTPUT_WINDOW_L + 1 ) / 2 ) ) ) - { + ( sio->tag[t] <= ( sio->opTextRline + ( OUTPUT_WINDOW_L + 1 ) / 2 ) ) ) { /* This tag is on the visible page */ wattrset( sio->outputWindow, A_BOLD | COLOR_PAIR( CP_BASELINETEXT ) ); mvwprintw( sio->outputWindow, ( OUTPUT_WINDOW_L ) / 2 + sio->tag[t] - sio->opTextRline - 1, OUTPUT_WINDOW_W - 1, "%d", t ); } - } - else - { + } else { wattrset( sio->statusWindow, A_BOLD | COLOR_PAIR( CP_BASELINE ) ); } wprintw( sio->statusWindow, "%d", t ); } - if ( !sio->warnTimeout ) - { + if ( !sio->warnTimeout ) { wprintw( sio->statusWindow, " " ); } } /* Deal with the various modes */ - if ( sio->enteringSaveFilename ) - { + if ( sio->enteringSaveFilename ) { wattrset( sio->statusWindow, A_BOLD | COLOR_PAIR( CP_SEARCH ) ); mvwprintw( sio->statusWindow, 1, 2, "Save Filename :%s", sio->saveFilename ); } - if ( sio->searchMode ) - { + if ( sio->searchMode ) { wattrset( sio->statusWindow, A_BOLD | COLOR_PAIR( CP_SEARCH ) ); mvwprintw( sio->statusWindow, 1, 2, "%sSearch %s :%s", sio->searchOK ? "" : "(Failing) ", ( sio->searchMode == SRCH_FORWARDS ) ? "Forwards" : "Backwards", sio->searchString ); } - if ( sio->enteringMark ) - { + if ( sio->enteringMark ) { wattrset( sio->statusWindow, A_BOLD | COLOR_PAIR( CP_SEARCH ) ); mvwprintw( sio->statusWindow, 1, 2, "Mark Number?" ); } @@ -845,15 +763,11 @@ static void _updateWindows( struct SIOInstance *sio, bool isTick, bool isKey, ui bool refreshStatus = false; /* Flag indicating that status window needs updating */ /* First, work with the output window */ - if ( sio->outputtingHelp ) - { + if ( sio->outputtingHelp ) { _outputHelp( sio ); refreshOutput = true; - } - else - { - if ( ( sio->oldopTextRline != sio->opTextRline ) || ( sio->forceRefresh ) ) - { + } else { + if ( ( sio->oldopTextRline != sio->opTextRline ) || ( sio->forceRefresh ) ) { _outputOutput( sio ); sio->oldopTextRline = sio->opTextRline; refreshOutput = true; @@ -861,8 +775,7 @@ static void _updateWindows( struct SIOInstance *sio, bool isTick, bool isKey, ui } /* Now update the status */ - if ( ( isTick ) || ( isKey ) || ( sio->forceRefresh ) || ( sio->warnTimeout ) ) - { + if ( ( isTick ) || ( isKey ) || ( sio->forceRefresh ) || ( sio->warnTimeout ) ) { _outputStatus( sio, oldintervalBytes ); refreshOutput = refreshStatus = true; } @@ -870,13 +783,11 @@ static void _updateWindows( struct SIOInstance *sio, bool isTick, bool isKey, ui sio->forceRefresh = false; /* Now do any refreshes that are needed */ - if ( refreshOutput ) - { + if ( refreshOutput ) { wrefresh( sio->outputWindow ); } - if ( refreshStatus ) - { + if ( refreshStatus ) { wrefresh( sio->statusWindow ); } } @@ -911,10 +822,8 @@ struct SIOInstance *SIOsetup( const char *progname, const char *elffile, bool is sio->lines = LINES; sio->cols = COLS; - if ( OK == start_color() ) - { - for ( int i = 0; i < 16; i++ ) - { + if ( OK == start_color() ) { + for ( int i = 0; i < 16; i++ ) { init_pair( i, COLOR_BLACK + i, COLOR_BLACK ); } @@ -971,8 +880,7 @@ int32_t SIOgetLastLineno( struct SIOInstance *sio ) void SIOsetCurrentLineno( struct SIOInstance *sio, int32_t l ) { - if ( ( l >= 0 ) && ( l < sio->opTextWline - 1 ) ) - { + if ( ( l >= 0 ) && ( l < sio->opTextWline - 1 ) ) { sio->opTextRline = l; } } @@ -1014,26 +922,19 @@ void SIOsetOutputBuffer( struct SIOInstance *sio, int32_t numLines, int32_t curr sio->opText = opTextSet; /* If we're starting diving store the current cursor position, on surfacing restore it */ - if ( ( !sio->amDiving ) && ( amDiving ) ) - { + if ( ( !sio->amDiving ) && ( amDiving ) ) { sio->pushedopTextRline = sio->opTextRline; } - if ( opTextSet ) - { + if ( opTextSet ) { sio->opTextWline = numLines; - if ( ( sio->amDiving ) && ( !amDiving ) ) - { + if ( ( sio->amDiving ) && ( !amDiving ) ) { sio->opTextRline = sio->pushedopTextRline; - } - else - { + } else { sio->opTextRline = currentLine; } - } - else - { + } else { sio->opTextWline = sio->opTextRline = 0; _deleteTags( sio ); } @@ -1069,24 +970,17 @@ enum SIOEvent SIOHandler( struct SIOInstance *sio, bool isTick, uint64_t oldinte sio->Key = wgetch( sio->statusWindow ); - if ( sio->Key != ERR ) - { - if ( sio->enteringSaveFilename ) - { + if ( sio->Key != ERR ) { + if ( sio->enteringSaveFilename ) { op = _processSaveFilename( sio ); - } - else - { + } else { op = ( sio->searchMode ) ? _processSearchKeys( sio ) : _processRegularKeys( sio ); } - if ( op != SIO_EV_CONSUMED ) - { - switch ( sio->Key ) - { + if ( op != SIO_EV_CONSUMED ) { + switch ( sio->Key ) { case KEY_RESIZE: - case 12: /* CTRL-L, refresh ----------------------------------------------------- */ - { + case 12: { /* CTRL-L, refresh ----------------------------------------------------- */ #if defined(WIN32) getmaxyx( sio->outputWindow, sio->lines, sio->cols ); #else @@ -1109,8 +1003,7 @@ enum SIOEvent SIOHandler( struct SIOInstance *sio, bool isTick, uint64_t oldinte case '^': op = SIO_EV_CONSUMED; - if ( supportDebug ) - { + if ( supportDebug ) { isTick = true; sio->outputDebug = !sio->outputDebug; SIOrequestRefresh( sio ); diff --git a/Src/stream_file_posix.c b/Src/stream_file_posix.c index 0b684f1b..15dbb115 100644 --- a/Src/stream_file_posix.c +++ b/Src/stream_file_posix.c @@ -6,8 +6,7 @@ #include "generics.h" -struct PosixFileStream -{ +struct PosixFileStream { struct Stream base; int file; }; @@ -25,21 +24,18 @@ static enum ReceiveResult _posixFileStreamReceive( struct Stream *stream, void * int r = select( self->file + 1, &readFd, NULL, NULL, timeout ); - if ( r < 0 ) - { + if ( r < 0 ) { return RECEIVE_RESULT_ERROR; } - if ( r == 0 ) - { + if ( r == 0 ) { *receivedSize = 0; return RECEIVE_RESULT_TIMEOUT; } *receivedSize = read( self->file, buffer, bufferSize ); - if ( *receivedSize == 0 ) - { + if ( *receivedSize == 0 ) { return RECEIVE_RESULT_EOF; } @@ -58,8 +54,7 @@ static int _posixFileStreamCreate( const char *file ) { int f = open( file, O_RDONLY ); - if ( f < 0 ) - { + if ( f < 0 ) { genericsExit( -4, "Can't open file %s" EOL, file ); } @@ -84,8 +79,7 @@ struct Stream *streamCreateFile( const char *file ) { struct PosixFileStream *stream = SELF( calloc( 1, sizeof( struct PosixFileStream ) ) ); - if ( stream == NULL ) - { + if ( stream == NULL ) { return NULL; } @@ -93,8 +87,7 @@ struct Stream *streamCreateFile( const char *file ) stream->base.close = _posixFileStreamClose; stream->file = _posixFileStreamCreate( file ); - if ( stream->file == -1 ) - { + if ( stream->file == -1 ) { free( stream ); return NULL; } diff --git a/Src/stream_file_win32.c b/Src/stream_file_win32.c index c23a79f4..9e425b87 100644 --- a/Src/stream_file_win32.c +++ b/Src/stream_file_win32.c @@ -6,8 +6,7 @@ #include "generics.h" -struct Win32FileStream -{ +struct Win32FileStream { struct Win32Stream base; }; @@ -50,13 +49,11 @@ struct Stream *streamCreateFile( const char *file ) { struct Win32FileStream *stream = SELF( calloc( 1, sizeof( struct Win32FileStream ) ) ); - if ( stream == NULL ) - { + if ( stream == NULL ) { return NULL; } - if ( !streamWin32Initialize( ( struct Win32Stream * )stream, _win32FileStreamCreate( file ) ) ) - { + if ( !streamWin32Initialize( ( struct Win32Stream * )stream, _win32FileStreamCreate( file ) ) ) { free( stream ); return NULL; } diff --git a/Src/stream_socket_posix.c b/Src/stream_socket_posix.c index b011c54f..a2d93d0a 100644 --- a/Src/stream_socket_posix.c +++ b/Src/stream_socket_posix.c @@ -16,8 +16,7 @@ /* How long to wait for a connection before declaring failure */ #define CONNECT_WAIT_TIME_MS (2000) -struct PosixSocketStream -{ +struct PosixSocketStream { struct Stream base; int socket; }; @@ -44,21 +43,18 @@ static enum ReceiveResult _posixSocketStreamReceive( struct Stream *stream, void int r = select( self->socket + 1, &readFd, NULL, NULL, timeout ); - if ( r < 0 ) - { + if ( r < 0 ) { return RECEIVE_RESULT_ERROR; } - if ( r == 0 ) - { + if ( r == 0 ) { *receivedSize = 0; return RECEIVE_RESULT_TIMEOUT; } ssize_t result = recv( self->socket, buffer, bufferSize, 0 ); - if ( result <= 0 ) - { + if ( result <= 0 ) { // report connection broken as error return RECEIVE_RESULT_ERROR; } @@ -82,8 +78,7 @@ static int _posixSocketStreamCreate( const char *server, int port ) struct sockaddr_in serv_addr; struct hostent *serverEnt = gethostbyname( server ); - if ( !serverEnt ) - { + if ( !serverEnt ) { close( sockfd ); genericsReport( V_ERROR, "Cannot find host" EOL ); return -1; @@ -91,8 +86,7 @@ static int _posixSocketStreamCreate( const char *server, int port ) setsockopt( sockfd, SOL_SOCKET, SO_REUSEPORT, ( const void * )&flag, sizeof( flag ) ); - if ( sockfd < 0 ) - { + if ( sockfd < 0 ) { genericsReport( V_ERROR, "Error creating socket" EOL ); return -1; } @@ -114,16 +108,14 @@ static int _posixSocketStreamCreate( const char *server, int port ) connect( sockfd, ( struct sockaddr * )&serv_addr, sizeof( serv_addr ) ); - if ( ( errno != EWOULDBLOCK ) && ( errno != EINPROGRESS ) ) - { + if ( ( errno != EWOULDBLOCK ) && ( errno != EINPROGRESS ) ) { close( sockfd ); return -1; } struct pollfd pfds[] = { { .fd = sockfd, .events = POLLOUT } }; - if ( 0 == poll( pfds, 1, CONNECT_WAIT_TIME_MS ) ) - { + if ( 0 == poll( pfds, 1, CONNECT_WAIT_TIME_MS ) ) { close( sockfd ); return -1; } @@ -131,16 +123,14 @@ static int _posixSocketStreamCreate( const char *server, int port ) socklen_t error; socklen_t len = sizeof( socklen_t ); - if ( 0 != getsockopt( sockfd, SOL_SOCKET, SO_ERROR, &error, &len ) ) - { + if ( 0 != getsockopt( sockfd, SOL_SOCKET, SO_ERROR, &error, &len ) ) { flag = -1; } fcntl( sockfd, F_SETFL, sockfd_flags_before ); /* If we got an error give up */ - if ( 0 != error ) - { + if ( 0 != error ) { close( sockfd ); return -1; } @@ -166,8 +156,7 @@ struct Stream *streamCreateSocket( const char *server, int port ) { struct PosixSocketStream *stream = SELF( calloc( 1, sizeof( struct PosixSocketStream ) ) ); - if ( stream == NULL ) - { + if ( stream == NULL ) { return NULL; } @@ -175,8 +164,7 @@ struct Stream *streamCreateSocket( const char *server, int port ) stream->base.close = _posixSocketStreamClose; stream->socket = _posixSocketStreamCreate( server, port ); - if ( stream->socket == -1 ) - { + if ( stream->socket == -1 ) { free( stream ); return NULL; } diff --git a/Src/stream_socket_win32.c b/Src/stream_socket_win32.c index 75165486..0ee12105 100644 --- a/Src/stream_socket_win32.c +++ b/Src/stream_socket_win32.c @@ -9,8 +9,7 @@ #include "generics.h" -struct Win32SocketStream -{ +struct Win32SocketStream { struct Win32Stream base; }; @@ -48,18 +47,16 @@ static HANDLE _win32SocketStreamCreate( const char *server, int port ) int sockfd = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP ); int flag = 1; - setsockopt( sockfd, SOL_SOCKET, SO_REUSEPORT, ( const void * )&flag, sizeof( flag ) ); + setsockopt( sockfd, SOL_SOCKET, SO_REUSEPORT, ( const char * )&flag, sizeof( flag ) ); - if ( sockfd < 0 ) - { + if ( sockfd < 0 ) { genericsReport( V_ERROR, "Error creating socket" EOL ); return INVALID_HANDLE_VALUE; } struct hostent *serverEnt = gethostbyname( server ); - if ( !serverEnt ) - { + if ( !serverEnt ) { close( sockfd ); genericsReport( V_ERROR, "Cannot find host" EOL ); return INVALID_HANDLE_VALUE; @@ -76,8 +73,7 @@ static HANDLE _win32SocketStreamCreate( const char *server, int port ) serv_addr.sin_port = htons( port ); - if ( connect( sockfd, ( struct sockaddr * ) &serv_addr, sizeof( serv_addr ) ) < 0 ) - { + if ( connect( sockfd, ( struct sockaddr * ) &serv_addr, sizeof( serv_addr ) ) < 0 ) { close( sockfd ); return INVALID_HANDLE_VALUE; } @@ -98,13 +94,11 @@ struct Stream *streamCreateSocket( const char *server, int port ) { struct Win32SocketStream *stream = SELF( calloc( 1, sizeof( struct Win32SocketStream ) ) ); - if ( stream == NULL ) - { + if ( stream == NULL ) { return NULL; } - if ( !streamWin32Initialize( ( struct Win32Stream * )stream, _win32SocketStreamCreate( server, port ) ) ) - { + if ( !streamWin32Initialize( ( struct Win32Stream * )stream, _win32SocketStreamCreate( server, port ) ) ) { free( stream ); return NULL; } diff --git a/Src/stream_win32.c b/Src/stream_win32.c index 29c76841..c0e27c8b 100644 --- a/Src/stream_win32.c +++ b/Src/stream_win32.c @@ -13,12 +13,9 @@ // ==================================================================================================== static uint32_t _convertTimeout( const struct timeval *timeout ) { - if ( timeout != NULL ) - { + if ( timeout != NULL ) { return ( timeout->tv_sec * ( uint64_t )1000 ) + ( timeout->tv_usec / 1000 ); - } - else - { + } else { return INFINITE; } } @@ -40,15 +37,13 @@ static enum ReceiveResult _win32StreamReceive( struct Stream *stream, void *buff DWORD bytesRead; bool readResult = ReadFile( self->source, buffer, bufferSize, &bytesRead, &asyncRead ); - if ( readResult ) - { + if ( readResult ) { *receivedSize = bytesRead; asyncRead.Offset += bytesRead; return RECEIVE_RESULT_OK; } - if ( GetLastError() != ERROR_IO_PENDING ) - { + if ( GetLastError() != ERROR_IO_PENDING ) { return RECEIVE_RESULT_ERROR; } @@ -56,32 +51,25 @@ static enum ReceiveResult _win32StreamReceive( struct Stream *stream, void *buff DWORD waitResult = WaitForSingleObjectEx( self->readDoneEvent, _convertTimeout( timeout ), true ); - if ( waitResult == WAIT_TIMEOUT ) - { + if ( waitResult == WAIT_TIMEOUT ) { CancelIoEx( self->source, &asyncRead ); WaitForSingleObjectEx( self->readDoneEvent, INFINITE, true ); GetOverlappedResult( self->source, &asyncRead, &bytesRead, true ); return RECEIVE_RESULT_TIMEOUT; } - if ( GetOverlappedResult( self->source, &asyncRead, &bytesRead, true ) == 0 ) - { - if ( GetLastError() != ERROR_HANDLE_EOF ) - { + if ( GetOverlappedResult( self->source, &asyncRead, &bytesRead, true ) == 0 ) { + if ( GetLastError() != ERROR_HANDLE_EOF ) { return RECEIVE_RESULT_ERROR; } } *receivedSize = bytesRead; - if ( bytesRead == 0 ) - { - if ( GetLastError() == ERROR_HANDLE_EOF ) - { + if ( bytesRead == 0 ) { + if ( GetLastError() == ERROR_HANDLE_EOF ) { return RECEIVE_RESULT_EOF; - } - else - { + } else { return RECEIVE_RESULT_TIMEOUT; } } @@ -108,8 +96,7 @@ static void _win32StreamCloseInner( struct Stream *stream ) // ==================================================================================================== bool streamWin32Initialize( struct Win32Stream *stream, HANDLE sourceHandle ) { - if ( sourceHandle == INVALID_HANDLE_VALUE ) - { + if ( sourceHandle == INVALID_HANDLE_VALUE ) { return false; } @@ -124,8 +111,7 @@ bool streamWin32Initialize( struct Win32Stream *stream, HANDLE sourceHandle ) // ==================================================================================================== void streamWin32Close( struct Win32Stream *stream ) { - if ( stream->source != INVALID_HANDLE_VALUE ) - { + if ( stream->source != INVALID_HANDLE_VALUE ) { CancelIo( stream->source ); CloseHandle( stream->source ); stream->source = INVALID_HANDLE_VALUE; diff --git a/Src/symbols.c b/Src/symbols.c index bd109d16..196ac328 100644 --- a/Src/symbols.c +++ b/Src/symbols.c @@ -26,8 +26,8 @@ #define SOURCE_INDICATOR "sRc##" #define SYM_NOT_FOUND (0xffffffff) -#define NO_FUNCTION_TXT "No Function Name" -#define NO_FILE_TXT "No Source" +#define NO_FUNCTION_TXT (char*)"No Function Name" +#define NO_FILE_TXT (char*)"No Source" //#define GPTI_DEBUG 1 /* Define this for objdump data collection state machine trace */ @@ -54,8 +54,7 @@ static uint32_t _getFileEntryIdx( struct SymbolSet *s, char *filename ) { uint32_t i = 0; - while ( ( i < s->fileCount ) && ( strcmp( s->files[i].name, filename ) ) ) - { + while ( ( i < s->fileCount ) && ( strcmp( s->files[i].name, filename ) ) ) { i++; } @@ -71,23 +70,20 @@ static uint32_t _getOrAddFileEntryIdx( struct SymbolSet *s, char *filename ) char *d = s->deleteMaterial; /* Scan forwards past any delete material on the front */ - while ( ( d ) && ( *d ) && ( *fl == *d ) ) - { + while ( ( d ) && ( *d ) && ( *fl == *d ) ) { d++; fl++; } /* If we didn't manage to delete everything then don't delete anything */ - if ( fl - filename != strlen( s->deleteMaterial ) ) - { + if ( fl - filename != ( long int )strlen( s->deleteMaterial ) ) { fl = filename; } uint32_t f = _getFileEntryIdx( s, fl ); - if ( SYM_NOT_FOUND == f ) - { + if ( SYM_NOT_FOUND == f ) { /* Doesn't exist, so create it */ s->files = ( struct fileEntry * )realloc( s->files, sizeof( struct fileEntry ) * ( s->fileCount + 1 ) ); f = s->fileCount; @@ -106,8 +102,7 @@ static uint32_t _getFunctionEntryIdx( struct SymbolSet *s, char *function ) { uint32_t i = 0; - while ( ( i < s->functionCount ) && ( strcmp( s->functions[i].name, function ) ) ) - { + while ( ( i < s->functionCount ) && ( strcmp( s->functions[i].name, function ) ) ) { i++; } @@ -126,8 +121,7 @@ static uint32_t _getOrAddFunctionEntryIdx( struct SymbolSet *s, char *function ) { uint32_t f = _getFunctionEntryIdx( s, function ); - if ( SYM_NOT_FOUND == f ) - { + if ( SYM_NOT_FOUND == f ) { /* Doesn't exist, so create it */ s->functions = ( struct functionEntry * )realloc( s->functions, sizeof( struct functionEntry ) * ( s->functionCount + 1 ) ); f = s->functionCount; @@ -164,14 +158,12 @@ static int _compareLines( const void *a, const void *b ) struct sourceLineEntry *sb = ( struct sourceLineEntry * )b; /* Is it before the start of this line? */ - if ( sa->startAddr < sb->startAddr ) - { + if ( sa->startAddr < sb->startAddr ) { return -1; } /* Is it after the end of this line? */ - if ( sa->startAddr > sb->endAddr ) - { + if ( sa->startAddr > sb->endAddr ) { return 1; } @@ -199,10 +191,9 @@ static bool _find_symbol( struct SymbolSet *s, uint32_t workingAddr, { struct sourceLineEntry needle = { .startAddr = workingAddr, .endAddr = workingAddr }; - struct sourceLineEntry *found = bsearch( &needle, s->sources, s->sourceCount, sizeof( struct sourceLineEntry ), _compareLines ); + struct sourceLineEntry *found = ( struct sourceLineEntry * )bsearch( &needle, s->sources, s->sourceCount, sizeof( struct sourceLineEntry ), _compareLines ); - if ( found ) - { + if ( found ) { *pline = found->lineNo; *linesInBlock = found->linesInBlock; *psource = found->lineText; @@ -211,17 +202,14 @@ static bool _find_symbol( struct SymbolSet *s, uint32_t workingAddr, *functionindex = found->functionIdx; /* If there is assembly then match the line too */ - for ( *assyLine = 0; *assyLine < found->assyLines; ( *assyLine )++ ) - { - if ( ( *assy )[*assyLine].addr == workingAddr ) - { + for ( *assyLine = 0; *assyLine < found->assyLines; ( *assyLine )++ ) { + if ( ( *assy )[*assyLine].addr == workingAddr ) { break; } } /* If the assembly line wasn't found then indicate that */ - if ( *assyLine == found->assyLines ) - { + if ( *assyLine == found->assyLines ) { *assyLine = ASSY_NOT_FOUND; } @@ -237,70 +225,58 @@ static enum LineType _getLineType( char *sourceLine, char *p1, char *p2, char *p { /* If it's empty, something is badly wrong */ - if ( !*sourceLine ) - { + if ( !*sourceLine ) { return LT_NULL; } /* If it starts with a source tag, it's unambigious */ - if ( !strncmp( sourceLine, SOURCE_INDICATOR, strlen( SOURCE_INDICATOR ) ) ) - { + if ( !strncmp( sourceLine, SOURCE_INDICATOR, strlen( SOURCE_INDICATOR ) ) ) { return LT_SOURCE; } /* If it has an address followed by pairs of hex digits then it's a data block and we're not interested */ - if ( 1 == sscanf( sourceLine, " %*[0-9a-fA-F]: %[0-9a-fA-F]", p1 ) ) - { + if ( 1 == sscanf( sourceLine, " %*[0-9a-fA-F]: %[0-9a-fA-F]", p1 ) ) { /* Match is two digits followed by a whitespace */ - if ( ( isxdigit( *p1 ) ) && ( isxdigit( *( p1 + 1 ) ) ) && ( !( *( p1 + 2 ) ) ) ) - { + if ( ( isxdigit( *p1 ) ) && ( isxdigit( *( p1 + 1 ) ) ) && ( !( *( p1 + 2 ) ) ) ) { return LT_NOISE; } } /* If it has something with in it, it's a proc label (function) */ - if ( 2 == sscanf( sourceLine, "%[0-9a-fA-F] <%[^>]>", p1, p2 ) ) - { + if ( 2 == sscanf( sourceLine, "%[0-9a-fA-F] <%[^>]>", p1, p2 ) ) { return LT_PROC_LABEL; } /* If it has (): on the end it's a label */ - if ( 2 == sscanf( sourceLine, "%[^(]()%c", p1, p2 ) ) - { - if ( *p2 == ':' ) - { + if ( 2 == sscanf( sourceLine, "%[^(]()%c", p1, p2 ) ) { + if ( *p2 == ':' ) { return LT_LABEL; } } /* If it starts with a space and has specific fields, it's a 16 or 32 bit assembly line */ - if ( 4 == sscanf( sourceLine, " %[0-9a-fA-F]: %[0-9a-fA-F]%*1[ ]%[0-9a-fA-F] %[^\n]", p1, p2, p3, p4 ) ) - { + if ( 4 == sscanf( sourceLine, " %[0-9a-fA-F]: %[0-9a-fA-F]%*1[ ]%[0-9a-fA-F] %[^\n]", p1, p2, p3, p4 ) ) { return LT_ASSEMBLY; } *p2 = 0; - if ( 3 == sscanf( sourceLine, " %[0-9a-fA-F]: %[0-9a-fA-F] %[^\n]", p1, p3, p4 ) ) - { + if ( 3 == sscanf( sourceLine, " %[0-9a-fA-F]: %[0-9a-fA-F] %[^\n]", p1, p3, p4 ) ) { return LT_ASSEMBLY; } /* If it contains text:num then it's a file and line */ - if ( 2 == sscanf( sourceLine, "%[^:]:%[0-9]", p1, p2 ) ) - { + if ( 2 == sscanf( sourceLine, "%[^:]:%[0-9]", p1, p2 ) ) { return LT_FILEANDLINE; } /* Alternative form for Windows; If it contains Drive:text:num then it's a file and line */ - if ( 3 == sscanf( sourceLine, "%2c%[^:]:%[0-9]", p1, &p1[2], p2 ) ) - { + if ( 3 == sscanf( sourceLine, "%2c%[^:]:%[0-9]", p1, &p1[2], p2 ) ) { return LT_FILEANDLINE; } /* If it contains nothing other than newline then its a newline */ - if ( ( *sourceLine == '\n' ) || ( *sourceLine == '\r' ) ) - { + if ( ( *sourceLine == '\n' ) || ( *sourceLine == '\r' ) ) { return LT_NEWLINE; } @@ -316,8 +292,7 @@ static bool _getDest( char *assy, uint32_t *dest ) { int r = sscanf( assy, "%*[^\t]\t%x", dest ); - if ( r == 1 ) - { + if ( r == 1 ) { return r; } @@ -386,8 +361,7 @@ static FILE *_openProcess( char *commandLine, PROCESS_INFORMATION *processInfo, CloseHandle( processOutPipe ); CloseHandle( processErrorPipe ); - if ( !success ) - { + if ( !success ) { CloseHandle( readingPipe ); CloseHandle( errorReadingPipe ); return NULL; @@ -396,8 +370,7 @@ static FILE *_openProcess( char *commandLine, PROCESS_INFORMATION *processInfo, int fd = _open_osfhandle( ( intptr_t )readingPipe, _O_RDONLY ); - if ( fd == -1 ) - { + if ( fd == -1 ) { CloseHandle( readingPipe ); CloseHandle( errorReadingPipe ); return NULL; @@ -405,16 +378,14 @@ static FILE *_openProcess( char *commandLine, PROCESS_INFORMATION *processInfo, FILE *f = _fdopen( fd, "r" ); - if ( f == NULL ) - { + if ( f == NULL ) { _close( fd ); return NULL; } int errorFd = _open_osfhandle( ( intptr_t )errorReadingPipe, _O_RDONLY ); - if ( errorFd == -1 ) - { + if ( errorFd == -1 ) { fclose( f ); CloseHandle( errorReadingPipe ); return NULL; @@ -422,8 +393,7 @@ static FILE *_openProcess( char *commandLine, PROCESS_INFORMATION *processInfo, *errorOutput = _fdopen( errorFd, "r" ); - if ( *errorOutput == NULL ) - { + if ( *errorOutput == NULL ) { _close( errorFd ); fclose( f ); return NULL; @@ -460,17 +430,13 @@ static enum symbolErr _getTargetProgramInfo( struct SymbolSet *s ) uint32_t nullFileEntry; /* Tag for when we don't have a filename */ struct sourceLineEntry *sourceEntry = NULL; /* pointer to current source entry */ - if ( stat( s->elfFile, &s->st ) != 0 ) - { + if ( stat( s->elfFile, &s->st ) != 0 ) { return SYMBOL_NOELF; } - if ( getenv( OBJENVNAME ) ) - { + if ( getenv( OBJENVNAME ) ) { snprintf( commandLine, MAX_LINE_LEN, "%s -Sl%s --source-comment=" SOURCE_INDICATOR " %s %s", getenv( OBJENVNAME ), s->demanglecpp ? " -C" : "", s->elfFile, s->odoptions ); - } - else - { + } else { snprintf( commandLine, MAX_LINE_LEN, OBJDUMP " -Sl%s --source-comment=" SOURCE_INDICATOR " %s %s", s->demanglecpp ? " -C" : "", s->elfFile, s->odoptions ); } @@ -483,8 +449,7 @@ static enum symbolErr _getTargetProgramInfo( struct SymbolSet *s ) f = popen( commandLine, "r" ); #endif - if ( !f ) - { + if ( !f ) { return SYMBOL_NOOBJDUMP; } @@ -493,14 +458,12 @@ static enum symbolErr _getTargetProgramInfo( struct SymbolSet *s ) functionEntryIdx = _getOrAddFunctionEntryIdx( s, NO_FUNCTION_TXT ); nullFileEntry = fileEntryIdx = _getOrAddFileEntryIdx( s, NO_FILE_TXT ); - while ( !feof( f ) ) - { + while ( !feof( f ) ) { fgets( line, MAX_LINE_LEN, f ); lt = _getLineType( line, p1, p2, p3, p4 ); - if ( lt == LT_ERROR ) - { + if ( lt == LT_ERROR ) { pclose( f ); return SYMBOL_UNSPECIFIED; } @@ -511,8 +474,7 @@ static enum symbolErr _getTargetProgramInfo( struct SymbolSet *s ) #ifdef GPTI_DEBUG - switch ( ps ) - { + switch ( ps ) { case PS_IDLE: GTPIP( "IDLE(" ); break; @@ -526,8 +488,7 @@ static enum symbolErr _getTargetProgramInfo( struct SymbolSet *s ) break; } - switch ( lt ) - { + switch ( lt ) { case LT_NOISE: GTPIP( "NOISE" ); break; @@ -564,11 +525,9 @@ static enum symbolErr _getTargetProgramInfo( struct SymbolSet *s ) GTPIP( ")" EOL ); #endif - switch ( ps ) - { + switch ( ps ) { case PS_IDLE: /* Waiting for name of function ================================== */ - switch ( lt ) - { + switch ( lt ) { case LT_NOISE: /* ------------------------------------------------------ */ break; @@ -622,8 +581,7 @@ static enum symbolErr _getTargetProgramInfo( struct SymbolSet *s ) break; case PS_GET_SOURCE: /* Collecting source ========================================== */ - switch ( lt ) - { + switch ( lt ) { case LT_NOISE: /* ------------------------------------------------------ */ break; @@ -634,8 +592,7 @@ static enum symbolErr _getTargetProgramInfo( struct SymbolSet *s ) sourceEntry->lineNo = lineNo; // Add this to source line repository - if ( s->recordSource ) - { + if ( s->recordSource ) { sourceEntry->lineText = ( char * )realloc( sourceEntry->lineText, strlen( line ) - strlen( SOURCE_INDICATOR ) + existingTextLen + 1 ); strcpy( &sourceEntry->lineText[existingTextLen], &line[strlen( SOURCE_INDICATOR )] ); sourceEntry->linesInBlock++; @@ -662,8 +619,7 @@ static enum symbolErr _getTargetProgramInfo( struct SymbolSet *s ) break; case PS_GET_ASSY: /* Waiting for assembly ========================================= */ - switch ( lt ) - { + switch ( lt ) { case LT_NOISE: /* ------------------------------------------------------ */ break; @@ -683,15 +639,13 @@ static enum symbolErr _getTargetProgramInfo( struct SymbolSet *s ) s->functions[functionEntryIdx].endAddr = sourceEntry->endAddr; /* If we're recording entries and this is not seomthing we explicitly want to ignore */ - if ( ( s->recordAssy ) && ( !strstr( p4, ".word" ) ) && ( !strstr( p4, ".short" ) ) ) - { + if ( ( s->recordAssy ) && ( !strstr( p4, ".word" ) ) && ( !strstr( p4, ".short" ) ) ) { sourceEntry->assy = ( struct assyLineEntry * )realloc( sourceEntry->assy, sizeof( struct assyLineEntry ) * ( sourceEntry->assyLines + 1 ) ); sourceEntry->assy[sourceEntry->assyLines].addr = sourceEntry->endAddr; sourceEntry->assy[sourceEntry->assyLines].is4Byte = ( ( *p2 ) != 0 ); sourceEntry->assy[sourceEntry->assyLines].codes = strtoul( p3, NULL, 16 ); - if ( *p2 ) - { + if ( *p2 ) { sourceEntry->assy[sourceEntry->assyLines].codes |= ( strtoul( p2, NULL, 16 ) << 16 ); } @@ -725,12 +679,9 @@ static enum symbolErr _getTargetProgramInfo( struct SymbolSet *s ) MASKED_COMPARE( 0xffd08000, 0xe9908000 ) || /* LDMDB */ MASKED_COMPARE( 0xfe10f000, 0xf810f000 ) || /* LDR to PC */ MASKED_COMPARE( 0xf8008000, 0xf0008000 ) /* Branches and misc control */ - ) - { + ) { sourceEntry->assy[sourceEntry->assyLines].etm4branch = true; - } - else - { + } else { sourceEntry->assy[sourceEntry->assyLines].etm4branch = false; } @@ -743,8 +694,7 @@ static enum symbolErr _getTargetProgramInfo( struct SymbolSet *s ) if ( MASKED_COMPARE( 0xf800D000, 0xf000D000 ) || /* BL Encoding T1 */ MASKED_COMPARE( 0xffffff80, 0x00004780 ) /* BLX rx */ - ) - { + ) { sourceEntry->assy[sourceEntry->assyLines].isSubCall = true; _getDest( sourceEntry->assy[sourceEntry->assyLines].assy, &sourceEntry->assy[sourceEntry->assyLines].jumpdest ); } @@ -760,8 +710,7 @@ static enum symbolErr _getTargetProgramInfo( struct SymbolSet *s ) MASKED_COMPARE( 0xffff8000, 0xe8bd8000 ) || MASKED_COMPARE( 0xffffffff, 0x000047f0 ) || /* BLX LR */ MASKED_COMPARE( 0xffffffff, 0x00004770 ) /* BX LR */ - ) - { + ) { sourceEntry->assy[sourceEntry->assyLines].isReturn = true; } @@ -775,12 +724,10 @@ static enum symbolErr _getTargetProgramInfo( struct SymbolSet *s ) MASKED_COMPARE( 0xf800d000, 0xf0009000 ) || /* Bc Label (T4) */ ( MASKED_COMPARE( 0xf800d000, 0xf0008000 ) && ( !( MASKED_COMPARE( 0x03800000, 0x03800000 ) ) ) ) /* Bc Label (T3) (Excludes AL condition ) */ - ) - { + ) { sourceEntry->assy[sourceEntry->assyLines].isJump = true; - if ( !_getDest( sourceEntry->assy[sourceEntry->assyLines].assy, &sourceEntry->assy[sourceEntry->assyLines].jumpdest ) ) - { + if ( !_getDest( sourceEntry->assy[sourceEntry->assyLines].assy, &sourceEntry->assy[sourceEntry->assyLines].jumpdest ) ) { GTPIP( "Failed to get jump destination for text %s " EOL, sourceEntry->assy[sourceEntry->assyLines].assy ); } } @@ -790,8 +737,7 @@ static enum symbolErr _getTargetProgramInfo( struct SymbolSet *s ) *label = 0; - if ( !startAddrSet ) - { + if ( !startAddrSet ) { startAddrSet = true; sourceEntry->startAddr = sourceEntry->endAddr; } @@ -819,18 +765,15 @@ static enum symbolErr _getTargetProgramInfo( struct SymbolSet *s ) DWORD exitCode = 1; - if ( !GetExitCodeProcess( processInfo.hProcess, &exitCode ) ) - { + if ( !GetExitCodeProcess( processInfo.hProcess, &exitCode ) ) { exitCode = 1; } CloseHandle( processInfo.hThread ); CloseHandle( processInfo.hProcess ); - if ( exitCode != 0 ) - { - while ( !feof( errorOut ) ) - { + if ( exitCode != 0 ) { + while ( !feof( errorOut ) ) { fgets( line, MAX_LINE_LEN, errorOut ); fputs( line, stderr ); } @@ -841,8 +784,7 @@ static enum symbolErr _getTargetProgramInfo( struct SymbolSet *s ) fclose( errorOut ); #else - if ( 0 != pclose( f ) ) - { + if ( 0 != pclose( f ) ) { /* Something went wrong in the subprocess */ return SYMBOL_NOOBJDUMP; } @@ -856,11 +798,9 @@ static enum symbolErr _getTargetProgramInfo( struct SymbolSet *s ) const char *SymbolFilename( struct SymbolSet *s, uint32_t index ) { - switch ( index ) - { + switch ( index ) { default: - if ( index < s->fileCount ) - { + if ( index < s->fileCount ) { return s->files[index].name; } @@ -871,8 +811,7 @@ const char *SymbolFilename( struct SymbolSet *s, uint32_t index ) const char *SymbolFunction( struct SymbolSet *s, uint32_t index ) { - switch ( index ) - { + switch ( index ) { case FN_SLEEPING: return FN_SLEEPING_STR; @@ -880,8 +819,7 @@ const char *SymbolFunction( struct SymbolSet *s, uint32_t index ) return FN_INTERRUPT_STR; default: - if ( index < s->functionCount ) - { + if ( index < s->functionCount ) { return s->functions[index].name; } @@ -905,16 +843,14 @@ bool SymbolLookup( struct SymbolSet *s, uint32_t addr, struct nameEntry *n ) memset( n, 0, sizeof( struct nameEntry ) ); assert( s ); - if ( ( addr & SPECIALS_MASK ) == SPECIALS_MASK ) - { + if ( ( addr & SPECIALS_MASK ) == SPECIALS_MASK ) { /* Address is some sort of interrupt */ n->line = 0; n->fileindex = n->functionindex = n->addr = INTERRUPT; return true; } - if ( _find_symbol( s, addr, &fileindex, &functionindex, &line, &linesInBlock, &source, &assy, &assyLine ) ) - { + if ( _find_symbol( s, addr, &fileindex, &functionindex, &line, &linesInBlock, &source, &assy, &assyLine ) ) { n->fileindex = fileindex; n->functionindex = functionindex; n->source = source ? source : ""; @@ -939,17 +875,13 @@ void SymbolSetDelete( struct SymbolSet **s ) /* Delete existing symbol set, by means of deleting all memory-allocated components of it first */ { - if ( *s ) - { + if ( *s ) { free( ( *s )->elfFile ); /* Free off any files dynamic memory we allocated */ - if ( ( *s )->files ) - { - for ( uint32_t i = 0; i < ( *s )->fileCount; i++ ) - { - if ( ( *s )->files[i].name ) - { + if ( ( *s )->files ) { + for ( uint32_t i = 0; i < ( *s )->fileCount; i++ ) { + if ( ( *s )->files[i].name ) { free( ( *s )->files[i].name ); } } @@ -958,12 +890,9 @@ void SymbolSetDelete( struct SymbolSet **s ) } /* Free off any functions dynamic memory we allocated */ - if ( ( *s )->functions ) - { - for ( uint32_t i = 0; i < ( *s )->functionCount; i++ ) - { - if ( ( *s )->functions[i].name ) - { + if ( ( *s )->functions ) { + for ( uint32_t i = 0; i < ( *s )->functionCount; i++ ) { + if ( ( *s )->functions[i].name ) { free( ( *s )->functions[i].name ); } } @@ -972,27 +901,20 @@ void SymbolSetDelete( struct SymbolSet **s ) } /* Free off any sources dynamic memory we allocated */ - if ( ( *s )->sources ) - { - for ( uint32_t i = 0; i < ( *s )->sourceCount; i++ ) - { - if ( ( *s )->sources[i].lineText ) - { + if ( ( *s )->sources ) { + for ( uint32_t i = 0; i < ( *s )->sourceCount; i++ ) { + if ( ( *s )->sources[i].lineText ) { free( ( *s )->sources[i].lineText ); } /* For any source line, free off it's assembly if there is some */ - if ( ( *s )->sources[i].assy ) - { - if ( ( *s )->sources[i].assy->label ) - { + if ( ( *s )->sources[i].assy ) { + if ( ( *s )->sources[i].assy->label ) { free( ( *s )->sources[i].assy->label ); } - for ( uint32_t j = 0; j < ( *s )->sources[i].assyLines; j++ ) - { - if ( ( *s )->sources[i].assy[j].lineText ) - { + for ( uint32_t j = 0; j < ( *s )->sources[i].assyLines; j++ ) { + if ( ( *s )->sources[i].assy[j].lineText ) { free( ( *s )->sources[i].assy[j].lineText ); } } @@ -1004,13 +926,11 @@ void SymbolSetDelete( struct SymbolSet **s ) free( ( *s )->sources ); } - if ( ( *s )->deleteMaterial ) - { + if ( ( *s )->deleteMaterial ) { free( ( *s )->deleteMaterial ); } - if ( ( *s )->odoptions ) - { + if ( ( *s )->odoptions ) { free( ( *s )->odoptions ); } @@ -1026,8 +946,7 @@ bool SymbolSetValid( struct SymbolSet **s, char *filename ) { struct stat n; - if ( 0 != stat( filename, &n ) ) - { + if ( 0 != stat( filename, &n ) ) { /* We can't even stat the file, assume it's invalid */ SymbolSetDelete( s ); return false; @@ -1035,25 +954,22 @@ bool SymbolSetValid( struct SymbolSet **s, char *filename ) /* We check filesize, modification time and status change time for any differences */ if ( ( !( *s ) ) || - ( memcmp( &n.st_size, &( ( *s )->st.st_size ), sizeof( off_t ) ) ) || + ( memcmp( &n.st_size, &( ( *s )->st.st_size ), sizeof( off_t ) ) ) || #ifdef OSX - ( memcmp( &n.st_mtimespec, &( ( *s )->st.st_mtimespec ), sizeof( struct timespec ) ) ) || - ( memcmp( &n.st_ctimespec, &( ( *s )->st.st_ctimespec ), sizeof( struct timespec ) ) ) + ( memcmp( &n.st_mtimespec, &( ( *s )->st.st_mtimespec ), sizeof( struct timespec ) ) ) || + ( memcmp( &n.st_ctimespec, &( ( *s )->st.st_ctimespec ), sizeof( struct timespec ) ) ) #elif WIN32 - ( memcmp( &n.st_mtime, &( ( *s )->st.st_mtime ), sizeof( n.st_mtime ) ) ) || - ( memcmp( &n.st_ctime, &( ( *s )->st.st_ctime ), sizeof( n.st_ctime ) ) ) + ( memcmp( &n.st_mtime, &( ( *s )->st.st_mtime ), sizeof( n.st_mtime ) ) ) || + ( memcmp( &n.st_ctime, &( ( *s )->st.st_ctime ), sizeof( n.st_ctime ) ) ) #else - ( memcmp( &n.st_mtim, &( ( *s )->st.st_mtim ), sizeof( struct timespec ) ) ) || - ( memcmp( &n.st_ctim, &( ( *s )->st.st_ctim ), sizeof( struct timespec ) ) ) + ( memcmp( &n.st_mtim, &( ( *s )->st.st_mtim ), sizeof( struct timespec ) ) ) || + ( memcmp( &n.st_ctim, &( ( *s )->st.st_ctim ), sizeof( struct timespec ) ) ) #endif - ) - { + ) { SymbolSetDelete( s ); return false; - } - else - { + } else { return true; } } @@ -1074,34 +990,29 @@ enum symbolErr SymbolSetCreate( struct SymbolSet **ss, const char *filename, con enum symbolErr ret = SYMBOL_UNSPECIFIED; s = ( struct SymbolSet * )calloc( sizeof( struct SymbolSet ), 1 ); - MEMCHECK( s, 0 ); + MEMCHECK( s, SYMBOL_OOM ); s->odoptions = strdup( objdumpOptions ? objdumpOptions : "" ); - MEMCHECK( s->odoptions, 0 ); + MEMCHECK( s->odoptions, SYMBOL_OOM ); s->elfFile = strdup( filename ); - MEMCHECK( s->elfFile, 0 ); + MEMCHECK( s->elfFile, SYMBOL_OOM ); s->deleteMaterial = strdup( deleteMaterial ? deleteMaterial : "" ); - MEMCHECK( s->deleteMaterial, 0 ); + MEMCHECK( s->deleteMaterial, SYMBOL_OOM ); s->recordSource = recordSource; s->demanglecpp = demanglecpp; s->recordAssy = recordAssy; /* Make sure this file is stable before trying to load it */ - if ( ( stat( filename, &statbuf ) != 0 ) || !( statbuf.st_mode & S_IFREG ) ) - { + if ( ( stat( filename, &statbuf ) != 0 ) || !( statbuf.st_mode & S_IFREG ) ) { ret = SYMBOL_NOELF; - } - else - { + } else { /* There is at least a file here */ - while ( 1 ) - { + while ( 1 ) { usleep( ELF_RELOAD_DELAY_TIME ); - if ( stat( filename, &newstatbuf ) == 0 ) - { + if ( stat( filename, &newstatbuf ) == 0 ) { /* We check filesize, modification time and status change time for any differences */ if ( ( !newstatbuf.st_size ) || @@ -1116,14 +1027,11 @@ enum symbolErr SymbolSetCreate( struct SymbolSet **ss, const char *filename, con ( memcmp( &statbuf.st_mtim, &newstatbuf.st_mtim, sizeof( struct timespec ) ) ) || ( memcmp( &statbuf.st_ctim, &newstatbuf.st_ctim, sizeof( struct timespec ) ) ) #endif - ) - { + ) { /* Make this the version we check next time around */ memcpy( &statbuf, &newstatbuf, sizeof( struct stat ) ); continue; - } - else - { + } else { break; } } @@ -1133,8 +1041,7 @@ enum symbolErr SymbolSetCreate( struct SymbolSet **ss, const char *filename, con ret = _getTargetProgramInfo( s ); } - if ( ret != SYMBOL_OK ) - { + if ( ret != SYMBOL_OK ) { SymbolSetDelete( &s ); s = NULL; } diff --git a/Src/tpiuDecoder.c b/Src/tpiuDecoder.c index 396d2699..bc7320fd 100644 --- a/Src/tpiuDecoder.c +++ b/Src/tpiuDecoder.c @@ -33,7 +33,7 @@ #define HALFSYNC_HIGH 0x7F // Halfsync indicator, last arriving byte #define HALFSYNC_LOW 0XFF // Halfsync indicator, first arriving byte #define NO_CHANNEL_CHANGE (0xFF) // Flag to not change channel -#define TPIU_TIMEOUT_US (200000U) // Note that this timeout must be less than 1sec (<1000000 us) +#define TPIU_TIMEOUT_US (200000) // Note that this timeout must be less than 1sec (<1000000 us) #define STAT_SYNC_BYTE (0xA6) // Sync header for status // ==================================================================================================== @@ -50,9 +50,8 @@ void TPIUDecoderInit( struct TPIUDecoder *t ) /* Reset a TPIUDecoder instance */ { - if ( !t ) - { - t = calloc( 1, sizeof( struct TPIUDecoder ) ); + if ( !t ) { + t = ( struct TPIUDecoder * )calloc( 1, sizeof( struct TPIUDecoder ) ); t->selfAllocated = true; } @@ -82,8 +81,7 @@ void TPIUDecoderForceSync( struct TPIUDecoder *t, uint8_t offset ) /* Force the decoder into a specific sync state */ { - if ( t->state == TPIU_UNSYNCED ) - { + if ( t->state == TPIU_UNSYNCED ) { t->stats.syncCount++; } @@ -102,33 +100,24 @@ bool TPIUGetPacket( struct TPIUDecoder *t, struct TPIUPacket *p ) uint8_t delayedStreamChange = NO_CHANNEL_CHANGE; /* This should have been reset in the call */ - if ( ( t->byteCount ) || ( !p ) ) - { + if ( ( t->byteCount ) || ( !p ) ) { return false; } p->len = 0; uint8_t lowbits = t->rxedPacket[TPIU_PACKET_LEN - 1]; - for ( uint32_t i = 0; i < TPIU_PACKET_LEN; i += 2 ) - { - if ( ( t->rxedPacket[i] ) & 1 ) - { + for ( uint32_t i = 0; i < TPIU_PACKET_LEN; i += 2 ) { + if ( ( t->rxedPacket[i] ) & 1 ) { /* This is a stream change - either before or after the data byte */ - if ( lowbits & 1 ) - { + if ( lowbits & 1 ) { delayedStreamChange = t->rxedPacket[i] >> 1; - } - else - { + } else { t->currentStream = t->rxedPacket[i] >> 1; } - } - else - { + } else { /* This is a data byte - store it, provided it's not padding */ - if ( t->currentStream ) - { + if ( t->currentStream ) { p->packet[p->len].d = t->rxedPacket[i] | ( lowbits & 1 ); p->packet[p->len].s = t->currentStream; p->len++; @@ -136,11 +125,9 @@ bool TPIUGetPacket( struct TPIUDecoder *t, struct TPIUPacket *p ) } /* Now deal with the second byte of the pair */ - if ( i < 14 ) - { + if ( i < 14 ) { /* Now deal with the other byte of the pair ... this is always data */ - if ( t->currentStream ) - { + if ( t->currentStream ) { p->packet[p->len].d = t->rxedPacket[i + 1]; p->packet[p->len].s = t->currentStream; p->len++; @@ -148,8 +135,7 @@ bool TPIUGetPacket( struct TPIUDecoder *t, struct TPIUPacket *p ) } /* ... and finally, if there's a delayed channel change, deal with it */ - if ( delayedStreamChange != NO_CHANNEL_CHANGE ) - { + if ( delayedStreamChange != NO_CHANNEL_CHANGE ) { t->currentStream = delayedStreamChange; delayedStreamChange = NO_CHANNEL_CHANGE; } @@ -188,24 +174,19 @@ enum TPIUPumpEvent TPIUPump( struct TPIUDecoder *t, uint8_t d ) t->syncMonitor = ( t->syncMonitor << 8 ) | d; - if ( t->syncMonitor == SYNCPATTERN ) - { + if ( t->syncMonitor == SYNCPATTERN ) { enum TPIUPumpEvent r; - if ( t->state != TPIU_UNSYNCED ) - { + if ( t->state != TPIU_UNSYNCED ) { r = TPIU_EV_SYNCED; - } - else - { + } else { r = TPIU_EV_NEWSYNC; } /* Deal with the special state that these are communication stats from the link */ /* ...it is still a reset though! */ - if ( ( t->byteCount == 14 ) && ( t->rxedPacket[0] == STAT_SYNC_BYTE ) ) - { + if ( ( t->byteCount == 14 ) && ( t->rxedPacket[0] == STAT_SYNC_BYTE ) ) { _decodeCommsStats( t ); } @@ -221,8 +202,7 @@ enum TPIUPumpEvent TPIUPump( struct TPIUDecoder *t, uint8_t d ) return r; } - switch ( t->state ) - { + switch ( t->state ) { // ----------------------------------- case TPIU_UNSYNCED: return TPIU_EV_NONE; @@ -231,8 +211,7 @@ enum TPIUPumpEvent TPIUPump( struct TPIUDecoder *t, uint8_t d ) case TPIU_RXING: // We collect in sets of 16 bits, in order to filter halfsyncs (0x7fff) - if ( !t->got_lowbits ) - { + if ( !t->got_lowbits ) { t->got_lowbits = true; t->rxedPacket[t->byteCount] = d; return TPIU_EV_NONE; @@ -240,8 +219,7 @@ enum TPIUPumpEvent TPIUPump( struct TPIUDecoder *t, uint8_t d ) t->got_lowbits = false; - if ( ( d == HALFSYNC_HIGH ) && ( t->rxedPacket[t->byteCount] == HALFSYNC_LOW ) ) - { + if ( ( d == HALFSYNC_HIGH ) && ( t->rxedPacket[t->byteCount] == HALFSYNC_LOW ) ) { // A halfsync, waste of space, to be ignored t->stats.halfSyncCount++; return TPIU_EV_NONE; @@ -252,8 +230,7 @@ enum TPIUPumpEvent TPIUPump( struct TPIUDecoder *t, uint8_t d ) t->byteCount++; t->rxedPacket[t->byteCount++] = d; - if ( t->byteCount != TPIU_PACKET_LEN ) - { + if ( t->byteCount != TPIU_PACKET_LEN ) { return TPIU_EV_RXING; } @@ -264,14 +241,11 @@ enum TPIUPumpEvent TPIUPump( struct TPIUDecoder *t, uint8_t d ) t->byteCount = 0; /* If it was less than the timeout period then it's valid */ - if ( ( diffTime.tv_sec == 0 ) && ( diffTime.tv_usec < TPIU_TIMEOUT_US ) ) - { + if ( ( diffTime.tv_sec == 0 ) && ( diffTime.tv_usec < TPIU_TIMEOUT_US ) ) { t->stats.packets++; genericsReport( V_DEBUG, EOL ); return TPIU_EV_RXEDPACKET; - } - else - { + } else { genericsReport( V_WARN, ">>>>>>>>> PACKET INTERVAL TOO LONG <<<<<<<<<<<<<<" EOL ); t->state = TPIU_UNSYNCED; t->stats.lostSync++; @@ -304,10 +278,8 @@ void TPIUPump2( struct TPIUDecoder *t, uint8_t *frame, int len, timersub( &nowTime, &t->lastPacket, &diffTime ); /* If it excedes the keepalive time then it's not validly synced */ - if ( ( diffTime.tv_sec > 0 ) || ( diffTime.tv_usec > TPIU_TIMEOUT_US ) ) - { - if ( t->lastPacket.tv_sec ) - { + if ( ( diffTime.tv_sec > 0 ) || ( diffTime.tv_usec > TPIU_TIMEOUT_US ) ) { + if ( t->lastPacket.tv_sec ) { /* There was a legal value for last time...this is not the startup case */ genericsReport( V_WARN, ">>>>>>>>> PACKET INTERVAL TOO LONG <<<<<<<<<<<<<<" EOL ); t->stats.lostSync++; @@ -320,21 +292,18 @@ void TPIUPump2( struct TPIUDecoder *t, uint8_t *frame, int len, memcpy( &t->lastPacket, &nowTime, sizeof( struct timeval ) ); /* Now process the packet */ - while ( len-- ) - { + while ( len-- ) { d = *frame++; t->syncMonitor = ( t->syncMonitor << 8 ) | d; /* ----------------------------------------------------------------------------------- */ /* First case : This is a sync pattern. If so then process it, then move to next octet */ - if ( t->syncMonitor == SYNCPATTERN ) - { + if ( t->syncMonitor == SYNCPATTERN ) { packetRxed( ( t->state == TPIU_UNSYNCED ) ? TPIU_EV_NEWSYNC : TPIU_EV_SYNCED, NULL, param ); /* Deal with the special state that these are communication stats from the link */ /* ...it is still a reset though! */ - if ( ( t->byteCount == 14 ) && ( t->rxedPacket[0] == STAT_SYNC_BYTE ) ) - { + if ( ( t->byteCount == 14 ) && ( t->rxedPacket[0] == STAT_SYNC_BYTE ) ) { _decodeCommsStats( t ); } @@ -351,8 +320,7 @@ void TPIUPump2( struct TPIUDecoder *t, uint8_t *frame, int len, /* ----------------------------------------------- */ /* Second case : We're not synced, just move along */ - if ( t->state == TPIU_UNSYNCED ) - { + if ( t->state == TPIU_UNSYNCED ) { continue; } @@ -360,8 +328,7 @@ void TPIUPump2( struct TPIUDecoder *t, uint8_t *frame, int len, /* Otherwise : Process this into a frame, and deal with the frame if it's complete */ // We collect in sets of 16 bits, in order to filter halfsyncs (0x7fff) - if ( !t->got_lowbits ) - { + if ( !t->got_lowbits ) { t->got_lowbits = true; t->rxedPacket[t->byteCount] = d; continue; @@ -369,8 +336,7 @@ void TPIUPump2( struct TPIUDecoder *t, uint8_t *frame, int len, t->got_lowbits = false; - if ( ( d == HALFSYNC_HIGH ) && ( t->rxedPacket[t->byteCount] == HALFSYNC_LOW ) ) - { + if ( ( d == HALFSYNC_HIGH ) && ( t->rxedPacket[t->byteCount] == HALFSYNC_LOW ) ) { // A halfsync, waste of space, to be ignored t->stats.halfSyncCount++; continue; @@ -381,14 +347,12 @@ void TPIUPump2( struct TPIUDecoder *t, uint8_t *frame, int len, t->byteCount++; t->rxedPacket[t->byteCount++] = d; - if ( t->byteCount == TPIU_PACKET_LEN ) - { + if ( t->byteCount == TPIU_PACKET_LEN ) { t->stats.packets++; t->byteCount = 0; genericsReport( V_DEBUG, EOL ); - if ( TPIUGetPacket( t, &_packet ) ) - { + if ( TPIUGetPacket( t, &_packet ) ) { packetRxed( TPIU_EV_RXEDPACKET, &_packet, param ); } } diff --git a/Src/traceDecoder.c b/Src/traceDecoder.c index 51507d3a..4702e579 100644 --- a/Src/traceDecoder.c +++ b/Src/traceDecoder.c @@ -66,8 +66,8 @@ struct TRACECPUState *TRACECPUState( struct TRACEDecoder *i ) const char *TRACEExceptionName( int exceptionNumber ) { - return ( ( char *[] ) - {"???", "PE Reset", "NMI", "HardFault", "MemManage", "BusFault", "UsageFault", "SecureFault", "???", "???", "???", "SVC", "Debug Monitor", "???", "PendSV", "SysTick", "IRQ" + return ( ( const char *[] ) { + "???", "PE Reset", "NMI", "HardFault", "MemManage", "BusFault", "UsageFault", "SecureFault", "???", "???", "???", "SVC", "Debug Monitor", "???", "PendSV", "SysTick", "IRQ" } )[( exceptionNumber < 16 ) ? exceptionNumber : 16]; } // ==================================================================================================== @@ -87,14 +87,10 @@ void TRACEDecoderForceSync( struct TRACEDecoder *i, bool isSynced ) assert( i ); assert( i->engine ); - if ( isSynced ) - { + if ( isSynced ) { i->stats.syncCount++; - } - else - { - if ( TRACEDecoderIsSynced( i ) ) - { + } else { + if ( TRACEDecoderIsSynced( i ) ) { i->stats.lostSyncCount++; } } @@ -111,26 +107,19 @@ void TRACEDecoderPump( struct TRACEDecoder *i, uint8_t *buf, int len, traceDecod /* len can arrive as 0 for the case of an unwrapped buffer */ - if ( i->engine->action ) - { - while ( len-- ) - { - if ( i->engine->action( i->engine, &i->cpu, *( buf++ ) ) ) - { + if ( i->engine->action ) { + while ( len-- ) { + if ( i->engine->action( i->engine, &i->cpu, *( buf++ ) ) ) { /* Something worthy of being reported happened */ cb( d ); } } - } - else if ( i->engine->actionPair ) - { - while ( len > 7 ) - { + } else if ( i->engine->actionPair ) { + while ( len > 7 ) { /* MTB processes two words at a time...a from and to address */ /* (yes, that could be +1 on a uint32_t increment, but I prefer being explicit) */ - if ( i->engine->actionPair( i->engine, &i->cpu, *( uint32_t * )buf, *( uint32_t * )( buf + 4 ) ) ) - { + if ( i->engine->actionPair( i->engine, &i->cpu, *( uint32_t * )buf, *( uint32_t * )( buf + 4 ) ) ) { /* Something worthy of being reported happened */ cb( d ); } @@ -158,8 +147,7 @@ void TRACEDecoderInit( struct TRACEDecoder *i, enum TRACEprotocol protocol, bool i->engine = _engine[ protocol ](); - if ( i->engine->altAddrEncode ) - { + if ( i->engine->altAddrEncode ) { i->engine->altAddrEncode( i->engine, usingAltAddrEncodeSet ); } } diff --git a/Src/traceDecoder_etm35.c b/Src/traceDecoder_etm35.c index ba456674..d5205196 100644 --- a/Src/traceDecoder_etm35.c +++ b/Src/traceDecoder_etm35.c @@ -17,8 +17,7 @@ #include "generics.h" /* Internal states of the protocol machine */ -enum TRACE_ETM35protoState -{ +enum TRACE_ETM35protoState { TRACE_UNSYNCED, TRACE_WAIT_ISYNC, TRACE_IDLE, @@ -35,16 +34,14 @@ enum TRACE_ETM35protoState TRACE_GET_CONTEXTID }; -static const char *_protoStateName[] = -{ +static const char *_protoStateName[] = { "UNSYNCED", "WAIT_ISYNC", "IDLE", "COLLECT_BA_STD", "COLLECT_BA_ALT", "COLLECT_EXCEPTION", "WAIT_CONTEXTBYTE", "WAIT_INFOBYTE", "WAIT_IADDRESS", "WAIT_ICYCLECOUNT", "WAIT_CYCLECOUNT", "GET_VMID", "GET_TSTAMP", "GET_CONTEXTID" }; -struct ETM35DecodeState -{ +struct ETM35DecodeState { struct TRACEDecoderEngine e; /* Must be first to allow object method access */ enum TRACE_ETM35protoState p; /* Current state of the receiver */ @@ -99,17 +96,13 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu enum TRACEDecoderPumpEvent retVal = TRACE_EV_NONE; /* Perform A-Sync accumulation check */ - if ( ( j->asyncCount >= 5 ) && ( c == 0x80 ) ) - { + if ( ( j->asyncCount >= 5 ) && ( c == 0x80 ) ) { DEBUG( "A-Sync Accumulation complete" EOL ); newState = TRACE_IDLE; - } - else - { + } else { j->asyncCount = c ? 0 : j->asyncCount + 1; - switch ( j->p ) - { + switch ( j->p ) { // ----------------------------------------------------- case TRACE_UNSYNCED: break; @@ -121,12 +114,10 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu // ************************************************* // ************** BRANCH PACKET ******************** // ************************************************* - if ( c & 0b1 ) - { + if ( c & 0b1 ) { /* The lowest order 6 bits of address info... */ - switch ( cpu->addrMode ) - { + switch ( cpu->addrMode ) { case TRACE_ADDRMODE_ARM: j->addrConstruct = ( j->addrConstruct & ~( 0b11111100 ) ) | ( ( c & 0b01111110 ) << 1 ); break; @@ -152,16 +143,14 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu // ************************************************* // ************** A-SYNC PACKET ******************** // ************************************************* - if ( c == 0b00000000 ) - { + if ( c == 0b00000000 ) { break; } // ************************************************* // ************ CYCLECOUNT PACKET ****************** // ************************************************* - if ( c == 0b00000100 ) - { + if ( c == 0b00000100 ) { DEBUG( "CYCCNT " EOL ); j->byteCount = 0; j->cycleConstruct = 0; @@ -172,8 +161,7 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu // ************************************************* // ************** ISYNC PACKETS ******************** // ************************************************* - if ( c == 0b00001000 ) /* Normal ISYNC */ - { + if ( c == 0b00001000 ) { /* Normal ISYNC */ DEBUG( "Normal ISYNC " EOL ); /* Collect either the context or the Info Byte next */ j->byteCount = 0; @@ -181,8 +169,7 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu newState = j->contextBytes ? TRACE_GET_CONTEXTBYTE : TRACE_GET_INFOBYTE; /* We won't start reporting data until a valid ISYNC has been received */ - if ( !j->rxedISYNC ) - { + if ( !j->rxedISYNC ) { DEBUG( "Initial ISYNC" ); cpu->changeRecord = 0; j->rxedISYNC = true; @@ -191,8 +178,7 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu break; } - if ( c == 0b01110000 ) /* ISYNC with Cycle Count */ - { + if ( c == 0b01110000 ) { /* ISYNC with Cycle Count */ DEBUG( "ISYNC+CYCCNT " EOL ); /* Collect the cycle count next */ j->byteCount = 0; @@ -204,8 +190,7 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu // ************************************************* // ************** TRIGGER PACKET ******************* // ************************************************* - if ( c == 0b00001100 ) - { + if ( c == 0b00001100 ) { DEBUG( "TRIGGER " EOL ); _stateChange( cpu, EV_CH_TRIGGER ); retVal = TRACE_EV_MSG_RXED; @@ -215,8 +200,7 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu // ************************************************* // **************** VMID PACKET ******************** // ************************************************* - if ( c == 0b00111100 ) - { + if ( c == 0b00111100 ) { DEBUG( "VMID " EOL ); newState = TRACE_GET_VMID; break; @@ -225,13 +209,11 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu // ************************************************* // *********** TIMESTAMP PACKET ******************** // ************************************************* - if ( ( c & 0b11111011 ) == 0b01000010 ) - { + if ( ( c & 0b11111011 ) == 0b01000010 ) { DEBUG( "TS " EOL ); newState = TRACE_GET_TSTAMP; - if ( ( c & ( 1 << 2 ) ) != 0 ) - { + if ( ( c & ( 1 << 2 ) ) != 0 ) { _stateChange( cpu, EV_CH_CLOCKSPEED ); } @@ -242,8 +224,7 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu // ************************************************* // ************** IGNORE PACKET ******************** // ************************************************* - if ( c == 0b01100110 ) - { + if ( c == 0b01100110 ) { DEBUG( "Ignore Packet" EOL ); break; } @@ -251,8 +232,7 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu // ************************************************* // ************ CONTEXTID PACKET ******************* // ************************************************* - if ( c == 0b01101110 ) - { + if ( c == 0b01101110 ) { DEBUG( "CONTEXTID " EOL ); newState = TRACE_GET_CONTEXTID; cpu->contextID = 0; @@ -263,8 +243,7 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu // ************************************************* // ******** EXCEPTION EXIT PACKET ****************** // ************************************************* - if ( c == 0b01110110 ) - { + if ( c == 0b01110110 ) { DEBUG( "EXCEPT-EXIT " EOL ); _stateChange( cpu, EV_CH_EX_EXIT ); retVal = TRACE_EV_MSG_RXED; @@ -274,8 +253,7 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu // ************************************************* // ******** EXCEPTION ENTRY PACKET ***************** // ************************************************* - if ( c == 0b01111110 ) - { + if ( c == 0b01111110 ) { /* Note this is only used on CPUs with data tracing */ DEBUG( "EXCEPT-ENTRY " EOL ); _stateChange( cpu, EV_CH_EX_ENTRY ); @@ -286,12 +264,9 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu // ************************************************* // ************** P-HEADER PACKET ****************** // ************************************************* - if ( ( c & 0b10000001 ) == 0b10000000 ) - { - if ( !j->cycleAccurate ) - { - if ( ( c & 0b10000011 ) == 0b10000000 ) - { + if ( ( c & 0b10000001 ) == 0b10000000 ) { + if ( !j->cycleAccurate ) { + if ( ( c & 0b10000011 ) == 0b10000000 ) { /* Format-1 P-header */ cpu->eatoms = ( c & 0x3C ) >> 2; cpu->natoms = ( c & ( 1 << 6 ) ) ? 1 : 0; @@ -305,8 +280,7 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu break; } - if ( ( c & 0b11110011 ) == 0b10000010 ) - { + if ( ( c & 0b11110011 ) == 0b10000010 ) { /* Format-2 P-header */ cpu->eatoms = ( ( c & ( 1 << 2 ) ) == 0 ) + ( ( c & ( 1 << 3 ) ) == 0 ); cpu->natoms = 2 - cpu->eatoms; @@ -323,11 +297,8 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu } DEBUG( "Unprocessed P-Header (%02X)" EOL, c ); - } - else - { - if ( c == 0b10000000 ) - { + } else { + if ( c == 0b10000000 ) { /* Format 0 cycle-accurate P-header */ cpu->watoms = 1; cpu->instCount += cpu->watoms; @@ -340,8 +311,7 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu break; } - if ( ( c & 0b10100011 ) == 0b10000000 ) - { + if ( ( c & 0b10100011 ) == 0b10000000 ) { /* Format 1 cycle-accurate P-header */ cpu->eatoms = ( c & 0x1c ) >> 2; cpu->natoms = ( c & 0x40 ) != 0; @@ -356,8 +326,7 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu break; } - if ( ( c & 0b11110011 ) == 0b10000010 ) - { + if ( ( c & 0b11110011 ) == 0b10000010 ) { /* Format 2 cycle-accurate P-header */ cpu->eatoms = ( ( c & ( 1 << 2 ) ) != 0 ) + ( ( c & ( 1 << 3 ) ) != 0 ); cpu->natoms = 2 - cpu->eatoms; @@ -372,8 +341,7 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu break; } - if ( ( c & 0b10100000 ) == 0b10100000 ) - { + if ( ( c & 0b10100000 ) == 0b10100000 ) { /* Format 3 cycle-accurate P-header */ cpu->eatoms = ( c & 0x40 ) != 0; cpu->natoms = 0; @@ -389,8 +357,7 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu break; } - if ( ( c & 0b11111011 ) == 0b10010010 ) - { + if ( ( c & 0b11111011 ) == 0b10010010 ) { /* Format 4 cycle-accurate P-header */ cpu->eatoms = ( c & 0x4 ) != 0; cpu->natoms = ( c & 0x4 ) == 0; @@ -452,16 +419,14 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu terminateAddrByte: /* Check to see if this packet is complete, and encode to return if so */ - if ( ( !C ) || ( j->byteCount == 5 ) ) - { + if ( ( !C ) || ( j->byteCount == 5 ) ) { cpu->addr = j->addrConstruct; - if ( ( j->byteCount == 5 ) && ( cpu->addrMode == TRACE_ADDRMODE_ARM ) && C ) - { + if ( ( j->byteCount == 5 ) && ( cpu->addrMode == TRACE_ADDRMODE_ARM ) && C ) { /* There is (legacy) exception information in here */ cpu->exception = ( c >> 4 ) & 0x07; _stateChange( cpu, EV_CH_EX_ENTRY ); - _stateChange( cpu, ( ( c & 0x40 ) != 0 ) ? EV_CH_CANCELLED : 0 ); + _stateChange( cpu, ( ( c & 0x40 ) != 0 ) ? EV_CH_CANCELLED : EV_CH_NONE ); newState = TRACE_IDLE; retVal = TRACE_EV_MSG_RXED; @@ -469,15 +434,12 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu break; } - if ( ( !C ) & ( !X ) ) - { + if ( ( !C ) & ( !X ) ) { /* This packet is complete, so can return it */ newState = TRACE_IDLE; retVal = TRACE_EV_MSG_RXED; DEBUG( "Branch to %08x" EOL, cpu->addr ); - } - else - { + } else { /* This packet also contains exception information, so collect it */ j->byteCount = 0; /* Used as a flag of which byte of exception we're collecting */ cpu->resume = 0; @@ -491,62 +453,48 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu // ----------------------------------------------------- case TRACE_COLLECT_EXCEPTION: /* Collecting exception information */ - if ( j->byteCount == 0 ) - { - if ( ( ( c & ( 1 << 0 ) ) != 0 ) != cpu->nonSecure ) - { + if ( j->byteCount == 0 ) { + if ( ( ( c & ( 1 << 0 ) ) != 0 ) != cpu->nonSecure ) { cpu->nonSecure = ( ( c & ( 1 << 0 ) ) != 0 ); _stateChange( cpu, EV_CH_SECURE ); } cpu->exception = ( c >> 1 ) & 0x0f; - _stateChange( cpu, ( ( c & ( 1 << 5 ) ) != 0 ) ? EV_CH_CANCELLED : 0 ); + _stateChange( cpu, ( ( c & ( 1 << 5 ) ) != 0 ) ? EV_CH_CANCELLED : EV_CH_NONE ); - if ( cpu->altISA != ( ( c & ( 1 << 6 ) ) != 0 ) ) - { + if ( cpu->altISA != ( ( c & ( 1 << 6 ) ) != 0 ) ) { cpu->altISA = ( ( c & ( 1 << 6 ) ) != 0 ); _stateChange( cpu, EV_CH_ALTISA ); } - if ( c & 0x80 ) - { + if ( c & 0x80 ) { j->byteCount++; - } - else - { + } else { DEBUG( "Exception jump (%d) to 0x%08x" EOL, cpu->exception, cpu->addr ); newState = TRACE_IDLE; retVal = TRACE_EV_MSG_RXED; } - } - else - { - if ( c & 0x80 ) - { + } else { + if ( c & 0x80 ) { /* This is exception byte 1 */ cpu->exception |= ( c & 0x1f ) << 4; - if ( cpu->hyp != ( ( c & ( 1 << 5 ) ) != 0 ) ) - { + if ( cpu->hyp != ( ( c & ( 1 << 5 ) ) != 0 ) ) { cpu->hyp = ( ( c & ( 1 << 5 ) ) != 0 ); _stateChange( cpu, EV_CH_HYP ); } - if ( !( c & 0x40 ) ) - { + if ( !( c & 0x40 ) ) { /* There will not be another one along, return idle */ DEBUG( "Exception jump (%d) to 0x%08x" EOL, cpu->exception, cpu->addr ); newState = TRACE_IDLE; retVal = TRACE_EV_MSG_RXED; } - } - else - { + } else { /* This is exception byte 2 */ cpu->resume = ( c & 0xf ); - if ( cpu->resume ) - { + if ( cpu->resume ) { _stateChange( cpu, EV_CH_RESUME ); } @@ -564,8 +512,7 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu // VMID RELATED ACTIVITIES // ----------------------------------------------------- case TRACE_GET_VMID: /* Collecting virtual machine ID */ - if ( cpu->vmid != c ) - { + if ( cpu->vmid != c ) { cpu->vmid = c; _stateChange( cpu, EV_CH_VMID ); } @@ -580,19 +527,15 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu // ----------------------------------------------------- case TRACE_GET_TSTAMP: /* Collecting current timestamp */ - if ( j->byteCount < 8 ) - { + if ( j->byteCount < 8 ) { j->tsConstruct = ( j->tsConstruct & ( ~( 0x7F << j->byteCount ) ) ) | ( ( c & 0x7f ) << j->byteCount ); - } - else - { + } else { j->tsConstruct = ( j->tsConstruct & ( ~( 0xff << j->byteCount ) ) ) | ( ( c & 0xff ) << j->byteCount ); } j->byteCount++; - if ( ( !( c & 0x80 ) ) || ( j->byteCount == 9 ) ) - { + if ( ( !( c & 0x80 ) ) || ( j->byteCount == 9 ) ) { newState = TRACE_IDLE; cpu->ts = j->tsConstruct; _stateChange( cpu, EV_CH_TSTAMP ); @@ -611,8 +554,7 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu j->cycleConstruct = ( j->cycleConstruct & ~( 0x7f << ( ( j->byteCount ) * 7 ) ) ) | ( ( c & 0x7f ) << ( ( j->byteCount ) * 7 ) ); j->byteCount++; - if ( ( !( c & ( 1 << 7 ) ) ) || ( j->byteCount == 5 ) ) - { + if ( ( !( c & ( 1 << 7 ) ) ) || ( j->byteCount == 5 ) ) { newState = TRACE_IDLE; cpu->cycleCount = j->cycleConstruct; _stateChange( cpu, EV_CH_CYCLECOUNT ); @@ -632,10 +574,8 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu j->contextConstruct = j->contextConstruct + ( c << ( 8 * j->byteCount ) ); j->byteCount++; - if ( j->byteCount == j->contextBytes ) - { - if ( cpu->contextID != j->contextConstruct ) - { + if ( j->byteCount == j->contextBytes ) { + if ( cpu->contextID != j->contextConstruct ) { cpu->contextID = j->contextConstruct; _stateChange( cpu, EV_CH_CONTEXTID ); } @@ -653,10 +593,8 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu // ----------------------------------------------------- case TRACE_WAIT_ISYNC: - if ( c == 0b00001000 ) - { - if ( !j->rxedISYNC ) - { + if ( c == 0b00001000 ) { + if ( !j->rxedISYNC ) { retVal = TRACE_EV_SYNCED; j->rxedISYNC = true; } @@ -674,10 +612,8 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu j->contextConstruct = j->contextConstruct + ( c << ( 8 * j->byteCount ) ); j->byteCount++; - if ( j->byteCount == j->contextBytes ) - { - if ( cpu->contextID != j->contextConstruct ) - { + if ( j->byteCount == j->contextBytes ) { + if ( cpu->contextID != j->contextConstruct ) { cpu->contextID = j->contextConstruct; _stateChange( cpu, EV_CH_CONTEXTID ); } @@ -690,52 +626,43 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu // ----------------------------------------------------- case TRACE_GET_INFOBYTE: /* Collecting I-Sync Information byte */ - if ( ( ( c & 0x10000000 ) != 0 ) != cpu->isLSiP ) - { + if ( ( ( c & 0x10000000 ) != 0 ) != cpu->isLSiP ) { cpu->isLSiP = ( c & 0x10000000 ) != 0; _stateChange( cpu, EV_CH_ISLSIP ); } - if ( cpu->reason != ( ( c & 0x01100000 ) >> 5 ) ) - { - cpu->reason = ( c & 0x01100000 ) >> 5; + if ( cpu->reason != ( ( c & 0x01100000 ) >> 5 ) ) { + cpu->reason = ( enum Reason )( ( c & 0x01100000 ) >> 5 ); _stateChange( cpu, EV_CH_REASON ); } - if ( cpu->jazelle != ( ( c & 0x00010000 ) != 0 ) ) - { + if ( cpu->jazelle != ( ( c & 0x00010000 ) != 0 ) ) { cpu->jazelle = ( c & 0x00010000 ) != 0; _stateChange( cpu, EV_CH_JAZELLE ); } - if ( cpu->nonSecure != ( ( c & 0x00001000 ) != 0 ) ) - { + if ( cpu->nonSecure != ( ( c & 0x00001000 ) != 0 ) ) { cpu->nonSecure = ( c & 0x00001000 ) != 0; _stateChange( cpu, EV_CH_SECURE ); } - if ( cpu->altISA != ( ( c & 0x00000100 ) != 0 ) ) - { + if ( cpu->altISA != ( ( c & 0x00000100 ) != 0 ) ) { cpu->altISA = ( c & 0x00000100 ) != 0; _stateChange( cpu, EV_CH_ALTISA ); } - if ( cpu->hyp != ( ( c & 0x00000010 ) != 0 ) ) - { + if ( cpu->hyp != ( ( c & 0x00000010 ) != 0 ) ) { cpu->hyp = ( c & 0x00000010 ) != 0; _stateChange( cpu, EV_CH_HYP ); } j->byteCount = 0; - if ( j->dataOnlyMode ) - { + if ( j->dataOnlyMode ) { DEBUG( "ISYNC in dataOnlyMode" EOL ); retVal = TRACE_EV_MSG_RXED; newState = TRACE_IDLE; - } - else - { + } else { newState = TRACE_GET_IADDRESS; } @@ -747,45 +674,34 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu j->addrConstruct = ( j->addrConstruct & ( ~( 0xff << ( 8 * j->byteCount ) ) ) ) | ( c << ( 8 * j->byteCount ) ) ; j->byteCount++; - if ( j->byteCount == 4 ) - { + if ( j->byteCount == 4 ) { _stateChange( cpu, EV_CH_ADDRESS ); - if ( cpu->jazelle ) - { + if ( cpu->jazelle ) { /* This is Jazelle mode..can ignore the AltISA bit */ /* and bit 0 is bit 0 of the address */ cpu->addrMode = TRACE_ADDRMODE_JAZELLE; cpu->addr = j->addrConstruct; - } - else - { - if ( ( j->addrConstruct & ( 1 << 0 ) ) ^ ( !cpu->thumb ) ) - { + } else { + if ( ( j->addrConstruct & ( 1 << 0 ) ) ^ ( !cpu->thumb ) ) { cpu->thumb = ( c & 0x00000001 ) != 0; _stateChange( cpu, EV_CH_THUMB ); } - if ( j->addrConstruct & ( 1 << 0 ) ) - { + if ( j->addrConstruct & ( 1 << 0 ) ) { cpu->addrMode = TRACE_ADDRMODE_THUMB; j->addrConstruct &= ~( 1 << 0 ); cpu->addr = j->addrConstruct; - } - else - { + } else { cpu->addrMode = TRACE_ADDRMODE_ARM; cpu->addr = j->addrConstruct & 0xFFFFFFFC; } } - if ( cpu->isLSiP ) - { + if ( cpu->isLSiP ) { /* If this is an LSiP packet we need to go get the address */ newState = ( j->usingAltAddrEncode ) ? TRACE_COLLECT_BA_ALT_FORMAT : TRACE_COLLECT_BA_STD_FORMAT; - } - else - { + } else { DEBUG( "ISYNC with IADDRESS 0x%08x" EOL, cpu->addr ); newState = TRACE_IDLE; retVal = TRACE_EV_MSG_RXED; @@ -800,8 +716,7 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu j->cycleConstruct = ( j->cycleConstruct & ~( 0x7f << ( ( j->byteCount ) * 7 ) ) ) | ( ( c & 0x7f ) << ( ( j->byteCount ) * 7 ) ); j->byteCount++; - if ( ( !( c & ( 1 << 7 ) ) ) || ( j->byteCount == 5 ) ) - { + if ( ( !( c & ( 1 << 7 ) ) ) || ( j->byteCount == 5 ) ) { /* Now go to get the rest of the ISYNC packet */ /* Collect either the context or the Info Byte next */ cpu->cycleCount = j->cycleConstruct; @@ -819,8 +734,7 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu } } - if ( j->p != TRACE_UNSYNCED ) - { + if ( j->p != TRACE_UNSYNCED ) { DEBUG( "%02x:%s --> %s %s(%d)", c, ( j->p == TRACE_IDLE ) ? _protoStateName[j->p] : "", _protoStateName[newState], ( ( newState == TRACE_IDLE ) ? ( ( retVal == TRACE_EV_NONE ) ? "!!!" : "OK" ) : " : " ), retVal ); } @@ -850,10 +764,10 @@ static bool _synced( struct TRACEDecoderEngine *e ) // ==================================================================================================== -static void _usingAltAddrEncode( struct TRACEDecoderEngine *e, bool using ) +static void _usingAltAddrEncode( struct TRACEDecoderEngine *e, bool amusing ) { - ( ( struct ETM35DecodeState * )e )->usingAltAddrEncode = using; + ( ( struct ETM35DecodeState * )e )->usingAltAddrEncode = amusing; } // ==================================================================================================== @@ -861,8 +775,7 @@ static void _usingAltAddrEncode( struct TRACEDecoderEngine *e, bool using ) static void _forceSync( struct TRACEDecoderEngine *e, bool isSynced ) { - if ( !isSynced ) - { + if ( !isSynced ) { ( ( struct ETM35DecodeState * )e )->asyncCount = 0; ( ( struct ETM35DecodeState * )e )->rxedISYNC = false; } diff --git a/Src/traceDecoder_etm4.c b/Src/traceDecoder_etm4.c index 2d8d3e38..fb323f19 100644 --- a/Src/traceDecoder_etm4.c +++ b/Src/traceDecoder_etm4.c @@ -21,8 +21,7 @@ /* Internal states of the protocol machine */ -enum TRACE_ETM4protoState -{ +enum TRACE_ETM4protoState { TRACE_UNSYNCED, TRACE_IDLE, TRACE_GET_CYCLECOUNT, @@ -46,8 +45,7 @@ enum TRACE_ETM4protoState TRACE_GET_EXCEPTIONINFO2 }; -static const char *_protoStateName[] = -{ +static const char *_protoStateName[] = { "UNSYNCED", "IDLE", "GET_CYCLECOUNT", @@ -78,8 +76,7 @@ static const char *_protoStateName[] = /* Word-aligned ARM, Halfword Aligned Thumb, Table 6-19, Pg 6-292 */ enum InstSet { IS0, IS1 }; -struct ETM4DecodeState -{ +struct ETM4DecodeState { struct TRACEDecoderEngine e; /* Must be first to allow object method access */ enum TRACE_ETM4protoState p; /* Current state of the receiver */ @@ -105,8 +102,7 @@ struct ETM4DecodeState bool cc_follows; /* Indication if CC follows from TS */ uint8_t idx; /* General counter used for multi-byte payload indexing */ uint32_t cntUpdate; /* Count construction for TS packets */ - struct - { + struct { uint64_t addr; enum InstSet inst; } q[3]; /* Address queue for pushed addresses */ @@ -177,26 +173,21 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu assert( j ); /* Perform A-Sync accumulation check ( Section 6.4.2 ) */ - if ( ( j->asyncCount == 11 ) && ( c == 0x80 ) ) - { + if ( ( j->asyncCount == 11 ) && ( c == 0x80 ) ) { DEBUG( "A-Sync Accumulation complete" EOL ); j->rxedISYNC = true; newState = TRACE_WAIT_INFO; - } - else - { + } else { j->asyncCount = c ? 0 : j->asyncCount + 1; - switch ( j->p ) - { + switch ( j->p ) { // ----------------------------------------------------- case TRACE_UNSYNCED: break; // ----------------------------------------------------- case TRACE_IDLE: - switch ( c ) - { + switch ( c ) { case 0b00000001: newState = TRACE_GET_INFO_PLCTL; break; @@ -212,8 +203,7 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu DEBUG( "Atom Format 1 [%b]", cpu->disposition ); - if ( cpu->addr != ADDRESS_UNKNOWN ) - { + if ( cpu->addr != ADDRESS_UNKNOWN ) { retVal = TRACE_EV_MSG_RXED; _stateChange( cpu, EV_CH_ENATOMS ); } @@ -229,8 +219,7 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu cpu->disposition = c & 3; DEBUG( "Atom Format 2 [%02b]", cpu->disposition ); - if ( cpu->addr != ADDRESS_UNKNOWN ) - { + if ( cpu->addr != ADDRESS_UNKNOWN ) { retVal = TRACE_EV_MSG_RXED; _stateChange( cpu, EV_CH_ENATOMS ); } @@ -246,8 +235,7 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu cpu->disposition = c & 7; DEBUG( "Atom Format 3 [%03b]", cpu->disposition ); - if ( cpu->addr != ADDRESS_UNKNOWN ) - { + if ( cpu->addr != ADDRESS_UNKNOWN ) { retVal = TRACE_EV_MSG_RXED; _stateChange( cpu, EV_CH_ENATOMS ); } @@ -255,8 +243,7 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu break; case 0b11011100 ... 0b11011111: /* Atom Format 4, Figure 6-42, Pg 6-305 */ - switch ( c & 3 ) - { + switch ( c & 3 ) { case 0b00: cpu->natoms = 1; cpu->disposition = 0b1110; @@ -282,8 +269,7 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu cpu->instCount += 4; DEBUG( "Atom Format 4 [%04b]", cpu->disposition ); - if ( cpu->addr != ADDRESS_UNKNOWN ) - { + if ( cpu->addr != ADDRESS_UNKNOWN ) { retVal = TRACE_EV_MSG_RXED; _stateChange( cpu, EV_CH_ENATOMS ); } @@ -295,8 +281,7 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu case 0b11010110: case 0b11010111: case 0b11110101: /* Atom format 5, Figure 6-43, Pg 6-306 ... use bits 5, 1 and 0 */ - switch ( ( ( 0 != ( c & ( 1 << 5 ) ) ) << 2 ) | ( ( 0 != ( c & ( 1 << 1 ) ) ) << 1 ) | ( ( 0 != ( c & ( 1 << 0 ) ) ) << 0 ) ) - { + switch ( ( ( 0 != ( c & ( 1 << 5 ) ) ) << 2 ) | ( ( 0 != ( c & ( 1 << 1 ) ) ) << 1 ) | ( ( 0 != ( c & ( 1 << 0 ) ) ) << 0 ) ) { case 0b101: cpu->natoms = 1; cpu->disposition = 0b11110; @@ -326,8 +311,7 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu cpu->instCount += 5; DEBUG( "Atom Format 5 [%05b]", cpu->disposition ); - if ( cpu->addr != ADDRESS_UNKNOWN ) - { + if ( cpu->addr != ADDRESS_UNKNOWN ) { retVal = TRACE_EV_MSG_RXED; _stateChange( cpu, EV_CH_ENATOMS ); } @@ -340,14 +324,11 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu cpu->instCount = cpu->eatoms; cpu->disposition = ( 1 << ( cpu->eatoms + 1 ) ) - 1; - if ( c & ( 1 << 5 ) ) - { + if ( c & ( 1 << 5 ) ) { cpu->disposition &= 0xfffffffe; cpu->eatoms--; cpu->natoms = 1; - } - else - { + } else { cpu->natoms = 0; } @@ -355,8 +336,7 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu sprintf( construct, "Atom Format 6 [%%ld %%%" PRId64 "b]", cpu->instCount ); DEBUG( construct, cpu->instCount, cpu->disposition ); - if ( cpu->addr != ADDRESS_UNKNOWN ) - { + if ( cpu->addr != ADDRESS_UNKNOWN ) { retVal = TRACE_EV_MSG_RXED; _stateChange( cpu, EV_CH_ENATOMS ); } @@ -369,23 +349,19 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu break; case 0b01110001 ... 0b01111111: /* Event tracing, Figure 6-31, Pg 6-289 */ - if ( c & 0b0001 ) - { + if ( c & 0b0001 ) { _stateChange( cpu, EV_CH_EVENT0 ); } - if ( c & 0b0010 ) - { + if ( c & 0b0010 ) { _stateChange( cpu, EV_CH_EVENT1 ); } - if ( c & 0b0100 ) - { + if ( c & 0b0100 ) { _stateChange( cpu, EV_CH_EVENT2 ); } - if ( c & 0b1000 ) - { + if ( c & 0b1000 ) { _stateChange( cpu, EV_CH_EVENT3 ); } @@ -516,8 +492,7 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu newState = TRACE_GET_TIMESTAMP; j->cc_follows = ( 0 != ( c & 1 ) ); - if ( !j->cc_follows ) - { + if ( !j->cc_follows ) { cpu->cycleCount = COUNT_UNKNOWN; } @@ -570,20 +545,15 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu cpu->amSecure = ( 0 == ( c & ( 1 << 5 ) ) ); j->haveContext = ( 0 != ( c & ( 1 << 7 ) ) ); - if ( c & ( 1 << 6 ) ) - { + if ( c & ( 1 << 6 ) ) { j->vcontext = 0; j->idx = 0; newState = TRACE_GET_VCONTEXT; - } - else if ( j->haveContext ) - { + } else if ( j->haveContext ) { j->context = 0; j->idx = 0; newState = TRACE_GET_CONTEXT_ID; - } - else - { + } else { retVal = TRACE_EV_MSG_RXED; _stateChange( cpu, EV_CH_CONTEXTID ); newState = TRACE_IDLE; @@ -617,15 +587,12 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu j->vcontext |= c << j->idx; j->idx += 8; - if ( ( j->idx == 32 ) && ( !j->haveContext ) ) - { + if ( ( j->idx == 32 ) && ( !j->haveContext ) ) { cpu->vmid = j->vcontext; retVal = TRACE_EV_MSG_RXED; _stateChange( cpu, EV_CH_VMID ); newState = TRACE_IDLE; - } - else - { + } else { j->context = 0; j->idx = 0; newState = TRACE_GET_CONTEXT_ID; @@ -639,8 +606,7 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu j->context |= c << j->idx; j->idx += 8; - if ( j->idx == 32 ) - { + if ( j->idx == 32 ) { cpu->contextID = j->vcontext; retVal = TRACE_EV_MSG_RXED; _stateChange( cpu, EV_CH_CONTEXTID ); @@ -651,20 +617,16 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu // ----------------------------------------------------- case TRACE_GET_SHORT_ADDR: /* Short format address for IS0 or IS1, offset set by idx. Figure 6-32, Pg 6-294 */ - if ( j->idx <= 2 ) - { + if ( j->idx <= 2 ) { /* First byte of received data */ j->q[0].addr = ( j->q[0].addr & ~( 0x7f << j->idx ) ) | ( ( c & 0x7f ) << ( j->idx ) ); j->idx += 7; - } - else - { + } else { j->q[0].addr = ( j->q[0].addr & ~( 0xff << j->idx ) ) | ( ( c & 0xff ) << ( j->idx ) ); j->idx += 8; } - if ( ( !( c & 0x80 ) ) || ( j->idx > 9 ) ) - { + if ( ( !( c & 0x80 ) ) || ( j->idx > 9 ) ) { cpu->addr = j->q[0].addr; retVal = TRACE_EV_MSG_RXED; _stateChange( cpu, EV_CH_ADDRESS ); @@ -675,38 +637,28 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu // ----------------------------------------------------- case TRACE_GET_32BIT_ADDR: /* Long format 32 bit address for IS0 or IS1, offset set by idx. Figure 6-33, Pg 6-295 and Figure 6-37, Pg 6-299 */ - if ( j->idx < 3 ) - { + if ( j->idx < 3 ) { /* First byte of received data */ j->q[0].addr = ( j->q[0].addr & ( ~( 0x7F << j->idx ) ) ) | ( ( c & 0x7f ) << ( j->idx ) ); j->idx += 7; - } - else - { - if ( j->idx == 8 ) - { + } else { + if ( j->idx == 8 ) { /* Second byte of IS1 case - mask MSB */ j->q[0].addr = ( j->q[0].addr & ( ~( 0x7F << j->idx ) ) ) | ( ( c & 0x7f ) << ( j->idx ) ); j->idx = 16; - } - else - { + } else { j->q[0].addr = ( j->q[0].addr & ( ~( 0xFF << j->idx ) ) ) | ( ( c & 0xFf ) << ( j->idx ) ); j->idx += 8; } } - if ( j->idx == 32 ) - { + if ( j->idx == 32 ) { cpu->addr = j->q[0].addr; _stateChange( cpu, EV_CH_ADDRESS ); - if ( j->haveContext ) - { + if ( j->haveContext ) { newState = TRACE_GET_CONTEXT; - } - else - { + } else { retVal = TRACE_EV_MSG_RXED; newState = TRACE_IDLE; } @@ -717,38 +669,28 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu // ----------------------------------------------------- case TRACE_GET_64BIT_ADDR: /* Long format 64 bit address for IS0 or IS1, offset set by idx. Figure 6-34, Pg 6-295 */ - if ( j->idx < 3 ) - { + if ( j->idx < 3 ) { /* First byte of received data */ j->q[0].addr = ( j->q[0].addr & ( 0x7F << j->idx ) ) | ( ( c & 0x7f ) << ( j->idx ) ); j->idx += 7; - } - else - { - if ( ( j->q[0].inst == IS1 ) && ( j->idx == 8 ) ) - { + } else { + if ( ( j->q[0].inst == IS1 ) && ( j->idx == 8 ) ) { /* Second byte of IS1 case - mask MSB */ j->q[0].addr = ( j->q[0].addr & ( 0x7F << j->idx ) ) | ( ( c & 0x7f ) << ( j->idx ) ); j->idx = 16; - } - else - { + } else { j->q[0].addr = ( j->q[0].addr & ( 0xFF << j->idx ) ) | ( ( c & 0xFf ) << ( j->idx ) ); j->idx += 8; } } - if ( j->idx == 64 ) - { + if ( j->idx == 64 ) { cpu->addr = j->q[0].addr; _stateChange( cpu, EV_CH_ADDRESS ); - if ( j->haveContext ) - { + if ( j->haveContext ) { newState = TRACE_GET_CONTEXT; - } - else - { + } else { retVal = TRACE_EV_MSG_RXED; newState = TRACE_IDLE; } @@ -758,40 +700,29 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu // ----------------------------------------------------- case TRACE_GET_TIMESTAMP: /* Timestamp, Figure 6-7, Pg 6-264 */ - if ( j->idx < 56 ) - { + if ( j->idx < 56 ) { cpu->ts = ( cpu->ts & ( 0x7F << j->idx ) ) | ( ( c & 0x7f ) << j->idx ); - } - else - { + } else { cpu->ts = ( cpu->ts & ( 0xFF << j->idx ) ) | ( ( c & 0xff ) << j->idx ); } j->idx += 7; - if ( ( !( c & 0x80 ) ) || ( j->idx == 63 ) ) - { - if ( cpu->cycleCount != COUNT_UNKNOWN ) - { + if ( ( !( c & 0x80 ) ) || ( j->idx == 63 ) ) { + if ( cpu->cycleCount != COUNT_UNKNOWN ) { _stateChange( cpu, EV_CH_TSTAMP ); } - if ( j->cc_enabled ) - { - if ( j->cc_follows ) - { + if ( j->cc_enabled ) { + if ( j->cc_follows ) { j->idx = 0; j->cntUpdate = 0; newState = TRACE_GET_TS_CC; - } - else - { + } else { retVal = TRACE_EV_MSG_RXED; newState = TRACE_IDLE; } - } - else - { + } else { retVal = TRACE_EV_MSG_RXED; newState = TRACE_IDLE; } @@ -801,19 +732,15 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu // ----------------------------------------------------- case TRACE_GET_TS_CC: /* Part of timestamp, Figure 6-7, Pg 6-264 */ - if ( j->idx < 2 ) - { + if ( j->idx < 2 ) { j->cntUpdate |= ( c & 0x7f ) << ( j->idx * 7 ); - } - else - { + } else { j->cntUpdate |= ( c & 0x7f ) << ( j->idx * 7 ); } j->idx++; - if ( ( j->idx == 3 ) || ( c & 0x80 ) ) - { + if ( ( j->idx == 3 ) || ( c & 0x80 ) ) { cpu->cycleCount += j->cntUpdate; retVal = TRACE_EV_MSG_RXED; @@ -825,8 +752,7 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu // ----------------------------------------------------- case TRACE_EXTENSION: - switch ( c ) - { + switch ( c ) { case 0b00000011: /* Discard packet, Figure 6.4, Pg 6-262 */ _stateChange( cpu, EV_CH_DISCARD ); _stateChange( cpu, EV_CH_TRACESTOP ); @@ -850,8 +776,7 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu // ----------------------------------------------------- case TRACE_WAIT_INFO: - if ( c == 0b00000001 ) - { + if ( c == 0b00000001 ) { newState = TRACE_GET_INFO_PLCTL; } @@ -862,24 +787,15 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu j->nextrhkey = 0; _flushQ( j ); /* Reset the address stack too ( Section 6.4.12, Pg 6-291 ) */ - if ( j->plctl & ( 1 << 0 ) ) - { + if ( j->plctl & ( 1 << 0 ) ) { newState = TRACE_GET_INFO_INFO; - } - else if ( j->plctl & ( 1 << 1 ) ) - { + } else if ( j->plctl & ( 1 << 1 ) ) { newState = TRACE_GET_INFO_KEY; - } - else if ( j->plctl & ( 1 << 2 ) ) - { + } else if ( j->plctl & ( 1 << 2 ) ) { newState = TRACE_GET_INFO_SPEC; - } - else if ( j->plctl & ( 1 << 3 ) ) - { + } else if ( j->plctl & ( 1 << 3 ) ) { newState = TRACE_GET_INFO_CYCT; - } - else - { + } else { _reportInfo( cpu, j ); retVal = TRACE_EV_MSG_RXED; newState = TRACE_IDLE; @@ -893,20 +809,13 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu j->load_traced = ( 0 != ( c & ( 1 << 4 ) ) ); j->store_traced = ( 0 != ( c & ( 1 << 5 ) ) ); - if ( j->plctl & ( 1 << 1 ) ) - { + if ( j->plctl & ( 1 << 1 ) ) { newState = TRACE_GET_INFO_KEY; - } - else if ( j->plctl & ( 1 << 2 ) ) - { + } else if ( j->plctl & ( 1 << 2 ) ) { newState = TRACE_GET_INFO_SPEC; - } - else if ( j->plctl & ( 1 << 3 ) ) - { + } else if ( j->plctl & ( 1 << 3 ) ) { newState = TRACE_GET_INFO_CYCT; - } - else - { + } else { _reportInfo( cpu, j ); retVal = TRACE_EV_MSG_RXED; newState = TRACE_IDLE; @@ -917,16 +826,11 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu case TRACE_GET_INFO_KEY: j->nextrhkey = c; // FIXME: Greater than 256 keys??? - if ( j->plctl & ( 1 << 2 ) ) - { + if ( j->plctl & ( 1 << 2 ) ) { newState = TRACE_GET_INFO_SPEC; - } - else if ( j->plctl & ( 1 << 3 ) ) - { + } else if ( j->plctl & ( 1 << 3 ) ) { newState = TRACE_GET_INFO_CYCT; - } - else - { + } else { _reportInfo( cpu, j ); retVal = TRACE_EV_MSG_RXED; newState = TRACE_IDLE; @@ -937,13 +841,10 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu case TRACE_GET_INFO_SPEC: j->spec = c; - if ( j->plctl & ( 1 << 3 ) ) - { + if ( j->plctl & ( 1 << 3 ) ) { _reportInfo( cpu, j ); newState = TRACE_GET_INFO_CYCT; - } - else - { + } else { _reportInfo( cpu, j ); retVal = TRACE_EV_MSG_RXED; newState = TRACE_IDLE; @@ -959,13 +860,11 @@ static bool _pumpAction( struct TRACEDecoderEngine *e, struct TRACECPUState *cpu } } - if ( j->p != TRACE_UNSYNCED ) - { + if ( j->p != TRACE_UNSYNCED ) { DEBUG( "%02x:%s --> %s (%s:%d)", c, ( j->p == TRACE_IDLE ) ? _protoStateName[j->p] : "", _protoStateName[newState], ( ( newState == TRACE_IDLE ) ? ( ( retVal == TRACE_EV_NONE ) ? "DROPPED" : "OK" ) : "-" ), retVal ); - if ( newState == TRACE_IDLE ) - { + if ( newState == TRACE_IDLE ) { DEBUG( "\r\n" ); } } diff --git a/Src/traceDecoder_mtb.c b/Src/traceDecoder_mtb.c index 2bd6eaf3..dee9d092 100644 --- a/Src/traceDecoder_mtb.c +++ b/Src/traceDecoder_mtb.c @@ -15,14 +15,12 @@ #include "generics.h" /* Internal states of the protocol machine */ -enum TRACE_MTBprotoState -{ +enum TRACE_MTBprotoState { TRACE_UNSYNCED, TRACE_IDLE }; -struct MTBDecodeState -{ +struct MTBDecodeState { struct TRACEDecoderEngine e; /* Must be first to allow object method access */ enum TRACE_MTBprotoState p; /* Current state of the receiver */ }; @@ -55,8 +53,7 @@ static bool _pumpActionPair( struct TRACEDecoderEngine *e, struct TRACECPUState REPORT( "[From 0x%08x to 0x%08x]" EOL, source, dest ); - switch ( j->p ) - { + switch ( j->p ) { // ----------------------------------------------------- case TRACE_UNSYNCED: @@ -65,8 +62,7 @@ static bool _pumpActionPair( struct TRACEDecoderEngine *e, struct TRACECPUState cpu->nextAddr = ( dest & 0xFFFFFFFE ) | ( source & 1 ); /* If the low bit of dest was set then this is a start of trace event */ - if ( dest & 1 ) - { + if ( dest & 1 ) { _stateChange( cpu, EV_CH_TRACESTART ); } @@ -76,15 +72,13 @@ static bool _pumpActionPair( struct TRACEDecoderEngine *e, struct TRACECPUState // ----------------------------------------------------- case TRACE_IDLE: - if ( cpu->nextAddr & 1 ) - { + if ( cpu->nextAddr & 1 ) { /* If low bit of nextAddr is set then we got here via an exception */ _stateChange( cpu, EV_CH_EX_ENTRY ); } /* If low bit of dest is set then this is a start of trace */ - if ( dest & 1 ) - { + if ( dest & 1 ) { _stateChange( cpu, EV_CH_TRACESTART ); } diff --git a/Support/orbcfg.toml b/Support/orbcfg.toml new file mode 100644 index 00000000..7e4eba46 --- /dev/null +++ b/Support/orbcfg.toml @@ -0,0 +1,30 @@ +# This is the basic configuration file for orbuculum and clients +# Options set here are overridden by command line settings +# Syntax is standard TOML at defined at https://toml.io/en/v1.0.0 +# Defaults are present but commented out + +[orbuculum.source] +#serial = { port = '/dev/ttyUSB0', speed = 115_200 } +#server = { name = "localhost", port = 3333 } +#serial_number='ABCD1234' +#file=input.filename +#exit_at_eof=true + +[orbuculum.processing] +#hires=false +#tpiu_channels=[1,2] + +[orbuculum.presentation] +#monitor_interval=100 +#data_speed=115_200 +#colour=true +verbose=2 +#run_orbtrace= + +[orbuculum.output] +#port= +#file= +#pace_delay= + +############################################################## + diff --git a/config/astyle.conf b/config/astyle.conf index 03273f59..59ba3713 100644 --- a/config/astyle.conf +++ b/config/astyle.conf @@ -1,7 +1,6 @@ ---style=gnu +--style=linux -n --attach-extern-c ---style=break --align-pointer=name --align-reference=name --indent-col1-comments diff --git a/meson.build b/meson.build index 89270993..aba72ff4 100644 --- a/meson.build +++ b/meson.build @@ -1,5 +1,5 @@ -project('orbuculum', 'c', version:'2.1.0', meson_version: '>=0.63') +project('orbuculum', 'c', 'cpp', version:'2.1.0', meson_version: '>=0.63', default_options:['cpp_std=c++14']) uicolours_default = declare_dependency(compile_args: ['-include', 'uicolours_default.h']) @@ -23,24 +23,29 @@ if host_machine.system() == 'windows' winsock2 ] elif host_machine.system() == 'darwin' - add_project_arguments('-DOSX', language: 'c') + add_project_arguments('-DOSX', language: ['c','cpp']) else - add_project_arguments('-DLINUX', language: 'c') - add_project_arguments('-ggdb', language: 'c') - add_project_arguments('-D_GNU_SOURCE', language: 'c') + add_project_arguments('-DLINUX', language: ['c','cpp']) + add_project_arguments('-ggdb', language: ['c','cpp']) + add_project_arguments('-D_GNU_SOURCE', language: ['c','cpp']) install_data('Support/60-orbcode.rules', install_dir : '/etc/udev/rules.d') install_data('Support/gdbtrace.init', install_dir : 'share/orbcode') endif -add_project_arguments('-DSCREEN_HANDLING', language: 'c') -add_project_arguments('-Wno-error=deprecated-declarations', language: 'c') -add_project_arguments(['-include', 'uicolours_default.h'], language: 'c') +add_project_arguments('-x', language: 'c') +add_project_arguments('c++', language: 'c') +add_project_arguments('-DSCREEN_HANDLING', language: ['c','cpp']) +add_project_arguments('-Wno-error=deprecated-declarations', language: ['c','cpp']) +add_project_arguments(['-include', 'uicolours_default.h'], language: ['c','cpp']) libdwarf = subproject('libdwarf').get_variable('libdwarf') dependencies += libdwarf +tomlplusplus_dep = dependency('tomlplusplus') +dependencies += tomlplusplus_dep + if host_machine.system() == 'windows' stream_src = [ 'Src/stream_win32.c', diff --git a/subprojects/tomlplusplus.wrap b/subprojects/tomlplusplus.wrap new file mode 100644 index 00000000..71acdd1e --- /dev/null +++ b/subprojects/tomlplusplus.wrap @@ -0,0 +1,9 @@ +[wrap-file] +directory = tomlplusplus-3.3.0 +source_url = https://github.com/marzer/tomlplusplus/archive/v3.3.0.tar.gz +source_filename = tomlplusplus-3.3.0.tar.gz +source_hash = fc1a5eb410f3c67e90e5ad1264a1386d020067cfb01b633cc8c0441789aa6cf2 +wrapdb_version = 3.3.0-1 + +[provide] +dependency_names = tomlplusplus