Apply suggestions from @henrygab

Check if memory allocation fails
Fix memory leak
Initialize struct in declaration
Add/Fix some notes
Remove unlikely() in favor of readability
Remove a hard-coded magic number
This commit is contained in:
wh201906 2023-11-15 18:04:52 +08:00
commit 3ee13c9ba6
No known key found for this signature in database
12 changed files with 113 additions and 44 deletions

View file

@ -306,7 +306,7 @@ uint32_t DoAcquisition(uint8_t decimation, uint8_t bits_per_sample, bool avg, in
// only every 4000th times, in order to save time when collecting samples.
// interruptible only when logging not yet triggered
if (unlikely(trigger_hit == false && (checked >= 4000))) {
if (trigger_hit == false && (checked >= 4000)) {
if (data_available()) {
checked = -1;
break;
@ -329,7 +329,7 @@ uint32_t DoAcquisition(uint8_t decimation, uint8_t bits_per_sample, bool avg, in
if (ledcontrol) LED_D_OFF();
// threshold either high or low values 128 = center 0. if trigger = 178
if (unlikely(trigger_hit == false)) {
if (trigger_hit == false) {
if ((trigger_threshold > 0) && (sample < (trigger_threshold + 128)) && (sample > (128 - trigger_threshold))) {
if (cancel_after > 0) {
cancel_counter++;
@ -341,7 +341,7 @@ uint32_t DoAcquisition(uint8_t decimation, uint8_t bits_per_sample, bool avg, in
trigger_hit = true;
}
if (unlikely(samples_to_skip > 0)) {
if (samples_to_skip > 0) {
samples_to_skip--;
continue;
}
@ -441,7 +441,6 @@ int ReadLF_realtime(bool reader_field) {
int32_t samples_to_skip = config.samples_to_skip;
const uint8_t decimation = config.decimation;
uint32_t sample_buffer_len = 64;
const int8_t size_threshold_table[9] = {0, 64, 64, 60, 64, 60, 60, 56, 64};
const int8_t size_threshold = size_threshold_table[bits_per_sample];
@ -450,8 +449,9 @@ int ReadLF_realtime(bool reader_field) {
uint8_t curr_byte = 0;
int return_value = PM3_SUCCESS;
uint32_t sample_buffer_len = AT91C_USB_EP_IN_SIZE;
initSampleBuffer(&sample_buffer_len);
if (sample_buffer_len != 64) {
if (sample_buffer_len != AT91C_USB_EP_IN_SIZE) {
return PM3_EFAILED;
}
@ -469,7 +469,7 @@ int ReadLF_realtime(bool reader_field) {
while (BUTTON_PRESS() == false) {
// only every 4000th times, in order to save time when collecting samples.
// interruptible only when logging not yet triggered
if (unlikely(trigger_hit == false && (checked >= 4000))) {
if (trigger_hit == false && (checked >= 4000)) {
if (data_available()) {
checked = -1;
break;
@ -492,21 +492,21 @@ int ReadLF_realtime(bool reader_field) {
LED_D_OFF();
// threshold either high or low values 128 = center 0. if trigger = 178
if (unlikely(trigger_hit == false)) {
if (trigger_hit == false) {
if ((trigger_threshold > 0) && (sample < (trigger_threshold + 128)) && (sample > (128 - trigger_threshold))) {
continue;
}
trigger_hit = true;
}
if (unlikely(samples_to_skip > 0)) {
if (samples_to_skip > 0) {
samples_to_skip--;
continue;
}
logSample(sample, decimation, bits_per_sample, false);
// write to USB FIFO if byte changed
// Write to USB FIFO if byte changed
curr_byte = data.numbits >> 3;
if (curr_byte > last_byte) {
async_usb_write_pushByte(data.buffer[last_byte]);
@ -514,20 +514,20 @@ int ReadLF_realtime(bool reader_field) {
last_byte = curr_byte;
if (samples.total_saved == size_threshold) {
// request usb transmission and change FIFO bank
// Request USB transmission and change FIFO bank
if (async_usb_write_requestWrite() == false) {
return_value = PM3_EIO;
break;
}
// reset sample
// Reset sample
last_byte = 0;
data.numbits = 0;
samples.counter = size_threshold;
samples.total_saved = 0;
} else if (samples.total_saved == 1) {
// check if there is any data from client
// Check if there is any data from client
if (data_available_fast()) {
break;
}

View file

@ -298,6 +298,8 @@ int BUTTON_HELD(int ms) {
return BUTTON_ERROR;
}
// This function returns false if no data is available or
// the USB connection is invalid.
bool data_available(void) {
#ifdef WITH_FPC_USART_HOST
return usb_poll_validate_length() || (usart_rxdata_available() > 0);
@ -306,6 +308,9 @@ bool data_available(void) {
#endif
}
// This function doesn't check if the USB connection is valid.
// In most of the cases, you should use data_available() unless
// the timing is critical.
bool data_available_fast(void) {
#ifdef WITH_FPC_USART_HOST
return usb_available_length() || (usart_rxdata_available() > 0);

View file

@ -1012,6 +1012,10 @@ static int CmdUndecimate(const char *Cmd) {
//We have memory, don't we?
int *swap = calloc(MAX_GRAPH_TRACE_LEN, sizeof(int));
if (swap == NULL) {
PrintAndLogEx(FAILED, "failed to allocate memory");
return PM3_EMALLOC;
}
uint32_t g_index = 0, s_index = 0;
while (g_index < g_GraphTraceLen && s_index + factor < MAX_GRAPH_TRACE_LEN) {
int count = 0;
@ -1709,6 +1713,10 @@ int CmdHpf(const char *Cmd) {
CLIParserFree(ctx);
uint8_t *bits = malloc(g_GraphTraceLen);
if (bits == NULL) {
PrintAndLogEx(FAILED, "failed to allocate memory");
return PM3_EMALLOC;
}
size_t size = getFromGraphBuf(bits);
removeSignalOffset(bits, size);
// push it back to graph
@ -2106,6 +2114,10 @@ static int CmdLoad(const char *Cmd) {
if (nofix == false) {
uint8_t *bits = malloc(g_GraphTraceLen);
if (bits == NULL) {
PrintAndLogEx(FAILED, "failed to allocate memory");
return PM3_EMALLOC;
}
size_t size = getFromGraphBuf(bits);
removeSignalOffset(bits, size);
@ -2244,6 +2256,10 @@ int CmdNorm(const char *Cmd) {
}
uint8_t *bits = malloc(g_GraphTraceLen);
if (bits == NULL) {
PrintAndLogEx(FAILED, "failed to allocate memory");
return PM3_EMALLOC;
}
size_t size = getFromGraphBuf(bits);
// set signal properties low/high/mean/amplitude and is_noise detection
computeSignalProperties(bits, size);
@ -2391,6 +2407,10 @@ static int CmdDirectionalThreshold(const char *Cmd) {
// set signal properties low/high/mean/amplitude and isnoice detection
uint8_t *bits = malloc(g_GraphTraceLen);
if (bits == NULL) {
PrintAndLogEx(FAILED, "failed to allocate memory");
return PM3_EMALLOC;
}
size_t size = getFromGraphBuf(bits);
// set signal properties low/high/mean/amplitude and is_noice detection
computeSignalProperties(bits, size);
@ -2435,6 +2455,10 @@ static int CmdZerocrossings(const char *Cmd) {
}
uint8_t *bits = malloc(g_GraphTraceLen);
if (bits == NULL) {
PrintAndLogEx(FAILED, "failed to allocate memory");
return PM3_EMALLOC;
}
size_t size = getFromGraphBuf(bits);
// set signal properties low/high/mean/amplitude and is_noise detection
computeSignalProperties(bits, size);
@ -2749,6 +2773,10 @@ static int CmdDataIIR(const char *Cmd) {
iceSimple_Filter(g_GraphBuffer, g_GraphTraceLen, k);
uint8_t *bits = malloc(g_GraphTraceLen);
if (bits == NULL) {
PrintAndLogEx(FAILED, "failed to allocate memory");
return PM3_EMALLOC;
}
size_t size = getFromGraphBuf(bits);
// set signal properties low/high/mean/amplitude and is_noise detection
computeSignalProperties(bits, size);
@ -3377,6 +3405,10 @@ static int CmdCenterThreshold(const char *Cmd) {
// set signal properties low/high/mean/amplitude and isnoice detection
uint8_t *bits = malloc(g_GraphTraceLen);
if (bits == NULL) {
PrintAndLogEx(FAILED, "failed to allocate memory");
return PM3_EMALLOC;
}
size_t size = getFromGraphBuf(bits);
// set signal properties low/high/mean/amplitude and is_noice detection
computeSignalProperties(bits, size);
@ -3423,6 +3455,10 @@ static int CmdEnvelope(const char *Cmd) {
envelope_square(g_GraphBuffer, g_GraphBuffer, g_GraphTraceLen);
uint8_t *bits = malloc(g_GraphTraceLen);
if (bits == NULL) {
PrintAndLogEx(FAILED, "failed to allocate memory");
return PM3_EMALLOC;
}
size_t size = getFromGraphBuf(bits);
// set signal properties low/high/mean/amplitude and is_noice detection
computeSignalProperties(bits, size);

View file

@ -432,6 +432,10 @@ int CmdFlexdemod(const char *Cmd) {
int i, j, start, bit, sum;
int *data = malloc(g_GraphTraceLen * sizeof(int));
if (data == NULL) {
PrintAndLogEx(FAILED, "failed to allocate memory");
return PM3_EMALLOC;
}
memcpy(data, g_GraphBuffer, g_GraphTraceLen);
size_t size = g_GraphTraceLen;
@ -697,7 +701,7 @@ int CmdLFConfig(const char *Cmd) {
static int lf_read_internal(bool realtime, bool verbose, uint64_t samples) {
if (!g_session.pm3_present) return PM3_ENOTTY;
lf_sample_payload_t payload;
lf_sample_payload_t payload = {0};
payload.realtime = realtime;
payload.verbose = verbose;
@ -720,7 +724,7 @@ static int lf_read_internal(bool realtime, bool verbose, uint64_t samples) {
SendCommandNG(CMD_LF_ACQ_RAW_ADC, (uint8_t *)&payload, sizeof(payload));
if (is_trigger_threshold_set) {
size_t first_receive_len = 32; // larger than the response of CMD_WTX
// wait until a bunch of data arrives
// Wait until a bunch of data arrives
first_receive_len = WaitForRawDataTimeout(realtimeBuf, first_receive_len, -1, false);
sample_bytes = WaitForRawDataTimeout(realtimeBuf + first_receive_len, sample_bytes - first_receive_len, 1000 + FPGA_LOAD_WAIT_TIME, true);
sample_bytes += first_receive_len;
@ -759,7 +763,8 @@ int lf_read(bool verbose, uint64_t samples) {
}
int CmdLFRead(const char *Cmd) {
// In real-time mode, the first few bytes might be the response of CMD_WTX rather than the real samples
// In real-time mode, the first few bytes might be the response of CMD_WTX
// rather than the real samples if the LF FPGA image is not ready.
CLIParserContext *ctx;
CLIParserInit(&ctx, "lf read",
"Sniff low frequency signal.\n"
@ -805,7 +810,7 @@ int CmdLFRead(const char *Cmd) {
int lf_sniff(bool realtime, bool verbose, uint64_t samples) {
if (!g_session.pm3_present) return PM3_ENOTTY;
lf_sample_payload_t payload;
lf_sample_payload_t payload = {0};
payload.realtime = realtime;
payload.verbose = verbose;
@ -828,7 +833,7 @@ int lf_sniff(bool realtime, bool verbose, uint64_t samples) {
SendCommandNG(CMD_LF_SNIFF_RAW_ADC, (uint8_t *)&payload, sizeof(payload));
if (is_trigger_threshold_set) {
size_t first_receive_len = 32; // larger than the response of CMD_WTX
// wait until a bunch of data arrives
// Wait until a bunch of data arrives
first_receive_len = WaitForRawDataTimeout(realtimeBuf, first_receive_len, -1, false);
sample_bytes = WaitForRawDataTimeout(realtimeBuf + first_receive_len, sample_bytes - first_receive_len, 1000 + FPGA_LOAD_WAIT_TIME, true);
sample_bytes += first_receive_len;
@ -863,7 +868,8 @@ int lf_sniff(bool realtime, bool verbose, uint64_t samples) {
}
int CmdLFSniff(const char *Cmd) {
// In real-time mode, the first few bytes might be the response of CMD_WTX rather than the real samples
// In real-time mode, the first few bytes might be the response of CMD_WTX
// rather than the real samples if the LF FPGA image is not ready.
CLIParserContext *ctx;
CLIParserInit(&ctx, "lf sniff",
"Sniff low frequency signal. You need to configure the LF part on the Proxmark3 device manually.\n"

View file

@ -118,6 +118,10 @@ int demodHID(bool verbose) {
uint32_t hi2 = 0, hi = 0, lo = 0;
uint8_t *bits = malloc(g_GraphTraceLen);
if (bits == NULL) {
PrintAndLogEx(FAILED, "failed to allocate memory");
return PM3_EMALLOC;
}
size_t size = getFromGraphBuf(bits);
if (size == 0) {
PrintAndLogEx(DEBUG, "DEBUG: Error - " _RED_("HID not enough samples"));
@ -142,6 +146,7 @@ int demodHID(bool verbose) {
else
PrintAndLogEx(DEBUG, "DEBUG: Error - " _RED_("HID error demoding fsk %d"), idx);
free(bits);
return PM3_ESOFT;
}

View file

@ -404,6 +404,10 @@ static int CmdIndalaDemodAlt(const char *Cmd) {
// worst case with g_GraphTraceLen=40000 is < 4096
// under normal conditions it's < 2048
uint8_t *data = calloc(MAX_GRAPH_TRACE_LEN, sizeof(uint8_t));
if (data == NULL) {
PrintAndLogEx(FAILED, "failed to allocate memory");
return PM3_EMALLOC;
}
size_t datasize = getFromGraphBuf(data);
uint8_t rawbits[4096] = {0};

View file

@ -67,6 +67,10 @@ int demodIOProx(bool verbose) {
(void) verbose; // unused so far
int idx = 0, retval = PM3_SUCCESS;
uint8_t *bits = calloc(MAX_GRAPH_TRACE_LEN, sizeof(uint8_t));
if (bits == NULL) {
PrintAndLogEx(FAILED, "failed to allocate memory");
return PM3_EMALLOC;
}
size_t size = getFromGraphBuf(bits);
if (size < 65) {
PrintAndLogEx(DEBUG, "DEBUG: Error - IO prox not enough samples in GraphBuffer");

View file

@ -104,6 +104,10 @@ int demodParadox(bool verbose, bool oldChksum) {
(void) verbose; // unused so far
//raw fsk demod no manchester decoding no start bit finding just get binary from wave
uint8_t *bits = calloc(MAX_GRAPH_TRACE_LEN, sizeof(uint8_t));
if (bits == NULL) {
PrintAndLogEx(FAILED, "failed to allocate memory");
return PM3_EMALLOC;
}
size_t size = getFromGraphBuf(bits);
if (size == 0) {
PrintAndLogEx(DEBUG, "DEBUG: Error - Paradox not enough samples");

View file

@ -44,6 +44,10 @@ int demodPyramid(bool verbose) {
(void) verbose; // unused so far
//raw fsk demod no manchester decoding no start bit finding just get binary from wave
uint8_t *bits = calloc(MAX_GRAPH_TRACE_LEN, sizeof(uint8_t));
if (bits == NULL) {
PrintAndLogEx(FAILED, "failed to allocate memory");
return PM3_EMALLOC;
}
size_t size = getFromGraphBuf(bits);
if (size == 0) {
PrintAndLogEx(DEBUG, "DEBUG: Error - Pyramid not enough samples");

View file

@ -350,7 +350,7 @@ __attribute__((force_align_arg_pointer))
bool commfailed = false;
PacketResponseNG rx;
PacketResponseNGRaw rx_raw;
// stash the last state of is_receiving_raw, to detect if state changed
// Stash the last state of is_receiving_raw, to detect if state changed
bool is_receiving_raw_last = false;
#if defined(__MACH__) && defined(__APPLE__)
@ -398,7 +398,7 @@ __attribute__((force_align_arg_pointer))
}
}
} else {
// ignore data when bufferPos >= bufferLen and is_receiving_raw has not been set to false
// Ignore data when bufferPos >= bufferLen and is_receiving_raw has not been set to false
uint8_t dummyData[64];
uint32_t dummyLen;
uart_receive(sp, dummyData, sizeof(dummyData), &dummyLen);
@ -407,7 +407,7 @@ __attribute__((force_align_arg_pointer))
if (is_receiving_raw_last) {
// is_receiving_raw changed from true to false
// set the buffer as undefined
// Set the buffer as undefined
// comm_raw_data == NULL is used in SetCommunicationReceiveMode()
__atomic_store_n(&comm_raw_data, NULL, __ATOMIC_SEQ_CST);
}
@ -849,11 +849,11 @@ size_t WaitForRawDataTimeout(uint8_t *buffer, size_t len, size_t ms_timeout, boo
while (pos < len) {
if (kbd_enter_pressed()) {
// send anything to stop the transfer
// Send anything to stop the transfer
PrintAndLogEx(INFO, "Stopping");
SendCommandNG(CMD_BREAK_LOOP, NULL, 0);
// for ms_timeout == -1, pos < len might always be true
// For ms_timeout == -1, pos < len might always be true
// so user need a spectial way to break this loop
if (ms_timeout == (size_t) - 1) {
break;
@ -862,15 +862,15 @@ size_t WaitForRawDataTimeout(uint8_t *buffer, size_t len, size_t ms_timeout, boo
pos = __atomic_load_n(&comm_raw_pos, __ATOMIC_SEQ_CST);
// check the timeout if pos is not updated
// Check the timeout if pos is not updated
if (last_pos == pos) {
uint64_t tmp_clk = __atomic_load_n(&timeout_start_time, __ATOMIC_SEQ_CST);
// if ms_timeout == -1, the loop can only be breaked by pressing Enter or receiving enough data
// If ms_timeout == -1, the loop can only be breaked by pressing Enter or receiving enough data
if ((ms_timeout != (size_t) - 1) && (msclock() - tmp_clk > ms_timeout)) {
break;
}
} else {
// print when (print_counter % 64) == 0
// Print process when (print_counter % 64) == 0
if (show_process && (print_counter & 0x3F) == 0) {
PrintAndLogEx(INFO, "[%zu/%zu]", pos, len);
}
@ -881,11 +881,11 @@ size_t WaitForRawDataTimeout(uint8_t *buffer, size_t len, size_t ms_timeout, boo
msleep(10);
}
if (pos == len && (ms_timeout != (size_t) - 1)) {
// if ms_timeout != -1, when the desired data is received, tell the arm side
// If ms_timeout != -1, when the desired data is received, tell the arm side
// to stop the current process, and wait for some time to make sure the process
// has been stopped
// if ms_timeout == -1, the user might not want to break the existing process
// on the arm side
// has been stopped.
// If ms_timeout == -1, the user might not want to break the existing process
// on the arm side.
SendCommandNG(CMD_BREAK_LOOP, NULL, 0);
msleep(ms_timeout);
}

View file

@ -37,10 +37,7 @@ AT91SAM7S256 USB Device Port
#define AT91C_EP_IN 2 // cfg bulk in
#define AT91C_EP_NOTIFY 3 // cfg cdc notification interrup
#define AT91C_EP_CONTROL_SIZE 8
#define AT91C_EP_OUT_SIZE 64
#define AT91C_EP_IN_SIZE 64
// The endpoint size is defined in usb_cdc.h
// Section: USB Descriptors
#define USB_DESCRIPTOR_DEVICE 0x01 // DescriptorType for a Device Descriptor.
@ -128,7 +125,7 @@ static const char devDescriptor[] = {
2, // Device Class: Communication Device Class
0, // Device Subclass: CDC class sub code ACM [ice 0x02 = win10 virtual comport ]
0, // Device Protocol: CDC Device protocol (unused)
AT91C_EP_CONTROL_SIZE, // MaxPacketSize0
AT91C_USB_EP_CONTROL_SIZE, // MaxPacketSize0
0xc4, 0x9a, // Vendor ID [0x9ac4 = J. Westhues]
0x8f, 0x4b, // Product ID [0x4b8f = Proxmark-3 RFID Instrument]
0x00, 0x01, // BCD Device release number (1.00)
@ -218,7 +215,7 @@ static const char cfgDescriptor[] = {
USB_DESCRIPTOR_ENDPOINT, // Descriptor Type
_EP03_IN, // EndpointAddress: Endpoint 03 - IN
_INTERRUPT, // Attributes
AT91C_EP_CONTROL_SIZE, 0x00, // MaxPacket Size: EP0 - 8
AT91C_USB_EP_CONTROL_SIZE, 0x00, // MaxPacket Size: EP0 - 8
0xFF, // Interval polling
@ -239,7 +236,7 @@ static const char cfgDescriptor[] = {
USB_DESCRIPTOR_ENDPOINT, // Descriptor Type
_EP01_OUT, // Endpoint Address: Endpoint 01 - OUT
_BULK, // Attributes: BULK
AT91C_EP_OUT_SIZE, 0x00, // MaxPacket Size: 64 bytes
AT91C_USB_EP_OUT_SIZE, 0x00, // MaxPacket Size: 64 bytes
0, // Interval: ignored for bulk
/* Endpoint descriptor */
@ -247,7 +244,7 @@ static const char cfgDescriptor[] = {
USB_DESCRIPTOR_ENDPOINT, // Descriptor Type
_EP02_IN, // Endpoint Address: Endpoint 02 - IN
_BULK, // Attribute: BULK
AT91C_EP_IN_SIZE, 0x00, // MaxPacket Size: 64 bytes
AT91C_USB_EP_IN_SIZE, 0x00, // MaxPacket Size: 64 bytes
0 // Interval: ignored for bulk
};
@ -775,7 +772,7 @@ int usb_write(const uint8_t *data, const size_t len) {
// send first chunk
cpt = MIN(length, AT91C_EP_IN_SIZE);
cpt = MIN(length, AT91C_USB_EP_IN_SIZE);
length -= cpt;
while (cpt--) {
pUdp->UDP_FDR[AT91C_EP_IN] = *data++;
@ -786,7 +783,7 @@ int usb_write(const uint8_t *data, const size_t len) {
while (length) {
// Send next chunk
cpt = MIN(length, AT91C_EP_IN_SIZE);
cpt = MIN(length, AT91C_USB_EP_IN_SIZE);
length -= cpt;
while (cpt--) {
pUdp->UDP_FDR[AT91C_EP_IN] = *data++;
@ -814,7 +811,7 @@ int usb_write(const uint8_t *data, const size_t len) {
while (pUdp->UDP_CSR[AT91C_EP_IN] & AT91C_UDP_TXCOMP) {};
if (len % AT91C_EP_IN_SIZE == 0) {
if (len % AT91C_USB_EP_IN_SIZE == 0) {
// like AT91F_USB_SendZlp(), in non ping-pong mode
UDP_SET_EP_FLAGS(AT91C_EP_IN, AT91C_UDP_TXPKTRDY);
while (!(pUdp->UDP_CSR[AT91C_EP_IN] & AT91C_UDP_TXCOMP)) {};
@ -857,8 +854,8 @@ int async_usb_write_start(void) {
* \brief Push one byte to the FIFO of IN endpoint (time-critical)
*
* This function simply push a byte to the FIFO of IN endpoint.
* The FIFO size is AT91C_EP_IN_SIZE. Make sure this function is not called
* over AT91C_EP_IN_SIZE times between each async_usb_write_requestWrite().
* The FIFO size is AT91C_USB_EP_IN_SIZE. Make sure this function is not called
* over AT91C_USB_EP_IN_SIZE times between each async_usb_write_requestWrite().
*----------------------------------------------------------------------------
*/
inline void async_usb_write_pushByte(uint8_t data) {
@ -947,7 +944,7 @@ void AT91F_USB_SendData(AT91PS_UDP pudp, const char *pData, uint32_t length) {
AT91_REG csr;
do {
uint32_t cpt = MIN(length, AT91C_EP_CONTROL_SIZE);
uint32_t cpt = MIN(length, AT91C_USB_EP_CONTROL_SIZE);
length -= cpt;
while (cpt--)

View file

@ -23,6 +23,10 @@
#include "common.h"
#include "at91sam7s512.h"
#define AT91C_USB_EP_CONTROL_SIZE 8
#define AT91C_USB_EP_OUT_SIZE 64
#define AT91C_USB_EP_IN_SIZE 64
void usb_disable(void);
void usb_enable(void);
bool usb_check(void);