From 084a8161d4ded1056ab71ba50b412030a4732e80 Mon Sep 17 00:00:00 2001
From: iceman1001
Date: Tue, 28 Apr 2020 18:24:52 +0200
Subject: [PATCH 001/632] coverity fix: 279106
---
client/src/cmdhfmfdes.c | 18 +++++++++++++++---
1 file changed, 15 insertions(+), 3 deletions(-)
diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c
index 65b02b5f8..11f93ec95 100644
--- a/client/src/cmdhfmfdes.c
+++ b/client/src/cmdhfmfdes.c
@@ -3081,13 +3081,25 @@ static void DecodeAccessRights(uint16_t accrights) {
if (car == NULL) return;
char *rwa = DecodeAccessValue(read_write_access);
- if (rwa == NULL) return;
+ if (rwa == NULL) {
+ free(car);
+ return;
+ }
char *wa = DecodeAccessValue(write_access);
- if (wa == NULL) return;
+ if (wa == NULL) {
+ free(car);
+ free(rwa);
+ return;
+ }
char *ra = DecodeAccessValue(read_access);
- if (ra == NULL) return;
+ if (ra == NULL) {
+ free(car);
+ free(rwa);
+ free(wa);
+ return;
+ }
PrintAndLogEx(INFO, " Access Rights: 0x%04X - Change %s - RW %s - W %s - R %s", accrights, car, rwa, wa, ra);
free(car);
From 12f87938ea80f7d478ea46dd69b903f0ffb7ac9c Mon Sep 17 00:00:00 2001
From: iceman1001
Date: Tue, 28 Apr 2020 18:51:24 +0200
Subject: [PATCH 002/632] coverity fix 279110
---
client/src/cmdhfmfdes.c | 12 ++++++------
1 file changed, 6 insertions(+), 6 deletions(-)
diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c
index 11f93ec95..90d5df814 100644
--- a/client/src/cmdhfmfdes.c
+++ b/client/src/cmdhfmfdes.c
@@ -1824,15 +1824,15 @@ static int CmdHF14ADesCreateApp(const char *Cmd) {
uint8_t aid[3] = {0};
uint8_t fid[2] = {0};
uint8_t name[16] = {0};
- uint8_t keysetting1 = 0;
- uint8_t keysetting2 = 0;
+ uint8_t keysetting1[1] = {0};
+ uint8_t keysetting2[1] = {0};
int keylen1 = 1;
int keylen2 = 1;
int namelen = 16;
CLIGetHexWithReturn(1, aid, &aidlength);
CLIGetHexWithReturn(2, fid, &fidlength);
- CLIGetHexWithReturn(3, &keysetting1, &keylen1);
- CLIGetHexWithReturn(4, &keysetting2, &keylen2);
+ CLIGetHexWithReturn(3, keysetting1, &keylen1);
+ CLIGetHexWithReturn(4, keysetting2, &keylen2);
CLIGetStrWithReturn(5, name, &namelen);
CLIParserFree();
@@ -1882,8 +1882,8 @@ static int CmdHF14ADesCreateApp(const char *Cmd) {
aidhdr_t aidhdr;
memcpy(aidhdr.aid, aid, sizeof(aid));
- aidhdr.keysetting1 = keysetting1;
- aidhdr.keysetting2 = keysetting2;
+ aidhdr.keysetting1 = keysetting1[0];
+ aidhdr.keysetting2 = keysetting2[0];
if (usefid) memcpy(aidhdr.fid, fid, sizeof(fid));
From 857526a945a50040815543ef010fdc33dfa6448a Mon Sep 17 00:00:00 2001
From: iceman1001
Date: Tue, 28 Apr 2020 19:08:07 +0200
Subject: [PATCH 003/632] coverity fix 286651
---
client/src/cmdhfmfdes.c | 85 +++++++++++++++++++++++++++++------------
1 file changed, 60 insertions(+), 25 deletions(-)
diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c
index 90d5df814..5ec08a1c3 100644
--- a/client/src/cmdhfmfdes.c
+++ b/client/src/cmdhfmfdes.c
@@ -3584,16 +3584,22 @@ void DesFill2bPattern(uint8_t deskeyList[MAX_KEYS_LIST_LEN][8], size_t *deskeyLi
}
*startPattern = pt;
- if ((*deskeyListLen == MAX_KEYS_LIST_LEN) && (*aeskeyListLen == MAX_KEYS_LIST_LEN) && (*k3kkeyListLen == MAX_KEYS_LIST_LEN))
+ if ( (*deskeyListLen == MAX_KEYS_LIST_LEN) &&
+ (*aeskeyListLen == MAX_KEYS_LIST_LEN) &&
+ (*k3kkeyListLen == MAX_KEYS_LIST_LEN)) {
break;
+ }
}
(*startPattern)++;
}
static int AuthCheckDesfire(uint8_t *aid, uint8_t deskeyList[MAX_KEYS_LIST_LEN][8], size_t deskeyListLen, uint8_t aeskeyList[MAX_KEYS_LIST_LEN][16], size_t aeskeyListLen, uint8_t k3kkeyList[MAX_KEYS_LIST_LEN][24], size_t k3kkeyListLen, uint8_t foundKeys[4][0xE][24 + 1], bool *result) {
+
+ uint32_t curaid = (aid[0] & 0xFF) + ((aid[1] & 0xFF) << 8) + ((aid[2] & 0xFF) << 16);
+
int res = handler_desfire_select_application(aid);
if (res != PM3_SUCCESS) {
- PrintAndLogEx(ERR, "AID %X does not exist.");
+ PrintAndLogEx(ERR, "AID 0x%06X does not exist.", curaid);
return res;
}
@@ -3608,24 +3614,31 @@ static int AuthCheckDesfire(uint8_t *aid, uint8_t deskeyList[MAX_KEYS_LIST_LEN][
uint8_t file_ids_len = 0;
// Get File IDs
if (handler_desfire_fileids(file_ids, &file_ids_len) == PM3_SUCCESS) {
+
for (int j = file_ids_len - 1; j >= 0; j--) {
+
uint8_t filesettings[20] = {0};
int fileset_len = 0;
+
res = handler_desfire_filesettings(file_ids[j], filesettings, &fileset_len);
if (res == PM3_SUCCESS) {
+
uint16_t accrights = (filesettings[3] << 8) + filesettings[2];
int change_access_rights = accrights & 0xF;
int read_write_access = (accrights >> 4) & 0xF;
int write_access = (accrights >> 8) & 0xF;
int read_access = (accrights >> 12) & 0xF;
+
if (change_access_rights == 0xE) change_access_rights = 0x0;
if (read_write_access == 0xE) read_write_access = 0x0;
if (write_access == 0xE) write_access = 0x0;
if (read_access == 0xE) read_access = 0x0;
+
usedkeys[change_access_rights] = 1;
usedkeys[read_write_access] = 1;
usedkeys[write_access] = 1;
usedkeys[read_access] = 1;
+
if (res == PM3_SUCCESS) {
switch (fileset_len >> 6) {
case 0:
@@ -3644,6 +3657,7 @@ static int AuthCheckDesfire(uint8_t *aid, uint8_t deskeyList[MAX_KEYS_LIST_LEN][
}
}
}
+
if (file_ids_len == 0) {
for (int z = 0; z < 0xE; z++) {
usedkeys[z] = 1;
@@ -3654,24 +3668,33 @@ static int AuthCheckDesfire(uint8_t *aid, uint8_t deskeyList[MAX_KEYS_LIST_LEN][
}
}
}
- } else des = true;
+ } else {
+ des = true;
+ }
+
int error = PM3_SUCCESS;
bool badlen = false;
+
mfdes_authinput_t payload;
- uint32_t curaid = (aid[0] & 0xFF) + ((aid[1] & 0xFF) << 8) + ((aid[2] & 0xFF) << 16);
+ mfdes_auth_res_t payload_res;
+
if (des) {
- for (int keyno = 0; keyno < 0xE; keyno++)
+
+ for (uint8_t keyno = 0; keyno < 0xE; keyno++) {
+
if (usedkeys[keyno] == 1 && foundKeys[0][keyno][0] == 0) {
+
for (int curkey = 0; curkey < deskeyListLen; curkey++) {
+
payload.keylen = 8;
memcpy(payload.key, deskeyList[curkey], 8);
payload.mode = MFDES_AUTH_DES;
payload.algo = MFDES_ALGO_DES;
payload.keyno = keyno;
- mfdes_auth_res_t rpayload;
- error = handler_desfire_auth(&payload, &rpayload, false);
+
+ error = handler_desfire_auth(&payload, &payload_res, false);
if (error == PM3_SUCCESS) {
- PrintAndLogEx(SUCCESS, "AID 0x%06X, Found DES Key %d : " _GREEN_("%s"), curaid, keyno, sprint_hex(deskeyList[curkey], 8));
+ PrintAndLogEx(SUCCESS, "AID 0x%06X, Found DES Key %u : " _GREEN_("%s"), curaid, keyno, sprint_hex(deskeyList[curkey], 8));
foundKeys[0][keyno][0] = 0x01;
*result = true;
memcpy(&foundKeys[0][keyno][1], deskeyList[curkey], 8);
@@ -3681,7 +3704,6 @@ static int AuthCheckDesfire(uint8_t *aid, uint8_t deskeyList[MAX_KEYS_LIST_LEN][
DropField();
res = handler_desfire_select_application(aid);
if (res != PM3_SUCCESS) {
- PrintAndLogEx(ERR, "AID 0x%06X does not exist", curaid);
return res;
}
break;
@@ -3692,20 +3714,26 @@ static int AuthCheckDesfire(uint8_t *aid, uint8_t deskeyList[MAX_KEYS_LIST_LEN][
break;
}
}
+ }
}
+
if (tdes) {
- for (int keyno = 0; keyno < 0xE; keyno++)
+
+ for (uint8_t keyno = 0; keyno < 0xE; keyno++) {
+
if (usedkeys[keyno] == 1 && foundKeys[1][keyno][0] == 0) {
+
for (int curkey = 0; curkey < aeskeyListLen; curkey++) {
+
payload.keylen = 16;
memcpy(payload.key, aeskeyList[curkey], 16);
payload.mode = MFDES_AUTH_DES;
payload.algo = MFDES_ALGO_3DES;
payload.keyno = keyno;
- mfdes_auth_res_t rpayload;
- error = handler_desfire_auth(&payload, &rpayload, false);
+
+ error = handler_desfire_auth(&payload, &payload_res, false);
if (error == PM3_SUCCESS) {
- PrintAndLogEx(SUCCESS, "AID 0x%06X, Found 3DES Key %d : " _GREEN_("%s"), curaid, keyno, sprint_hex(aeskeyList[curkey], 16));
+ PrintAndLogEx(SUCCESS, "AID 0x%06X, Found 3DES Key %u : " _GREEN_("%s"), curaid, keyno, sprint_hex(aeskeyList[curkey], 16));
foundKeys[1][keyno][0] = 0x01;
*result = true;
memcpy(&foundKeys[1][keyno][1], aeskeyList[curkey], 16);
@@ -3715,7 +3743,6 @@ static int AuthCheckDesfire(uint8_t *aid, uint8_t deskeyList[MAX_KEYS_LIST_LEN][
DropField();
res = handler_desfire_select_application(aid);
if (res != PM3_SUCCESS) {
- PrintAndLogEx(ERR, "AID %X does not exist.");
return res;
}
break;
@@ -3726,21 +3753,26 @@ static int AuthCheckDesfire(uint8_t *aid, uint8_t deskeyList[MAX_KEYS_LIST_LEN][
break;
}
}
+ }
}
if (aes) {
- for (int keyno = 0; keyno < 0xE; keyno++)
+
+ for (uint8_t keyno = 0; keyno < 0xE; keyno++) {
+
if (usedkeys[keyno] == 1 && foundKeys[2][keyno][0] == 0) {
+
for (int curkey = 0; curkey < aeskeyListLen; curkey++) {
+
payload.keylen = 16;
memcpy(payload.key, aeskeyList[curkey], 16);
payload.mode = MFDES_AUTH_AES;
payload.algo = MFDES_ALGO_AES;
payload.keyno = keyno;
- mfdes_auth_res_t rpayload;
- error = handler_desfire_auth(&payload, &rpayload, false);
+
+ error = handler_desfire_auth(&payload, &payload_res, false);
if (error == PM3_SUCCESS) {
- PrintAndLogEx(SUCCESS, "AID 0x%06X, Found AES Key %d : " _GREEN_("%s"), curaid, keyno, sprint_hex(aeskeyList[curkey], 16));
+ PrintAndLogEx(SUCCESS, "AID 0x%06X, Found AES Key %u : " _GREEN_("%s"), curaid, keyno, sprint_hex(aeskeyList[curkey], 16));
foundKeys[2][keyno][0] = 0x01;
*result = true;
memcpy(&foundKeys[2][keyno][1], aeskeyList[curkey], 16);
@@ -3750,7 +3782,6 @@ static int AuthCheckDesfire(uint8_t *aid, uint8_t deskeyList[MAX_KEYS_LIST_LEN][
DropField();
res = handler_desfire_select_application(aid);
if (res != PM3_SUCCESS) {
- PrintAndLogEx(ERR, "AID %X does not exist.");
return res;
}
break;
@@ -3761,21 +3792,25 @@ static int AuthCheckDesfire(uint8_t *aid, uint8_t deskeyList[MAX_KEYS_LIST_LEN][
break;
}
}
+ }
}
if (k3kdes) {
- for (int keyno = 0; keyno < 0xE; keyno++)
+
+ for (uint8_t keyno = 0; keyno < 0xE; keyno++) {
+
if (usedkeys[keyno] == 1 && foundKeys[3][keyno][0] == 0) {
+
for (int curkey = 0; curkey < k3kkeyListLen; curkey++) {
payload.keylen = 24;
memcpy(payload.key, k3kkeyList[curkey], 24);
payload.mode = MFDES_AUTH_ISO;
payload.algo = MFDES_ALGO_3K3DES;
payload.keyno = keyno;
- mfdes_auth_res_t rpayload;
- error = handler_desfire_auth(&payload, &rpayload, false);
+
+ error = handler_desfire_auth(&payload, &payload_res, false);
if (error == PM3_SUCCESS) {
- PrintAndLogEx(SUCCESS, "AID 0x%06X, Found 3K3 Key %d : " _GREEN_("%s"), curaid, keyno, sprint_hex(k3kkeyList[curkey], 24));
+ PrintAndLogEx(SUCCESS, "AID 0x%06X, Found 3K3 Key %u : " _GREEN_("%s"), curaid, keyno, sprint_hex(k3kkeyList[curkey], 24));
foundKeys[3][keyno][0] = 0x01;
*result = true;
memcpy(&foundKeys[3][keyno][1], k3kkeyList[curkey], 16);
@@ -3785,17 +3820,17 @@ static int AuthCheckDesfire(uint8_t *aid, uint8_t deskeyList[MAX_KEYS_LIST_LEN][
DropField();
res = handler_desfire_select_application(aid);
if (res != PM3_SUCCESS) {
- PrintAndLogEx(ERR, "AID %X does not exist.");
return res;
}
break;
}
}
+
if (badlen == true) {
- badlen = false;
break;
}
}
+ }
}
DropField();
return PM3_SUCCESS;
From fbd0a7e28444f3958507b4e42ea2dd99f7d5c71f Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Tue, 28 Apr 2020 19:58:07 +0200
Subject: [PATCH 004/632] typo
---
client/src/cmdhf15.c | 28 ++++++++++++++--------------
client/src/cmdhficlass.c | 4 ++--
client/src/cmdhflto.c | 14 +++++++-------
client/src/cmdhfmfdes.c | 2 +-
client/src/cmdhftopaz.c | 4 ++--
client/src/cmdlft55xx.c | 6 +++---
include/pm3_cmd.h | 2 +-
7 files changed, 30 insertions(+), 30 deletions(-)
diff --git a/client/src/cmdhf15.c b/client/src/cmdhf15.c
index 620a75bd7..67e47c0d4 100644
--- a/client/src/cmdhf15.c
+++ b/client/src/cmdhf15.c
@@ -746,14 +746,14 @@ static int NxpSysInfo(uint8_t *uid) {
if (status < 2) {
PrintAndLogEx(WARNING, "iso15693 card doesn't answer to NXP systeminfo command");
- return PM3_EWRONGANSVER;
+ return PM3_EWRONGANSWER;
}
recv = resp.data.asBytes;
if (recv[0] & ISO15_RES_ERROR) {
PrintAndLogEx(ERR, "iso15693 card returned error %i: %s", recv[0], TagErrorStr(recv[0]));
- return PM3_EWRONGANSVER;
+ return PM3_EWRONGANSWER;
}
bool support_signature = (recv[5] & 0x01);
@@ -855,14 +855,14 @@ static int NxpSysInfo(uint8_t *uid) {
if (status < 2) {
PrintAndLogEx(WARNING, "iso15693 card doesn't answer to READ SIGNATURE command");
- return PM3_EWRONGANSVER;
+ return PM3_EWRONGANSWER;
}
recv = resp.data.asBytes;
if (recv[0] & ISO15_RES_ERROR) {
PrintAndLogEx(ERR, "iso15693 card returned error %i: %s", recv[0], TagErrorStr(recv[0]));
- return PM3_EWRONGANSVER;
+ return PM3_EWRONGANSWER;
}
uint8_t signature[32] = {0x00};
@@ -916,14 +916,14 @@ static int CmdHF15Info(const char *Cmd) {
if (status < 2) {
PrintAndLogEx(WARNING, "iso15693 card doesn't answer to systeminfo command");
- return PM3_EWRONGANSVER;
+ return PM3_EWRONGANSWER;
}
recv = resp.data.asBytes;
if (recv[0] & ISO15_RES_ERROR) {
PrintAndLogEx(ERR, "iso15693 card returned error %i: %s", recv[0], TagErrorStr(recv[0]));
- return PM3_EWRONGANSVER;
+ return PM3_EWRONGANSWER;
}
memcpy(uid, recv + 2, sizeof(uid));
@@ -1090,7 +1090,7 @@ static int CmdHF15WriteAfi(const char *Cmd) {
if (recv[0] & ISO15_RES_ERROR) {
PrintAndLogEx(ERR, "iso15693 card returned error %i: %s", recv[0], TagErrorStr(recv[0]));
- return PM3_EWRONGANSVER;
+ return PM3_EWRONGANSWER;
}
PrintAndLogEx(NORMAL, "");
@@ -1149,7 +1149,7 @@ static int CmdHF15WriteDsfid(const char *Cmd) {
if (recv[0] & ISO15_RES_ERROR) {
PrintAndLogEx(ERR, "iso15693 card returned error %i: %s", recv[0], TagErrorStr(recv[0]));
- return PM3_EWRONGANSVER;
+ return PM3_EWRONGANSWER;
}
PrintAndLogEx(NORMAL, "");
@@ -1430,7 +1430,7 @@ static int CmdHF15Readmulti(const char *Cmd) {
uint32_t status = resp.oldarg[0];
if (status < 2) {
PrintAndLogEx(FAILED, "iso15693 card select failed");
- return PM3_EWRONGANSVER;
+ return PM3_EWRONGANSWER;
}
recv = resp.data.asBytes;
@@ -1442,7 +1442,7 @@ static int CmdHF15Readmulti(const char *Cmd) {
if (recv[0] & ISO15_RES_ERROR) {
PrintAndLogEx(FAILED, "iso15693 card returned error %i: %s", recv[0], TagErrorStr(recv[0]));
- return PM3_EWRONGANSVER;
+ return PM3_EWRONGANSWER;
}
// skip status byte
@@ -1512,7 +1512,7 @@ static int CmdHF15Read(const char *Cmd) {
uint32_t status = resp.oldarg[0];
if (status < 2) {
PrintAndLogEx(ERR, "iso15693 card select failed");
- return PM3_EWRONGANSVER;
+ return PM3_EWRONGANSWER;
}
recv = resp.data.asBytes;
@@ -1524,7 +1524,7 @@ static int CmdHF15Read(const char *Cmd) {
if (recv[0] & ISO15_RES_ERROR) {
PrintAndLogEx(ERR, "iso15693 card returned error %i: %s", recv[0], TagErrorStr(recv[0]));
- return PM3_EWRONGANSVER;
+ return PM3_EWRONGANSWER;
}
// print response
@@ -1598,7 +1598,7 @@ static int CmdHF15Write(const char *Cmd) {
uint32_t status = resp.oldarg[0];
if (status < 2) {
PrintAndLogEx(FAILED, "iso15693 card select failed");
- return PM3_EWRONGANSVER;
+ return PM3_EWRONGANSWER;
}
recv = resp.data.asBytes;
@@ -1610,7 +1610,7 @@ static int CmdHF15Write(const char *Cmd) {
if (recv[0] & ISO15_RES_ERROR) {
PrintAndLogEx(ERR, "iso15693 card returned error %i: %s", recv[0], TagErrorStr(recv[0]));
- return PM3_EWRONGANSVER;
+ return PM3_EWRONGANSWER;
}
PrintAndLogEx(NORMAL, "OK");
diff --git a/client/src/cmdhficlass.c b/client/src/cmdhficlass.c
index c687e316d..321b02133 100644
--- a/client/src/cmdhficlass.c
+++ b/client/src/cmdhficlass.c
@@ -1469,7 +1469,7 @@ static int WriteBlock(uint8_t blockno, uint8_t *bldata, uint8_t *KEY, bool use_c
if (resp.status != PM3_SUCCESS) {
if (verbose) PrintAndLogEx(ERR, "failed to communicate with card");
DropField();
- return PM3_EWRONGANSVER;
+ return PM3_EWRONGANSWER;
}
if (resp.data.asBytes[0] == 1)
@@ -1811,7 +1811,7 @@ static int ReadBlock(uint8_t *KEY, uint8_t blockno, uint8_t keyType, bool elite,
if (resp.status != PM3_SUCCESS) {
if (verbose) PrintAndLogEx(ERR, "failed to communicate with card");
DropField();
- return PM3_EWRONGANSVER;
+ return PM3_EWRONGANSWER;
}
result = (struct p *)resp.data.asBytes;
diff --git a/client/src/cmdhflto.c b/client/src/cmdhflto.c
index 6434a9e88..947e2bacf 100644
--- a/client/src/cmdhflto.c
+++ b/client/src/cmdhflto.c
@@ -149,14 +149,14 @@ static int lto_select(uint8_t *id_response, uint8_t id_len, uint8_t *type_respon
resp_len = id_len;
status = lto_send_cmd_raw(select_sn_cmd, sizeof(select_sn_cmd), id_response, &resp_len, false, false, verbose);
if (status == PM3_ETIMEOUT || status == PM3_ESOFT) {
- return PM3_EWRONGANSVER; // REQUEST SERIAL NUMBER failed
+ return PM3_EWRONGANSWER; // REQUEST SERIAL NUMBER failed
}
memcpy(select_cmd + 2, id_response, sizeof(select_cmd) - 2);
resp_len = 1;
status = lto_send_cmd_raw(select_cmd, sizeof(select_cmd), resp, &resp_len, true, false, verbose);
if (status == PM3_ETIMEOUT || status == PM3_ESOFT || resp[0] != 0x0A) {
- return PM3_EWRONGANSVER; // SELECT failed
+ return PM3_EWRONGANSWER; // SELECT failed
}
// tag is now INIT and SELECTED.
@@ -222,12 +222,12 @@ static int lto_rdbl(uint8_t blk, uint8_t *block_responce, uint8_t *block_cnt_res
int status = lto_send_cmd_raw(rdbl_cmd, sizeof(rdbl_cmd), block_responce, &resp_len, true, false, verbose);
if (status == PM3_ETIMEOUT || status == PM3_ESOFT) {
- return PM3_EWRONGANSVER; // READ BLOCK failed
+ return PM3_EWRONGANSWER; // READ BLOCK failed
}
status = lto_send_cmd_raw(rdbl_cnt_cmd, sizeof(rdbl_cnt_cmd), block_cnt_responce, &resp_len, false, false, verbose);
if (status == PM3_ETIMEOUT || status == PM3_ESOFT) {
- return PM3_EWRONGANSVER; // READ BLOCK CONTINUE failed
+ return PM3_EWRONGANSWER; // READ BLOCK CONTINUE failed
}
return PM3_SUCCESS;
@@ -334,17 +334,17 @@ static int lto_wrbl(uint8_t blk, uint8_t *data, bool verbose) {
int status = lto_send_cmd_raw(wrbl_cmd, sizeof(wrbl_cmd), resp, &resp_len, true, false, verbose);
if (status == PM3_ETIMEOUT || status == PM3_ESOFT || resp[0] != 0x0A) {
- return PM3_EWRONGANSVER; // WRITE BLOCK failed
+ return PM3_EWRONGANSWER; // WRITE BLOCK failed
}
status = lto_send_cmd_raw(wrbl_d00_d15, sizeof(wrbl_d00_d15), resp, &resp_len, true, false, verbose);
if (status == PM3_ETIMEOUT || status == PM3_ESOFT || resp[0] != 0x0A) {
- return PM3_EWRONGANSVER; // WRITE BLOCK failed
+ return PM3_EWRONGANSWER; // WRITE BLOCK failed
}
status = lto_send_cmd_raw(wrbl_d16_d31, sizeof(wrbl_d16_d31), resp, &resp_len, true, false, verbose);
if (status == PM3_ETIMEOUT || status == PM3_ESOFT || resp[0] != 0x0A) {
- return PM3_EWRONGANSVER; // WRITE BLOCK failed
+ return PM3_EWRONGANSWER; // WRITE BLOCK failed
}
return PM3_SUCCESS;
diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c
index 5ec08a1c3..2968a5ef7 100644
--- a/client/src/cmdhfmfdes.c
+++ b/client/src/cmdhfmfdes.c
@@ -534,7 +534,7 @@ static char *GetErrorString(int res, uint16_t *sw) {
return "Generic TTY error";
case PM3_EINIT:
return "Initialization error";
- case PM3_EWRONGANSVER:
+ case PM3_EWRONGANSWER:
return "Expected a different answer error";
case PM3_EOUTOFBOUND:
return "Memory out-of-bounds error";
diff --git a/client/src/cmdhftopaz.c b/client/src/cmdhftopaz.c
index 1408a6e46..6410d67bc 100644
--- a/client/src/cmdhftopaz.c
+++ b/client/src/cmdhftopaz.c
@@ -109,7 +109,7 @@ static int topaz_select(uint8_t *atqa, uint8_t atqa_len, uint8_t *rid_response,
status = topaz_send_cmd(rid_cmd, sizeof(rid_cmd), rid_response, &resp_len, verbose);
if (status == PM3_ETIMEOUT || status == PM3_ESOFT) {
topaz_switch_off_field();
- return PM3_EWRONGANSVER; // RID failed
+ return PM3_EWRONGANSWER; // RID failed
}
return PM3_SUCCESS;
@@ -529,7 +529,7 @@ int readTopazUid(bool verbose) {
return PM3_ESOFT;
}
- if (status == PM3_EWRONGANSVER) {
+ if (status == PM3_EWRONGANSWER) {
if (verbose) PrintAndLogEx(ERR, "Error: tag didn't answer to RID");
topaz_switch_off_field();
return PM3_ESOFT;
diff --git a/client/src/cmdlft55xx.c b/client/src/cmdlft55xx.c
index 6d384c33d..5994e2232 100644
--- a/client/src/cmdlft55xx.c
+++ b/client/src/cmdlft55xx.c
@@ -611,7 +611,7 @@ bool t55xxVerifyWrite(uint8_t block, bool page1, bool usepwd, uint8_t override,
if (GetT55xxBlockData(&read_data) == false)
return false;
- } else if (res == PM3_EWRONGANSVER) {
+ } else if (res == PM3_EWRONGANSWER) {
// could't decode. Lets see if this was a block 0 write and try read/detect it auto.
// this messes up with ppls config..
@@ -852,7 +852,7 @@ int T55xxReadBlockEx(uint8_t block, bool page1, bool usepwd, uint8_t override, u
if (tryDetectModulation(downlink_mode, false) == false) {
PrintAndLogEx(WARNING, "Safety check: Could not detect if PWD bit is set in config block. Exits.");
- return PM3_EWRONGANSVER;
+ return PM3_EWRONGANSWER;
} else {
PrintAndLogEx(WARNING, "Safety check: PWD bit is NOT set in config block. Reading without password...");
usepwd = false;
@@ -867,7 +867,7 @@ int T55xxReadBlockEx(uint8_t block, bool page1, bool usepwd, uint8_t override, u
return PM3_ERFTRANS;
if (DecodeT55xxBlock() == false)
- return PM3_EWRONGANSVER;
+ return PM3_EWRONGANSWER;
if (verbose)
printT55xxBlock(block, page1);
diff --git a/include/pm3_cmd.h b/include/pm3_cmd.h
index 6ce271aab..c9125b1aa 100644
--- a/include/pm3_cmd.h
+++ b/include/pm3_cmd.h
@@ -613,7 +613,7 @@ typedef struct {
// Initialization error pm3: error related to trying to initalize the pm3 / fpga for different operations
#define PM3_EINIT -15
// Expected a different answer error client/pm3: error when expecting one answer and got another one
-#define PM3_EWRONGANSVER -16
+#define PM3_EWRONGANSWER -16
// Memory out-of-bounds error client/pm3: error when a read/write is outside the expected array
#define PM3_EOUTOFBOUND -17
// exchange with card error client/pm3: error when cant get answer from card or got an incorrect answer
From d2e85b00405b4b0adde6a2f36ff03ba0734d5794 Mon Sep 17 00:00:00 2001
From: iceman1001
Date: Tue, 28 Apr 2020 19:58:15 +0200
Subject: [PATCH 005/632] coverity fix: shawdowfunction (stdio)\n.
unsupported command shouldn't break execution (dfnames)
---
client/src/cmdhfmfdes.c | 107 ++++++++++++++++++++++------------------
1 file changed, 59 insertions(+), 48 deletions(-)
diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c
index 5ec08a1c3..eefa8b698 100644
--- a/client/src/cmdhfmfdes.c
+++ b/client/src/cmdhfmfdes.c
@@ -1272,15 +1272,21 @@ static int handler_desfire_dfnames(dfname_t *dest, uint8_t *dfname_count) {
if (dest == NULL) PrintAndLogEx(ERR, "DEST=NULL");
if (dfname_count == NULL) PrintAndLogEx(ERR, "DFNAME_COUNT=NULL");
}
+
if (dest == NULL || dfname_count == NULL) return PM3_EINVARG;
+
+ *dfname_count = 0;
+
sAPDU apdu = {0x90, MFDES_GET_DF_NAMES, 0x00, 0x00, 0x00, NULL}; //0x6d
int recv_len = 0;
uint16_t sw = 0;
int res = send_desfire_cmd(&apdu, true, (uint8_t *)dest, &recv_len, &sw, sizeof(dfname_t), true);
if (res != PM3_SUCCESS)
return res;
+
if (sw != status(MFDES_S_OPERATION_OK))
return PM3_ESOFT;
+
*dfname_count = recv_len;
return res;
}
@@ -1957,8 +1963,8 @@ static int CmdHF14ADesClearRecordFile(const char *Cmd) {
CLIGetHexWithReturn(1, aid, &aidlength);
int filenolen = 0;
- uint8_t fileno[1] = {0};
- CLIGetHexWithReturn(2, fileno, &filenolen);
+ uint8_t _fileno[1] = {0};
+ CLIGetHexWithReturn(2, _fileno, &filenolen);
int fidlength = 0;
uint8_t fid[2] = {0};
@@ -1970,7 +1976,7 @@ static int CmdHF14ADesClearRecordFile(const char *Cmd) {
return PM3_EINVARG;
}
- if (fileno[0] > 0x1F) {
+ if (_fileno[0] > 0x1F) {
PrintAndLogEx(ERR, "Fileno must be lower 0x1F.");
return PM3_EINVARG;
}
@@ -1988,7 +1994,7 @@ static int CmdHF14ADesClearRecordFile(const char *Cmd) {
return res;
}
- res = handler_desfire_clearrecordfile(fileno[0]);
+ res = handler_desfire_clearrecordfile(_fileno[0]);
if (res == PM3_SUCCESS) {
PrintAndLogEx(SUCCESS, "Successfully cleared record file.");
} else {
@@ -2017,8 +2023,8 @@ static int CmdHF14ADesDeleteFile(const char *Cmd) {
CLIGetHexWithReturn(1, aid, &aidlength);
int filenolen = 0;
- uint8_t fileno[1] = {0};
- CLIGetHexWithReturn(2, fileno, &filenolen);
+ uint8_t _fileno[1] = {0};
+ CLIGetHexWithReturn(2, _fileno, &filenolen);
int fidlength = 0;
uint8_t fid[2] = {0};
@@ -2030,7 +2036,7 @@ static int CmdHF14ADesDeleteFile(const char *Cmd) {
return PM3_EINVARG;
}
- if (fileno[0] > 0x1F) {
+ if (_fileno[0] > 0x1F) {
PrintAndLogEx(ERR, "Fileno must be lower 0x1F.");
return PM3_EINVARG;
}
@@ -2048,7 +2054,7 @@ static int CmdHF14ADesDeleteFile(const char *Cmd) {
return res;
}
- res = handler_desfire_deletefile(fileno[0]);
+ res = handler_desfire_deletefile(_fileno[0]);
if (res == PM3_SUCCESS) {
PrintAndLogEx(SUCCESS, "Successfully deleted file..");
} else {
@@ -2082,8 +2088,8 @@ static int CmdHF14ADesCreateFile(const char *Cmd) {
CLIGetHexWithReturn(1, aid, &aidlength);
int filenolen = 0;
- uint8_t fileno[1] = {0};
- CLIGetHexWithReturn(2, fileno, &filenolen);
+ uint8_t _fileno[1] = {0};
+ CLIGetHexWithReturn(2, _fileno, &filenolen);
int fidlength = 0;
uint8_t fid[2] = {0};
@@ -2110,7 +2116,7 @@ static int CmdHF14ADesCreateFile(const char *Cmd) {
return PM3_EINVARG;
}
- if (fileno[0] > 0x1F) {
+ if (_fileno[0] > 0x1F) {
PrintAndLogEx(ERR, "File number range is invalid (0x00-0x1F).");
return PM3_EINVARG;
}
@@ -2150,18 +2156,20 @@ static int CmdHF14ADesCreateFile(const char *Cmd) {
mfdes_file_t ft;
memcpy(ft.fid, fid, 2);
memcpy(ft.filesize, filesize, 3);
- ft.fileno = fileno[0];
+ ft.fileno = _fileno[0];
ft.comset = comset;
memcpy(ft.access_rights, ar, 2);
- if (isbackup) res = handler_desfire_create_backup_file(&ft);
- else res = handler_desfire_create_std_file(&ft);
+ if (isbackup)
+ res = handler_desfire_create_backup_file(&ft);
+ else
+ res = handler_desfire_create_std_file(&ft);
- if (res == PM3_SUCCESS) {
+ if (res == PM3_SUCCESS)
PrintAndLogEx(SUCCESS, "Successfully created standard/backup file.");
- } else {
+ else
PrintAndLogEx(ERR, "Couldn't create standard/backup file. Error %d", res);
- }
+
DropField();
return res;
}
@@ -2186,8 +2194,8 @@ static int CmdHF14ADesGetValueData(const char *Cmd) {
CLIGetHexWithReturn(1, aid, &aidlength);
int filenolen = 0;
- uint8_t fileno[1] = {0};
- CLIGetHexWithReturn(2, fileno, &filenolen);
+ uint8_t _fileno[1] = {0};
+ CLIGetHexWithReturn(2, _fileno, &filenolen);
CLIParserFree();
if (filenolen != 1) {
@@ -2195,7 +2203,7 @@ static int CmdHF14ADesGetValueData(const char *Cmd) {
return PM3_EINVARG;
}
- if (fileno[0] > 0x1F) {
+ if (_fileno[0] > 0x1F) {
PrintAndLogEx(ERR, "File number range is invalid (0x00-0x1F)");
return PM3_EINVARG;
}
@@ -2215,12 +2223,12 @@ static int CmdHF14ADesGetValueData(const char *Cmd) {
return res;
}
mfdes_value_t value;
- value.fileno = fileno[0];
+ value.fileno = _fileno[0];
int len = 0;
res = handler_desfire_getvalue(&value, &len);
if (res == PM3_SUCCESS) {
- PrintAndLogEx(SUCCESS, "Successfully read value from File %u:", fileno[0]);
+ PrintAndLogEx(SUCCESS, "Successfully read value from File %u:", _fileno[0]);
PrintAndLogEx(NORMAL, "\nOffset | Data | Ascii");
PrintAndLogEx(NORMAL, "----------------------------------------------------------------------------");
for (int i = 0; i < len; i += 16) {
@@ -2256,8 +2264,8 @@ static int CmdHF14ADesReadData(const char *Cmd) {
CLIGetHexWithReturn(1, aid, &aidlength);
int filenolen = 0;
- uint8_t fileno[1] = {0};
- CLIGetHexWithReturn(2, fileno, &filenolen);
+ uint8_t _fileno[1] = {0};
+ CLIGetHexWithReturn(2, _fileno, &filenolen);
int offsetlength = 0;
uint8_t offset[3] = {0};
@@ -2285,7 +2293,7 @@ static int CmdHF14ADesReadData(const char *Cmd) {
return PM3_EINVARG;
}
- if (fileno[0] > 0x1F) {
+ if (_fileno[0] > 0x1F) {
PrintAndLogEx(ERR, "File number range is invalid (0x00-0x1F)");
return PM3_EINVARG;
}
@@ -2310,11 +2318,12 @@ static int CmdHF14ADesReadData(const char *Cmd) {
mfdes_data_t ft;
memcpy(ft.offset, offset, 3);
memcpy(ft.length, filesize, 3);
- ft.fileno = fileno[0];
+ ft.fileno = _fileno[0];
int bytestoread = le24toh(filesize);
- if (bytestoread == 0) bytestoread = 0xFFFFFF;
+ if (bytestoread == 0)
+ bytestoread = 0xFFFFFF;
uint8_t *data = (uint8_t *)calloc(bytestoread, sizeof(uint8_t));
if (data != NULL) {
@@ -2361,9 +2370,9 @@ static int CmdHF14ADesChangeValue(const char *Cmd) {
CLIGetHexWithReturn(1, aid, &aidlength);
int filenolen = 0;
- uint8_t fileno[1] = {0};
- CLIGetHexWithReturn(2, fileno, &filenolen);
- value.fileno = fileno[0];
+ uint8_t _fileno[1] = {0};
+ CLIGetHexWithReturn(2, _fileno, &filenolen);
+ value.fileno = _fileno[0];
int vlength = 0x0;
CLIParamHexToBuf(arg_get_str(3), value.value, 4, &vlength);
@@ -2453,8 +2462,8 @@ static int CmdHF14ADesWriteData(const char *Cmd) {
CLIGetHexWithReturn(1, aid, &aidlength);
int filenolen = 0;
- uint8_t fileno[1] = {0};
- CLIGetHexWithReturn(2, fileno, &filenolen);
+ uint8_t _fileno[1] = {0};
+ CLIGetHexWithReturn(2, _fileno, &filenolen);
int offsetlength = 0;
uint8_t offset[3] = {0};
@@ -2499,7 +2508,7 @@ static int CmdHF14ADesWriteData(const char *Cmd) {
return PM3_EINVARG;
}
- if (fileno[0] > 0x1F) {
+ if (_fileno[0] > 0x1F) {
PrintAndLogEx(ERR, "File number range is invalid (0x00-0x1F)");
if (data) free(data);
return PM3_EINVARG;
@@ -2524,7 +2533,7 @@ static int CmdHF14ADesWriteData(const char *Cmd) {
memcpy(ft.offset, offset, 3);
htole24(dlength, ft.length);
- ft.fileno = fileno[0];
+ ft.fileno = _fileno[0];
if (data != NULL) {
ft.data = data;
@@ -2566,8 +2575,8 @@ static int CmdHF14ADesCreateRecordFile(const char *Cmd) {
CLIGetHexWithReturn(1, aid, &aidlength);
int filenolen = 0;
- uint8_t fileno[1] = {0};
- CLIGetHexWithReturn(2, fileno, &filenolen);
+ uint8_t _fileno[1] = {0};
+ CLIGetHexWithReturn(2, _fileno, &filenolen);
int fidlength = 0;
uint8_t fid[2] = {0};
@@ -2609,7 +2618,7 @@ static int CmdHF14ADesCreateRecordFile(const char *Cmd) {
return PM3_EINVARG;
}
- if (fileno[0] > 0x1F) {
+ if (_fileno[0] > 0x1F) {
PrintAndLogEx(ERR, "File number range is invalid (0x00-0x1F).");
return PM3_EINVARG;
}
@@ -2648,15 +2657,20 @@ static int CmdHF14ADesCreateRecordFile(const char *Cmd) {
}
mfdes_linear_t ft;
- ft.fileno = fileno[0];
+
+ ft.fileno = _fileno[0];
memcpy(ft.fid, fid, 2);
ft.comset = comset;
memcpy(ft.access_rights, ar, 2);
memcpy(ft.recordsize, recordsize, 3);
memcpy(ft.maxnumrecords, maxnumrecords, 3);
- if (cyclic) res = handler_desfire_create_cyclicrecordfile(&ft);
- else res = handler_desfire_create_linearrecordfile(&ft);
+ if (cyclic) {
+ res = handler_desfire_create_cyclicrecordfile(&ft);
+ } else {
+ res = handler_desfire_create_linearrecordfile(&ft);
+ }
+
if (res == PM3_SUCCESS) {
PrintAndLogEx(SUCCESS, "Successfully created linear/cyclic record file.");
} else {
@@ -2691,8 +2705,8 @@ static int CmdHF14ADesCreateValueFile(const char *Cmd) {
CLIGetHexWithReturn(1, aid, &aidlength);
int filenolen = 0;
- uint8_t fileno[1] = {0};
- CLIGetHexWithReturn(2, fileno, &filenolen);
+ uint8_t _fileno[1] = {0};
+ CLIGetHexWithReturn(2, _fileno, &filenolen);
uint8_t comset = arg_get_int(3);
int arlength = 0;
@@ -2727,7 +2741,7 @@ static int CmdHF14ADesCreateValueFile(const char *Cmd) {
return PM3_EINVARG;
}
- if (fileno[0] > 0x1F) {
+ if (_fileno[0] > 0x1F) {
PrintAndLogEx(ERR, "File number range is invalid (0x00-0x1F)");
return PM3_EINVARG;
}
@@ -2775,7 +2789,8 @@ static int CmdHF14ADesCreateValueFile(const char *Cmd) {
}
mfdes_value_file_t ft;
- ft.fileno = fileno[0];
+
+ ft.fileno = _fileno[0];
ft.comset = comset;
memcpy(ft.access_rights, ar, 2);
memcpy(ft.lowerlimit, lowerlimit, 4);
@@ -3166,8 +3181,6 @@ static int CmdHF14ADesDump(const char *Cmd) {
if (handler_desfire_dfnames(dfnames, &dfname_count) != PM3_SUCCESS) {
PrintAndLogEx(WARNING, _RED_("Can't get DF Names"));
- DropField();
- return PM3_ESOFT;
}
PrintAndLogEx(NORMAL, "");
@@ -3312,8 +3325,6 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) {
if (handler_desfire_dfnames(dfnames, &dfname_count) != PM3_SUCCESS) {
PrintAndLogEx(WARNING, _RED_("Can't get DF Names"));
- DropField();
- return PM3_ESOFT;
}
PrintAndLogEx(NORMAL, "");
From cd19bf81a8fc1d8d88e938f87f799cbb0a0d829e Mon Sep 17 00:00:00 2001
From: iceman1001
Date: Tue, 28 Apr 2020 21:51:13 +0200
Subject: [PATCH 006/632] cppcheck fix
---
client/src/cmdhfmfu.c | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)
diff --git a/client/src/cmdhfmfu.c b/client/src/cmdhfmfu.c
index f70c3887e..3d90a36de 100644
--- a/client/src/cmdhfmfu.c
+++ b/client/src/cmdhfmfu.c
@@ -934,7 +934,6 @@ static int ulev1_print_signature(TagTypeUL_t tagtype, uint8_t *uid, uint8_t *sig
};
*/
uint8_t i;
- int res;
bool is_valid = false;
for (i = 0; i < ARRAYLEN(nxp_mfu_public_keys); i++) {
@@ -942,7 +941,7 @@ static int ulev1_print_signature(TagTypeUL_t tagtype, uint8_t *uid, uint8_t *sig
uint8_t key[PUBLIC_ECDA_KEYLEN];
param_gethex_to_eol(nxp_mfu_public_keys[i].value, 0, key, PUBLIC_ECDA_KEYLEN, &dl);
- res = ecdsa_signature_r_s_verify(MBEDTLS_ECP_DP_SECP128R1, key, uid, 7, signature, signature_len, false);
+ int res = ecdsa_signature_r_s_verify(MBEDTLS_ECP_DP_SECP128R1, key, uid, 7, signature, signature_len, false);
is_valid = (res == 0);
if (is_valid)
From 78cc7e10a586d38bce09c0ac01d434381582c03f Mon Sep 17 00:00:00 2001
From: iceman1001
Date: Tue, 28 Apr 2020 21:53:01 +0200
Subject: [PATCH 007/632] cppcheck fix - duplicate condition
---
client/src/cmdhfmfu.c | 4 +---
1 file changed, 1 insertion(+), 3 deletions(-)
diff --git a/client/src/cmdhfmfu.c b/client/src/cmdhfmfu.c
index 3d90a36de..88e44285e 100644
--- a/client/src/cmdhfmfu.c
+++ b/client/src/cmdhfmfu.c
@@ -1293,10 +1293,8 @@ static int CmdHF14AMfUInfo(const char *Cmd) {
// re-select
if (ul_auth_select(&card, tagtype, hasAuthKey, authkeyptr, pack, sizeof(pack)) == PM3_ESOFT) return PM3_ESOFT;
}
- }
- // Get Version
- if ((tagtype & (UL_EV1_48 | UL_EV1_128 | UL_EV1 | UL_NANO_40 | NTAG_213 | NTAG_213_F | NTAG_215 | NTAG_216 | NTAG_216_F | NTAG_I2C_1K | NTAG_I2C_2K | NTAG_I2C_1K_PLUS | NTAG_I2C_2K_PLUS))) {
+ // Get Version
uint8_t version[10] = {0x00};
status = ulev1_getVersion(version, sizeof(version));
if (status == -1) {
From a7ececcb5dfe631fb159c17bcddf574aeb4123ca Mon Sep 17 00:00:00 2001
From: iceman1001
Date: Tue, 28 Apr 2020 22:26:16 +0200
Subject: [PATCH 008/632] cppcheck fix - duplicate condition
---
client/src/loclass/ikeys.c | 6 ++++--
1 file changed, 4 insertions(+), 2 deletions(-)
diff --git a/client/src/loclass/ikeys.c b/client/src/loclass/ikeys.c
index 9d9926547..11a082867 100644
--- a/client/src/loclass/ikeys.c
+++ b/client/src/loclass/ikeys.c
@@ -578,8 +578,10 @@ static void print64bits(const char *name, uint64_t val) {
static uint64_t testCryptedCSN(uint64_t crypted_csn, uint64_t expected) {
int retval = 0;
uint8_t result[8] = {0};
- if (debug_print) PrintAndLogEx(DEBUG, "debug_print %d", debug_print);
- if (debug_print) print64bits(" {csn} ", crypted_csn);
+ if (debug_print) {
+ PrintAndLogEx(DEBUG, "debug_print %d", debug_print);
+ print64bits(" {csn} ", crypted_csn);
+ }
uint64_t crypted_csn_swapped = swapZvalues(crypted_csn);
From 31125b9d342f0143ada6428e011334ef2da64728 Mon Sep 17 00:00:00 2001
From: iceman1001
Date: Tue, 28 Apr 2020 22:27:50 +0200
Subject: [PATCH 009/632] cppchecker fix - conditionknown
---
common/lfdemod.c | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/common/lfdemod.c b/common/lfdemod.c
index bc753f45d..c73734a75 100644
--- a/common/lfdemod.c
+++ b/common/lfdemod.c
@@ -1582,9 +1582,10 @@ static uint16_t cleanAskRawDemod(uint8_t *bits, size_t *size, int clk, int inver
if (waveHigh) {
bits[bitCnt++] = invert;
- } else if (!waveHigh) {
+ } else {
bits[bitCnt++] = invert ^ 1;
}
+
if (*startIdx == 0) {
*startIdx = i - cl_2;
if (g_debugMode == 2) prnt("DEBUG ASK: cleanAskRawDemod minus half clock [%d]", *startIdx);
From 39fd06f947a5b949f8e8f1d151965e2e0714d298 Mon Sep 17 00:00:00 2001
From: iceman1001
Date: Tue, 28 Apr 2020 22:29:22 +0200
Subject: [PATCH 010/632] cppchecker fix - conditionknown
---
common/lfdemod.c | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/common/lfdemod.c b/common/lfdemod.c
index c73734a75..8b10b2fb3 100644
--- a/common/lfdemod.c
+++ b/common/lfdemod.c
@@ -1560,7 +1560,7 @@ static uint16_t cleanAskRawDemod(uint8_t *bits, size_t *size, int clk, int inver
} else if (waveHigh) {
bits[bitCnt++] = invert;
bits[bitCnt++] = invert;
- } else if (!waveHigh) {
+ } else {
bits[bitCnt++] = invert ^ 1;
bits[bitCnt++] = invert ^ 1;
}
From 4896390dde5b194cfe4a343ca144493c6dd006bd Mon Sep 17 00:00:00 2001
From: iceman1001
Date: Tue, 28 Apr 2020 22:31:45 +0200
Subject: [PATCH 011/632] cppchecker fix
---
client/src/cmdlfindala.c | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/client/src/cmdlfindala.c b/client/src/cmdlfindala.c
index 69c1e5a55..6cf5ed28f 100644
--- a/client/src/cmdlfindala.c
+++ b/client/src/cmdlfindala.c
@@ -838,11 +838,12 @@ int detectIndala(uint8_t *dest, size_t *size, uint8_t *invert) {
goto inv;
}
-inv:
if (res == 0) {
return -4;
}
+inv:
+
*invert ^= 1;
if (*invert && idx > 0) {
From b86d9f2b969fe44121f7f58929120b1dfa2a84b2 Mon Sep 17 00:00:00 2001
From: iceman1001
Date: Tue, 28 Apr 2020 22:36:57 +0200
Subject: [PATCH 012/632] cppcheck fix
---
common/crapto1/crypto1.c | 6 ++----
1 file changed, 2 insertions(+), 4 deletions(-)
diff --git a/common/crapto1/crypto1.c b/common/crapto1/crypto1.c
index dd5541b29..82203ef5e 100644
--- a/common/crapto1/crypto1.c
+++ b/common/crapto1/crypto1.c
@@ -18,7 +18,6 @@
Copyright (C) 2008-2008 bla
*/
#include
-
#include "crapto1.h"
#include "parity.h"
@@ -34,7 +33,6 @@ void crypto1_init(struct Crypto1State *state, uint64_t key) {
state->odd = state->odd << 1 | BIT(key, (i - 1) ^ 7);
state->even = state->even << 1 | BIT(key, i ^ 7);
}
- return;
}
void crypto1_deinit(struct Crypto1State *state) {
@@ -42,9 +40,9 @@ void crypto1_deinit(struct Crypto1State *state) {
state->even = 0;
}
-#if !defined(__arm__) || defined(__linux__) || defined(_WIN32) || defined(__APPLE__) // bare metal ARM Proxmark lacks malloc()/free()
+#if !defined(__arm__) || defined(__linux__) || defined(_WIN32) || defined(__APPLE__) // bare metal ARM Proxmark lacks calloc()/free()
struct Crypto1State *crypto1_create(uint64_t key) {
- struct Crypto1State *state = malloc(sizeof(*state));
+ struct Crypto1State *state = calloc(sizeof(*state), sizeof(uint8_t));
if (!state) return NULL;
crypto1_init(state, key);
return state;
From 1b16b955653139cfad1e5a97e32d5d2af68da78c Mon Sep 17 00:00:00 2001
From: iceman1001
Date: Tue, 28 Apr 2020 22:39:04 +0200
Subject: [PATCH 013/632] cppchecker fix
---
tools/hitag2crack/crack2/ht2crack2gentest.c | 5 +----
1 file changed, 1 insertion(+), 4 deletions(-)
diff --git a/tools/hitag2crack/crack2/ht2crack2gentest.c b/tools/hitag2crack/crack2/ht2crack2gentest.c
index fb9ff484b..0f255a5b6 100644
--- a/tools/hitag2crack/crack2/ht2crack2gentest.c
+++ b/tools/hitag2crack/crack2/ht2crack2gentest.c
@@ -41,7 +41,6 @@ int main(int argc, char *argv[]) {
int i, j;
int numtests;
int urandomfd;
- FILE *fp;
if (argc < 2) {
printf("ht2crack2gentest number\n");
@@ -68,7 +67,7 @@ int main(int argc, char *argv[]) {
makerandom(nR, 4, urandomfd);
sprintf(filename, "keystream.key-%s.uid-%s.nR-%s", key, uid, nR);
- fp = fopen(filename, "w");
+ FILE *fp = fopen(filename, "w");
if (!fp) {
printf("cannot open file '%s' for writing\n", filename);
exit(1);
@@ -87,9 +86,7 @@ int main(int argc, char *argv[]) {
fclose(fp);
}
-
return 0;
-
}
From cdb99fe65096ef874da44c00c8f9112148ab9168 Mon Sep 17 00:00:00 2001
From: iceman1001
Date: Tue, 28 Apr 2020 22:58:05 +0200
Subject: [PATCH 014/632] cppchecker fix - duplicate
---
client/src/cmdhficlass.c | 6 ++----
1 file changed, 2 insertions(+), 4 deletions(-)
diff --git a/client/src/cmdhficlass.c b/client/src/cmdhficlass.c
index 321b02133..d05afdae2 100644
--- a/client/src/cmdhficlass.c
+++ b/client/src/cmdhficlass.c
@@ -2983,13 +2983,11 @@ int readIclass(bool loop, bool verbose) {
if (isHidRange) {
if (legacy)
- PrintAndLogEx(SUCCESS, " : Possible iClass - legacy credential tag");
+ PrintAndLogEx(SUCCESS, " : Possible iClass - "_YELLOW_("legacy")" credential tag");
if (se_enabled)
- PrintAndLogEx(SUCCESS, " : Possible iClass - SE credential tag");
- }
+ PrintAndLogEx(SUCCESS, " : Possible iClass - "_YELLOW_("SE")" credential tag");
- if (isHidRange) {
PrintAndLogEx(SUCCESS, " : Tag is "_YELLOW_("iClass")", CSN is in HID range");
} else {
PrintAndLogEx(SUCCESS, " : Tag is "_YELLOW_("PicoPass")", CSN is not in HID range");
From 305736b16a8f83c717610e9f16ac76b88425de78 Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Wed, 29 Apr 2020 09:38:32 +0200
Subject: [PATCH 015/632] travis: remove libsndfile
---
.travis.yml | 2 --
1 file changed, 2 deletions(-)
diff --git a/.travis.yml b/.travis.yml
index d136892a4..0b052044a 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -27,11 +27,9 @@ addons:
packages:
- gcc-arm-none-eabi
- libnewlib-dev
- - libsndfile1-dev
homebrew:
packages:
- readline
- - libsndfile
- qt5
- RfidResearchGroup/proxmark3/arm-none-eabi-gcc
taps: RfidResearchGroup/proxmark3
From f80f123061eb8d36f3eaf3ed93e32f1f53495889 Mon Sep 17 00:00:00 2001
From: iceman1001
Date: Wed, 29 Apr 2020 12:00:49 +0200
Subject: [PATCH 016/632] Chg: Bt dongle, bt direct listing of serial ports on
WSL and PS3.x, now using powershell.exe since wmic is deprecated
---
pm3 | 70 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
1 file changed, 68 insertions(+), 2 deletions(-)
diff --git a/pm3 b/pm3
index 52b434e13..b3bee7ea5 100755
--- a/pm3
+++ b/pm3
@@ -79,18 +79,43 @@ function get_pm3_list_macOS {
function get_pm3_list_Windows {
N=$1
PM3LIST=()
- for DEV in $(wmic path Win32_SerialPort where "PNPDeviceID like '%VID_9AC4&PID_4B8F%'" get DeviceID,PNPDeviceID 2>/dev/null|awk '/^COM/{print $1}'); do
+ # Normal SERIAL PORTS (COM)
+ for DEV in $(powershell.exe -command "Get-CimInstance -ClassName Win32_serialport | Where-Object PNPDeviceID -like '*VID_9AC4&PID_4B8F*' | Select DeviceID" 2>/dev/null|awk '/^COM/{print $1}'); do
DEV=${DEV/ */}
PM3LIST+=("$DEV")
if [ ${#PM3LIST[*]} -ge $N ]; then
return
fi
done
+
+ #white BT dongle SERIAL PORTS (COM)
+ if $FINDBTDONGLE; then
+ for DEV in $(powershell.exe -command "Get-CimInstance -ClassName Win32_serialport | Where-Object PNPDeviceID -like '*VID_10C4&PID_EA60*' | Select DeviceID" 2>/dev/null|awk '/^COM/{print $1}'); do
+ DEV=${DEV/ */}
+ PM3LIST+=("$DEV")
+ if [ ${#PM3LIST[*]} -ge $N ]; then
+ return
+ fi
+ done
+ fi
+
+ #BT direct SERIAL PORTS (COM)
+ if $FINDBTDIRECT; then
+ for DEV in $(powershell.exe -command "Get-CimInstance -ClassName Win32_PnPEntity | Where-Object Caption -like 'Standard Serial over Bluetooth link (COM*' | Select Name" 2> /dev/null | awk '$0 ~ /COM/{print substr($6,2,4)}'); do
+ DEV=${DEV/ */}
+ PM3LIST+=("$DEV")
+ if [ ${#PM3LIST[*]} -ge $N ]; then
+ return
+ fi
+ done
+ fi
}
function get_pm3_list_WSL {
+ N=$1
PM3LIST=()
- for DEV in $(wmic.exe path Win32_SerialPort where "PNPDeviceID like '%VID_9AC4&PID_4B8F%'" get DeviceID,PNPDeviceID 2>/dev/null|awk '/^COM/{print $1}'); do
+ # Normal SERIAL PORTS (COM)
+ for DEV in $(powershell.exe -command "Get-CimInstance -ClassName Win32_serialport | Where-Object PNPDeviceID -like '*VID_9AC4&PID_4B8F*' | Select DeviceID" 2>/dev/null|awk '/^COM/{print $1}'); do
DEV=${DEV/ */}
DEV="/dev/ttyS${DEV#COM}"
# ttyS counterpart takes some more time to appear
@@ -105,6 +130,47 @@ function get_pm3_list_WSL {
fi
fi
done
+
+ #white BT dongle SERIAL PORTS (COM)
+ if $FINDBTDONGLE; then
+ for DEV in $(powershell.exe -command "Get-CimInstance -ClassName Win32_serialport | Where-Object PNPDeviceID -like '*VID_10C4&PID_EA60*' | Select DeviceID" 2>/dev/null|awk '/^COM/{print $1}'); do
+ DEV=${DEV/ */}
+ DEV="/dev/ttyS${DEV#COM}"
+ # ttyS counterpart takes some more time to appear
+ if [ -e "$DEV" ]; then
+ PM3LIST+=("$DEV")
+ if [ ! -w "$DEV" ]; then
+ echo "[!!] Let's give users read/write access to $DEV"
+ sudo chmod 666 "$DEV"
+ fi
+ if [ ${#PM3LIST[*]} -ge $N ]; then
+ return
+ fi
+ fi
+
+ done
+ fi
+
+ #BT direct SERIAL PORTS (COM)
+ if $FINDBTDIRECT; then
+ for DEV in $(powershell.exe -command "Get-CimInstance -ClassName Win32_PnPEntity | Where-Object Caption -like 'Standard Serial over Bluetooth link (COM*' | Select Name" 2> /dev/null | awk '$0 ~ /COM/{print substr($6,2,4)}'); do
+
+ DEV=${DEV/ */}
+ DEV="/dev/ttyS${DEV#COM}"
+ # ttyS counterpart takes some more time to appear
+ if [ -e "$DEV" ]; then
+ PM3LIST+=("$DEV")
+ if [ ! -w "$DEV" ]; then
+ echo "[!!] Let's give users read/write access to $DEV"
+ sudo chmod 666 "$DEV"
+ fi
+ if [ ${#PM3LIST[*]} -ge $N ]; then
+ return
+ fi
+ fi
+
+ done
+ fi
}
SCRIPT=$(basename -- "$0")
From 73e6f0d07ea52f202da486bb4bd52af048d47e7e Mon Sep 17 00:00:00 2001
From: iceman1001
Date: Wed, 29 Apr 2020 14:07:26 +0200
Subject: [PATCH 017/632] chg: moved WSL/PS3.x bt native to be tested first.
Since call to Win32_serialport crashes it.
---
pm3 | 91 +++++++++++++++++++++++++++++++------------------------------
1 file changed, 47 insertions(+), 44 deletions(-)
diff --git a/pm3 b/pm3
index b3bee7ea5..2b2258b50 100755
--- a/pm3
+++ b/pm3
@@ -29,7 +29,7 @@ function get_pm3_list_Linux {
N=$1
PM3LIST=()
for DEV in $(find /dev/ttyACM* 2>/dev/null); do
- if udevadm info -q property -n "$DEV" |grep -q "ID_VENDOR=proxmark.org"; then
+ if udevadm info -q property -n "$DEV" | grep -q "ID_VENDOR=proxmark.org"; then
PM3LIST+=("$DEV")
if [ ${#PM3LIST[*]} -ge $N ]; then
return
@@ -39,7 +39,7 @@ function get_pm3_list_Linux {
if $FINDBTDONGLE; then
# check if the HC-06-USB white dongle is present (still, that doesn't tell us if it's paired with a Proxmark3...)
for DEV in $(find /dev/ttyUSB* 2>/dev/null); do
- if udevadm info -q property -n "$DEV" |grep -q "ID_MODEL=CP2104_USB_to_UART_Bridge_Controller"; then
+ if udevadm info -q property -n "$DEV" | grep -q "ID_MODEL=CP2104_USB_to_UART_Bridge_Controller"; then
PM3LIST+=("$DEV")
if [ ${#PM3LIST[*]} -ge $N ]; then
return
@@ -49,7 +49,7 @@ function get_pm3_list_Linux {
fi
if $FINDBTDIRECT; then
# check if the MAC of a Proxmark3 was bound to a local rfcomm interface
- for DEVMAC in $(rfcomm -a|grep " 20:19:0[45]"|sed 's/^\(.*\): \([0-9:]*\) .*/\1@\2/'); do
+ for DEVMAC in $(rfcomm -a 2>/dev/null | grep " 20:19:0[45]" | sed 's/^\(.*\): \([0-9:]*\) .*/\1@\2/'); do
DEV=${DEVMAC/@*/}
MAC=${DEVMAC/*@/}
# check if Proxmark3 is actually present
@@ -66,7 +66,7 @@ function get_pm3_list_Linux {
function get_pm3_list_macOS {
N=$1
PM3LIST=()
- for DEV in $(ioreg -r -c "IOUSBHostDevice" -l|awk -F '"' '
+ for DEV in $(ioreg -r -c "IOUSBHostDevice" -l | awk -F '"' '
$2=="USB Vendor Name"{b=($4=="proxmark.org")}
b==1 && $2=="IODialinDevice"{print $4}'); do
PM3LIST+=("$DEV")
@@ -79,18 +79,10 @@ function get_pm3_list_macOS {
function get_pm3_list_Windows {
N=$1
PM3LIST=()
- # Normal SERIAL PORTS (COM)
- for DEV in $(powershell.exe -command "Get-CimInstance -ClassName Win32_serialport | Where-Object PNPDeviceID -like '*VID_9AC4&PID_4B8F*' | Select DeviceID" 2>/dev/null|awk '/^COM/{print $1}'); do
- DEV=${DEV/ */}
- PM3LIST+=("$DEV")
- if [ ${#PM3LIST[*]} -ge $N ]; then
- return
- fi
- done
-
- #white BT dongle SERIAL PORTS (COM)
- if $FINDBTDONGLE; then
- for DEV in $(powershell.exe -command "Get-CimInstance -ClassName Win32_serialport | Where-Object PNPDeviceID -like '*VID_10C4&PID_EA60*' | Select DeviceID" 2>/dev/null|awk '/^COM/{print $1}'); do
+ # Need to look for this first, the call to Win32_serialport "crashes" then native bt serial port. Don't ask why.
+ #BT direct SERIAL PORTS (COM)
+ if $FINDBTDIRECT; then
+ for DEV in $(powershell.exe -command "Get-CimInstance -ClassName Win32_PnPEntity | Where-Object Caption -like 'Standard Serial over Bluetooth link (COM*' | Select Name" 2> /dev/null | awk '$0 ~ /COM/{print substr($6,2,4)}'); do
DEV=${DEV/ */}
PM3LIST+=("$DEV")
if [ ${#PM3LIST[*]} -ge $N ]; then
@@ -99,43 +91,38 @@ function get_pm3_list_Windows {
done
fi
- #BT direct SERIAL PORTS (COM)
- if $FINDBTDIRECT; then
- for DEV in $(powershell.exe -command "Get-CimInstance -ClassName Win32_PnPEntity | Where-Object Caption -like 'Standard Serial over Bluetooth link (COM*' | Select Name" 2> /dev/null | awk '$0 ~ /COM/{print substr($6,2,4)}'); do
+ # Normal SERIAL PORTS (COM)
+ for DEV in $(powershell.exe -command "Get-CimInstance -ClassName Win32_serialport | Where-Object PNPDeviceID -like '*VID_9AC4&PID_4B8F*' | Select DeviceID" 2>/dev/null | awk '/^COM/{print $1}'); do
+ DEV=${DEV/ */}
+ PM3LIST+=("$DEV")
+ if [ ${#PM3LIST[*]} -ge $N ]; then
+ return
+ fi
+ done
+
+ #white BT dongle SERIAL PORTS (COM)
+ if $FINDBTDONGLE; then
+ for DEV in $(powershell.exe -command "Get-CimInstance -ClassName Win32_serialport | Where-Object PNPDeviceID -like '*VID_10C4&PID_EA60*' | Select DeviceID" 2>/dev/null | awk '/^COM/{print $1}'); do
DEV=${DEV/ */}
PM3LIST+=("$DEV")
if [ ${#PM3LIST[*]} -ge $N ]; then
return
fi
- done
+ done
fi
}
function get_pm3_list_WSL {
N=$1
PM3LIST=()
- # Normal SERIAL PORTS (COM)
- for DEV in $(powershell.exe -command "Get-CimInstance -ClassName Win32_serialport | Where-Object PNPDeviceID -like '*VID_9AC4&PID_4B8F*' | Select DeviceID" 2>/dev/null|awk '/^COM/{print $1}'); do
- DEV=${DEV/ */}
- DEV="/dev/ttyS${DEV#COM}"
- # ttyS counterpart takes some more time to appear
- if [ -e "$DEV" ]; then
- PM3LIST+=("$DEV")
- if [ ! -w "$DEV" ]; then
- echo "[!!] Let's give users read/write access to $DEV"
- sudo chmod 666 "$DEV"
- fi
- if [ ${#PM3LIST[*]} -ge $N ]; then
- return
- fi
- fi
- done
- #white BT dongle SERIAL PORTS (COM)
- if $FINDBTDONGLE; then
- for DEV in $(powershell.exe -command "Get-CimInstance -ClassName Win32_serialport | Where-Object PNPDeviceID -like '*VID_10C4&PID_EA60*' | Select DeviceID" 2>/dev/null|awk '/^COM/{print $1}'); do
+ # Need to look for this first, the call to Win32_serialport "crashes" then native bt serial port. Don't ask why.
+ #BT direct SERIAL PORTS (COM)
+ if $FINDBTDIRECT; then
+ for DEV in $(powershell.exe -command "Get-CimInstance -ClassName Win32_PnPEntity | Where-Object Caption -like 'Standard Serial over Bluetooth link (COM*' | Select Name" 2> /dev/null | awk '$0 ~ /COM/{print substr($6,2,4)}'); do
+
DEV=${DEV/ */}
- DEV="/dev/ttyS${DEV#COM}"
+ DEV="/dev/ttyS${DEV#COM}"
# ttyS counterpart takes some more time to appear
if [ -e "$DEV" ]; then
PM3LIST+=("$DEV")
@@ -151,12 +138,28 @@ function get_pm3_list_WSL {
done
fi
- #BT direct SERIAL PORTS (COM)
- if $FINDBTDIRECT; then
- for DEV in $(powershell.exe -command "Get-CimInstance -ClassName Win32_PnPEntity | Where-Object Caption -like 'Standard Serial over Bluetooth link (COM*' | Select Name" 2> /dev/null | awk '$0 ~ /COM/{print substr($6,2,4)}'); do
+ # Normal SERIAL PORTS (COM)
+ for DEV in $(powershell.exe -command "Get-CimInstance -ClassName Win32_serialport | Where-Object PNPDeviceID -like '*VID_9AC4&PID_4B8F*' | Select DeviceID" 2>/dev/null | awk '/^COM/{print $1}'); do
+ DEV=${DEV/ */}
+ DEV="/dev/ttyS${DEV#COM}"
+ # ttyS counterpart takes some more time to appear
+ if [ -e "$DEV" ]; then
+ PM3LIST+=("$DEV")
+ if [ ! -w "$DEV" ]; then
+ echo "[!!] Let's give users read/write access to $DEV"
+ sudo chmod 666 "$DEV"
+ fi
+ if [ ${#PM3LIST[*]} -ge $N ]; then
+ return
+ fi
+ fi
+ done
+ #white BT dongle SERIAL PORTS (COM)
+ if $FINDBTDONGLE; then
+ for DEV in $(powershell.exe -command "Get-CimInstance -ClassName Win32_serialport | Where-Object PNPDeviceID -like '*VID_10C4&PID_EA60*' | Select DeviceID" 2>/dev/null | awk '/^COM/{print $1}'); do
DEV=${DEV/ */}
- DEV="/dev/ttyS${DEV#COM}"
+ DEV="/dev/ttyS${DEV#COM}"
# ttyS counterpart takes some more time to appear
if [ -e "$DEV" ]; then
PM3LIST+=("$DEV")
From 7ca7677568e209d5462bd441c8e4869dd2f0b3ad Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Wed, 29 Apr 2020 01:41:22 +0200
Subject: [PATCH 018/632] Linux: add native support for Bluetooth in client
---
.travis.yml | 1 +
client/CMakeLists.txt | 9 +++
client/Makefile | 28 +++++++++-
client/src/comms.c | 5 +-
client/src/uart/uart_posix.c | 56 ++++++++++++++++++-
doc/bt_manual_v10.md | 53 +++++++++++++-----
.../Linux-Installation-Instructions.md | 14 ++++-
.../4_Advanced-compilation-parameters.md | 8 +++
8 files changed, 151 insertions(+), 23 deletions(-)
diff --git a/.travis.yml b/.travis.yml
index 0b052044a..f8cf8228f 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -27,6 +27,7 @@ addons:
packages:
- gcc-arm-none-eabi
- libnewlib-dev
+ - libbluetooth-dev
homebrew:
packages:
- readline
diff --git a/client/CMakeLists.txt b/client/CMakeLists.txt
index 0bbf1067c..921e0d04b 100644
--- a/client/CMakeLists.txt
+++ b/client/CMakeLists.txt
@@ -35,6 +35,9 @@ foreach(_qt_package IN LISTS QT_PACKAGELIST)
endif(NOT ${_qt_package}_FOUND)
endforeach()
+find_package(PkgConfig)
+pkg_search_module(BLUEZ QUIET bluez)
+
SET (CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
add_subdirectory(deps)
@@ -208,6 +211,12 @@ else (Qt5_FOUND)
${TARGET_SOURCES})
endif (Qt5_FOUND)
+if (BLUEZ_FOUND)
+ message("Bluez library found, building native Bluetooth support :)")
+ add_definitions("-DHAVE_BLUEZ")
+ set(ADDITIONAL_LNK bluetooth ${ADDITIONAL_LNK})
+endif (BLUEZ_FOUND)
+
add_executable(
proxmark3
${TARGET_SOURCES}
diff --git a/client/Makefile b/client/Makefile
index d3461a302..d7709f656 100644
--- a/client/Makefile
+++ b/client/Makefile
@@ -90,6 +90,14 @@ else
endif
endif
+ifneq ($(SKIPBT),1)
+ BTLDLIBS = $(shell $(PKG_CONFIG_ENV) pkg-config --libs bluez 2>/dev/null)
+endif
+
+ifneq ($(BTLDLIBS),)
+ PM3CFLAGS += -DHAVE_BLUEZ
+endif
+
ifneq ($(SKIPQT),1)
# Check for correctly configured Qt5
QTINCLUDES = $(shell $(PKG_CONFIG_ENV) pkg-config --cflags Qt5Core Qt5Widgets 2>/dev/null)
@@ -132,6 +140,24 @@ else
QTGUIOBJS = $(OBJDIR)/guidummy.o
endif
+$(info ===================================================================)
+$(info Client platform: $(platform))
+ifeq ($(SKIPQT),1)
+$(info GUI support: skipped)
+else ifneq ($(QTLDLIBS),)
+$(info GUI support: QT found, enabled)
+else
+$(info GUI support: QT not found, disabled)
+endif
+ifeq ($(SKIPBT),1)
+$(info native BT support: skipped)
+else ifneq ($(BTLDLIBS),)
+$(info native BT support: Bluez found, enabled)
+else
+$(info native BT support: Bluez not found, disabled)
+endif
+$(info ===================================================================)
+
# Flags to generate temporary dependency files
DEPFLAGS = -MT $@ -MMD -MP -MF $(OBJDIR)/$*.Td
# make temporary to final dependency files after successful compilation
@@ -286,7 +312,7 @@ all: $(BINS)
all-static: LDLIBS:=-static $(LDLIBS)
all-static: $(BINS)
-proxmark3: LDLIBS+=$(LUALIB) $(JANSSONLIB) $(MBEDTLSLIB) $(CBORLIB) $(ZLIB) $(REVENGLIB) $(AMIIBOLIB) $(HARDNESTEDLIB) $(CLIPARSERLIB) $(QTLDLIBS)
+proxmark3: LDLIBS+=$(LUALIB) $(JANSSONLIB) $(MBEDTLSLIB) $(CBORLIB) $(ZLIB) $(REVENGLIB) $(AMIIBOLIB) $(HARDNESTEDLIB) $(CLIPARSERLIB) $(BTLDLIBS) $(QTLDLIBS)
proxmark3: $(OBJDIR)/proxmark3.o $(COREOBJS) $(CMDOBJS) $(OBJCOBJS) $(QTGUIOBJS) $(LUALIB) $(JANSSONLIB) $(CBORLIB) $(REVENGLIB) $(MBEDTLSLIB) $(ZLIB) $(AMIIBOLIB) $(HARDNESTEDLIB) $(CLIPARSERLIB) lualibs/pm3_cmd.lua lualibs/mfc_default_keys.lua
$(info [=] LD $@)
$(Q)$(LD) $(LDFLAGS) $(OBJDIR)/proxmark3.o $(COREOBJS) $(CMDOBJS) $(OBJCOBJS) $(QTGUIOBJS) $(LDLIBS) -o $@
diff --git a/client/src/comms.c b/client/src/comms.c
index 88ffde16c..36f035bdd 100644
--- a/client/src/comms.c
+++ b/client/src/comms.c
@@ -639,9 +639,10 @@ int TestProxmark(void) {
conn.send_via_fpc_usart = pm3_capabilities.via_fpc;
conn.uart_speed = pm3_capabilities.baudrate;
- PrintAndLogEx(INFO, "Communicating with PM3 over %s%s",
+ PrintAndLogEx(INFO, "Communicating with PM3 over %s%s%s",
conn.send_via_fpc_usart ? _YELLOW_("FPC UART") : _YELLOW_("USB-CDC"),
- memcmp(conn.serial_port_name, "tcp:", 4) == 0 ? " over " _YELLOW_("TCP") : "");
+ memcmp(conn.serial_port_name, "tcp:", 4) == 0 ? " over " _YELLOW_("TCP") : "",
+ memcmp(conn.serial_port_name, "bt:", 3) == 0 ? " over " _YELLOW_("BT") : "");
if (conn.send_via_fpc_usart) {
PrintAndLogEx(INFO, "PM3 UART serial baudrate: " _YELLOW_("%u") "\n", conn.uart_speed);
diff --git a/client/src/uart/uart_posix.c b/client/src/uart/uart_posix.c
index a2b324b49..cf0837845 100644
--- a/client/src/uart/uart_posix.c
+++ b/client/src/uart/uart_posix.c
@@ -48,10 +48,16 @@
#include
#include
#include
-#include "sys/socket.h"
-#include "sys/un.h"
+#include
+#include
+
+#ifdef HAVE_BLUEZ
+#include
+#include
+#endif
#include "comms.h"
+#include "ui.h"
// Taken from https://github.com/unbit/uwsgi/commit/b608eb1772641d525bfde268fe9d6d8d0d5efde7
#ifndef SOL_TCP
@@ -158,6 +164,52 @@ serial_port uart_open(const char *pcPortName, uint32_t speed) {
return sp;
}
+ if (memcmp(pcPortName, "bt:", 3) == 0) {
+#ifdef HAVE_BLUEZ
+ if (strlen(pcPortName) != 20) {
+ free(sp);
+ return INVALID_SERIAL_PORT;
+ }
+ char *addrstr = strndup(pcPortName + 3, 17);
+
+ if (addrstr == NULL) {
+ printf("Error: malloc\n");
+ free(sp);
+ return INVALID_SERIAL_PORT;
+ }
+
+ struct sockaddr_rc addr = { 0 };
+ addr.rc_family = AF_BLUETOOTH;
+ addr.rc_channel = (uint8_t) 1;
+ if (str2ba(addrstr, &addr.rc_bdaddr) != 0) {
+ PrintAndLogEx(ERR, "Invalid Bluetooth MAC address " _RED_("%s"), addrstr);
+ free(addrstr);
+ free(sp);
+ return INVALID_SERIAL_PORT;
+ }
+ int sfd = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
+ if (sfd == -1) {
+ PrintAndLogEx(ERR, "Error opening Bluetooth socket");
+ free(addrstr);
+ free(sp);
+ return INVALID_SERIAL_PORT;
+ }
+ if (connect(sfd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
+ PrintAndLogEx(ERR, "Error: cannot connect device " _YELLOW_("%s") " over Bluetooth", addrstr);
+ close(sfd);
+ free(addrstr);
+ free(sp);
+ return INVALID_SERIAL_PORT;
+ }
+
+ sp->fd = sfd;
+ return sp;
+#else // HAVE_BLUEZ
+ PrintAndLogEx(ERR, "Sorry, this client doesn't support native Bluetooth addresses");
+ free(sp);
+ return INVALID_SERIAL_PORT;
+#endif // HAVE_BLUEZ
+ }
// The socket for abstract namespace implement.
// Is local socket buffer, not a TCP or any net connection!
// so, you can't connect with address like: 127.0.0.1, or any IP
diff --git a/doc/bt_manual_v10.md b/doc/bt_manual_v10.md
index 38f5f0d3b..c009ba025 100644
--- a/doc/bt_manual_v10.md
+++ b/doc/bt_manual_v10.md
@@ -102,7 +102,9 @@ http://www.silabs.com/products/development-tools/software/usb-to-uart-bridge-vcp
#### Linux
-#### (1) Connecting rdv4.0 with Bluetooth on Linux computer
+#### (1) Connecting rdv4.0 with Bluetooth on Linux computer via native Bluetooth support in the client
+
+This requires to have compiled the client with Bluetooth support.
1. Find the MAC address of the Bluetooth add-on, named PM3_RDV4.0.
@@ -114,21 +116,9 @@ Scanning ...
Instead of `aa:bb:cc:dd:ee:ff`, you'll see your MAC address.
-2. Bind your BT add-on MAC address to a serial port
+2. Use Proxmark client with Bluetooth MAC address as bt:
```sh
-sudo rfcomm bind rfcomm0 aa:bb:cc:dd:ee:ff
-```
-
-Replace `aa:bb:cc:dd:ee:ff` by your MAC address.
-
-3. The blue state LED on the add-on will keep blinking after the
-connection is established. Only when the Proxmark3 client opens the
-`/dev/rfcomm0` port, the blue LED turns on solid, indicating that the
-connection is successful.
-
-4. Use Proxmark client on BT-serial port
-```sh
-./proxmark3 /dev/rfcomm0
+./proxmark3 bt:aa:bb:cc:dd:ee:ff
```
The first time, your OS will ask you for pairing. The default PIN is
1234. If PIN is not typed in quickly, the client might timeout. Simply
@@ -172,6 +162,39 @@ turn on solid.
./proxmark3 /dev/ttyUSB0
```
+#### (1b, deprecated) Connecting rdv4.0 with Bluetooth on Linux computer via rfcomm
+
+rfcomm is a deprecated tool which might be unavailable in your Linux distribution.
+
+1. Find the MAC address of the Bluetooth add-on, named PM3_RDV4.0.
+
+```sh
+sudo hcitool scan
+Scanning ...
+ aa:bb:cc:dd:ee:ff PM3_RDV4.0
+```
+
+Instead of `aa:bb:cc:dd:ee:ff`, you'll see your MAC address.
+
+2. Bind your BT add-on MAC address to a serial port
+```sh
+sudo rfcomm bind rfcomm0 aa:bb:cc:dd:ee:ff
+```
+
+Replace `aa:bb:cc:dd:ee:ff` by your MAC address.
+
+3. The blue state LED on the add-on will keep blinking after the
+connection is established. Only when the Proxmark3 client opens the
+`/dev/rfcomm0` port, the blue LED turns on solid, indicating that the
+connection is successful.
+
+4. Use Proxmark client on BT-serial port
+```sh
+./proxmark3 /dev/rfcomm0
+```
+
+See instructions above (method 1) for initial pairing.
+
#### MacOS
#### (1) Connecting rdv4.0 with Bluetooth on MacOS
diff --git a/doc/md/Installation_Instructions/Linux-Installation-Instructions.md b/doc/md/Installation_Instructions/Linux-Installation-Instructions.md
index b381eb7d9..8cb6b47ff 100644
--- a/doc/md/Installation_Instructions/Linux-Installation-Instructions.md
+++ b/doc/md/Installation_Instructions/Linux-Installation-Instructions.md
@@ -25,9 +25,11 @@ Install the requirements
```sh
sudo apt-get install --no-install-recommends git ca-certificates build-essential pkg-config \
-libreadline-dev gcc-arm-none-eabi libnewlib-dev qtbase5-dev
+libreadline-dev gcc-arm-none-eabi libnewlib-dev qtbase5-dev libbluetooth-dev
```
+If you don't need the native Bluetooth support in the client, you can skip the installation of `libbluetooth-dev`.
+
If you don't need the graphical components of the Proxmark3 client (such as in `hw tune`), you can skip the installation of `qtbase5-dev`.
If you get some (non blocking) error at runtime such as _Gtk-Message: Failed to load module "canberra-gtk-module"_ you may have to install `libcanberra-gtk-module`.
@@ -35,17 +37,21 @@ If you get some (non blocking) error at runtime such as _Gtk-Message: Failed to
## On ArchLinux
```sh
-sudo pacman -Sy git base-devel readline arm-none-eabi-gcc arm-none-eabi-newlib qt5-base --needed
+sudo pacman -Sy git base-devel readline arm-none-eabi-gcc arm-none-eabi-newlib qt5-base bluez --needed
```
+If you don't need the native Bluetooth support in the client, you can skip the installation of `bluez`.
+
If you don't need the graphical components of the Proxmark3 client (such as in `hw tune`), you can skip the installation of `qt5-base`.
## On Fedora
```sh
-sudo dnf install git make gcc gcc-c++ arm-none-eabi-gcc-cs arm-none-eabi-newlib readline-devel qt5-qtbase-devel libatomic
+sudo dnf install git make gcc gcc-c++ arm-none-eabi-gcc-cs arm-none-eabi-newlib readline-devel qt5-qtbase-devel bluez-libs-devel libatomic
```
+If you don't need the native Bluetooth support in the client, you can skip the installation of `bluez-libs-devel`.
+
If you don't need the graphical components of the Proxmark3 client (such as in `hw tune`), you can skip the installation of `qt5-qtbase-devel`.
## On openSUSE
@@ -56,6 +62,8 @@ sudo zypper install git patterns-devel-base-devel_basis gcc-c++ readline-devel c
If you don't need the graphical components of the Proxmark3 client (such as in `hw tune`), you can skip the installation of `libqt5-qtbase-devel`.
+Note that Bluez is not available on openSUSE so the native Bluetooth support won't be available in the client.
+
# Clone the RRG/Iceman repository
```sh
diff --git a/doc/md/Use_of_Proxmark/4_Advanced-compilation-parameters.md b/doc/md/Use_of_Proxmark/4_Advanced-compilation-parameters.md
index 5e953883a..46e1c6504 100644
--- a/doc/md/Use_of_Proxmark/4_Advanced-compilation-parameters.md
+++ b/doc/md/Use_of_Proxmark/4_Advanced-compilation-parameters.md
@@ -19,6 +19,14 @@ make clean
make SKIPQT=1
```
+On Linux hosts, if the Bluez headers and library are present, the client will be compiled with native Bluetooth support. It's possible to explicitly skip Bluetooth support with:
+
+```
+make clean
+make SKIPBT=1
+```
+
+
## Firmware
By default, the firmware is of course tuned for the Proxmark3 Rdv4.0 device, which has built-in support for 256kb onboard flash SPI memory, Sim module (smart card support), FPC connector.
From 4c085245c5acfce7fb13ae07074ae44be887ebdc Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Wed, 29 Apr 2020 15:15:25 +0200
Subject: [PATCH 019/632] pm3 for direct bt devices
---
pm3 | 26 +++++++++++++++++++++-----
1 file changed, 21 insertions(+), 5 deletions(-)
diff --git a/pm3 b/pm3
index 2b2258b50..a91fced11 100755
--- a/pm3
+++ b/pm3
@@ -2,10 +2,12 @@
# Usage: run option -h to get help
-# BT auto detection: only working under Linux at the moment
+# BT auto detection
# Shall we look for white HC-06-USB dongle ?
FINDBTDONGLE=true
# Shall we look for rfcomm interface ?
+FINDBTRFCOMM=true
+# Shall we look for registered BT device ? (Linux only)
FINDBTDIRECT=true
PM3PATH=$(dirname "$0")
@@ -47,12 +49,13 @@ function get_pm3_list_Linux {
fi
done
fi
- if $FINDBTDIRECT; then
+ if $FINDBTRFCOMM; then
# check if the MAC of a Proxmark3 was bound to a local rfcomm interface
+ # (on OSes without deprecated rfcomm and hcitool, the loop will be simply skipped)
for DEVMAC in $(rfcomm -a 2>/dev/null | grep " 20:19:0[45]" | sed 's/^\(.*\): \([0-9:]*\) .*/\1@\2/'); do
DEV=${DEVMAC/@*/}
MAC=${DEVMAC/*@/}
- # check if Proxmark3 is actually present
+ # check which are Proxmark3 and, side-effect, if they're actually present
if hcitool name "$MAC" | grep -q "PM3"; then
PM3LIST+=("/dev/$DEV")
if [ ${#PM3LIST[*]} -ge $N ]; then
@@ -61,6 +64,15 @@ function get_pm3_list_Linux {
fi
done
fi
+ if $FINDBTDIRECT; then
+ # check if the MAC of a Proxmark3 was registered in the known devices
+ MACS=()
+ for MAC in $(dbus-send --system --print-reply --type=method_call --dest='org.bluez' '/' org.freedesktop.DBus.ObjectManager.GetManagedObjects|\
+ awk '/"Address"/{getline;gsub(/"/,"",$3);a=$3}/Name/{getline;if (/PM3_RDV4/) print a}'); do
+ PM3LIST+=("bt:$MAC")
+ done
+ # we don't probe the device so there is no guarantee the device is actually present
+ fi
}
function get_pm3_list_macOS {
@@ -81,7 +93,7 @@ function get_pm3_list_Windows {
PM3LIST=()
# Need to look for this first, the call to Win32_serialport "crashes" then native bt serial port. Don't ask why.
#BT direct SERIAL PORTS (COM)
- if $FINDBTDIRECT; then
+ if $FINDBTRFCOMM; then
for DEV in $(powershell.exe -command "Get-CimInstance -ClassName Win32_PnPEntity | Where-Object Caption -like 'Standard Serial over Bluetooth link (COM*' | Select Name" 2> /dev/null | awk '$0 ~ /COM/{print substr($6,2,4)}'); do
DEV=${DEV/ */}
PM3LIST+=("$DEV")
@@ -118,7 +130,7 @@ function get_pm3_list_WSL {
# Need to look for this first, the call to Win32_serialport "crashes" then native bt serial port. Don't ask why.
#BT direct SERIAL PORTS (COM)
- if $FINDBTDIRECT; then
+ if $FINDBTRFCOMM; then
for DEV in $(powershell.exe -command "Get-CimInstance -ClassName Win32_PnPEntity | Where-Object Caption -like 'Standard Serial over Bluetooth link (COM*' | Select Name" 2> /dev/null | awk '$0 ~ /COM/{print substr($6,2,4)}'); do
DEV=${DEV/ */}
@@ -201,6 +213,7 @@ EOF
}
elif [ "$SCRIPT" = "pm3-flash" ]; then
FINDBTDONGLE=false
+ FINDBTRFCOMM=false
FINDBTDIRECT=false
CMD() {
ARGS=("--port" "$1" "--flash")
@@ -238,6 +251,7 @@ EOF
}
elif [ "$SCRIPT" = "pm3-flash-all" ]; then
FINDBTDONGLE=false
+ FINDBTRFCOMM=false
FINDBTDIRECT=false
CMD() { $CLIENT "--port" "$1" "--flash" "--unlock-bootloader" "--image" "$BOOTIMAGE" "--image" "$FULLIMAGE"; }
HELP() {
@@ -257,6 +271,7 @@ EOF
}
elif [ "$SCRIPT" = "pm3-flash-fullimage" ]; then
FINDBTDONGLE=false
+ FINDBTRFCOMM=false
FINDBTDIRECT=false
CMD() { $CLIENT "--port" "$1" "--flash" "--image" "$FULLIMAGE"; }
HELP() {
@@ -276,6 +291,7 @@ EOF
}
elif [ "$SCRIPT" = "pm3-flash-bootrom" ]; then
FINDBTDONGLE=false
+ FINDBTRFCOMM=false
FINDBTDIRECT=false
CMD() { $CLIENT "--port" "$1" "--flash" "--unlock-bootloader" "--image" "$BOOTIMAGE"; }
HELP() {
From ba08d5794c55d48efcfd0e03afc6fde3bf81c03e Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Wed, 29 Apr 2020 15:29:34 +0200
Subject: [PATCH 020/632] silent err if dbus absent
---
pm3 | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/pm3 b/pm3
index a91fced11..4af441c40 100755
--- a/pm3
+++ b/pm3
@@ -67,7 +67,7 @@ function get_pm3_list_Linux {
if $FINDBTDIRECT; then
# check if the MAC of a Proxmark3 was registered in the known devices
MACS=()
- for MAC in $(dbus-send --system --print-reply --type=method_call --dest='org.bluez' '/' org.freedesktop.DBus.ObjectManager.GetManagedObjects|\
+ for MAC in $(dbus-send --system --print-reply --type=method_call --dest='org.bluez' '/' org.freedesktop.DBus.ObjectManager.GetManagedObjects 2>/dev/null|\
awk '/"Address"/{getline;gsub(/"/,"",$3);a=$3}/Name/{getline;if (/PM3_RDV4/) print a}'); do
PM3LIST+=("bt:$MAC")
done
From 536338584570dd35535f0fdd08806c4e0fa6c287 Mon Sep 17 00:00:00 2001
From: iceman1001
Date: Wed, 29 Apr 2020 16:35:08 +0200
Subject: [PATCH 021/632] coverity fix 286655
---
client/src/cmdhfmfdes.c | 233 +++++++++++++++++++---------------------
1 file changed, 112 insertions(+), 121 deletions(-)
diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c
index f70e91326..be5975049 100644
--- a/client/src/cmdhfmfdes.c
+++ b/client/src/cmdhfmfdes.c
@@ -925,7 +925,7 @@ void AuthToError(int error) {
PrintAndLogEx(ERR, "Authentication failed. Invalid key number.");
break;
case 4:
- PrintAndLogEx(ERR, "Authentication failed. Length of answer %d doesn't match algo length %d.");
+ PrintAndLogEx(ERR, "Authentication failed. Length of answer doesn't match algo length");
break;
case 5:
PrintAndLogEx(ERR, "mbedtls_aes_setkey_dec failed");
@@ -3161,6 +3161,7 @@ static int DecodeFileSettings(uint8_t *src, int src_len, int maclen) {
static int CmdHF14ADesDump(const char *Cmd) {
(void)Cmd; // Cmd is not used so far
DropField();
+
uint8_t aid[3] = {0};
uint8_t app_ids[78] = {0};
uint8_t app_ids_len = 0;
@@ -3205,106 +3206,120 @@ static int CmdHF14ADesDump(const char *Cmd) {
uint8_t num_keys = 0;
uint8_t key_setting = 0;
res = handler_desfire_keysettings(&key_setting, &num_keys);
- if (res != PM3_SUCCESS) return res;
+ if (res != PM3_SUCCESS) continue;
res = handler_desfire_select_application(aid);
+ if (res != PM3_SUCCESS) continue;
- if (handler_desfire_fileids(file_ids, &file_ids_len) == PM3_SUCCESS) {
- for (int j = file_ids_len - 1; j >= 0; j--) {
- PrintAndLogEx(SUCCESS, "\n\n Fileid %d (0x%02x)", file_ids[j], file_ids[j]);
+ res = handler_desfire_fileids(file_ids, &file_ids_len);
+ if (res != PM3_SUCCESS) continue;
- uint8_t filesettings[20] = {0};
- int fileset_len = 0;
+ for (int j = file_ids_len - 1; j >= 0; j--) {
+ PrintAndLogEx(SUCCESS, "\n\n Fileid %d (0x%02x)", file_ids[j], file_ids[j]);
- res = handler_desfire_filesettings(file_ids[j], filesettings, &fileset_len);
- int maclen = 0; // To be implemented
+ uint8_t filesettings[20] = {0};
+ int fileset_len = 0;
+ res = handler_desfire_filesettings(file_ids[j], filesettings, &fileset_len);
+ if (res != PM3_SUCCESS) continue;
+
+ int maclen = 0; // To be implemented
+
+ if (fileset_len == 1 + 1 + 2 + 3 + maclen) {
+ int filesize = (filesettings[6] << 16) + (filesettings[5] << 8) + filesettings[4];
+ mfdes_data_t fdata;
+ fdata.fileno = file_ids[j];
+ memset(fdata.offset, 0, 3);
+ memset(fdata.length, 0, 3);
+
+ uint8_t *data = (uint8_t *)calloc(filesize, sizeof(uint8_t));
+ if (data == NULL) {
+ DropField();
+ return PM3_EMALLOC;
+ }
+
+ fdata.data = data;
+ res = handler_desfire_readdata(&fdata, MFDES_DATA_FILE);
if (res == PM3_SUCCESS) {
- //if (DecodeFileSettings(filesettings, fileset_len, maclen) != PM3_SUCCESS) {
- if (fileset_len == 1 + 1 + 2 + 3 + maclen) {
- int filesize = (filesettings[6] << 16) + (filesettings[5] << 8) + filesettings[4];
- mfdes_data_t fdata;
- fdata.fileno = file_ids[j];
- memset(fdata.offset, 0, 3);
- //memcpy(fdata.length,&filesettings[4],3);
- memset(fdata.length, 0, 3);
- uint8_t *data = (uint8_t *)malloc(filesize);
- fdata.data = data;
- if (data) {
- res = handler_desfire_readdata(&fdata, MFDES_DATA_FILE);
- if (res == PM3_SUCCESS) {
- PrintAndLogEx(NORMAL, "\nOffset | Data | Ascii");
- PrintAndLogEx(NORMAL, "----------------------------------------------------------------------------");
- int len = le24toh(fdata.length);
- for (int n = 0; n < len; n += 16) {
- PrintAndLogEx(NORMAL, "%02d/0x%02X | %s| %s", n, n, sprint_hex(&fdata.data[n], len > 16 ? 16 : len), sprint_ascii(&fdata.data[n], len > 16 ? 16 : len));
- }
- free(data);
- } else {
- PrintAndLogEx(ERR, "Couldn't read value. Error %d", res);
- res = handler_desfire_select_application(aid);
- }
- }
- } else if (fileset_len == 1 + 1 + 2 + 4 + 4 + 4 + 1 + maclen) {
- PrintAndLogEx(NORMAL, "\n\nValue file: 0x%0x", file_ids[j]);
- mfdes_value_t value;
- value.fileno = file_ids[j];
- int len = 0;
- res = handler_desfire_getvalue(&value, &len);
- if (res == PM3_SUCCESS) {
- PrintAndLogEx(NORMAL, "\nOffset | Value | Ascii");
- PrintAndLogEx(NORMAL, "----------------------------------------------------------------------------");
- for (int n = 0; n < len; n += 16) {
- PrintAndLogEx(NORMAL, "%02d/0x%02X | %s| %s", n, n, sprint_hex(&value.value[n], len > 16 ? 16 : len), sprint_ascii(&value.value[n], len > 16 ? 16 : len));
- }
- } else {
- PrintAndLogEx(ERR, "Couldn't read value. Error %d", res);
- res = handler_desfire_select_application(aid);
- }
- } else if (fileset_len == 1 + 1 + 2 + 3 + 3 + 3 + maclen) {
- int maxrecords = (filesettings[9] << 16) + (filesettings[8] << 8) + filesettings[7];
- int filesize = (filesettings[6] << 16) + (filesettings[5] << 8) + filesettings[4];
- mfdes_data_t fdata;
- fdata.fileno = file_ids[j];
- memset(fdata.length, 0, 3);
- //memcpy(fdata.length,&filesettings[4],3);
- uint8_t *data = (uint8_t *)malloc(filesize);
- fdata.data = data;
- if (data) {
- for (int offset = 0; offset < maxrecords; offset++) {
- PrintAndLogEx(NORMAL, "\n\nRecord offset: %024x", offset);
- memset(data, 0, filesize);
- fdata.offset[0] = offset & 0xFF;
- fdata.offset[1] = (offset >> 8) & 0xFF;
- fdata.offset[2] = (offset >> 16) & 0xFF;
- res = handler_desfire_readdata(&fdata, MFDES_RECORD_FILE);
- if (res == PM3_SUCCESS) {
- PrintAndLogEx(NORMAL, "\nOffset | Data | Ascii");
- PrintAndLogEx(NORMAL, "----------------------------------------------------------------------------");
- int len = le24toh(fdata.length);
- for (int n = 0; n < len; n += 16) {
- PrintAndLogEx(NORMAL, "%02d/0x%02X | %s| %s", n, n, sprint_hex(&fdata.data[n], len > 16 ? 16 : len), sprint_ascii(&fdata.data[n], len > 16 ? 16 : len));
- }
- } else {
- res = handler_desfire_select_application(aid);
- }
- }
- free(data);
- }
+ PrintAndLogEx(NORMAL, "\nOffset | Data | Ascii");
+ PrintAndLogEx(NORMAL, "----------------------------------------------------------------------------");
+ int len = le24toh(fdata.length);
+ for (int n = 0; n < len; n += 16) {
+ PrintAndLogEx(NORMAL, "%02d/0x%02X | %s| %s", n, n, sprint_hex(&fdata.data[n], len > 16 ? 16 : len), sprint_ascii(&fdata.data[n], len > 16 ? 16 : len));
+ }
+ } else {
+ PrintAndLogEx(ERR, "Couldn't read value. Error %d", res);
+ res = handler_desfire_select_application(aid);
+ if (res != PM3_SUCCESS) continue;
+ }
+
+ free(data);
+
+ } else if (fileset_len == 1 + 1 + 2 + 4 + 4 + 4 + 1 + maclen) {
+ PrintAndLogEx(NORMAL, "\n\nValue file: 0x%0x", file_ids[j]);
+ mfdes_value_t value;
+ value.fileno = file_ids[j];
+ int len = 0;
+ res = handler_desfire_getvalue(&value, &len);
+ if (res == PM3_SUCCESS) {
+ PrintAndLogEx(NORMAL, "\nOffset | Value | Ascii");
+ PrintAndLogEx(NORMAL, "----------------------------------------------------------------------------");
+ for (int n = 0; n < len; n += 16) {
+ PrintAndLogEx(NORMAL, "%02d/0x%02X | %s| %s", n, n, sprint_hex(&value.value[n], len > 16 ? 16 : len), sprint_ascii(&value.value[n], len > 16 ? 16 : len));
+ }
+ } else {
+ PrintAndLogEx(ERR, "Couldn't read value. Error %d", res);
+ res = handler_desfire_select_application(aid);
+ if (res != PM3_SUCCESS) continue;
+ }
+
+ } else if (fileset_len == 1 + 1 + 2 + 3 + 3 + 3 + maclen) {
+ int maxrecords = (filesettings[9] << 16) + (filesettings[8] << 8) + filesettings[7];
+ int filesize = (filesettings[6] << 16) + (filesettings[5] << 8) + filesettings[4];
+ mfdes_data_t fdata;
+ fdata.fileno = file_ids[j];
+ memset(fdata.length, 0, 3);
+ uint8_t *data = (uint8_t *)calloc(filesize, sizeof(uint8_t));
+ if (data == NULL) {
+ DropField();
+ return PM3_EMALLOC;
+ }
+
+ fdata.data = data;
+ for (int offset = 0; offset < maxrecords; offset++) {
+ PrintAndLogEx(NORMAL, "\n\nRecord offset: %024x", offset);
+ memset(data, 0, filesize);
+ fdata.offset[0] = offset & 0xFF;
+ fdata.offset[1] = (offset >> 8) & 0xFF;
+ fdata.offset[2] = (offset >> 16) & 0xFF;
+ res = handler_desfire_readdata(&fdata, MFDES_RECORD_FILE);
+ if (res == PM3_SUCCESS) {
+ PrintAndLogEx(NORMAL, "\nOffset | Data | Ascii");
+ PrintAndLogEx(NORMAL, "----------------------------------------------------------------------------");
+ int len = le24toh(fdata.length);
+ for (int n = 0; n < len; n += 16) {
+ PrintAndLogEx(NORMAL, "%02d/0x%02X | %s| %s", n, n, sprint_hex(&fdata.data[n], len > 16 ? 16 : len), sprint_ascii(&fdata.data[n], len > 16 ? 16 : len));
+ }
+ } else {
+ res = handler_desfire_select_application(aid);
+ if (res != PM3_SUCCESS) continue;
}
}
+ free(data);
}
}
}
+
PrintAndLogEx(INFO, "-------------------------------------------------------------");
DropField();
return PM3_SUCCESS;
}
static int CmdHF14ADesEnumApplications(const char *Cmd) {
+
(void)Cmd; // Cmd is not used so far
DropField();
-// uint8_t isOK = 0x00;
+
uint8_t aid[3] = {0};
uint8_t app_ids[78] = {0};
uint8_t app_ids_len = 0;
@@ -3315,8 +3330,6 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) {
dfname_t dfnames[255];
uint8_t dfname_count = 0;
- int res = 0;
-
if (handler_desfire_appids(app_ids, &app_ids_len) != PM3_SUCCESS) {
PrintAndLogEx(ERR, "Can't get list of applications on tag");
DropField();
@@ -3356,53 +3369,31 @@ static int CmdHF14ADesEnumApplications(const char *Cmd) {
}
}
- res = getKeySettings(aid);
- if (res != PM3_SUCCESS) return res;
+ int res = getKeySettings(aid);
+ if (res != PM3_SUCCESS) continue;
res = handler_desfire_select_application(aid);
+ if (res != PM3_SUCCESS) continue;
+ res = handler_desfire_fileids(file_ids, &file_ids_len);
+ if (res != PM3_SUCCESS) continue;
- // Get File IDs
- if (handler_desfire_fileids(file_ids, &file_ids_len) == PM3_SUCCESS) {
- PrintAndLogEx(SUCCESS, " Tag report " _GREEN_("%d") " file%c", file_ids_len, (file_ids_len == 1) ? ' ' : 's');
- for (int j = file_ids_len - 1; j >= 0; j--) {
- PrintAndLogEx(SUCCESS, " Fileid %d (0x%02x)", file_ids[j], file_ids[j]);
+ PrintAndLogEx(SUCCESS, " Tag report " _GREEN_("%d") " file%c", file_ids_len, (file_ids_len == 1) ? ' ' : 's');
+ for (int j = file_ids_len - 1; j >= 0; j--) {
+ PrintAndLogEx(SUCCESS, " Fileid %d (0x%02x)", file_ids[j], file_ids[j]);
- uint8_t filesettings[20] = {0};
- int fileset_len = 0;
- int maclen = 0; // To be implemented
+ uint8_t filesettings[20] = {0};
+ int fileset_len = 0;
+ int maclen = 0; // To be implemented
- res = handler_desfire_filesettings(file_ids[j], filesettings, &fileset_len);
- if (res == PM3_SUCCESS) {
- if (DecodeFileSettings(filesettings, fileset_len, maclen) != PM3_SUCCESS) {
- PrintAndLogEx(INFO, " Settings [%u] %s", fileset_len, sprint_hex(filesettings, fileset_len));
- }
- }
+ res = handler_desfire_filesettings(file_ids[j], filesettings, &fileset_len);
+ if (res != PM3_SUCCESS) continue;
+
+ if (DecodeFileSettings(filesettings, fileset_len, maclen) != PM3_SUCCESS) {
+ PrintAndLogEx(INFO, " Settings [%u] %s", fileset_len, sprint_hex(filesettings, fileset_len));
}
}
- /*
- // Get ISO File IDs
- {
- uint8_t data[] = {GET_ISOFILE_IDS, 0x00, 0x00, 0x00}; // 0x61
- SendCommandMIX(CMD_HF_DESFIRE_COMMAND, DISCONNECT, sizeof(data), 0, data, sizeof(data));
- }
-
- if (!WaitForResponseTimeout(CMD_ACK, &respFiles, 1500)) {
- PrintAndLogEx(WARNING, _RED_(" Timed-out"));
- continue;
- } else {
- isOK = respFiles.data.asBytes[2] & 0xff;
- if (!isOK) {
- PrintAndLogEx(WARNING, _RED_(" Can't get ISO file ids"));
- } else {
- int respfileLen = resp.oldarg[1] - 3 - 2;
- for (int j = 0; j < respfileLen; ++j) {
- PrintAndLogEx(SUCCESS, " ISO Fileid %d :", resp.data.asBytes[j + 3]);
- }
- }
- }
- */
}
PrintAndLogEx(INFO, "-------------------------------------------------------------");
DropField();
From 4c640805b6be011724950674363e1fd67af4cb52 Mon Sep 17 00:00:00 2001
From: iceman1001
Date: Wed, 29 Apr 2020 16:57:52 +0200
Subject: [PATCH 022/632] coverity fix: 267208
---
armsrc/hitag2.c | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/armsrc/hitag2.c b/armsrc/hitag2.c
index 7e4c7ca14..1c045c5e8 100644
--- a/armsrc/hitag2.c
+++ b/armsrc/hitag2.c
@@ -1062,7 +1062,7 @@ void SimulateHitag2(bool tag_mem_supplied, uint8_t *data) {
lf_init(false, true);
int response = 0;
- uint8_t rx[HITAG_FRAME_LEN];
+ uint8_t rx[HITAG_FRAME_LEN] = {0};
size_t rxlen = 0;
uint8_t tx[HITAG_FRAME_LEN];
size_t txlen = 0;
From 85f223316151284916bbcb02b667ed6fb21c51d4 Mon Sep 17 00:00:00 2001
From: iceman1001
Date: Wed, 29 Apr 2020 17:27:17 +0200
Subject: [PATCH 023/632] coverity fix 226496 226492 226490
---
client/deps/hardnested/hardnested_bf_core.c | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/client/deps/hardnested/hardnested_bf_core.c b/client/deps/hardnested/hardnested_bf_core.c
index 4e30dd894..45a996879 100644
--- a/client/deps/hardnested/hardnested_bf_core.c
+++ b/client/deps/hardnested/hardnested_bf_core.c
@@ -324,7 +324,7 @@ uint64_t CRACK_STATES_BITSLICED(uint32_t cuid, uint8_t *best_first_bytes, statel
crypto1_bs_f20b_2[0] = f20b(state_p[47 - 25].value, state_p[47 - 27].value, state_p[47 - 29].value, state_p[47 - 31].value);
crypto1_bs_f20b_3[0] = f20b(state_p[47 - 41].value, state_p[47 - 43].value, state_p[47 - 45].value, state_p[47 - 47].value);
- bitslice_value_t ksb[8];
+ bitslice_value_t ksb[9];
ksb[0] = f20c(f20a(state_p[47 - 9].value, state_p[47 - 11].value, state_p[47 - 13].value, state_p[47 - 15].value),
f20b(state_p[47 - 17].value, state_p[47 - 19].value, state_p[47 - 21].value, state_p[47 - 23].value),
crypto1_bs_f20b_2[0],
@@ -347,14 +347,14 @@ uint64_t CRACK_STATES_BITSLICED(uint32_t cuid, uint8_t *best_first_bytes, statel
}
// pre-compute first feedback bit vector. This is the same for all nonces
- bitslice_value_t fbb[8];
+ bitslice_value_t fbb[9];
fbb[0] = odd_feedback ^ bitsliced_even_feedback[block_idx];
// vector to contain test results (1 = passed, 0 = failed)
bitslice_t results = bs_ones;
// parity_bits
- bitslice_value_t par[8];
+ bitslice_value_t par[9];
par[0] = bs_zeroes.value;
uint32_t next_common_bits = 0;
From 250418f64bd1ab02086748c01895f5915b6b08f5 Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Wed, 29 Apr 2020 19:18:01 +0200
Subject: [PATCH 024/632] client Makefile: make sure to rebuild deps when
needed
---
client/Makefile | 40 ++++++++++++++++++++--------------------
1 file changed, 20 insertions(+), 20 deletions(-)
diff --git a/client/Makefile b/client/Makefile
index d7709f656..f62d7ab49 100644
--- a/client/Makefile
+++ b/client/Makefile
@@ -313,7 +313,7 @@ all-static: LDLIBS:=-static $(LDLIBS)
all-static: $(BINS)
proxmark3: LDLIBS+=$(LUALIB) $(JANSSONLIB) $(MBEDTLSLIB) $(CBORLIB) $(ZLIB) $(REVENGLIB) $(AMIIBOLIB) $(HARDNESTEDLIB) $(CLIPARSERLIB) $(BTLDLIBS) $(QTLDLIBS)
-proxmark3: $(OBJDIR)/proxmark3.o $(COREOBJS) $(CMDOBJS) $(OBJCOBJS) $(QTGUIOBJS) $(LUALIB) $(JANSSONLIB) $(CBORLIB) $(REVENGLIB) $(MBEDTLSLIB) $(ZLIB) $(AMIIBOLIB) $(HARDNESTEDLIB) $(CLIPARSERLIB) lualibs/pm3_cmd.lua lualibs/mfc_default_keys.lua
+proxmark3: $(OBJDIR)/proxmark3.o $(COREOBJS) $(CMDOBJS) $(OBJCOBJS) $(QTGUIOBJS) liblua jansson tinycbor reveng mbedtls zlib amiibo hardnested cliparser lualibs/pm3_cmd.lua lualibs/mfc_default_keys.lua
$(info [=] LD $@)
$(Q)$(LD) $(LDFLAGS) $(OBJDIR)/proxmark3.o $(COREOBJS) $(CMDOBJS) $(OBJCOBJS) $(QTGUIOBJS) $(LDLIBS) -o $@
@@ -373,44 +373,44 @@ tarbin: $(BINS)
$(Q)$(TAR) $(TARFLAGS) ../proxmark3-$(platform)-bin.tar $(BINS:%=client/%) $(WINBINS:%=client/%)
# local libraries:
-$(LUALIB):
- $(info [*] MAKE liblua for $(LUAPLATFORM))
+liblua:
+ $(info [*] MAKE $@ for $(LUAPLATFORM))
$(Q)$(MAKE) --no-print-directory -C $(LUALIBPATH) $(LUAPLATFORM)
-$(JANSSONLIB):
- $(info [*] MAKE jansson)
+jansson:
+ $(info [*] MAKE $@)
$(Q)$(MAKE) --no-print-directory -C $(JANSSONLIBPATH) all
-$(CBORLIB):
- $(info [*] MAKE tinycbor)
+tinycbor:
+ $(info [*] MAKE $@)
$(Q)$(MAKE) --no-print-directory -C $(CBORLIBPATH) all
-$(REVENGLIB):
- $(info [*] MAKE reveng)
+reveng:
+ $(info [*] MAKE $@)
$(Q)$(MAKE) --no-print-directory -C $(REVENGPATH) all
-$(HARDNESTEDLIB):
- $(info [*] MAKE hardnested)
+hardnested:
+ $(info [*] MAKE $@)
$(Q)$(MAKE) --no-print-directory -C $(HARDNESTEDPATH) all
-$(AMIIBOLIB):
- $(info [*] MAKE amiibo)
+amiibo:
+ $(info [*] MAKE $@)
$(Q)$(MAKE) --no-print-directory -C $(AMIIBOLIBPATH) all
-$(CLIPARSERLIB):
- $(info [*] MAKE cliparser)
+cliparser:
+ $(info [*] MAKE $@)
$(Q)$(MAKE) --no-print-directory -C $(CLIPARSERPATH) all
# common libraries:
-$(MBEDTLSLIB):
- $(info [*] MAKE mbedtls)
+mbedtls:
+ $(info [*] MAKE $@)
$(Q)$(MAKE) --no-print-directory -C $(MBEDTLSLIBPATH) OBJDIR=$(ROOT_DIR)$(OBJDIR) BINDIR=$(ROOT_DIR)$(OBJDIR) all
-$(ZLIB):
- $(info [*] MAKE zlib)
+zlib:
+ $(info [*] MAKE $@)
$(Q)$(MAKE) --no-print-directory -C $(ZLIBPATH) OBJDIR=$(ROOT_DIR)$(OBJDIR) BINDIR=$(ROOT_DIR)$(OBJDIR) all
-.PHONY: all clean install uninstall
+.PHONY: all clean install uninstall tarbin liblua jansson tinycbor reveng hardnested amiibo cliparser mbedtls zlib
# easy printing of MAKE VARIABLES
print-%: ; @echo $* = $($*)
From 155d30ce49502f2caa4d0dee267774add6f90e39 Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Wed, 29 Apr 2020 19:19:26 +0200
Subject: [PATCH 025/632] coverity fix 226278 and offset computation as side
effect
---
armsrc/appmain.c | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/armsrc/appmain.c b/armsrc/appmain.c
index b05a143f0..e14319df9 100644
--- a/armsrc/appmain.c
+++ b/armsrc/appmain.c
@@ -1642,7 +1642,7 @@ static void PacketReceived(PacketCommandNG *packet) {
struct p {
uint8_t flag;
uint16_t offset;
- uint8_t *data;
+ uint8_t data[PM3_CMD_DATA_SIZE - sizeof(uint8_t) - sizeof(uint16_t)];
} PACKED;
struct p *payload = (struct p *)packet->data.asBytes;
@@ -1654,11 +1654,11 @@ static void PacketReceived(PacketCommandNG *packet) {
}
// 40 000 - (512-3) 509 = 39491
- uint16_t offset = MIN(BIGBUF_SIZE - PM3_CMD_DATA_SIZE - 3, payload->offset);
+ uint16_t offset = MIN(BIGBUF_SIZE - sizeof(payload->data), payload->offset);
// need to copy len bytes of data, not PM3_CMD_DATA_SIZE - 3 - offset
// ensure len bytes copied wont go past end of bigbuf
- uint16_t len = MIN(BIGBUF_SIZE - offset, PM3_CMD_DATA_SIZE - 3);
+ uint16_t len = MIN(BIGBUF_SIZE - offset, sizeof(payload->data));
uint8_t *mem = BigBuf_get_addr();
From a626725477ae58e0e4745a771c504acb2c1b34c3 Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Wed, 29 Apr 2020 19:41:10 +0200
Subject: [PATCH 026/632] lf sim: fix offset of last packet
---
armsrc/appmain.c | 7 ++-----
1 file changed, 2 insertions(+), 5 deletions(-)
diff --git a/armsrc/appmain.c b/armsrc/appmain.c
index e14319df9..2a185b394 100644
--- a/armsrc/appmain.c
+++ b/armsrc/appmain.c
@@ -1653,18 +1653,15 @@ static void PacketReceived(PacketCommandNG *packet) {
BigBuf_free();
}
- // 40 000 - (512-3) 509 = 39491
- uint16_t offset = MIN(BIGBUF_SIZE - sizeof(payload->data), payload->offset);
+ // offset should not be over buffer
+ uint16_t offset = MIN(BIGBUF_SIZE - 1, payload->offset);
- // need to copy len bytes of data, not PM3_CMD_DATA_SIZE - 3 - offset
// ensure len bytes copied wont go past end of bigbuf
uint16_t len = MIN(BIGBUF_SIZE - offset, sizeof(payload->data));
uint8_t *mem = BigBuf_get_addr();
- // x + 394
memcpy(mem + offset, &payload->data, len);
- // memcpy(mem + offset, &payload->data, PM3_CMD_DATA_SIZE - 3 - offset);
reply_ng(CMD_LF_UPLOAD_SIM_SAMPLES, PM3_SUCCESS, NULL, 0);
break;
}
From b3f84bf7b3459152e3bfef8e9c9928ff7ccc2236 Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Wed, 29 Apr 2020 19:41:45 +0200
Subject: [PATCH 027/632] make style
---
armsrc/frozen.c | 2 +-
client/src/cmdhfmfdes.c | 42 +++++------
client/src/loclass/cipher.c | 98 ++++++++++++-------------
client/src/mifare/desfire_crypto.c | 2 +-
client/src/preferences.c | 8 +-
tools/hitag2crack/crack5/ht2crack5.c | 6 +-
tools/hitag2crack/crack5gpu/ht2crack5.c | 2 +-
7 files changed, 80 insertions(+), 80 deletions(-)
diff --git a/armsrc/frozen.c b/armsrc/frozen.c
index 6477e0602..4abd21ebf 100644
--- a/armsrc/frozen.c
+++ b/armsrc/frozen.c
@@ -863,7 +863,7 @@ struct json_scanf_info {
int json_unescape(const char *src, int slen, char *dst, int dlen) WEAK;
int json_unescape(const char *src, int slen, char *dst, int dlen) {
if (dst == NULL || dlen == 0)
- return JSON_STRING_INVALID;
+ return JSON_STRING_INVALID;
char *send = (char *) src + slen;
char *dend = dst + dlen;
diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c
index be5975049..b8c2271e1 100644
--- a/client/src/cmdhfmfdes.c
+++ b/client/src/cmdhfmfdes.c
@@ -1900,7 +1900,7 @@ static int CmdHF14ADesCreateApp(const char *Cmd) {
if (res != PM3_SUCCESS) {
DropField();
return res;
- }
+ }
res = handler_desfire_createapp(&aidhdr, usename, usefid);
DropField();
@@ -3245,7 +3245,7 @@ static int CmdHF14ADesDump(const char *Cmd) {
PrintAndLogEx(NORMAL, "----------------------------------------------------------------------------");
int len = le24toh(fdata.length);
for (int n = 0; n < len; n += 16) {
- PrintAndLogEx(NORMAL, "%02d/0x%02X | %s| %s", n, n, sprint_hex(&fdata.data[n], len > 16 ? 16 : len), sprint_ascii(&fdata.data[n], len > 16 ? 16 : len));
+ PrintAndLogEx(NORMAL, "%02d/0x%02X | %s| %s", n, n, sprint_hex(&fdata.data[n], len > 16 ? 16 : len), sprint_ascii(&fdata.data[n], len > 16 ? 16 : len));
}
} else {
PrintAndLogEx(ERR, "Couldn't read value. Error %d", res);
@@ -3262,15 +3262,15 @@ static int CmdHF14ADesDump(const char *Cmd) {
int len = 0;
res = handler_desfire_getvalue(&value, &len);
if (res == PM3_SUCCESS) {
- PrintAndLogEx(NORMAL, "\nOffset | Value | Ascii");
- PrintAndLogEx(NORMAL, "----------------------------------------------------------------------------");
- for (int n = 0; n < len; n += 16) {
- PrintAndLogEx(NORMAL, "%02d/0x%02X | %s| %s", n, n, sprint_hex(&value.value[n], len > 16 ? 16 : len), sprint_ascii(&value.value[n], len > 16 ? 16 : len));
- }
+ PrintAndLogEx(NORMAL, "\nOffset | Value | Ascii");
+ PrintAndLogEx(NORMAL, "----------------------------------------------------------------------------");
+ for (int n = 0; n < len; n += 16) {
+ PrintAndLogEx(NORMAL, "%02d/0x%02X | %s| %s", n, n, sprint_hex(&value.value[n], len > 16 ? 16 : len), sprint_ascii(&value.value[n], len > 16 ? 16 : len));
+ }
} else {
- PrintAndLogEx(ERR, "Couldn't read value. Error %d", res);
- res = handler_desfire_select_application(aid);
- if (res != PM3_SUCCESS) continue;
+ PrintAndLogEx(ERR, "Couldn't read value. Error %d", res);
+ res = handler_desfire_select_application(aid);
+ if (res != PM3_SUCCESS) continue;
}
} else if (fileset_len == 1 + 1 + 2 + 3 + 3 + 3 + maclen) {
@@ -3294,15 +3294,15 @@ static int CmdHF14ADesDump(const char *Cmd) {
fdata.offset[2] = (offset >> 16) & 0xFF;
res = handler_desfire_readdata(&fdata, MFDES_RECORD_FILE);
if (res == PM3_SUCCESS) {
- PrintAndLogEx(NORMAL, "\nOffset | Data | Ascii");
- PrintAndLogEx(NORMAL, "----------------------------------------------------------------------------");
- int len = le24toh(fdata.length);
- for (int n = 0; n < len; n += 16) {
- PrintAndLogEx(NORMAL, "%02d/0x%02X | %s| %s", n, n, sprint_hex(&fdata.data[n], len > 16 ? 16 : len), sprint_ascii(&fdata.data[n], len > 16 ? 16 : len));
- }
+ PrintAndLogEx(NORMAL, "\nOffset | Data | Ascii");
+ PrintAndLogEx(NORMAL, "----------------------------------------------------------------------------");
+ int len = le24toh(fdata.length);
+ for (int n = 0; n < len; n += 16) {
+ PrintAndLogEx(NORMAL, "%02d/0x%02X | %s| %s", n, n, sprint_hex(&fdata.data[n], len > 16 ? 16 : len), sprint_ascii(&fdata.data[n], len > 16 ? 16 : len));
+ }
} else {
- res = handler_desfire_select_application(aid);
- if (res != PM3_SUCCESS) continue;
+ res = handler_desfire_select_application(aid);
+ if (res != PM3_SUCCESS) continue;
}
}
free(data);
@@ -3586,9 +3586,9 @@ void DesFill2bPattern(uint8_t deskeyList[MAX_KEYS_LIST_LEN][8], size_t *deskeyLi
}
*startPattern = pt;
- if ( (*deskeyListLen == MAX_KEYS_LIST_LEN) &&
- (*aeskeyListLen == MAX_KEYS_LIST_LEN) &&
- (*k3kkeyListLen == MAX_KEYS_LIST_LEN)) {
+ if ((*deskeyListLen == MAX_KEYS_LIST_LEN) &&
+ (*aeskeyListLen == MAX_KEYS_LIST_LEN) &&
+ (*k3kkeyListLen == MAX_KEYS_LIST_LEN)) {
break;
}
}
diff --git a/client/src/loclass/cipher.c b/client/src/loclass/cipher.c
index af5d4f3a3..080ff66f5 100644
--- a/client/src/loclass/cipher.c
+++ b/client/src/loclass/cipher.c
@@ -68,17 +68,17 @@ typedef struct {
* T (x 0 x 1 . . . . . . x 15 ) = x 0 ⊕ x 1 ⊕ x 5 ⊕ x 7 ⊕ x 10 ⊕ x 11 ⊕ x 14 ⊕ x 15 .
**/
static bool T(State state) {
-/*
- bool x0 = state.t & 0x8000;
- bool x1 = state.t & 0x4000;
- bool x5 = state.t & 0x0400;
- bool x7 = state.t & 0x0100;
- bool x10 = state.t & 0x0020;
- bool x11 = state.t & 0x0010;
- bool x14 = state.t & 0x0002;
- bool x15 = state.t & 0x0001;
- return x0 ^ x1 ^ x5 ^ x7 ^ x10 ^ x11 ^ x14 ^ x15;
-*/
+ /*
+ bool x0 = state.t & 0x8000;
+ bool x1 = state.t & 0x4000;
+ bool x5 = state.t & 0x0400;
+ bool x7 = state.t & 0x0100;
+ bool x10 = state.t & 0x0020;
+ bool x11 = state.t & 0x0010;
+ bool x14 = state.t & 0x0002;
+ bool x15 = state.t & 0x0001;
+ return x0 ^ x1 ^ x5 ^ x7 ^ x10 ^ x11 ^ x14 ^ x15;
+ */
#define _x0 ((state.t & 0x8000) >> 15 )
#define _x1 ((state.t & 0x4000) >> 14 )
#define _x5 ((state.t & 0x0400) >> 10 )
@@ -86,7 +86,7 @@ static bool T(State state) {
#define _x10 ((state.t & 0x0020) >> 5 )
#define _x11 ((state.t & 0x0010) >> 4 )
#define _x14 ((state.t & 0x0002) >> 1 )
-#define _x15 (state.t & 0x0001)
+#define _x15 (state.t & 0x0001)
return (_x0) ^ (_x1) ^ (_x5) ^ (_x7) ^ (_x10) ^ (_x11) ^ (_x14) ^ (_x15);
}
/**
@@ -114,49 +114,49 @@ static bool T(State state) {
* z 2 = (r 3 ∧ r 5 ) ⊕ (r 4 ∧ r 6 ) ⊕ r 7 ⊕ x
**/
static uint8_t _select(bool x, bool y, uint8_t r) {
- #define _r0 ((r >> 7) & 0x01)
- #define _r1 ((r >> 6) & 0x01)
- #define _r2 ((r >> 5) & 0x01)
- #define _r3 ((r >> 4) & 0x01)
- #define _r4 ((r >> 3) & 0x01)
- #define _r5 ((r >> 2) & 0x01)
- #define _r6 ((r >> 1) & 0x01)
- #define _r7 (r & 0x01)
+#define _r0 ((r >> 7) & 0x01)
+#define _r1 ((r >> 6) & 0x01)
+#define _r2 ((r >> 5) & 0x01)
+#define _r3 ((r >> 4) & 0x01)
+#define _r4 ((r >> 3) & 0x01)
+#define _r5 ((r >> 2) & 0x01)
+#define _r6 ((r >> 1) & 0x01)
+#define _r7 (r & 0x01)
- #define _z0 ( (_r0 & _r2) ^ ( _r1 & (!_r3)) ^ (_r2 | _r4) )
- #define _z1 ( (_r0 | _r2) ^ ( _r5 | _r7) ^_r1 ^ _r6 ^ x ^ y )
- #define _z2 ( (_r3 & (!_r5)) ^ (_r4 & _r6) ^ _r7 ^ x )
+#define _z0 ( (_r0 & _r2) ^ ( _r1 & (!_r3)) ^ (_r2 | _r4) )
+#define _z1 ( (_r0 | _r2) ^ ( _r5 | _r7) ^_r1 ^ _r6 ^ x ^ y )
+#define _z2 ( (_r3 & (!_r5)) ^ (_r4 & _r6) ^ _r7 ^ x )
-/*
- uint8_t r0 = r >> 7 & 0x1;
- uint8_t r1 = r >> 6 & 0x1;
- uint8_t r2 = r >> 5 & 0x1;
- uint8_t r3 = r >> 4 & 0x1;
- uint8_t r4 = r >> 3 & 0x1;
- uint8_t r5 = r >> 2 & 0x1;
- uint8_t r6 = r >> 1 & 0x1;
- uint8_t r7 = r & 0x1;
+ /*
+ uint8_t r0 = r >> 7 & 0x1;
+ uint8_t r1 = r >> 6 & 0x1;
+ uint8_t r2 = r >> 5 & 0x1;
+ uint8_t r3 = r >> 4 & 0x1;
+ uint8_t r4 = r >> 3 & 0x1;
+ uint8_t r5 = r >> 2 & 0x1;
+ uint8_t r6 = r >> 1 & 0x1;
+ uint8_t r7 = r & 0x1;
- bool z0 = (r0 & r2) ^ (r1 & (!r3)) ^ (r2 | r4);
- bool z1 = (r0 | r2) ^ (r5 | r7) ^ r1 ^ r6 ^ x ^ y;
- bool z2 = (r3 & (!r5)) ^ (r4 & r6) ^ r7 ^ x;
+ bool z0 = (r0 & r2) ^ (r1 & (!r3)) ^ (r2 | r4);
+ bool z1 = (r0 | r2) ^ (r5 | r7) ^ r1 ^ r6 ^ x ^ y;
+ bool z2 = (r3 & (!r5)) ^ (r4 & r6) ^ r7 ^ x;
- // The three bitz z0.. z1 are packed into a uint8_t:
- // 00000ZZZ
- //Return value is a uint8_t
- return ((z0 << 2) & 4) | ((z1 << 1) & 2) | (z2 & 1);
-*/
- return ((_z0 << 2) & 4) | ((_z1 << 1) & 2) | (_z2 & 1);
+ // The three bitz z0.. z1 are packed into a uint8_t:
+ // 00000ZZZ
+ //Return value is a uint8_t
+ return ((z0 << 2) & 4) | ((z1 << 1) & 2) | (z2 & 1);
+ */
+ return ((_z0 << 2) & 4) | ((_z1 << 1) & 2) | (_z2 & 1);
-/*
- uint8_t retval = 0;
- retval |= (z0 << 2) & 4;
- retval |= (z1 << 1) & 2;
- retval |= (z2) & 1;
+ /*
+ uint8_t retval = 0;
+ retval |= (z0 << 2) & 4;
+ retval |= (z1 << 1) & 2;
+ retval |= (z2) & 1;
- // Return value 0 <= retval <= 7
- return retval;
-*/
+ // Return value 0 <= retval <= 7
+ return retval;
+ */
}
/**
diff --git a/client/src/mifare/desfire_crypto.c b/client/src/mifare/desfire_crypto.c
index a0e066b44..2cb9d7c3a 100644
--- a/client/src/mifare/desfire_crypto.c
+++ b/client/src/mifare/desfire_crypto.c
@@ -282,7 +282,7 @@ void cmac_generate_subkeys(desfirekey_t key) {
void cmac(const desfirekey_t key, uint8_t *ivect, const uint8_t *data, size_t len, uint8_t *cmac) {
int kbs = key_block_size(key);
if (kbs == 0) {
- return;
+ return;
}
uint8_t *buffer = malloc(padded_data_length(len, kbs));
diff --git a/client/src/preferences.c b/client/src/preferences.c
index b0534a671..4f92eb06e 100644
--- a/client/src/preferences.c
+++ b/client/src/preferences.c
@@ -95,7 +95,7 @@ int preferences_load(void) {
size_t dummyDL = 0x00;
// to better control json cant find file error msg.
- char* fn = prefGetFilename();
+ char *fn = prefGetFilename();
if (fileExists(fn)) {
PrintAndLogEx(INFO, "Loading Preferences...");
if (loadFileJSON(fn, &dummyData, sizeof(dummyData), &dummyDL) == PM3_SUCCESS) {
@@ -115,11 +115,11 @@ int preferences_save(void) {
PrintAndLogEx(INFO, "Saving Preferences...");
- char* fn = prefGetFilename();
+ char *fn = prefGetFilename();
int fnLen = strlen(fn) + 5; // .bak\0
// [FILENAME_MAX+sizeof(preferencesFilename)+10]
- char* backupFilename = (char *)calloc(fnLen, sizeof(uint8_t));
+ char *backupFilename = (char *)calloc(fnLen, sizeof(uint8_t));
if (backupFilename == NULL) {
PrintAndLogEx(ERR, "failed to allocate memory");
free(fn);
@@ -916,7 +916,7 @@ int CmdPrefSet(const char *Cmd) {
static int CmdPrefShow(const char *Cmd) {
- char* fn = prefGetFilename();
+ char *fn = prefGetFilename();
PrintAndLogEx(NORMAL, "");
PrintAndLogEx(NORMAL, _CYAN_("Preferences loaded from %s"), fn);
diff --git a/tools/hitag2crack/crack5/ht2crack5.c b/tools/hitag2crack/crack5/ht2crack5.c
index 79557bbfd..7f10ccd6b 100644
--- a/tools/hitag2crack/crack5/ht2crack5.c
+++ b/tools/hitag2crack/crack5/ht2crack5.c
@@ -117,9 +117,9 @@ int main(int argc, char *argv[]) {
uint32_t target = 0;
#ifndef __WIN32
- thread_count = sysconf(_SC_NPROCESSORS_CONF);
- if ( thread_count < 2)
- thread_count = 2;
+ thread_count = sysconf(_SC_NPROCESSORS_CONF);
+ if (thread_count < 2)
+ thread_count = 2;
#endif /* _WIN32 */
diff --git a/tools/hitag2crack/crack5gpu/ht2crack5.c b/tools/hitag2crack/crack5gpu/ht2crack5.c
index adaf1ae82..cfacecc98 100644
--- a/tools/hitag2crack/crack5gpu/ht2crack5.c
+++ b/tools/hitag2crack/crack5gpu/ht2crack5.c
@@ -236,7 +236,7 @@ int main(int argc, char *argv[]) {
for (size_t i0 = 0; i0 < 1 << 20; i0++) {
uint64_t state0 = expand(0x5806b4a2d16c, i0);
- if (f(state0) == target >> 31 ) {
+ if (f(state0) == target >> 31) {
// cf kernel, state is now split in 3 shorts >> 2
candidates[(layer_0_found * 3) + 0] = (uint16_t)((state0 >> (32 + 2)) & 0xffff);
candidates[(layer_0_found * 3) + 1] = (uint16_t)((state0 >> (16 + 2)) & 0xffff);
From 1410d4d9b5cd63f3b4a116d82220a3c767c4048b Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Wed, 29 Apr 2020 20:07:04 +0200
Subject: [PATCH 028/632] lf sim: better to return err on faulty offset, thanks
@iceman
---
armsrc/appmain.c | 10 ++++++----
1 file changed, 6 insertions(+), 4 deletions(-)
diff --git a/armsrc/appmain.c b/armsrc/appmain.c
index 2a185b394..abfe6a86e 100644
--- a/armsrc/appmain.c
+++ b/armsrc/appmain.c
@@ -1654,14 +1654,16 @@ static void PacketReceived(PacketCommandNG *packet) {
}
// offset should not be over buffer
- uint16_t offset = MIN(BIGBUF_SIZE - 1, payload->offset);
-
+ if (payload->offset >= BIGBUF_SIZE) {
+ reply_ng(CMD_LF_UPLOAD_SIM_SAMPLES, PM3_EOVFLOW, NULL, 0);
+ break;
+ }
// ensure len bytes copied wont go past end of bigbuf
- uint16_t len = MIN(BIGBUF_SIZE - offset, sizeof(payload->data));
+ uint16_t len = MIN(BIGBUF_SIZE - payload->offset, sizeof(payload->data));
uint8_t *mem = BigBuf_get_addr();
- memcpy(mem + offset, &payload->data, len);
+ memcpy(mem + payload->offset, &payload->data, len);
reply_ng(CMD_LF_UPLOAD_SIM_SAMPLES, PM3_SUCCESS, NULL, 0);
break;
}
From f1f3742333dad729b342aee2dca164a6e8d0298f Mon Sep 17 00:00:00 2001
From: iceman1001
Date: Wed, 29 Apr 2020 20:09:23 +0200
Subject: [PATCH 029/632] coverity fix 279922
---
armsrc/desfire_crypto.c | 10 +++++++---
1 file changed, 7 insertions(+), 3 deletions(-)
diff --git a/armsrc/desfire_crypto.c b/armsrc/desfire_crypto.c
index 99bb54743..db543bbe6 100644
--- a/armsrc/desfire_crypto.c
+++ b/armsrc/desfire_crypto.c
@@ -36,6 +36,7 @@
#include "printf.h"
#include "iso14443a.h"
#include "dbprint.h"
+#include "BigBuf.h"
#ifndef AddCrc14A
# define AddCrc14A(data, len) compute_crc(CRC_14443_A, (data), (len), (data)+(len), (data)+(len)+1)
@@ -282,7 +283,10 @@ void cmac_generate_subkeys(desfirekey_t key) {
void cmac(const desfirekey_t key, uint8_t *ivect, const uint8_t *data, size_t len, uint8_t *cmac) {
int kbs = key_block_size(key);
- uint8_t *buffer = malloc(padded_data_length(len, kbs));
+ if (kbs == 0)
+ return;
+
+ uint8_t *buffer = BigBuf_malloc(padded_data_length(len, kbs));
memcpy(buffer, data, len);
@@ -299,7 +303,7 @@ void cmac(const desfirekey_t key, uint8_t *ivect, const uint8_t *data, size_t le
mifare_cypher_blocks_chained(NULL, key, ivect, buffer, len, MCD_SEND, MCO_ENCYPHER);
memcpy(cmac, ivect, kbs);
- free(buffer);
+ //free(buffer);
}
size_t key_block_size(const desfirekey_t key) {
@@ -538,7 +542,7 @@ void *mifare_cryto_postprocess_data(desfiretag_t tag, void *data, size_t *nbytes
}
size_t edl = enciphered_data_length(tag, *nbytes - 1, communication_settings);
- edata = malloc(edl);
+ edata = BigBuf_malloc(edl);
memcpy(edata, data, *nbytes - 1);
memset((uint8_t *)edata + *nbytes - 1, 0, edl - *nbytes + 1);
From 07f41da74d12f1bf8a58b3b7dad89d00c9651d2b Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Wed, 29 Apr 2020 20:11:32 +0200
Subject: [PATCH 030/632] fix coverity 226490 even if in practice
next_common_bits is never > 7
---
client/deps/hardnested/hardnested_bf_core.c | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/client/deps/hardnested/hardnested_bf_core.c b/client/deps/hardnested/hardnested_bf_core.c
index 45a996879..9402d9684 100644
--- a/client/deps/hardnested/hardnested_bf_core.c
+++ b/client/deps/hardnested/hardnested_bf_core.c
@@ -324,7 +324,7 @@ uint64_t CRACK_STATES_BITSLICED(uint32_t cuid, uint8_t *best_first_bytes, statel
crypto1_bs_f20b_2[0] = f20b(state_p[47 - 25].value, state_p[47 - 27].value, state_p[47 - 29].value, state_p[47 - 31].value);
crypto1_bs_f20b_3[0] = f20b(state_p[47 - 41].value, state_p[47 - 43].value, state_p[47 - 45].value, state_p[47 - 47].value);
- bitslice_value_t ksb[9];
+ bitslice_value_t ksb[8];
ksb[0] = f20c(f20a(state_p[47 - 9].value, state_p[47 - 11].value, state_p[47 - 13].value, state_p[47 - 15].value),
f20b(state_p[47 - 17].value, state_p[47 - 19].value, state_p[47 - 21].value, state_p[47 - 23].value),
crypto1_bs_f20b_2[0],
@@ -347,14 +347,14 @@ uint64_t CRACK_STATES_BITSLICED(uint32_t cuid, uint8_t *best_first_bytes, statel
}
// pre-compute first feedback bit vector. This is the same for all nonces
- bitslice_value_t fbb[9];
+ bitslice_value_t fbb[8];
fbb[0] = odd_feedback ^ bitsliced_even_feedback[block_idx];
// vector to contain test results (1 = passed, 0 = failed)
bitslice_t results = bs_ones;
// parity_bits
- bitslice_value_t par[9];
+ bitslice_value_t par[8];
par[0] = bs_zeroes.value;
uint32_t next_common_bits = 0;
@@ -468,7 +468,7 @@ uint64_t CRACK_STATES_BITSLICED(uint32_t cuid, uint8_t *best_first_bytes, statel
}
// remember feedback and keystream vectors for later use
uint8_t bit = KEYSTREAM_SIZE - ks_idx;
- if (bit <= next_common_bits) { // if needed and not yet stored
+ if (bit <= MIN(next_common_bits, 7)) { // if needed and not yet stored
fbb[bit] = fb_bits;
ksb[bit] = ks_bits;
par[bit] = parity_bit_vector;
From 31ccc7d7ca14f9df885bda5d0d150ef5e6e8a0af Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Wed, 29 Apr 2020 20:20:06 +0200
Subject: [PATCH 031/632] hardnested: don't drop field when in test mode
---
client/src/cmdhfmf.c | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c
index 8c6247614..95e821781 100644
--- a/client/src/cmdhfmf.c
+++ b/client/src/cmdhfmf.c
@@ -1866,7 +1866,7 @@ static int CmdHF14AMfNestedHard(const char *Cmd) {
uint64_t foundkey = 0;
int16_t isOK = mfnestedhard(blockNo, keyType, key, trgBlockNo, trgKeyType, know_target_key ? trgkey : NULL, nonce_file_read, nonce_file_write, slow, tests, &foundkey, filename);
- DropField();
+ if (tests == 0) DropField();
if (isOK) {
switch (isOK) {
case 1 :
From fa44eee82c0368508fbbcdc9df1dadd930aff852 Mon Sep 17 00:00:00 2001
From: iceman1001
Date: Wed, 29 Apr 2020 20:33:29 +0200
Subject: [PATCH 032/632] chg: "lf sim" - now only fills until bigbuffer is
full
---
client/src/cmdlf.c | 10 +++++++---
1 file changed, 7 insertions(+), 3 deletions(-)
diff --git a/client/src/cmdlf.c b/client/src/cmdlf.c
index 1443a5d6a..9324062a1 100644
--- a/client/src/cmdlf.c
+++ b/client/src/cmdlf.c
@@ -702,6 +702,8 @@ int CmdLFSim(const char *Cmd) {
PrintAndLogEx(DEBUG, "DEBUG: Uploading %zu bytes", GraphTraceLen);
+ PacketResponseNG resp;
+
struct pupload {
uint8_t flag;
uint16_t offset;
@@ -726,9 +728,12 @@ int CmdLFSim(const char *Cmd) {
for (uint16_t j = 0; j < len; j++)
payload_up.data[j] = GraphBuffer[i + j];
-
SendCommandNG(CMD_LF_UPLOAD_SIM_SAMPLES, (uint8_t *)&payload_up, sizeof(struct pupload));
- WaitForResponse(CMD_LF_UPLOAD_SIM_SAMPLES, NULL);
+ WaitForResponse(CMD_LF_UPLOAD_SIM_SAMPLES, &resp);
+ if (resp.status != PM3_SUCCESS) {
+ PrintAndLogEx(INFO, "Bigbuf is full.");
+ break;
+ }
printf(".");
fflush(stdout);
payload_up.flag = 0;
@@ -750,7 +755,6 @@ int CmdLFSim(const char *Cmd) {
clearCommandBuffer();
SendCommandNG(CMD_LF_SIMULATE, (uint8_t *)&payload, sizeof(payload));
- PacketResponseNG resp;
WaitForResponse(CMD_LF_SIMULATE, &resp);
PrintAndLogEx(INFO, "Done");
From 00fb88ee4c85ed2268eb9705bb8ec519e125cb5b Mon Sep 17 00:00:00 2001
From: iceman1001
Date: Wed, 29 Apr 2020 20:34:47 +0200
Subject: [PATCH 033/632] cppcheck fix, make var conditional
---
armsrc/cmd.c | 8 ++++++++
1 file changed, 8 insertions(+)
diff --git a/armsrc/cmd.c b/armsrc/cmd.c
index c7f76960b..17534cbf1 100644
--- a/armsrc/cmd.c
+++ b/armsrc/cmd.c
@@ -62,7 +62,9 @@ int reply_old(uint64_t cmd, uint64_t arg0, uint64_t arg1, uint64_t arg2, void *d
}
}
+#ifdef WITH_FPC_USART_HOST
int resultfpc = PM3_EUNDEF;
+#endif
int resultusb = PM3_EUNDEF;
// Send frame and make sure all bytes are transmitted
@@ -79,7 +81,9 @@ int reply_old(uint64_t cmd, uint64_t arg0, uint64_t arg1, uint64_t arg2, void *d
}
// we got two results, let's prioritize the faulty one and USB over FPC.
if (reply_via_usb && (resultusb != PM3_SUCCESS)) return resultusb;
+#ifdef WITH_FPC_USART_HOST
if (reply_via_fpc && (resultfpc != PM3_SUCCESS)) return resultfpc;
+#endif
return PM3_SUCCESS;
}
@@ -117,7 +121,9 @@ static int reply_ng_internal(uint16_t cmd, int16_t status, uint8_t *data, size_t
}
txBufferNGLen = sizeof(PacketResponseNGPreamble) + len + sizeof(PacketResponseNGPostamble);
+#ifdef WITH_FPC_USART_HOST
int resultfpc = PM3_EUNDEF;
+#endif
int resultusb = PM3_EUNDEF;
// Send frame and make sure all bytes are transmitted
@@ -133,7 +139,9 @@ static int reply_ng_internal(uint16_t cmd, int16_t status, uint8_t *data, size_t
}
// we got two results, let's prioritize the faulty one and USB over FPC.
if (reply_via_usb && (resultusb != PM3_SUCCESS)) return resultusb;
+#ifdef WITH_FPC_USART_HOST
if (reply_via_fpc && (resultfpc != PM3_SUCCESS)) return resultfpc;
+#endif
return PM3_SUCCESS;
}
From f9eb1d3d77cf6ada8e36556fda8616ca3e477e2b Mon Sep 17 00:00:00 2001
From: Uli Heilmeier
Date: Wed, 29 Apr 2020 22:52:41 +0200
Subject: [PATCH 034/632] Makefile: fix PKG_CONFIG_ENV
renaming PKG_CONFIG_PATH to PKG_CONFIG_ENV was too greedy
---
client/Makefile | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/client/Makefile b/client/Makefile
index f62d7ab49..63860874d 100644
--- a/client/Makefile
+++ b/client/Makefile
@@ -83,7 +83,7 @@ else
LDLIBS := -L/usr/local/opt/readline/lib $(LDLIBS)
LIBS := -I/usr/local/opt/readline/include $(LIBS)
# cf brew info qt: qt not symlinked anymore
- PKG_CONFIG_ENV := PKG_CONFIG_ENV=/usr/local/opt/qt/lib/pkgconfig
+ PKG_CONFIG_ENV := PKG_CONFIG_PATH=/usr/local/opt/qt/lib/pkgconfig
else
LUALIB += -ldl
LUAPLATFORM = linux
From 40c596e8af7a52bc30069eae11ed78423ce204a8 Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Fri, 1 May 2020 00:08:07 +0200
Subject: [PATCH 035/632] client Makefile: allow to add includes (e.g. for
termux)
---
client/Makefile | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/client/Makefile b/client/Makefile
index 63860874d..e8358757e 100644
--- a/client/Makefile
+++ b/client/Makefile
@@ -54,7 +54,7 @@ ZLIBPATH = ../common/zlib
ZLIB = $(OBJDIR)/libz.a
LIBS = -I$(LUALIBPATH) -I$(MBEDTLSLIBPATH) -I$(JANSSONLIBPATH) -I$(CBORLIBPATH) -I$(ZLIBPATH) -I$(REVENGPATH) -I$(AMIIBOLIBPATH) -I$(HARDNESTEDPATH) -I$(CLIPARSERPATH)
-INCLUDES_CLIENT = -I./src -I../include -I../common -I../common_fpga $(LIBS)
+INCLUDES_CLIENT += -I./src -I../include -I../common -I../common_fpga $(LIBS)
CFLAGS ?= -Wall -Werror -O3
# We cannot just use CFLAGS+=... because it has impact on sub-makes if CFLAGS is defined in env:
PM3CFLAGS = $(CFLAGS) $(INCLUDES_CLIENT)
From f158f347e5b211f3a2a7b723b9509bd62950a095 Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Fri, 1 May 2020 00:13:56 +0200
Subject: [PATCH 036/632] reveng Makefile: allow to skip test (e.g. for
cross-compilation)
---
client/deps/reveng/Makefile | 2 ++
1 file changed, 2 insertions(+)
diff --git a/client/deps/reveng/Makefile b/client/deps/reveng/Makefile
index 1794b0bdb..0dbfa6007 100644
--- a/client/deps/reveng/Makefile
+++ b/client/deps/reveng/Makefile
@@ -22,6 +22,7 @@ MYCLEANOLDPATH = ../../reveng
include ../../../Makefile.host
+ifneq ($(SKIPREVENGTEST),1)
CLEAN += bmptst
$(BINDIR)/$(LIB_A): $(BINDIR)/bmptst
@@ -31,5 +32,6 @@ $(BINDIR)/bmptst: bmpbit.c config.h reveng.h
$(Q)$(CC) $(CFLAGS) -DBMPTST -o $@ $<
$(info [=] TEST $@)
$(Q)( ./$@ && $(TOUCH) $@ ) || ( $(RM) $@ && $(FALSE) )
+endif
.PHONY: all clean
From 43b69bd4e46dd8f08889275f5cce4377b8bfa44c Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Fri, 1 May 2020 00:25:04 +0200
Subject: [PATCH 037/632] client Makefile: link with pthread only if needed
---
client/Makefile | 10 +++++++---
1 file changed, 7 insertions(+), 3 deletions(-)
diff --git a/client/Makefile b/client/Makefile
index e8358757e..10cf51749 100644
--- a/client/Makefile
+++ b/client/Makefile
@@ -22,13 +22,17 @@ vpath %.dic dictionaries
OBJDIR = obj
LDLIBS ?= -L/usr/local/lib
-LDLIBS += -lreadline -lpthread -lm
+LDLIBS += -lreadline -lm
-# RPi Zero gcc requires -latomic
-# but MacOSX /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld
+# MacOSX /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld
# doesn't recognize option --as-needed
ifneq ($(platform),Darwin)
+# RPi Zero gcc requires -latomic
LDLIBS += -Wl,--as-needed -latomic -Wl,--no-as-needed
+# Android Termux doesn't have pthread
+ LDLIBS += -Wl,--as-needed -lpthread -Wl,--no-as-needed
+else
+ LDLIBS += -lpthread
endif
# local libraries
From 6d0afbdbf3e271e248e2c76aa60e00740e5c7ee6 Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Fri, 1 May 2020 00:28:28 +0200
Subject: [PATCH 038/632] Revert "client Makefile: link with pthread only if
needed"
This reverts commit 43b69bd4e46dd8f08889275f5cce4377b8bfa44c.
---
client/Makefile | 10 +++-------
1 file changed, 3 insertions(+), 7 deletions(-)
diff --git a/client/Makefile b/client/Makefile
index 10cf51749..e8358757e 100644
--- a/client/Makefile
+++ b/client/Makefile
@@ -22,17 +22,13 @@ vpath %.dic dictionaries
OBJDIR = obj
LDLIBS ?= -L/usr/local/lib
-LDLIBS += -lreadline -lm
+LDLIBS += -lreadline -lpthread -lm
-# MacOSX /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld
+# RPi Zero gcc requires -latomic
+# but MacOSX /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld
# doesn't recognize option --as-needed
ifneq ($(platform),Darwin)
-# RPi Zero gcc requires -latomic
LDLIBS += -Wl,--as-needed -latomic -Wl,--no-as-needed
-# Android Termux doesn't have pthread
- LDLIBS += -Wl,--as-needed -lpthread -Wl,--no-as-needed
-else
- LDLIBS += -lpthread
endif
# local libraries
From 475ec09b609d5a7ea681bdcd3c59f331cca3b9a6 Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Fri, 1 May 2020 00:49:13 +0200
Subject: [PATCH 039/632] more tips for maintainers
---
doc/md/Development/Maintainers.md | 12 ++++++++++++
1 file changed, 12 insertions(+)
diff --git a/doc/md/Development/Maintainers.md b/doc/md/Development/Maintainers.md
index ff3525784..705d97707 100644
--- a/doc/md/Development/Maintainers.md
+++ b/doc/md/Development/Maintainers.md
@@ -53,6 +53,18 @@ For verbose usage and see the actual commands being executed, add `V=1`.
Default compiler is gcc but you can use clang for the non-ARM parts with e.g. `make client CC=clang CXX=clang++ LD=clang++`.
+If your platform needs specific lib/include paths for the client, you can use `LDLIBS` and `INCLUDES_CLIENT` *as envvars*, e.g. `LDLIBS="-L/some/more/lib" INCLUDES_CLIENT="-I/some/more/include" make client ...`
+
+It's also possible to skip parts even if libraries are present in the compilation environment:
+
+* `make client SKIPQT=1` to skip GUI even if Qt is present
+* `make client SKIPBT=1` to skip native Bluetooth support even if libbluetooth is present
+
+If you're cross-compiling, these ones might be useful:
+
+* `make client SKIPREVENGTEST=1` to skip compilation and execution of a consistency test for reveng, which can be problematic in case of cross-compilation
+* `make client cpu_arch=generic` to skip Intel specialized hardnested components, which is required e.g. if cross-compilation host is Intel but not the target
+
`make install` is actually triggering the following individual targets which can be accessed individually:
* `make client/install`
From a17ad052610cd7ac1c85e72de37a9a7e09701a1b Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Fri, 1 May 2020 00:58:54 +0200
Subject: [PATCH 040/632] doc
---
doc/bt_manual_v10.md | 2 ++
1 file changed, 2 insertions(+)
diff --git a/doc/bt_manual_v10.md b/doc/bt_manual_v10.md
index c009ba025..1ae8bef29 100644
--- a/doc/bt_manual_v10.md
+++ b/doc/bt_manual_v10.md
@@ -116,6 +116,8 @@ Scanning ...
Instead of `aa:bb:cc:dd:ee:ff`, you'll see your MAC address.
+If you don't have `hcitool`, you can use `bluetoothctl` and `scan on` as shown in next section.
+
2. Use Proxmark client with Bluetooth MAC address as bt:
```sh
./proxmark3 bt:aa:bb:cc:dd:ee:ff
From 8710e9c3a09ac4ac757af3c9222e161cb6e588a4 Mon Sep 17 00:00:00 2001
From: Iceman
Date: Sat, 2 May 2020 17:21:33 +0200
Subject: [PATCH 041/632] Update bt_manual_v10.md
---
doc/bt_manual_v10.md | 13 ++++++++++---
1 file changed, 10 insertions(+), 3 deletions(-)
diff --git a/doc/bt_manual_v10.md b/doc/bt_manual_v10.md
index 1ae8bef29..42f8c04b9 100644
--- a/doc/bt_manual_v10.md
+++ b/doc/bt_manual_v10.md
@@ -1,6 +1,6 @@
# MANUAL
### Bluetooth / Battery add-on 'Blue Shark'
-_rev. v1.0 (draft)_
+_rev. v1.0_
### 1. FEATURES
@@ -55,10 +55,12 @@ https://github.com/RfidResearchGroup/proxmark3
To compile the client and firmware with FPC support, the easiest way is to
1. Copy the sample file: `Makefile.platform.sample` ⇒ `Makefile.platform`
+ * `mv Makefile.platform.sample Makefile.platform`
2. Edit `Makefile.platform`, uncomment the line `#PLATFORM_EXTRAS=BTADDON` by removing the `#`
3. Recompile the project:
- * `make clean; make -j8`
+ * `make clean; make -j`
4. Flash the firmware
+ * `./pm3-flash-fullimage`
You are now ready to run the client with the serial port you got from your BT device on your laptop etc.
See instructions below.
@@ -87,6 +89,11 @@ You can also switch serial port from inside the proxmark3 client using the new c
* Enter the paired password 1234 and establish the connection.
* The blue state LED on the add-on will keep blinking after the connection is established. Only when the mobile phone or computer opens the correct COM port, the blue LED turns on solid, indicating that the connection is successful.
+
+
+
+* First time you do this you might need to go into Bluetooth more settings and add a outgoing com port.
+
#### (2) Fast connection using dedicated USB Bluetooth adapter under Windows
@@ -129,7 +136,7 @@ restart it again after pairing.
If your OS doesn't prompt you for pairing, you can do it in command line, e.g. (again, replace with your addon MAC address):
```sh
-bluetoothctl
+sudo bluetoothctl
[bluetooth]# pairable on
[bluetooth]# scan on
Discovery started
From 96b53c4e2ae4d443e98ef2a0ed43ac7ea246b930 Mon Sep 17 00:00:00 2001
From: iceman1001
Date: Sat, 2 May 2020 17:23:27 +0200
Subject: [PATCH 042/632] chg: add bluetooth group to "make accessrights"
---
Makefile | 2 ++
1 file changed, 2 insertions(+)
diff --git a/Makefile b/Makefile
index 5c7947fc5..efb7b9a7a 100644
--- a/Makefile
+++ b/Makefile
@@ -186,8 +186,10 @@ udev:
accessrights:
ifneq ($(wildcard /etc/arch-release),) #If user is running ArchLinux
sudo usermod -aG uucp $(USER) #Use specific command and group
+ sudo usermod -aG bluetooth ${USER}
else
sudo adduser $(USER) dialout
+ sudo adduser ${USER} bluetooth
endif
# easy printing of MAKE VARIABLES
From c05e1d8beb5bc8a7ec36be16d62df9e88e0f4dfa Mon Sep 17 00:00:00 2001
From: iceman1001
Date: Sat, 2 May 2020 17:27:07 +0200
Subject: [PATCH 043/632] chg: missing tabs
---
Makefile | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/Makefile b/Makefile
index efb7b9a7a..1da96fa2e 100644
--- a/Makefile
+++ b/Makefile
@@ -186,10 +186,10 @@ udev:
accessrights:
ifneq ($(wildcard /etc/arch-release),) #If user is running ArchLinux
sudo usermod -aG uucp $(USER) #Use specific command and group
- sudo usermod -aG bluetooth ${USER}
+ sudo usermod -aG bluetooth $(USER) #Use specific command and group
else
sudo adduser $(USER) dialout
- sudo adduser ${USER} bluetooth
+ sudo adduser $(USER) bluetooth
endif
# easy printing of MAKE VARIABLES
From 96f03b4933e887ba6878b344bd701db8ab3db5c0 Mon Sep 17 00:00:00 2001
From: iceman1001
Date: Sat, 2 May 2020 17:52:22 +0100
Subject: [PATCH 044/632] chg: leanient parsing of tcp:/bt:/socket: vars
---
client/src/uart/uart_posix.c | 43 +++++++++++++++++++++++++++---------
1 file changed, 32 insertions(+), 11 deletions(-)
diff --git a/client/src/uart/uart_posix.c b/client/src/uart/uart_posix.c
index cf0837845..8a624934d 100644
--- a/client/src/uart/uart_posix.c
+++ b/client/src/uart/uart_posix.c
@@ -93,12 +93,27 @@ serial_port uart_open(const char *pcPortName, uint32_t speed) {
// init timeouts
timeout.tv_usec = UART_FPC_CLIENT_RX_TIMEOUT_MS * 1000;
- if (memcmp(pcPortName, "tcp:", 4) == 0) {
- struct addrinfo *addr = NULL, *rp;
- char *addrstr = strdup(pcPortName + 4);
+ char *prefix = strdup(pcPortName);
+ if (prefix == NULL) {
+ PrintAndLogEx(ERR, "error: malloc");
+ free(sp);
+ return INVALID_SERIAL_PORT;
+ }
+ str_lower(prefix);
+ if (memcmp(prefix, "tcp:", 4) == 0) {
+ free(prefix);
+
+ if (strlen(pcPortName) <= 4) {
+ free(sp);
+ return INVALID_SERIAL_PORT;
+ }
+
+ struct addrinfo *addr = NULL, *rp;
+
+ char *addrstr = strdup(pcPortName + 4);
if (addrstr == NULL) {
- printf("Error: strdup\n");
+ PrintAndLogEx(ERR, "error: malloc");
free(sp);
return INVALID_SERIAL_PORT;
}
@@ -122,7 +137,7 @@ serial_port uart_open(const char *pcPortName, uint32_t speed) {
int s = getaddrinfo(addrstr, portstr, &info, &addr);
if (s != 0) {
- printf("Error: getaddrinfo: %s\n", gai_strerror(s));
+ PrintAndLogEx(ERR, "error: getaddrinfo: %s", gai_strerror(s));
freeaddrinfo(addr);
free(addrstr);
free(sp);
@@ -143,7 +158,7 @@ serial_port uart_open(const char *pcPortName, uint32_t speed) {
}
if (rp == NULL) { /* No address succeeded */
- printf("Error: Could not connect\n");
+ PrintAndLogEx(ERR, "error: Could not connect");
freeaddrinfo(addr);
free(addrstr);
free(sp);
@@ -164,16 +179,18 @@ serial_port uart_open(const char *pcPortName, uint32_t speed) {
return sp;
}
- if (memcmp(pcPortName, "bt:", 3) == 0) {
+ if (memcmp(prefix, "bt:", 3) == 0) {
+ free(prefix);
+
#ifdef HAVE_BLUEZ
if (strlen(pcPortName) != 20) {
free(sp);
return INVALID_SERIAL_PORT;
}
- char *addrstr = strndup(pcPortName + 3, 17);
+ char *addrstr = strndup(pcPortName + 3, 17);
if (addrstr == NULL) {
- printf("Error: malloc\n");
+ PrintAndLogEx(ERR, "error: malloc");
free(sp);
return INVALID_SERIAL_PORT;
}
@@ -214,7 +231,9 @@ serial_port uart_open(const char *pcPortName, uint32_t speed) {
// Is local socket buffer, not a TCP or any net connection!
// so, you can't connect with address like: 127.0.0.1, or any IP
// see http://man7.org/linux/man-pages/man7/unix.7.html
- if (memcmp(pcPortName, "socket:", 7) == 0) {
+ if (memcmp(prefix, "socket:", 7) == 0) {
+ free(prefix);
+
if (strlen(pcPortName) <= 7) {
free(sp);
return INVALID_SERIAL_PORT;
@@ -255,6 +274,8 @@ serial_port uart_open(const char *pcPortName, uint32_t speed) {
return sp;
}
+ free(prefix);
+
sp->fd = open(pcPortName, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);
if (sp->fd == -1) {
uart_close(sp);
@@ -311,7 +332,7 @@ serial_port uart_open(const char *pcPortName, uint32_t speed) {
speed = 115200;
if (!uart_set_speed(sp, speed)) {
uart_close(sp);
- printf("[!] UART error while setting baudrate\n");
+ PrintAndLogEx(ERR, "UART error while setting baudrate");
return INVALID_SERIAL_PORT;
}
}
From 796cd36f85bfaf794df6ceaebbea9b3b4c55ece1 Mon Sep 17 00:00:00 2001
From: iceman1001
Date: Sat, 2 May 2020 19:24:52 +0200
Subject: [PATCH 045/632] chg: better error message when serial port allocation
fails
---
client/src/uart/uart_posix.c | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)
diff --git a/client/src/uart/uart_posix.c b/client/src/uart/uart_posix.c
index 8a624934d..076c02ddf 100644
--- a/client/src/uart/uart_posix.c
+++ b/client/src/uart/uart_posix.c
@@ -88,7 +88,11 @@ int uart_reconfigure_timeouts(uint32_t value) {
serial_port uart_open(const char *pcPortName, uint32_t speed) {
serial_port_unix *sp = calloc(sizeof(serial_port_unix), sizeof(uint8_t));
- if (sp == 0) return INVALID_SERIAL_PORT;
+
+ if (sp == 0) {
+ PrintAndLogEx(ERR, "UART failed to allocate memory");
+ return INVALID_SERIAL_PORT;
+ }
// init timeouts
timeout.tv_usec = UART_FPC_CLIENT_RX_TIMEOUT_MS * 1000;
From 0cb21c89c36fee89dbbe2d9a64e9510fe1624deb Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Sat, 2 May 2020 23:11:49 +0200
Subject: [PATCH 046/632] doc
---
armsrc/Standalone/readme.md | 2 +-
doc/bt_manual_v10.md | 13 +++++++++----
2 files changed, 10 insertions(+), 5 deletions(-)
diff --git a/armsrc/Standalone/readme.md b/armsrc/Standalone/readme.md
index d46943778..3775d848c 100644
--- a/armsrc/Standalone/readme.md
+++ b/armsrc/Standalone/readme.md
@@ -131,7 +131,7 @@ Remember only one can be selected at a time for now.
The final steps is to
- force recompilation of all code. ```make clean```
-- compile ```make -j8```
+- compile ```make -j```
- flash your device
- connect to your device
- press button long time to trigger ledshow and enter your new standalone mode
diff --git a/doc/bt_manual_v10.md b/doc/bt_manual_v10.md
index 42f8c04b9..8a08fcdcd 100644
--- a/doc/bt_manual_v10.md
+++ b/doc/bt_manual_v10.md
@@ -55,7 +55,7 @@ https://github.com/RfidResearchGroup/proxmark3
To compile the client and firmware with FPC support, the easiest way is to
1. Copy the sample file: `Makefile.platform.sample` ⇒ `Makefile.platform`
- * `mv Makefile.platform.sample Makefile.platform`
+ * `cp Makefile.platform.sample Makefile.platform`
2. Edit `Makefile.platform`, uncomment the line `#PLATFORM_EXTRAS=BTADDON` by removing the `#`
3. Recompile the project:
* `make clean; make -j`
@@ -113,10 +113,15 @@ http://www.silabs.com/products/development-tools/software/usb-to-uart-bridge-vcp
This requires to have compiled the client with Bluetooth support.
+Be sure your user has permissions to use Bluetooth
+
+ * On most distributions, you've to be part of group `bluetooth`: `sudo adduser $USER bluetooth` then log out and log in
+ * else, run the following commands as root : `sudo ...`
+
1. Find the MAC address of the Bluetooth add-on, named PM3_RDV4.0.
```sh
-sudo hcitool scan
+hcitool scan
Scanning ...
aa:bb:cc:dd:ee:ff PM3_RDV4.0
```
@@ -136,7 +141,7 @@ restart it again after pairing.
If your OS doesn't prompt you for pairing, you can do it in command line, e.g. (again, replace with your addon MAC address):
```sh
-sudo bluetoothctl
+bluetoothctl
[bluetooth]# pairable on
[bluetooth]# scan on
Discovery started
@@ -178,7 +183,7 @@ rfcomm is a deprecated tool which might be unavailable in your Linux distributio
1. Find the MAC address of the Bluetooth add-on, named PM3_RDV4.0.
```sh
-sudo hcitool scan
+hcitool scan
Scanning ...
aa:bb:cc:dd:ee:ff PM3_RDV4.0
```
From 0e39cb8e34a2266971d849f7b5f73c0bb176e09f Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Sat, 2 May 2020 23:54:27 +0200
Subject: [PATCH 047/632] stricter warnings, wip
---
Makefile.host | 3 ++-
client/deps/amiitool/amiibo.c | 10 +++++-----
client/deps/amiitool/keygen.c | 2 +-
client/deps/hardnested/hardnested_bf_core.c | 4 ++--
client/deps/hardnested/hardnested_bruteforce.c | 2 +-
client/deps/jansson/hashtable.c | 4 ++--
client/deps/jansson/hashtable_seed.c | 2 +-
client/deps/liblua/llex.c | 2 +-
client/src/cmdhfmfu.h | 2 +-
common/crapto1/crapto1.c | 2 +-
common/zlib/deflate.c | 3 +++
11 files changed, 20 insertions(+), 16 deletions(-)
diff --git a/Makefile.host b/Makefile.host
index 9f5688939..7ed942401 100644
--- a/Makefile.host
+++ b/Makefile.host
@@ -15,7 +15,8 @@ ifeq ($(DEFSBEENHERE),)
$(error Can't find Makefile.defs)
endif
-CFLAGS ?= -Wall -Werror -O3
+CFLAGS ?= -Wall -Werror -O3 -Wchar-subscripts -Wundef -Wshadow -Wcast-align -Wwrite-strings -Wunused -Wuninitialized -Wpointer-arith -Wredundant-decls -Winline -Wformat -Wformat-security -Winit-self -Wmissing-include-dirs -Wmissing-prototypes -Wstrict-prototypes -Wnested-externs -Wmissing-declarations
+# -Wbad-function-cast -Wextra -Wswitch-enum -Wold-style-definition
CFLAGS += $(MYDEFS) $(MYCFLAGS) $(MYINCLUDES)
vpath %.c $(MYSRCPATHS)
diff --git a/client/deps/amiitool/amiibo.c b/client/deps/amiitool/amiibo.c
index 809f611d3..ad41220bb 100644
--- a/client/deps/amiitool/amiibo.c
+++ b/client/deps/amiitool/amiibo.c
@@ -13,7 +13,7 @@
#define HMAC_POS_DATA 0x008
#define HMAC_POS_TAG 0x1B4
-void nfc3d_amiibo_calc_seed(const uint8_t *dump, uint8_t *key) {
+static void nfc3d_amiibo_calc_seed(const uint8_t *dump, uint8_t *key) {
memcpy(key + 0x00, dump + 0x029, 0x02);
memset(key + 0x02, 0x00, 0x0E);
memcpy(key + 0x10, dump + 0x1D4, 0x08);
@@ -21,14 +21,14 @@ void nfc3d_amiibo_calc_seed(const uint8_t *dump, uint8_t *key) {
memcpy(key + 0x20, dump + 0x1E8, 0x20);
}
-void nfc3d_amiibo_keygen(const nfc3d_keygen_masterkeys *masterKeys, const uint8_t *dump, nfc3d_keygen_derivedkeys *derivedKeys) {
+static void nfc3d_amiibo_keygen(const nfc3d_keygen_masterkeys *masterKeys, const uint8_t *dump, nfc3d_keygen_derivedkeys *derivedKeys) {
uint8_t seed[NFC3D_KEYGEN_SEED_SIZE];
nfc3d_amiibo_calc_seed(dump, seed);
nfc3d_keygen(masterKeys, seed, derivedKeys);
}
-void nfc3d_amiibo_cipher(const nfc3d_keygen_derivedkeys *keys, const uint8_t *in, uint8_t *out) {
+static void nfc3d_amiibo_cipher(const nfc3d_keygen_derivedkeys *keys, const uint8_t *in, uint8_t *out) {
mbedtls_aes_context aes;
size_t nc_off = 0;
unsigned char nonce_counter[16];
@@ -47,7 +47,7 @@ void nfc3d_amiibo_cipher(const nfc3d_keygen_derivedkeys *keys, const uint8_t *in
memcpy(out + 0x1D4, in + 0x1D4, 0x034);
}
-void nfc3d_amiibo_tag_to_internal(const uint8_t *tag, uint8_t *intl) {
+static void nfc3d_amiibo_tag_to_internal(const uint8_t *tag, uint8_t *intl) {
memcpy(intl + 0x000, tag + 0x008, 0x008);
memcpy(intl + 0x008, tag + 0x080, 0x020);
memcpy(intl + 0x028, tag + 0x010, 0x024);
@@ -57,7 +57,7 @@ void nfc3d_amiibo_tag_to_internal(const uint8_t *tag, uint8_t *intl) {
memcpy(intl + 0x1DC, tag + 0x054, 0x02C);
}
-void nfc3d_amiibo_internal_to_tag(const uint8_t *intl, uint8_t *tag) {
+static void nfc3d_amiibo_internal_to_tag(const uint8_t *intl, uint8_t *tag) {
memcpy(tag + 0x008, intl + 0x000, 0x008);
memcpy(tag + 0x080, intl + 0x008, 0x020);
memcpy(tag + 0x010, intl + 0x028, 0x024);
diff --git a/client/deps/amiitool/keygen.c b/client/deps/amiitool/keygen.c
index f148c0dc8..6322a0fe9 100644
--- a/client/deps/amiitool/keygen.c
+++ b/client/deps/amiitool/keygen.c
@@ -10,7 +10,7 @@
#include
#include
-void nfc3d_keygen_prepare_seed(const nfc3d_keygen_masterkeys *baseKeys, const uint8_t *baseSeed, uint8_t *output, size_t *outputSize) {
+static void nfc3d_keygen_prepare_seed(const nfc3d_keygen_masterkeys *baseKeys, const uint8_t *baseSeed, uint8_t *output, size_t *outputSize) {
assert(baseKeys != NULL);
assert(baseSeed != NULL);
assert(output != NULL);
diff --git a/client/deps/hardnested/hardnested_bf_core.c b/client/deps/hardnested/hardnested_bf_core.c
index 9402d9684..0f2d57f16 100644
--- a/client/deps/hardnested/hardnested_bf_core.c
+++ b/client/deps/hardnested/hardnested_bf_core.c
@@ -556,7 +556,7 @@ void SetSIMDInstr(SIMDExecInstr instr) {
bitslice_test_nonces_function_p = &bitslice_test_nonces_dispatch;
}
-static SIMDExecInstr GetSIMDInstr() {
+static SIMDExecInstr GetSIMDInstr(void) {
SIMDExecInstr instr = SIMD_NONE;
#if defined (__i386__) || defined (__x86_64__)
@@ -578,7 +578,7 @@ static SIMDExecInstr GetSIMDInstr() {
return instr;
}
-SIMDExecInstr GetSIMDInstrAuto() {
+SIMDExecInstr GetSIMDInstrAuto(void) {
SIMDExecInstr instr = intSIMDInstr;
if (instr == SIMD_AUTO)
return GetSIMDInstr();
diff --git a/client/deps/hardnested/hardnested_bruteforce.c b/client/deps/hardnested/hardnested_bruteforce.c
index 159454110..82f8c6c04 100644
--- a/client/deps/hardnested/hardnested_bruteforce.c
+++ b/client/deps/hardnested/hardnested_bruteforce.c
@@ -433,7 +433,7 @@ static bool read_bench_data(statelist_t *test_candidates) {
}
-float brute_force_benchmark() {
+float brute_force_benchmark(void) {
statelist_t test_candidates[NUM_BRUTE_FORCE_THREADS];
test_candidates[0].states[ODD_STATE] = malloc((TEST_BENCH_SIZE + 1) * sizeof(uint32_t));
diff --git a/client/deps/jansson/hashtable.c b/client/deps/jansson/hashtable.c
index 38c10a0c7..23fbc867b 100644
--- a/client/deps/jansson/hashtable.c
+++ b/client/deps/jansson/hashtable.c
@@ -5,14 +5,14 @@
* it under the terms of the MIT license. See LICENSE for details.
*/
-#if HAVE_CONFIG_H
+#ifdef HAVE_CONFIG_H
#include
#endif
#include
#include
-#if HAVE_STDINT_H
+#ifdef HAVE_STDINT_H
#include
#endif
diff --git a/client/deps/jansson/hashtable_seed.c b/client/deps/jansson/hashtable_seed.c
index 3856691d3..715279879 100644
--- a/client/deps/jansson/hashtable_seed.c
+++ b/client/deps/jansson/hashtable_seed.c
@@ -162,7 +162,7 @@ static int seed_from_timestamp_and_pid(uint32_t *seed) {
return 0;
}
-static uint32_t generate_seed() {
+static uint32_t generate_seed(void) {
uint32_t seed = 0;
int done = 0;
diff --git a/client/deps/liblua/llex.c b/client/deps/liblua/llex.c
index 3f0a1601b..bde26fa4f 100644
--- a/client/deps/liblua/llex.c
+++ b/client/deps/liblua/llex.c
@@ -197,7 +197,7 @@ static void buffreplace(LexState *ls, char from, char to) {
}
-#if ANDROID
+#if defined(ANDROID)
#define getlocaldecpoint() '.'
#elif !defined(getlocaledecpoint)
#define getlocaledecpoint() (localeconv()->decimal_point[0])
diff --git a/client/src/cmdhfmfu.h b/client/src/cmdhfmfu.h
index 85f6a8475..be52b1ed8 100644
--- a/client/src/cmdhfmfu.h
+++ b/client/src/cmdhfmfu.h
@@ -30,7 +30,7 @@ void printMFUdumpEx(mfu_dump_t *card, uint16_t pages, uint8_t startpage);
int CmdHFMFUltra(const char *Cmd);
uint32_t ul_ev1_pwdgenA(uint8_t *uid);
-uint32_t ul_ev1_pwdgenA(uint8_t *uid);
+uint32_t ul_ev1_pwdgenB(uint8_t *uid);
uint32_t ul_ev1_pwdgenC(uint8_t *uid);
uint32_t ul_ev1_pwdgenD(uint8_t *uid);
diff --git a/common/crapto1/crapto1.c b/common/crapto1/crapto1.c
index e697b68f0..0d7aaa49e 100644
--- a/common/crapto1/crapto1.c
+++ b/common/crapto1/crapto1.c
@@ -26,7 +26,7 @@
#if !defined LOWMEM && defined __GNUC__
static uint8_t filterlut[1 << 20];
-static void __attribute__((constructor)) fill_lut() {
+static void __attribute__((constructor)) fill_lut(void) {
uint32_t i;
for (i = 0; i < 1 << 20; ++i)
filterlut[i] = filter(i);
diff --git a/common/zlib/deflate.c b/common/zlib/deflate.c
index a44bdb3ab..f06654f95 100644
--- a/common/zlib/deflate.c
+++ b/common/zlib/deflate.c
@@ -82,6 +82,9 @@ local void slide_hash OF((deflate_state *s));
local void fill_window OF((deflate_state *s));
local block_state deflate_stored OF((deflate_state *s, int flush));
local block_state deflate_fast OF((deflate_state *s, int flush));
+#ifdef ZLIB_PM3_TUNED
+local uInt try_harder OF((deflate_state *s, uInt strstart, uInt lookahead, IPos hash_head));
+#endif
#ifndef FASTEST
local block_state deflate_slow OF((deflate_state *s, int flush));
#endif
From 93585548844770b86a6482c936154413651f846f Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Sun, 3 May 2020 00:33:28 +0200
Subject: [PATCH 048/632] stricter warnings, wip
---
client/Makefile | 3 +++
client/src/cmddata.c | 3 ++-
client/src/cmdhf.c | 1 +
client/src/cmdhf14a.c | 4 ++--
client/src/cmdhfmfdes.c | 26 +++++++++++++-------------
client/src/cmdlf.c | 1 +
client/src/cmdlfem4x.c | 1 +
client/src/cmdlfindala.c | 1 +
client/src/cmdlft55xx.c | 1 +
client/src/cmdlfti.c | 1 +
client/src/fileutils.c | 4 ++--
client/src/graph.c | 1 +
client/src/loclass/cipherutils.h | 1 -
client/src/ui.h | 10 ----------
client/src/util.h | 1 -
common/generator.c | 4 ++--
common/generator.h | 5 +----
17 files changed, 32 insertions(+), 36 deletions(-)
diff --git a/client/Makefile b/client/Makefile
index e8358757e..ed4e550ff 100644
--- a/client/Makefile
+++ b/client/Makefile
@@ -56,6 +56,9 @@ ZLIB = $(OBJDIR)/libz.a
LIBS = -I$(LUALIBPATH) -I$(MBEDTLSLIBPATH) -I$(JANSSONLIBPATH) -I$(CBORLIBPATH) -I$(ZLIBPATH) -I$(REVENGPATH) -I$(AMIIBOLIBPATH) -I$(HARDNESTEDPATH) -I$(CLIPARSERPATH)
INCLUDES_CLIENT += -I./src -I../include -I../common -I../common_fpga $(LIBS)
CFLAGS ?= -Wall -Werror -O3
+#CFLAGS ?= -Wall -Werror -O3 -Wchar-subscripts -Wundef -Wshadow -Wcast-align -Wwrite-strings -Wunused -Wuninitialized -Wpointer-arith -Wredundant-decls -Winline -Wformat -Wformat-security -Winit-self -Wmissing-include-dirs -Wmissing-prototypes -Wstrict-prototypes -Wnested-externs -Wmissing-declarations
+# -Wbad-function-cast -Wextra -Wswitch-enum -Wold-style-definition
+
# We cannot just use CFLAGS+=... because it has impact on sub-makes if CFLAGS is defined in env:
PM3CFLAGS = $(CFLAGS) $(INCLUDES_CLIENT)
# WIP Testing
diff --git a/client/src/cmddata.c b/client/src/cmddata.c
index 9a809f603..cf2256acb 100644
--- a/client/src/cmddata.c
+++ b/client/src/cmddata.c
@@ -18,6 +18,7 @@
#include "commonutil.h" // ARRAYLEN
#include "cmdparser.h" // for command_t
#include "ui.h" // for show graph controls
+#include "proxgui.h"
#include "graph.h" // for graph data
#include "comms.h"
#include "lfdemod.h" // for demod code
@@ -287,7 +288,7 @@ static int usage_data_buffclear(void) {
PrintAndLogEx(NORMAL, " h This help");
return PM3_SUCCESS;
}
-static int usage_data_fsktonrz() {
+static int usage_data_fsktonrz(void) {
PrintAndLogEx(NORMAL, "Usage: data fsktonrz c l f ");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " h This help");
diff --git a/client/src/cmdhf.c b/client/src/cmdhf.c
index fbc99dbd5..ea5472c9d 100644
--- a/client/src/cmdhf.c
+++ b/client/src/cmdhf.c
@@ -37,6 +37,7 @@
#include "cmdhfcryptorf.h" // CryptoRF
#include "cmdtrace.h" // trace list
#include "ui.h"
+#include "proxgui.h"
#include "cmddata.h"
#include "graph.h"
#include "fpga.h"
diff --git a/client/src/cmdhf14a.c b/client/src/cmdhf14a.c
index 262e879f4..7d2178c89 100644
--- a/client/src/cmdhf14a.c
+++ b/client/src/cmdhf14a.c
@@ -1245,7 +1245,7 @@ int CmdHF14A(const char *Cmd) {
return CmdsParse(CommandTable, Cmd);
}
-static void printTag(char *tag) {
+static void printTag(const char *tag) {
PrintAndLogEx(SUCCESS, "POSSIBLE TYPE:" _YELLOW_(" %s"), tag);
}
@@ -1340,7 +1340,7 @@ int detect_nxp_card(uint8_t sak, uint16_t atqa) {
typedef struct {
uint8_t uid0;
uint8_t uid1;
- char *desc;
+ const char *desc;
} uidname;
const uidname uidmap[] = {
diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c
index b8c2271e1..c44bb4a3a 100644
--- a/client/src/cmdhfmfdes.c
+++ b/client/src/cmdhfmfdes.c
@@ -170,7 +170,7 @@ typedef enum {
CL_AMISC7 = 0xFF,
} aidcluster_h;
-static char *cluster_to_text(uint8_t cluster) {
+static const char *cluster_to_text(uint8_t cluster) {
switch (cluster) {
case CL_ADMIN:
return "card administration";
@@ -375,7 +375,7 @@ static char *getVersionStr(uint8_t major, uint8_t minor) {
}
-int DESFIRESendApdu(bool activate_field, bool leavefield_on, sAPDU apdu, uint8_t *result, int max_result_len, int *result_len, uint16_t *sw) {
+static int DESFIRESendApdu(bool activate_field, bool leavefield_on, sAPDU apdu, uint8_t *result, int max_result_len, int *result_len, uint16_t *sw) {
*result_len = 0;
if (sw) *sw = 0;
@@ -433,7 +433,7 @@ int DESFIRESendApdu(bool activate_field, bool leavefield_on, sAPDU apdu, uint8_t
return PM3_SUCCESS;
}
-static char *getstatus(uint16_t *sw) {
+static const char *getstatus(uint16_t *sw) {
if (sw == NULL) return "--> sw argument error. This should never happen !";
if (((*sw >> 8) & 0xFF) == 0x91) {
switch (*sw & 0xFF) {
@@ -500,7 +500,7 @@ static char *getstatus(uint16_t *sw) {
return "Unknown error";
}
-static char *GetErrorString(int res, uint16_t *sw) {
+static const char *GetErrorString(int res, uint16_t *sw) {
switch (res) {
case PM3_EAPDU_FAIL:
return getstatus(sw);
@@ -642,7 +642,7 @@ static nxp_cardtype_t getCardType(uint8_t major, uint8_t minor) {
return DESFIRE_UNKNOWN;
}
-int handler_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rpayload, bool defaultkey) {
+static int handler_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rpayload, bool defaultkey) {
// 3 different way to authenticate AUTH (CRC16) , AUTH_ISO (CRC32) , AUTH_AES (CRC32)
// 4 different crypto arg1 DES, 3DES, 3K3DES, AES
// 3 different communication modes, PLAIN,MAC,CRYPTO
@@ -913,7 +913,7 @@ int handler_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rpayload,
return PM3_SUCCESS;
}
-void AuthToError(int error) {
+static void AuthToError(int error) {
switch (error) {
case 1:
PrintAndLogEx(SUCCESS, "Sending auth command failed");
@@ -953,7 +953,7 @@ void AuthToError(int error) {
}
}
// -- test if card supports 0x0A
-static int test_desfire_authenticate() {
+static int test_desfire_authenticate(void) {
uint8_t data[] = {0x00};
sAPDU apdu = {0x90, MFDES_AUTHENTICATE, 0x00, 0x00, 0x01, data}; // 0x0A, KEY 0
int recv_len = 0;
@@ -968,7 +968,7 @@ static int test_desfire_authenticate() {
}
// -- test if card supports 0x1A
-static int test_desfire_authenticate_iso() {
+static int test_desfire_authenticate_iso(void) {
uint8_t data[] = {0x00};
sAPDU apdu = {0x90, MFDES_AUTHENTICATE_ISO, 0x00, 0x00, 0x01, data}; // 0x1A, KEY 0
int recv_len = 0;
@@ -983,7 +983,7 @@ static int test_desfire_authenticate_iso() {
}
// -- test if card supports 0xAA
-static int test_desfire_authenticate_aes() {
+static int test_desfire_authenticate_aes(void) {
uint8_t data[] = {0x00};
sAPDU apdu = {0x90, MFDES_AUTHENTICATE_AES, 0x00, 0x00, 0x01, data}; // 0xAA, KEY 0
int recv_len = 0;
@@ -1210,7 +1210,7 @@ static int handler_desfire_keyversion(uint8_t curr_key, uint8_t *num_versions) {
return res;
}
-static int handler_desfire_commit_transaction() {
+static int handler_desfire_commit_transaction(void) {
sAPDU apdu = {0x90, MFDES_COMMIT_TRANSACTION, 0x00, 0x00, 0x00, NULL}; //0xC7
int recv_len = 0;
uint16_t sw = 0;
@@ -1225,7 +1225,7 @@ static int handler_desfire_commit_transaction() {
return res;
}
-/*static int handler_desfire_abort_transaction() {
+/*static int handler_desfire_abort_transaction(void) {
sAPDU apdu = {0x90, MFDES_ABORT_TRANSACTION, 0x00, 0x00, 0x00, NULL}; //0xA7
int recv_len = 0;
uint16_t sw = 0;
@@ -1647,7 +1647,7 @@ static int handler_desfire_create_backup_file(mfdes_file_t *file) {
return res;
}
-int getKeySettings(uint8_t *aid) {
+static int getKeySettings(uint8_t *aid) {
if (aid == NULL) return PM3_EINVARG;
int res = 0;
@@ -3558,7 +3558,7 @@ static int CmdHF14ADesAuth(const char *Cmd) {
return PM3_SUCCESS;
}
-void DesFill2bPattern(uint8_t deskeyList[MAX_KEYS_LIST_LEN][8], size_t *deskeyListLen, uint8_t aeskeyList[MAX_KEYS_LIST_LEN][16], size_t *aeskeyListLen, uint8_t k3kkeyList[MAX_KEYS_LIST_LEN][24], size_t *k3kkeyListLen, uint32_t *startPattern) {
+static void DesFill2bPattern(uint8_t deskeyList[MAX_KEYS_LIST_LEN][8], size_t *deskeyListLen, uint8_t aeskeyList[MAX_KEYS_LIST_LEN][16], size_t *aeskeyListLen, uint8_t k3kkeyList[MAX_KEYS_LIST_LEN][24], size_t *k3kkeyListLen, uint32_t *startPattern) {
for (uint32_t pt = *startPattern; pt < 0x10000; pt++) {
if (*deskeyListLen != MAX_KEYS_LIST_LEN) {
deskeyList[*deskeyListLen][0] = (pt >> 8) & 0xff;
diff --git a/client/src/cmdlf.c b/client/src/cmdlf.c
index 9324062a1..a08ec2b9e 100644
--- a/client/src/cmdlf.c
+++ b/client/src/cmdlf.c
@@ -25,6 +25,7 @@
#include "lfdemod.h" // device/client demods of LF signals
#include "ui.h" // for show graph controls
+#include "proxgui.h"
#include "graph.h" // for graph data
#include "cmddata.h" // for `lf search`
#include "cmdlfawid.h" // for awid menu
diff --git a/client/src/cmdlfem4x.c b/client/src/cmdlfem4x.c
index 734626700..f0e51b900 100644
--- a/client/src/cmdlfem4x.c
+++ b/client/src/cmdlfem4x.c
@@ -24,6 +24,7 @@
#include "util_posix.h"
#include "protocols.h"
#include "ui.h"
+#include "proxgui.h"
#include "graph.h"
#include "cmddata.h"
#include "cmdlf.h"
diff --git a/client/src/cmdlfindala.c b/client/src/cmdlfindala.c
index 6cf5ed28f..7f3c4ee87 100644
--- a/client/src/cmdlfindala.c
+++ b/client/src/cmdlfindala.c
@@ -22,6 +22,7 @@
#include "cliparser.h"
#include "commonutil.h"
#include "ui.h" // PrintAndLog
+#include "proxgui.h"
#include "lfdemod.h" // parityTest, bitbytes_to_byte
#include "cmddata.h"
#include "cmdlf.h" // lf_read
diff --git a/client/src/cmdlft55xx.c b/client/src/cmdlft55xx.c
index 5994e2232..09f2009bd 100644
--- a/client/src/cmdlft55xx.c
+++ b/client/src/cmdlft55xx.c
@@ -21,6 +21,7 @@
#include "comms.h"
#include "commonutil.h"
#include "protocols.h"
+#include "proxgui.h"
#include "graph.h"
#include "cmddata.h"
#include "lfdemod.h"
diff --git a/client/src/cmdlfti.c b/client/src/cmdlfti.c
index ed3b6f510..1c0dcbe1e 100644
--- a/client/src/cmdlfti.c
+++ b/client/src/cmdlfti.c
@@ -17,6 +17,7 @@
#include "comms.h"
#include "crc16.h"
#include "ui.h"
+#include "proxgui.h"
#include "graph.h"
#include "cmdlfti.h"
diff --git a/client/src/fileutils.c b/client/src/fileutils.c
index b0b8d9772..4ccd4fa8f 100644
--- a/client/src/fileutils.c
+++ b/client/src/fileutils.c
@@ -1151,7 +1151,7 @@ int loadFileDICTIONARY_safe(const char *preferredName, void **pdata, uint8_t key
fclose(f);
goto out;
} else {
- memset(*pdata + (mem_size - block_size), 0, block_size);
+ memset((uint8_t *)*pdata + (mem_size - block_size), 0, block_size);
}
}
@@ -1171,7 +1171,7 @@ int loadFileDICTIONARY_safe(const char *preferredName, void **pdata, uint8_t key
uint64_t key = strtoull(line, NULL, 16);
- num_to_bytes(key, keylen >> 1, *pdata + (*keycnt * (keylen >> 1)));
+ num_to_bytes(key, keylen >> 1, (uint8_t *)*pdata + (*keycnt * (keylen >> 1)));
(*keycnt)++;
diff --git a/client/src/graph.c b/client/src/graph.c
index f9e610414..d5f62a6b7 100644
--- a/client/src/graph.c
+++ b/client/src/graph.c
@@ -11,6 +11,7 @@
#include
#include
#include "ui.h"
+#include "proxgui.h"
#include "util.h" //param_get32ex
#include "lfdemod.h"
#include "cmddata.h" //for g_debugmode
diff --git a/client/src/loclass/cipherutils.h b/client/src/loclass/cipherutils.h
index 6c90326a6..2e6e3dab9 100644
--- a/client/src/loclass/cipherutils.h
+++ b/client/src/loclass/cipherutils.h
@@ -61,7 +61,6 @@ void pushBit(BitstreamOut *stream, bool bit);
int bitsLeft(BitstreamIn *stream);
#ifndef ON_DEVICE
int testCipherUtils(void);
-int testMAC(void);
#endif
void push6bits(BitstreamOut *stream, uint8_t bits);
void EncryptDES(bool key[56], bool outBlk[64], bool inBlk[64], int verbose) ;
diff --git a/client/src/ui.h b/client/src/ui.h
index e47031d70..ee101601e 100644
--- a/client/src/ui.h
+++ b/client/src/ui.h
@@ -48,22 +48,12 @@ extern session_arg_t session;
#endif
#define MAX_PRINT_BUFFER 2048
-void ShowGui(void);
-void HideGraphWindow(void);
-void ShowGraphWindow(void);
-void RepaintGraphWindow(void);
void PrintAndLogOptions(const char *str[][2], size_t size, size_t space);
void PrintAndLogEx(logLevel_t level, const char *fmt, ...);
void SetFlushAfterWrite(bool value);
void memcpy_filter_ansi(void *dest, const void *src, size_t n, bool filter);
void memcpy_filter_emoji(void *dest, const void *src, size_t n, emojiMode_t mode);
-extern double CursorScaleFactor;
-extern int PlotGridX, PlotGridY, PlotGridXdefault, PlotGridYdefault, GridOffset;
-extern uint32_t CursorCPos, CursorDPos;
-extern bool GridLocked;
-extern bool showDemod;
-
int searchHomeFilePath(char **foundpath, const char *filename, bool create_home);
extern pthread_mutex_t print_lock;
diff --git a/client/src/util.h b/client/src/util.h
index fb31e6013..59591ac24 100644
--- a/client/src/util.h
+++ b/client/src/util.h
@@ -87,7 +87,6 @@ void wiegand_add_parity(uint8_t *target, uint8_t *source, uint8_t length);
void wiegand_add_parity_swapped(uint8_t *target, uint8_t *source, uint8_t length);
//void xor(unsigned char *dst, unsigned char *src, size_t len);
-int32_t le24toh(uint8_t data[3]);
uint32_t PackBits(uint8_t start, uint8_t len, uint8_t *bits);
uint64_t HornerScheme(uint64_t num, uint64_t divider, uint64_t factor);
diff --git a/common/generator.c b/common/generator.c
index a456c6b78..653d57061 100644
--- a/common/generator.c
+++ b/common/generator.c
@@ -34,7 +34,7 @@
// XYZ 3D printing
// Vinglock
//------------------------------------
-void transform_D(uint8_t *ru) {
+static void transform_D(uint8_t *ru) {
const uint32_t c_D[] = {
0x6D835AFC, 0x7D15CD97, 0x0942B409, 0x32F9C923, 0xA811FB02, 0x64F121E8,
@@ -415,7 +415,7 @@ int mfc_algo_sky_all(uint8_t *uid, uint8_t *keys) {
//------------------------------------
// Self tests
//------------------------------------
-int generator_selftest() {
+int generator_selftest(void) {
#define NUM_OF_TEST 5
diff --git a/common/generator.h b/common/generator.h
index d7ca2b8ee..c90fe483a 100644
--- a/common/generator.h
+++ b/common/generator.h
@@ -32,9 +32,6 @@ int mfc_algo_yale_all(uint8_t *uid, uint8_t *keys);
int mfc_algo_saflok_one(uint8_t *uid, uint8_t sector, uint8_t keytype, uint64_t *key);
int mfc_algo_saflok_all(uint8_t *uid, uint8_t *keys);
-int mfc_algo_saflok_one(uint8_t *uid, uint8_t sector, uint8_t keytype, uint64_t *key);
-int mfc_algo_saflok_all(uint8_t *uid, uint8_t *keys);
-
int mfc_algo_mizip_one(uint8_t *uid, uint8_t sector, uint8_t keytype, uint64_t *key);
int mfc_algo_mizip_all(uint8_t *uid, uint8_t *keys);
@@ -44,5 +41,5 @@ int mfc_algo_di_all(uint8_t *uid, uint8_t *keys);
int mfc_algo_sky_one(uint8_t *uid, uint8_t sector, uint8_t keytype, uint64_t *key);
int mfc_algo_sky_all(uint8_t *uid, uint8_t *keys);
-int generator_selftest();
+int generator_selftest(void);
#endif
From 3529aea157fdb488fef2371b4fffbfcace000ed1 Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Sun, 3 May 2020 01:13:28 +0200
Subject: [PATCH 049/632] stricter warnings, wip
---
client/Makefile | 5 +--
client/deps/amiitool/amiitool.c | 2 +-
client/deps/cliparser/cliparser.c | 2 +-
client/src/aidsearch.c | 8 ++---
client/src/aidsearch.h | 2 +-
client/src/cmdhf.c | 6 ++--
client/src/cmdhf14a.c | 4 +--
client/src/cmdhf14b.c | 2 +-
client/src/cmdhffelica.c | 30 +++++++++---------
client/src/cmdhficlass.c | 2 +-
client/src/cmdhflist.c | 2 +-
client/src/cmdhfmf.c | 4 +--
client/src/cmdhfmfhard.c | 4 +--
client/src/cmdhfmfp.c | 4 +--
client/src/cmdhfmfu.c | 4 +--
client/src/cmdlf.c | 2 +-
client/src/cmdlfem4x.c | 12 ++++----
client/src/cmdlfhitag.c | 2 +-
client/src/cmdlfpcf7931.c | 10 +++---
client/src/cmdlft55xx.c | 46 ++++++++++++++--------------
client/src/cmdmain.c | 4 +--
client/src/cmdsmartcard.c | 2 +-
client/src/cmdtrace.c | 6 ++--
client/src/cmdusart.c | 4 +--
client/src/cmdwiegand.c | 8 ++---
client/src/comms.c | 2 +-
client/src/fileutils.c | 2 +-
client/src/graph.c | 2 +-
client/src/loclass/cipher.c | 2 +-
client/src/loclass/cipherutils.c | 4 +--
client/src/loclass/elite_crack.c | 6 ++--
client/src/loclass/ikeys.c | 8 ++---
client/src/pm3_binlib.c | 1 +
client/src/pm3_bitlib.c | 1 +
client/src/preferences.c | 51 ++++++++++++++++---------------
client/src/proxgui.h | 1 -
client/src/proxguiqt.cpp | 1 +
client/src/proxmark3.c | 8 ++---
client/src/util.c | 6 ----
client/src/util.h | 4 +--
client/src/wiegand_formats.c | 2 +-
client/src/wiegand_formats.h | 2 +-
client/src/wiegand_formatutils.c | 2 +-
43 files changed, 140 insertions(+), 142 deletions(-)
diff --git a/client/Makefile b/client/Makefile
index ed4e550ff..1f857e584 100644
--- a/client/Makefile
+++ b/client/Makefile
@@ -55,8 +55,9 @@ ZLIB = $(OBJDIR)/libz.a
LIBS = -I$(LUALIBPATH) -I$(MBEDTLSLIBPATH) -I$(JANSSONLIBPATH) -I$(CBORLIBPATH) -I$(ZLIBPATH) -I$(REVENGPATH) -I$(AMIIBOLIBPATH) -I$(HARDNESTEDPATH) -I$(CLIPARSERPATH)
INCLUDES_CLIENT += -I./src -I../include -I../common -I../common_fpga $(LIBS)
-CFLAGS ?= -Wall -Werror -O3
-#CFLAGS ?= -Wall -Werror -O3 -Wchar-subscripts -Wundef -Wshadow -Wcast-align -Wwrite-strings -Wunused -Wuninitialized -Wpointer-arith -Wredundant-decls -Winline -Wformat -Wformat-security -Winit-self -Wmissing-include-dirs -Wmissing-prototypes -Wstrict-prototypes -Wnested-externs -Wmissing-declarations
+#CFLAGS ?= -Wall -Werror -O3
+CFLAGS ?= -Wall -Werror -O3 -Wchar-subscripts -Wundef -Wcast-align -Wwrite-strings -Wunused -Wuninitialized -Wpointer-arith -Winline -Wformat -Wformat-security -Winit-self -Wmissing-include-dirs -Wstrict-prototypes -Wnested-externs -Wmissing-declarations
+# -Wshadow -Wmissing-prototypes -Wredundant-decls
# -Wbad-function-cast -Wextra -Wswitch-enum -Wold-style-definition
# We cannot just use CFLAGS+=... because it has impact on sub-makes if CFLAGS is defined in env:
diff --git a/client/deps/amiitool/amiitool.c b/client/deps/amiitool/amiitool.c
index b63222d50..d7cd08351 100644
--- a/client/deps/amiitool/amiitool.c
+++ b/client/deps/amiitool/amiitool.c
@@ -15,7 +15,7 @@
static char *self;
-void amiitool_usage() {
+void amiitool_usage(void) {
fprintf(stderr,
/*"amiitool build %i (commit %s-%08x)\n"*/
"by Marcos Del Sol Vives \n"
diff --git a/client/deps/cliparser/cliparser.c b/client/deps/cliparser/cliparser.c
index 1845aff29..27b0ed050 100644
--- a/client/deps/cliparser/cliparser.c
+++ b/client/deps/cliparser/cliparser.c
@@ -143,7 +143,7 @@ int CLIParserParseStringEx(const char *str, void *vargtable[], size_t vargtableL
return CLIParserParseArg(argc, argv, vargtable, vargtableLen, allowEmptyExec);
}
-void CLIParserFree() {
+void CLIParserFree(void) {
arg_freetable(argtable, argtableLen);
argtable = NULL;
diff --git a/client/src/aidsearch.c b/client/src/aidsearch.c
index 676db4cc7..291d2035c 100644
--- a/client/src/aidsearch.c
+++ b/client/src/aidsearch.c
@@ -13,7 +13,7 @@
#include "fileutils.h"
#include "pm3_cmd.h"
-int openAIDFile(json_t **root, bool verbose) {
+static int openAIDFile(json_t **root, bool verbose) {
json_error_t error;
char *path;
@@ -42,7 +42,7 @@ out:
return retval;
}
-int closeAIDFile(json_t *root) {
+static int closeAIDFile(json_t *root) {
json_decref(root);
return PM3_SUCCESS;
@@ -71,7 +71,7 @@ int AIDSearchFree(json_t *root) {
return closeAIDFile(root);
}
-const char *jsonStrGet(json_t *data, char *name) {
+static const char *jsonStrGet(json_t *data, const char *name) {
json_t *jstr;
jstr = json_object_get(data, name);
@@ -88,7 +88,7 @@ const char *jsonStrGet(json_t *data, char *name) {
return cstr;
}
-bool aidCompare(const char *aidlarge, const char *aidsmall) {
+static bool aidCompare(const char *aidlarge, const char *aidsmall) {
if (strcmp(aidlarge, aidsmall) == 0)
return true;
diff --git a/client/src/aidsearch.h b/client/src/aidsearch.h
index 00d2b134a..528146766 100644
--- a/client/src/aidsearch.h
+++ b/client/src/aidsearch.h
@@ -23,6 +23,6 @@ int PrintAIDDescriptionBuf(json_t *root, uint8_t *aid, size_t aidlen, bool verbo
json_t *AIDSearchInit(bool verbose);
json_t *AIDSearchGetElm(json_t *root, int elmindx);
bool AIDGetFromElm(json_t *data, uint8_t *aid, size_t aidmaxlen, int *aidlen);
-int AIDSearchFree();
+int AIDSearchFree(json_t *root);
#endif
diff --git a/client/src/cmdhf.c b/client/src/cmdhf.c
index ea5472c9d..ff2a5e79f 100644
--- a/client/src/cmdhf.c
+++ b/client/src/cmdhf.c
@@ -44,7 +44,7 @@
static int CmdHelp(const char *Cmd);
-static int usage_hf_search() {
+static int usage_hf_search(void) {
PrintAndLogEx(NORMAL, "Usage: hf search");
PrintAndLogEx(NORMAL, "Will try to find a HF read out of the unknown tag. Stops when found.");
PrintAndLogEx(NORMAL, "Options:");
@@ -53,7 +53,7 @@ static int usage_hf_search() {
return PM3_SUCCESS;
}
-static int usage_hf_sniff() {
+static int usage_hf_sniff(void) {
PrintAndLogEx(NORMAL, "The high frequence sniffer will assign all available memory on device for sniffed data");
PrintAndLogEx(NORMAL, "Use " _YELLOW_("'data samples'")" command to download from device, and " _YELLOW_("'data plot'")" to look at it");
PrintAndLogEx(NORMAL, "Press button to quit the sniffing.\n");
@@ -69,7 +69,7 @@ static int usage_hf_sniff() {
return PM3_SUCCESS;
}
-static int usage_hf_tune() {
+static int usage_hf_tune(void) {
PrintAndLogEx(NORMAL, "Continuously measure HF antenna tuning.");
PrintAndLogEx(NORMAL, "Press button or Enter to interrupt.");
PrintAndLogEx(NORMAL, "Usage: hf tune [h] []");
diff --git a/client/src/cmdhf14a.c b/client/src/cmdhf14a.c
index 7d2178c89..4e4e411e8 100644
--- a/client/src/cmdhf14a.c
+++ b/client/src/cmdhf14a.c
@@ -1261,7 +1261,7 @@ typedef enum {
} nxp_mifare_type_t;
// According to NXP AN10833 Rev 3.6 MIFARE Type Identification, Table 6
-int detect_nxp_card(uint8_t sak, uint16_t atqa) {
+static int detect_nxp_card(uint8_t sak, uint16_t atqa) {
int type = MTNONE;
if (sak == 0x00) {
@@ -1355,7 +1355,7 @@ const uidname uidmap[] = {
{0x00, 0x00, "None"}
};
-void getTagLabel(uint8_t uid0, uint8_t uid1) {
+static void getTagLabel(uint8_t uid0, uint8_t uid1) {
int i = 0;
while (uidmap[i].uid0 != 0x00) {
if ((uidmap[i].uid0 == uid0) && (uidmap[i].uid1 == uid1)) {
diff --git a/client/src/cmdhf14b.c b/client/src/cmdhf14b.c
index 859df4a23..7be829472 100644
--- a/client/src/cmdhf14b.c
+++ b/client/src/cmdhf14b.c
@@ -684,7 +684,7 @@ static bool HF14B_Std_Reader(bool verbose) {
}
// test for other 14b type tags (mimic another reader - don't have tags to identify)
-static bool HF14B_Other_Reader() {
+static bool HF14B_Other_Reader(void) {
// uint8_t data[] = {0x00, 0x0b, 0x3f, 0x80};
// uint8_t datalen = 4;
diff --git a/client/src/cmdhffelica.c b/client/src/cmdhffelica.c
index dc3b07a1b..9757e54a3 100644
--- a/client/src/cmdhffelica.c
+++ b/client/src/cmdhffelica.c
@@ -123,7 +123,7 @@ static int usage_hf_felica_request_response(void) {
return PM3_SUCCESS;
}
-static void print_status_flag1_interpretation() {
+static void print_status_flag1_interpretation(void) {
PrintAndLogEx(NORMAL, "\nStatus Flag1:");
PrintAndLogEx(NORMAL, " - 00h : Indicates the successful completion of a command.");
PrintAndLogEx(NORMAL, " - FFh : If an error occurs during the processing of a command that includes no list in the command packet, or if "
@@ -133,7 +133,7 @@ static void print_status_flag1_interpretation() {
"indicating the location of the error.");
}
-static void print_status_flag2_interpration() {
+static void print_status_flag2_interpration(void) {
PrintAndLogEx(NORMAL, "\nStatus Flag2:");
PrintAndLogEx(NORMAL, " - 00h : Indicates the successful completion of a command.");
PrintAndLogEx(NORMAL, " - 01h : The calculated result is either less than zero when the purse data is decremented, or exceeds 4"
@@ -167,7 +167,7 @@ static void print_status_flag2_interpration() {
PrintAndLogEx(NORMAL, " - C2h : Command is disabled already: This is the error that occurs in issuance commands.");
}
-static void print_block_list_element_constraints() {
+static void print_block_list_element_constraints(void) {
PrintAndLogEx(NORMAL, " - Each Block List Element shall satisfy the following conditions:");
PrintAndLogEx(NORMAL, " - The value of Service Code List Order shall not exceed Number of Service.");
PrintAndLogEx(NORMAL, " - Access Mode shall be 000b.");
@@ -177,22 +177,22 @@ static void print_block_list_element_constraints() {
PrintAndLogEx(NORMAL, " - Block Number shall be in the range of the number of Blocks assigned to the specified Service.");
}
-static void print_number_of_service_constraints() {
+static void print_number_of_service_constraints(void) {
PrintAndLogEx(NORMAL, " - Number of Service: shall be a positive integer in the range of 1 to 16, inclusive.");
}
-static void print_number_of_block_constraints() {
+static void print_number_of_block_constraints(void) {
PrintAndLogEx(NORMAL, " - Number of Block: shall be less than or equal to the maximum number of Blocks that can be read simultaneously. "
"The maximum number of Blocks that can be read simultaneously can differ, depending on the product being used. Use as default 01");
}
-static void print_service_code_list_constraints() {
+static void print_service_code_list_constraints(void) {
PrintAndLogEx(NORMAL, " - Service Code List: For Service Code List, only Service Code existing in the product shall be specified:");
PrintAndLogEx(NORMAL, " - Even when Service Code exists in the product, Service Code not referenced from Block List shall not be specified to Service Code List.");
PrintAndLogEx(NORMAL, " - For existence or nonexistence of Service in a product, please check using the Request Service (or Request Service v2) command.");
}
-static int usage_hf_felica_read_without_encryption() {
+static int usage_hf_felica_read_without_encryption(void) {
PrintAndLogEx(NORMAL, "\nInfo: Use this command to read Block Data from authentication-not-required Service.");
PrintAndLogEx(NORMAL, " - Mode shall be Mode0.");
print_number_of_service_constraints();
@@ -215,7 +215,7 @@ static int usage_hf_felica_read_without_encryption() {
return PM3_SUCCESS;
}
-static int usage_hf_felica_write_without_encryption() {
+static int usage_hf_felica_write_without_encryption(void) {
PrintAndLogEx(NORMAL, "\nInfo: Use this command to write Block Data to authentication-not-required Service.");
PrintAndLogEx(NORMAL, " - Mode shall be Mode0.");
print_number_of_service_constraints();
@@ -234,7 +234,7 @@ static int usage_hf_felica_write_without_encryption() {
return PM3_SUCCESS;
}
-static int usage_hf_felica_request_system_code() {
+static int usage_hf_felica_request_system_code(void) {
PrintAndLogEx(NORMAL, "\nInfo: Use this command to acquire System Code registered to the card.");
PrintAndLogEx(NORMAL, " - If a card is divided into more than one System, this command acquires System Code of each System existing in the card.");
PrintAndLogEx(NORMAL, "\nUsage: hf felica rqsyscode [-h] [-i]");
@@ -246,7 +246,7 @@ static int usage_hf_felica_request_system_code() {
return PM3_SUCCESS;
}
-static int usage_hf_felica_reset_mode() {
+static int usage_hf_felica_reset_mode(void) {
PrintAndLogEx(NORMAL, "\nInfo: Use this command to reset Mode to Mode 0.");
print_status_flag1_interpretation();
print_status_flag2_interpration();
@@ -261,7 +261,7 @@ static int usage_hf_felica_reset_mode() {
return PM3_SUCCESS;
}
-static int usage_hf_felica_request_specification_version() {
+static int usage_hf_felica_request_specification_version(void) {
PrintAndLogEx(NORMAL, "\nInfo: Use this command to acquire the version of card OS.");
PrintAndLogEx(NORMAL, " - Response:");
PrintAndLogEx(NORMAL, " - Format Version: Fixed value 00h. Provided only if Status Flag1 = 00h.");
@@ -283,7 +283,7 @@ static int usage_hf_felica_request_specification_version() {
return PM3_SUCCESS;
}
-static int usage_hf_felica_authentication1() {
+static int usage_hf_felica_authentication1(void) {
PrintAndLogEx(NORMAL, "\nInfo: Initiate mutual authentication. This command must always be executed before Authentication2 command"
", and mutual authentication is achieve only after Authentication2 command has succeeded.");
PrintAndLogEx(NORMAL, " - Auth1 Parameters:");
@@ -311,7 +311,7 @@ static int usage_hf_felica_authentication1() {
return PM3_SUCCESS;
}
-static int usage_hf_felica_authentication2() {
+static int usage_hf_felica_authentication2(void) {
PrintAndLogEx(NORMAL, "\nInfo: Complete mutual authentication. This command can only be executed subsquent to Authentication1"
" command.");
PrintAndLogEx(NORMAL, " - Auth2 Parameters:");
@@ -551,7 +551,7 @@ static bool check_last_idm(uint8_t *data, uint16_t datalen) {
* @param wr_noCry_resp frame in which the response will be saved.
* @return success if response was received.
*/
-int send_wr_unencrypted(uint8_t flags, uint16_t datalen, uint8_t *data, bool verbose, felica_status_response_t *wr_noCry_resp) {
+static int send_wr_unencrypted(uint8_t flags, uint16_t datalen, uint8_t *data, bool verbose, felica_status_response_t *wr_noCry_resp) {
clear_and_send_command(flags, datalen, data, verbose);
PacketResponseNG resp;
if (!waitCmdFelica(0, &resp, verbose)) {
@@ -1464,7 +1464,7 @@ static int CmdHFFelicaSimLite(const char *Cmd) {
return PM3_SUCCESS;
}
-static void printSep() {
+static void printSep(void) {
PrintAndLogEx(INFO, "------------------------------------------------------------------------------------");
}
diff --git a/client/src/cmdhficlass.c b/client/src/cmdhficlass.c
index d05afdae2..e46f045a3 100644
--- a/client/src/cmdhficlass.c
+++ b/client/src/cmdhficlass.c
@@ -191,7 +191,7 @@ static int usage_hf_iclass_readblock(void) {
PrintAndLogEx(NORMAL, "");
return PM3_SUCCESS;
}
-static int usage_hf_iclass_readtagfile() {
+static int usage_hf_iclass_readtagfile(void) {
PrintAndLogEx(NORMAL, "Print a iClass tag-dump file\n");
PrintAndLogEx(NORMAL, "Usage: hf iClass readtagfile [f ] [s ] [e ] [v]\n");
PrintAndLogEx(NORMAL, "Options:");
diff --git a/client/src/cmdhflist.c b/client/src/cmdhflist.c
index 7aeac0bc7..16fdb309e 100644
--- a/client/src/cmdhflist.c
+++ b/client/src/cmdhflist.c
@@ -37,7 +37,7 @@ enum MifareAuthSeq {
static enum MifareAuthSeq MifareAuthState;
static TAuthData AuthData;
-void ClearAuthData() {
+void ClearAuthData(void) {
AuthData.uid = 0;
AuthData.nt = 0;
AuthData.first_auth = true;
diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c
index 95e821781..ba017676c 100644
--- a/client/src/cmdhfmf.c
+++ b/client/src/cmdhfmf.c
@@ -3132,7 +3132,7 @@ out:
sector_t *k_sector = NULL;
uint8_t k_sectorsCount = 40;
-void showSectorTable() {
+void showSectorTable(void) {
if (k_sector != NULL) {
printKeyTable(k_sectorsCount, k_sector);
free(k_sector);
@@ -4806,7 +4806,7 @@ static int CmdHFMFNDEF(const char *Cmd) {
return PM3_SUCCESS;
}
-int CmdHFMFPersonalize(const char *cmd) {
+static int CmdHFMFPersonalize(const char *cmd) {
CLIParserInit("hf mf personalize",
"Personalize the UID of a Mifare Classic EV1 card. This is only possible if it is a 7Byte UID card and if it is not already personalized.",
diff --git a/client/src/cmdhfmfhard.c b/client/src/cmdhfmfhard.c
index 6fc146164..b8f3c0471 100644
--- a/client/src/cmdhfmfhard.c
+++ b/client/src/cmdhfmfhard.c
@@ -1302,7 +1302,7 @@ static void simulate_MFplus_RNG(uint32_t test_cuid, uint64_t test_key, uint32_t
}
-static void simulate_acquire_nonces() {
+static void simulate_acquire_nonces(void) {
time_t time1 = time(NULL);
last_sample_clock = 0;
sample_period = 1000; // for simulation
@@ -2108,7 +2108,7 @@ static uint16_t SumProperty(struct Crypto1State *s) {
return (sum_odd * (16 - sum_even) + (16 - sum_odd) * sum_even);
}
-static void Tests() {
+static void Tests(void) {
if (known_target_key == -1)
return;
diff --git a/client/src/cmdhfmfp.c b/client/src/cmdhfmfp.c
index 728101ce7..f9d2e661a 100644
--- a/client/src/cmdhfmfp.c
+++ b/client/src/cmdhfmfp.c
@@ -949,7 +949,7 @@ static int CmdHFMFPWrbl(const char *Cmd) {
#define AES_KEY_LEN 16
#define MAX_KEYS_LIST_LEN 1024
-int MFPKeyCheck(uint8_t startSector, uint8_t endSector, uint8_t startKeyAB, uint8_t endKeyAB,
+static int MFPKeyCheck(uint8_t startSector, uint8_t endSector, uint8_t startKeyAB, uint8_t endKeyAB,
uint8_t keyList[MAX_KEYS_LIST_LEN][AES_KEY_LEN], size_t keyListLen, uint8_t foundKeys[2][64][AES_KEY_LEN + 1],
bool verbose) {
int res;
@@ -1027,7 +1027,7 @@ int MFPKeyCheck(uint8_t startSector, uint8_t endSector, uint8_t startKeyAB, uint
return PM3_SUCCESS;
}
-void Fill2bPattern(uint8_t keyList[MAX_KEYS_LIST_LEN][AES_KEY_LEN], size_t *keyListLen, uint32_t *startPattern) {
+static void Fill2bPattern(uint8_t keyList[MAX_KEYS_LIST_LEN][AES_KEY_LEN], size_t *keyListLen, uint32_t *startPattern) {
for (uint32_t pt = *startPattern; pt < 0x10000; pt++) {
keyList[*keyListLen][0] = (pt >> 8) & 0xff;
keyList[*keyListLen][1] = pt & 0xff;
diff --git a/client/src/cmdhfmfu.c b/client/src/cmdhfmfu.c
index 88e44285e..c71cff645 100644
--- a/client/src/cmdhfmfu.c
+++ b/client/src/cmdhfmfu.c
@@ -855,7 +855,7 @@ static int ulev1_print_configuration(uint32_t tagtype, uint8_t *data, uint8_t st
return PM3_SUCCESS;
}
-static int ulev1_print_counters() {
+static int ulev1_print_counters(void) {
PrintAndLogEx(INFO, "--- " _CYAN_("Tag Counters"));
uint8_t tear[1] = {0};
uint8_t counter[3] = {0, 0, 0};
@@ -1004,7 +1004,7 @@ static int ulc_magic_test(){
return returnValue;
}
*/
-static int ul_magic_test() {
+static int ul_magic_test(void) {
// Magic Ultralight tests
// 1) take present UID, and try to write it back. OBSOLETE
// 2) make a wrong length write to page0, and see if tag answers with ACK/NACK:
diff --git a/client/src/cmdlf.c b/client/src/cmdlf.c
index a08ec2b9e..520407847 100644
--- a/client/src/cmdlf.c
+++ b/client/src/cmdlf.c
@@ -670,7 +670,7 @@ int CmdLFSniff(const char *Cmd) {
return PM3_SUCCESS;
}
-static void ChkBitstream() {
+static void ChkBitstream(void) {
// convert to bitstream if necessary
for (int i = 0; i < (int)(GraphTraceLen / 2); i++) {
if (GraphBuffer[i] > 1 || GraphBuffer[i] < 0) {
diff --git a/client/src/cmdlfem4x.c b/client/src/cmdlfem4x.c
index f0e51b900..f3986b19d 100644
--- a/client/src/cmdlfem4x.c
+++ b/client/src/cmdlfem4x.c
@@ -1055,7 +1055,7 @@ static int CmdEM4x50Dump(const char *Cmd) {
#define EM_PREAMBLE_LEN 6
// download samples from device and copy to Graphbuffer
-static bool downloadSamplesEM() {
+static bool downloadSamplesEM(void) {
// 8 bit preamble + 32 bit word response (max clock (128) * 40bits = 5120 samples)
uint8_t got[6000];
@@ -1097,7 +1097,7 @@ static bool doPreambleSearch(size_t *startIdx) {
return true;
}
-static bool detectFSK() {
+static bool detectFSK(void) {
// detect fsk clock
if (GetFskClock("", false) == 0) {
PrintAndLogEx(DEBUG, "DEBUG: Error - EM: FSK clock failed");
@@ -1112,7 +1112,7 @@ static bool detectFSK() {
return true;
}
// PSK clocks should be easy to detect ( but difficult to demod a non-repeating pattern... )
-static bool detectPSK() {
+static bool detectPSK(void) {
int ans = GetPskClock("", false);
if (ans <= 0) {
PrintAndLogEx(DEBUG, "DEBUG: Error - EM: PSK clock failed");
@@ -1136,7 +1136,7 @@ static bool detectPSK() {
return true;
}
// try manchester - NOTE: ST only applies to T55x7 tags.
-static bool detectASK_MAN() {
+static bool detectASK_MAN(void) {
bool stcheck = false;
if (ASKDemod_ext("0 0 0", false, false, 1, &stcheck) != PM3_SUCCESS) {
PrintAndLogEx(DEBUG, "DEBUG: Error - EM: ASK/Manchester Demod failed");
@@ -1145,7 +1145,7 @@ static bool detectASK_MAN() {
return true;
}
-static bool detectASK_BI() {
+static bool detectASK_BI(void) {
int ans = ASKbiphaseDemod("0 0 1", false);
if (ans != PM3_SUCCESS) {
PrintAndLogEx(DEBUG, "DEBUG: Error - EM: ASK/biphase normal demod failed");
@@ -1158,7 +1158,7 @@ static bool detectASK_BI() {
}
return true;
}
-static bool detectNRZ() {
+static bool detectNRZ(void) {
int ans = NRZrawDemod("0 0 1", false);
if (ans != PM3_SUCCESS) {
PrintAndLogEx(DEBUG, "DEBUG: Error - EM: NRZ normal demod failed");
diff --git a/client/src/cmdlfhitag.c b/client/src/cmdlfhitag.c
index 47971c713..4c35fedf1 100644
--- a/client/src/cmdlfhitag.c
+++ b/client/src/cmdlfhitag.c
@@ -22,7 +22,7 @@
static int CmdHelp(const char *Cmd);
-static char *getHitagTypeStr(uint32_t uid) {
+static const char *getHitagTypeStr(uint32_t uid) {
//uid s/n ********
uint8_t type = (uid >> 4) & 0xF;
switch (type) {
diff --git a/client/src/cmdlfpcf7931.c b/client/src/cmdlfpcf7931.c
index 4c2c9848c..2062c8582 100644
--- a/client/src/cmdlfpcf7931.c
+++ b/client/src/cmdlfpcf7931.c
@@ -32,7 +32,7 @@ struct pcf7931_config configPcf = {
};
// Resets the configuration settings to default values.
-int pcf7931_resetConfig() {
+int pcf7931_resetConfig(void) {
memset(configPcf.Pwd, 0xFF, sizeof(configPcf.Pwd));
configPcf.InitDelay = PCF7931_DEFAULT_INITDELAY;
configPcf.OffsetWidth = PCF7931_DEFAULT_OFFSET_WIDTH;
@@ -40,7 +40,7 @@ int pcf7931_resetConfig() {
return PM3_SUCCESS;
}
-int pcf7931_printConfig() {
+int pcf7931_printConfig(void) {
PrintAndLogEx(NORMAL, "Password (LSB first on bytes) : %s", sprint_hex(configPcf.Pwd, sizeof(configPcf.Pwd)));
PrintAndLogEx(NORMAL, "Tag initialization delay : %d us", configPcf.InitDelay);
PrintAndLogEx(NORMAL, "Offset low pulses width : %d us", configPcf.OffsetWidth);
@@ -48,7 +48,7 @@ int pcf7931_printConfig() {
return PM3_SUCCESS;
}
-static int usage_pcf7931_read() {
+static int usage_pcf7931_read(void) {
PrintAndLogEx(NORMAL, "Usage: lf pcf7931 read [h] ");
PrintAndLogEx(NORMAL, "This command tries to read a PCF7931 tag.");
PrintAndLogEx(NORMAL, "Options:");
@@ -58,7 +58,7 @@ static int usage_pcf7931_read() {
return PM3_SUCCESS;
}
-static int usage_pcf7931_write() {
+static int usage_pcf7931_write(void) {
PrintAndLogEx(NORMAL, "Usage: lf pcf7931 write [h] ");
PrintAndLogEx(NORMAL, "This command tries to write a PCF7931 tag.");
PrintAndLogEx(NORMAL, "Options:");
@@ -71,7 +71,7 @@ static int usage_pcf7931_write() {
return PM3_SUCCESS;
}
-static int usage_pcf7931_config() {
+static int usage_pcf7931_config(void) {
PrintAndLogEx(NORMAL, "Usage: lf pcf7931 config [h] [r] ");
PrintAndLogEx(NORMAL, "This command tries to set the configuration used with PCF7931 commands");
PrintAndLogEx(NORMAL, "The time offsets could be useful to correct slew rate generated by the antenna");
diff --git a/client/src/cmdlft55xx.c b/client/src/cmdlft55xx.c
index 09f2009bd..7f7eccb19 100644
--- a/client/src/cmdlft55xx.c
+++ b/client/src/cmdlft55xx.c
@@ -57,7 +57,7 @@ t55xx_conf_block_t config = {
t55xx_memory_item_t cardmem[T55x7_BLOCK_COUNT] = {{0}};
-t55xx_conf_block_t Get_t55xx_Config() {
+t55xx_conf_block_t Get_t55xx_Config(void) {
return config;
}
@@ -78,7 +78,7 @@ static void print_usage_t55xx_downloadlink(uint8_t ShowAll, uint8_t dl_mode_defa
PrintAndLogEx(NORMAL, " 4 - Try all downlink modes%s", (dl_mode_default == 4) ? " (default)" : "");
}
-static int usage_t55xx_config() {
+static int usage_t55xx_config(void) {
PrintAndLogEx(NORMAL, "Usage: lf t55xx config [c ] [d ] [i [0/1]] [o ] [Q5 [0/1]] [ST [0/1]]");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " h - This help");
@@ -99,7 +99,7 @@ static int usage_t55xx_config() {
PrintAndLogEx(NORMAL, "");
return PM3_SUCCESS;
}
-static int usage_t55xx_read() {
+static int usage_t55xx_read(void) {
PrintAndLogEx(NORMAL, "Usage: lf t55xx read [r ] b [p ] [o] ");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " b - block number to read. Between 0-7");
@@ -119,7 +119,7 @@ static int usage_t55xx_read() {
PrintAndLogEx(NORMAL, "");
return PM3_SUCCESS;
}
-static int usage_t55xx_resetread() {
+static int usage_t55xx_resetread(void) {
PrintAndLogEx(NORMAL, "Send Reset Cmd then lf read the stream to attempt to identify the start of it (needs a demod and/or plot after)");
PrintAndLogEx(NORMAL, "Usage: lf t55xx resetread [r ]");
PrintAndLogEx(NORMAL, "Options:");
@@ -130,7 +130,7 @@ static int usage_t55xx_resetread() {
PrintAndLogEx(NORMAL, "");
return PM3_SUCCESS;
}
-static int usage_t55xx_write() {
+static int usage_t55xx_write(void) {
PrintAndLogEx(NORMAL, "Usage: lf t55xx write [r ] b d [p ] [1] [t] [v]");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " b - block number to write. Between 0-7");
@@ -148,7 +148,7 @@ static int usage_t55xx_write() {
PrintAndLogEx(NORMAL, "");
return PM3_SUCCESS;
}
-static int usage_t55xx_trace() {
+static int usage_t55xx_trace(void) {
PrintAndLogEx(NORMAL, "Usage: lf t55xx trace [1] [r mode]");
PrintAndLogEx(NORMAL, "Options:");
print_usage_t55xx_downloadlink(T55XX_DLMODE_SINGLE, config.downlink_mode);
@@ -160,7 +160,7 @@ static int usage_t55xx_trace() {
PrintAndLogEx(NORMAL, "");
return PM3_SUCCESS;
}
-static int usage_t55xx_info() {
+static int usage_t55xx_info(void) {
PrintAndLogEx(NORMAL, "Usage: lf t55xx info [1] [r ] [c [q]]");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " (default) - read data from tag.");
@@ -180,7 +180,7 @@ static int usage_t55xx_info() {
PrintAndLogEx(NORMAL, "");
return PM3_SUCCESS;
}
-static int usage_t55xx_dump() {
+static int usage_t55xx_dump(void) {
PrintAndLogEx(NORMAL, "Usage: lf t55xx dump [r ] [p [o]]");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " p - OPTIONAL password 4bytes (8 hex symbols)");
@@ -194,7 +194,7 @@ static int usage_t55xx_dump() {
PrintAndLogEx(NORMAL, "");
return PM3_SUCCESS;
}
-static int usage_t55xx_restore() {
+static int usage_t55xx_restore(void) {
PrintAndLogEx(NORMAL, "Usage: lf t55xx restore f [p password]");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " f - filename of the dump file (.bin/.eml)");
@@ -208,7 +208,7 @@ static int usage_t55xx_restore() {
return PM3_SUCCESS;
}
-static int usage_t55xx_detect() {
+static int usage_t55xx_detect(void) {
PrintAndLogEx(NORMAL, "Usage: lf t55xx detect [1] [r ] [p ]");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " 1 - if set, use Graphbuffer otherwise read data from tag.");
@@ -222,7 +222,7 @@ static int usage_t55xx_detect() {
PrintAndLogEx(NORMAL, "");
return PM3_SUCCESS;
}
-static int usage_t55xx_detectP1() {
+static int usage_t55xx_detectP1(void) {
PrintAndLogEx(NORMAL, "Command: Detect Page 1 of a t55xx chip");
PrintAndLogEx(NORMAL, "Usage: lf t55xx p1detect [1] [r ] [p ]");
PrintAndLogEx(NORMAL, "Options:");
@@ -237,7 +237,7 @@ static int usage_t55xx_detectP1() {
PrintAndLogEx(NORMAL, "");
return PM3_SUCCESS;
}
-static int usage_t55xx_wakup() {
+static int usage_t55xx_wakup(void) {
PrintAndLogEx(NORMAL, "Usage: lf t55xx wakeup [h] [r ] p ");
PrintAndLogEx(NORMAL, "This commands sends the Answer-On-Request command and leaves the readerfield ON afterwards.");
PrintAndLogEx(NORMAL, "Options:");
@@ -249,7 +249,7 @@ static int usage_t55xx_wakup() {
PrintAndLogEx(NORMAL, " lf t55xx wakeup p 11223344 - send wakeup password");
return PM3_SUCCESS;
}
-static int usage_t55xx_chk() {
+static int usage_t55xx_chk(void) {
PrintAndLogEx(NORMAL, "This command uses a dictionary attack");
PrintAndLogEx(NORMAL, "press " _YELLOW_("'enter'") " to cancel the command");
PrintAndLogEx(NORMAL, _RED_("WARNING:") " this may brick non-password protected chips!");
@@ -267,7 +267,7 @@ static int usage_t55xx_chk() {
PrintAndLogEx(NORMAL, "");
return PM3_SUCCESS;
}
-static int usage_t55xx_bruteforce() {
+static int usage_t55xx_bruteforce(void) {
PrintAndLogEx(NORMAL, "This command uses bruteforce to scan a number range");
PrintAndLogEx(NORMAL, "press " _YELLOW_("'enter'") " to cancel the command");
PrintAndLogEx(NORMAL, _RED_("WARNING:") " this may brick non-password protected chips!");
@@ -285,7 +285,7 @@ static int usage_t55xx_bruteforce() {
PrintAndLogEx(NORMAL, "");
return PM3_SUCCESS;
}
-static int usage_t55xx_recoverpw() {
+static int usage_t55xx_recoverpw(void) {
PrintAndLogEx(NORMAL, "This command uses a few tricks to try to recover mangled password");
PrintAndLogEx(NORMAL, "press " _YELLOW_("'enter'") " to cancel the command");
PrintAndLogEx(NORMAL, _RED_("WARNING:") " this may brick non-password protected chips!");
@@ -306,7 +306,7 @@ static int usage_t55xx_recoverpw() {
PrintAndLogEx(NORMAL, "");
return PM3_SUCCESS;
}
-static int usage_t55xx_wipe() {
+static int usage_t55xx_wipe(void) {
PrintAndLogEx(NORMAL, "Usage: lf t55xx wipe [h] [Q5] [p ] [c ]");
PrintAndLogEx(NORMAL, "This commands wipes a tag, fills blocks 1-7 with zeros and a default configuration block");
PrintAndLogEx(NORMAL, "Options:");
@@ -319,7 +319,7 @@ static int usage_t55xx_wipe() {
PrintAndLogEx(NORMAL, " lf t55xx wipe q - wipes a T5555 ( Q5 ) tag, config block 0x6001F004");
return PM3_SUCCESS;
}
-static int usage_t55xx_deviceconfig() {
+static int usage_t55xx_deviceconfig(void) {
PrintAndLogEx(NORMAL, "Sets t55x7 timings for direct commands. The timings are set here in Field Clocks (FC), \nwhich is converted to (US) on device");
PrintAndLogEx(NORMAL, "Usage: lf t55xx deviceconfig [r ] a b c d e f g [p]");
PrintAndLogEx(NORMAL, "Options:");
@@ -340,7 +340,7 @@ static int usage_t55xx_deviceconfig() {
PrintAndLogEx(NORMAL, "");
return PM3_SUCCESS;
}
-static int usage_t55xx_protect() {
+static int usage_t55xx_protect(void) {
PrintAndLogEx(NORMAL, "This command sets the pwd bit on T5577.");
PrintAndLogEx(NORMAL, _RED_("WARNING:") " this locks the tag!");
PrintAndLogEx(NORMAL, "Usage: lf t55xx protect [r ] [p ] [o] [n ]");
@@ -356,7 +356,7 @@ static int usage_t55xx_protect() {
PrintAndLogEx(NORMAL, "");
return PM3_SUCCESS;
}
-static int usage_t55xx_dangerraw() {
+static int usage_t55xx_dangerraw(void) {
PrintAndLogEx(NORMAL, "This command allows to emit arbitrary raw commands on T5577 and cut the field after arbitrary duration.");
PrintAndLogEx(NORMAL, _RED_("WARNING:") " this may lock definitively the tag in an unusable state!");
PrintAndLogEx(NORMAL, "Uncontrolled usage can easily write an invalid configuration, activate lock bits,");
@@ -372,7 +372,7 @@ static int usage_t55xx_dangerraw() {
return PM3_SUCCESS;
}
-static int usage_t55xx_clonehelp() {
+static int usage_t55xx_clonehelp(void) {
PrintAndLogEx(NORMAL, "For cloning specific techs on T55xx tags, see commands available in corresponding LF sub-menus, e.g.:");
PrintAndLogEx(NORMAL, _GREEN_("lf awid clone"));
// todo: rename to clone
@@ -408,13 +408,13 @@ static int CmdT55xxCloneHelp(const char *Cmd) {
return usage_t55xx_clonehelp();
}
-void T55x7_SaveBlockData(uint8_t idx, uint32_t data) {
+static void T55x7_SaveBlockData(uint8_t idx, uint32_t data) {
if (idx < T55x7_BLOCK_COUNT) {
cardmem[idx].valid = true;
cardmem[idx].blockdata = data;
}
}
-void T55x7_ClearAllBlockData(void) {
+static void T55x7_ClearAllBlockData(void) {
for (uint8_t idx = 0; idx < T55x7_BLOCK_COUNT; idx++) {
cardmem[idx].valid = false;
cardmem[idx].blockdata = 0x00;
@@ -1011,7 +1011,7 @@ static int SanityOfflineCheck(bool useGraphBuffer) {
return PM3_SUCCESS;
}
-void T55xx_Print_DownlinkMode(uint8_t downlink_mode) {
+static void T55xx_Print_DownlinkMode(uint8_t downlink_mode) {
char msg[80];
sprintf(msg, "Downlink Mode used : ");
diff --git a/client/src/cmdmain.c b/client/src/cmdmain.c
index f9cfe310a..1e9c8d257 100644
--- a/client/src/cmdmain.c
+++ b/client/src/cmdmain.c
@@ -79,7 +79,7 @@ static int usage_auto(void) {
return PM3_SUCCESS;
}
-static void AppendDate(char *s, size_t slen, char *fmt) {
+static void AppendDate(char *s, size_t slen, const char *fmt) {
struct tm *ct, tm_buf;
time_t now = time(NULL);
#if defined(_WIN32)
@@ -287,7 +287,7 @@ int CommandReceived(char *Cmd) {
return CmdsParse(CommandTable, Cmd);
}
-command_t *getTopLevelCommandTable() {
+command_t *getTopLevelCommandTable(void) {
return CommandTable;
}
diff --git a/client/src/cmdsmartcard.c b/client/src/cmdsmartcard.c
index ba48fae96..f21ef5c4a 100644
--- a/client/src/cmdsmartcard.c
+++ b/client/src/cmdsmartcard.c
@@ -875,7 +875,7 @@ static int CmdSmartList(const char *Cmd) {
return 0;
}
-static void smart_brute_prim() {
+static void smart_brute_prim(void) {
uint8_t *buf = calloc(PM3_CMD_DATA_SIZE, sizeof(uint8_t));
if (!buf)
diff --git a/client/src/cmdtrace.c b/client/src/cmdtrace.c
index 41c102aa1..85d2bea09 100644
--- a/client/src/cmdtrace.c
+++ b/client/src/cmdtrace.c
@@ -25,7 +25,7 @@ static int CmdHelp(const char *Cmd);
static uint8_t *trace;
long traceLen = 0;
-static int usage_trace_list() {
+static int usage_trace_list(void) {
PrintAndLogEx(NORMAL, "List protocol data in trace buffer.");
PrintAndLogEx(NORMAL, "Usage: trace list [f][c| <0|1>");
PrintAndLogEx(NORMAL, " f - show frame delay times as well");
@@ -56,14 +56,14 @@ static int usage_trace_list() {
PrintAndLogEx(NORMAL, " trace list iclass");
return PM3_SUCCESS;
}
-static int usage_trace_load() {
+static int usage_trace_load(void) {
PrintAndLogEx(NORMAL, "Load protocol data from file to trace buffer.");
PrintAndLogEx(NORMAL, "Usage: trace load ");
PrintAndLogEx(NORMAL, "Examples:");
PrintAndLogEx(NORMAL, " trace load mytracefile.bin");
return PM3_SUCCESS;
}
-static int usage_trace_save() {
+static int usage_trace_save(void) {
PrintAndLogEx(NORMAL, "Save protocol data from trace buffer to file.");
PrintAndLogEx(NORMAL, "Usage: trace save ");
PrintAndLogEx(NORMAL, "Examples:");
diff --git a/client/src/cmdusart.c b/client/src/cmdusart.c
index 3168d66b7..56d4b88bb 100644
--- a/client/src/cmdusart.c
+++ b/client/src/cmdusart.c
@@ -274,7 +274,7 @@ static int usart_bt_testcomm(uint32_t baudrate, uint8_t parity) {
if (ret != PM3_SUCCESS)
return ret;
- char *string = "AT+VERSION";
+ const char *string = "AT+VERSION";
uint8_t data[PM3_CMD_DATA_SIZE] = {0x00};
size_t len = 0;
@@ -359,7 +359,7 @@ static int CmdUsartBtFactory(const char *Cmd) {
}
PrintAndLogEx(INFO, "Reconfiguring add-on to default settings.");
- char *string;
+ const char *string;
uint8_t data[PM3_CMD_DATA_SIZE];
size_t len = 0;
memset(data, 0, sizeof(data));
diff --git a/client/src/cmdwiegand.c b/client/src/cmdwiegand.c
index 3c939261f..19f166284 100644
--- a/client/src/cmdwiegand.c
+++ b/client/src/cmdwiegand.c
@@ -24,11 +24,11 @@
static int CmdHelp(const char *Cmd);
-static int usage_wiegand_list() {
+static int usage_wiegand_list(void) {
PrintAndLogEx(NORMAL, "List available wiegand formats");
return PM3_SUCCESS;
}
-static int usage_wiegand_encode() {
+static int usage_wiegand_encode(void) {
PrintAndLogEx(NORMAL, "Encode wiegand formatted number to raw hex");
PrintAndLogEx(NORMAL, "Usage: wiegand encode [w ] [ ] {...}");
PrintAndLogEx(NORMAL, "Options:");
@@ -42,7 +42,7 @@ static int usage_wiegand_encode() {
PrintAndLogEx(NORMAL, " wiegand encode w H10301 f 101 c 1337");
return PM3_SUCCESS;
}
-static int usage_wiegand_decode() {
+static int usage_wiegand_decode(void) {
PrintAndLogEx(NORMAL, "Decode raw hex to wiegand format");
PrintAndLogEx(NORMAL, "Usage: wiegand decode [id] ");
PrintAndLogEx(NORMAL, " p ignore invalid parity");
@@ -52,7 +52,7 @@ static int usage_wiegand_decode() {
return PM3_SUCCESS;
}
-void PrintTagId(wiegand_message_t *packed) {
+static void PrintTagId(wiegand_message_t *packed) {
if (packed->Top != 0) {
PrintAndLogEx(SUCCESS, "Card ID: %X%08X%08X",
(uint32_t)packed->Top,
diff --git a/client/src/comms.c b/client/src/comms.c
index 36f035bdd..de5eafb24 100644
--- a/client/src/comms.c
+++ b/client/src/comms.c
@@ -202,7 +202,7 @@ void SendCommandMIX(uint64_t cmd, uint64_t arg0, uint64_t arg1, uint64_t arg2, v
* A better method could have been to have explicit command-ACKS, so we can know which ACK goes to which
* operation. Right now we'll just have to live with this.
*/
-void clearCommandBuffer() {
+void clearCommandBuffer(void) {
//This is a very simple operation
pthread_mutex_lock(&rxBufferMutex);
cmd_tail = cmd_head;
diff --git a/client/src/fileutils.c b/client/src/fileutils.c
index 4ccd4fa8f..ac9196e4c 100644
--- a/client/src/fileutils.c
+++ b/client/src/fileutils.c
@@ -1360,7 +1360,7 @@ static int searchFinalFile(char **foundpath, const char *pm3dir, const char *sea
(strcmp(FIRMWARES_SUBDIR, pm3dir) == 0) ||
(strcmp(BOOTROM_SUBDIR, pm3dir) == 0) ||
(strcmp(FULLIMAGE_SUBDIR, pm3dir) == 0))) {
- char *above = "../";
+ const char *above = "../";
char *path = calloc(strlen(exec_path) + strlen(above) + strlen(pm3dir) + strlen(filename) + 1, sizeof(char));
if (path == NULL)
goto out;
diff --git a/client/src/graph.c b/client/src/graph.c
index d5f62a6b7..2d75f3d30 100644
--- a/client/src/graph.c
+++ b/client/src/graph.c
@@ -116,7 +116,7 @@ bool isGraphBitstream(void) {
return true;
}
-void convertGraphFromBitstream() {
+void convertGraphFromBitstream(void) {
convertGraphFromBitstreamEx(1, 0);
}
diff --git a/client/src/loclass/cipher.c b/client/src/loclass/cipher.c
index 080ff66f5..9cc683300 100644
--- a/client/src/loclass/cipher.c
+++ b/client/src/loclass/cipher.c
@@ -283,7 +283,7 @@ void doMAC_N(uint8_t *address_data_p, uint8_t address_data_size, uint8_t *div_ke
}
#ifndef ON_DEVICE
-int testMAC() {
+int testMAC(void) {
PrintAndLogEx(SUCCESS, "Testing MAC calculation...");
//From the "dismantling.IClass" paper:
diff --git a/client/src/loclass/cipherutils.c b/client/src/loclass/cipherutils.c
index 09f4bccd7..95628226d 100644
--- a/client/src/loclass/cipherutils.c
+++ b/client/src/loclass/cipherutils.c
@@ -190,7 +190,7 @@ void printarr_human_readable(const char *title, uint8_t *arr, int len) {
//-----------------------------
#ifndef ON_DEVICE
-static int testBitStream() {
+static int testBitStream(void) {
uint8_t input [] = {0xDE, 0xAD, 0xBE, 0xEF, 0xDE, 0xAD, 0xBE, 0xEF};
uint8_t output [] = {0, 0, 0, 0, 0, 0, 0, 0};
BitstreamIn in = { input, sizeof(input) * 8, 0};
@@ -215,7 +215,7 @@ static int testBitStream() {
return PM3_SUCCESS;
}
-static int testReversedBitstream() {
+static int testReversedBitstream(void) {
uint8_t input [] = {0xDE, 0xAD, 0xBE, 0xEF, 0xDE, 0xAD, 0xBE, 0xEF};
uint8_t reverse [] = {0, 0, 0, 0, 0, 0, 0, 0};
uint8_t output [] = {0, 0, 0, 0, 0, 0, 0, 0};
diff --git a/client/src/loclass/elite_crack.c b/client/src/loclass/elite_crack.c
index 03a9a3080..5ef58f01e 100644
--- a/client/src/loclass/elite_crack.c
+++ b/client/src/loclass/elite_crack.c
@@ -568,7 +568,7 @@ int bruteforceFileNoKeys(const char *filename) {
// ----------------------------------------------------------------------------
// TEST CODE BELOW
// ----------------------------------------------------------------------------
-static int _testBruteforce() {
+static int _testBruteforce(void) {
PrintAndLogEx(INFO, "Testing crack from dumpfile...");
@@ -596,7 +596,7 @@ static int _testBruteforce() {
return errors;
}
-static int _test_iclass_key_permutation() {
+static int _test_iclass_key_permutation(void) {
uint8_t testcase[8] = {0x6c, 0x8d, 0x44, 0xf9, 0x2a, 0x2d, 0x01, 0xbf};
uint8_t testcase_output[8] = {0};
uint8_t testcase_output_correct[8] = {0x8a, 0x0d, 0xb9, 0x88, 0xbb, 0xa7, 0x90, 0xea};
@@ -622,7 +622,7 @@ static int _test_iclass_key_permutation() {
return 0;
}
-static int _testHash1() {
+static int _testHash1(void) {
uint8_t expected[8] = {0x7E, 0x72, 0x2F, 0x40, 0x2D, 0x02, 0x51, 0x42};
uint8_t csn[8] = {0x01, 0x02, 0x03, 0x04, 0xF7, 0xFF, 0x12, 0xE0};
uint8_t k[8] = {0};
diff --git a/client/src/loclass/ikeys.c b/client/src/loclass/ikeys.c
index 11a082867..3bbe9fc2b 100644
--- a/client/src/loclass/ikeys.c
+++ b/client/src/loclass/ikeys.c
@@ -219,7 +219,7 @@ static void permute(BitstreamIn *p_in, uint64_t z, int l, int r, BitstreamOut *o
}
}
-static void printbegin() {
+static void printbegin(void) {
if (debug_print < 2)
return;
@@ -369,7 +369,7 @@ void diversifyKey(uint8_t csn[8], uint8_t key[8], uint8_t div_key[8]) {
hash0(crypt_csn, div_key);
}
/*
-static void testPermute() {
+static void testPermute(void) {
uint64_t x = 0;
pushbackSixBitByte(&x, 0x00, 0);
pushbackSixBitByte(&x, 0x01, 1);
@@ -555,7 +555,7 @@ Testcase testcases[] = {
{{0}, {0}, {0}}
};
-static int testKeyDiversificationWithMasterkeyTestcases() {
+static int testKeyDiversificationWithMasterkeyTestcases(void) {
int i, error = 0;
uint8_t empty[8] = {0};
@@ -630,7 +630,7 @@ static int testDES2(uint64_t csn, uint64_t expected) {
* @brief doTestsWithKnownInputs
* @return
*/
-static int doTestsWithKnownInputs() {
+static int doTestsWithKnownInputs(void) {
// KSel from http://www.proxmark.org/forum/viewtopic.php?pid=10977#p10977
int errors = 0;
PrintAndLogEx(SUCCESS, "Testing DES encryption");
diff --git a/client/src/pm3_binlib.c b/client/src/pm3_binlib.c
index d694ee3b0..f4e49c137 100644
--- a/client/src/pm3_binlib.c
+++ b/client/src/pm3_binlib.c
@@ -318,6 +318,7 @@ static const luaL_Reg binlib[] = {
{NULL, NULL}
};
+LUALIB_API int luaopen_binlib(lua_State *L);
LUALIB_API int luaopen_binlib(lua_State *L) {
luaL_newlib(L, binlib);
return 1;
diff --git a/client/src/pm3_bitlib.c b/client/src/pm3_bitlib.c
index 15fdbd5d0..b5ef6e0ae 100644
--- a/client/src/pm3_bitlib.c
+++ b/client/src/pm3_bitlib.c
@@ -126,6 +126,7 @@ static const struct luaL_Reg bitlib[] = {
{NULL, NULL}
};
+LUALIB_API int luaopen_bit(lua_State *L);
LUALIB_API int luaopen_bit(lua_State *L) {
luaL_newlib(L, bitlib);
//luaL_register(L, "bit", bitlib);
diff --git a/client/src/preferences.c b/client/src/preferences.c
index 4f92eb06e..0ef715075 100644
--- a/client/src/preferences.c
+++ b/client/src/preferences.c
@@ -44,7 +44,7 @@ static char *prefGetFilename(void) {
if (searchHomeFilePath(&path, preferencesFilename, false) == PM3_SUCCESS)
return path;
else
- return preferencesFilename;
+ return strdup(preferencesFilename);
}
int preferences_load(void) {
@@ -314,7 +314,7 @@ void preferences_load_callback(json_t *root) {
// Help Functions
-static int usage_set_emoji() {
+static int usage_set_emoji(void) {
PrintAndLogEx(NORMAL, "Usage: pref set emoji ");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " "_GREEN_("help")" - This help");
@@ -325,7 +325,7 @@ static int usage_set_emoji() {
return PM3_SUCCESS;
}
-static int usage_set_color() {
+static int usage_set_color(void) {
PrintAndLogEx(NORMAL, "Usage: pref set color ");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " "_GREEN_("help")" - This help");
@@ -334,7 +334,7 @@ static int usage_set_color() {
return PM3_SUCCESS;
}
-static int usage_set_debug() {
+static int usage_set_debug(void) {
PrintAndLogEx(NORMAL, "Usage: pref set clientdebug ");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " "_GREEN_("help")" - This help");
@@ -344,7 +344,7 @@ static int usage_set_debug() {
return PM3_SUCCESS;
}
/*
-static int usage_set_devicedebug() {
+static int usage_set_devicedebug(void) {
PrintAndLogEx(NORMAL, "Usage: pref set devicedebug ");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " "_GREEN_("help")" - This help");
@@ -357,7 +357,7 @@ static int usage_set_devicedebug() {
return PM3_SUCCESS;
}
*/
-static int usage_set_hints() {
+static int usage_set_hints(void) {
PrintAndLogEx(NORMAL, "Usage: pref set hints ");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " "_GREEN_("help")" - This help");
@@ -366,7 +366,7 @@ static int usage_set_hints() {
return PM3_SUCCESS;
}
/*
-static int usage_set_savePaths() {
+static int usage_set_savePaths(void) {
PrintAndLogEx(NORMAL, "Usage: pref set savepaths [help] [create] [default ] [dump ] [trace ]");
PrintAndLogEx(NORMAL, "Options:");
PrintAndLogEx(NORMAL, " "_GREEN_("help")" - This help");
@@ -382,7 +382,7 @@ static int usage_set_savePaths() {
// typedef enum preferenceId {prefNONE,prefHELP,prefEMOJI,prefCOLOR,prefPLOT,prefOVERLAY,prefHINTS,prefCLIENTDEBUG} preferenceId_t;
typedef enum prefShowOpt {prefShowNone, prefShowOLD, prefShowNEW} prefShowOpt_t;
-const char *prefShowMsg(prefShowOpt_t Opt) {
+static const char *prefShowMsg(prefShowOpt_t Opt) {
switch (Opt) {
case prefShowOLD:
return _YELLOW_("[old]");
@@ -395,7 +395,7 @@ const char *prefShowMsg(prefShowOpt_t Opt) {
return "";
}
-void showEmojiState(prefShowOpt_t Opt) {
+static void showEmojiState(prefShowOpt_t Opt) {
switch (session.emoji_mode) {
case ALIAS:
@@ -415,7 +415,7 @@ void showEmojiState(prefShowOpt_t Opt) {
}
}
-void showColorState(prefShowOpt_t Opt) {
+static void showColorState(prefShowOpt_t Opt) {
if (session.supports_colors)
PrintAndLogEx(NORMAL, " %s color.................. "_GREEN_("ansi"), prefShowMsg(Opt));
@@ -423,7 +423,7 @@ void showColorState(prefShowOpt_t Opt) {
PrintAndLogEx(NORMAL, " %s color.................. "_WHITE_("off"), prefShowMsg(Opt));
}
-void showClientDebugState(prefShowOpt_t Opt) {
+static void showClientDebugState(prefShowOpt_t Opt) {
switch (session.client_debug_level) {
case cdbOFF:
@@ -440,7 +440,7 @@ void showClientDebugState(prefShowOpt_t Opt) {
}
}
/*
-void showDeviceDebugState(prefShowOpt_t Opt) {
+static void showDeviceDebugState(prefShowOpt_t Opt) {
switch (session.device_debug_level) {
case ddbOFF:
PrintAndLogEx(NORMAL, " %s device debug........... "_WHITE_("off"), prefShowMsg(Opt));
@@ -463,7 +463,7 @@ void showDeviceDebugState(prefShowOpt_t Opt) {
}
*/
/*
-void showSavePathState(savePaths_t pathIndex, prefShowOpt_t Opt) {
+static void showSavePathState(savePaths_t pathIndex, prefShowOpt_t Opt) {
char tempStr[50];
@@ -485,18 +485,19 @@ void showSavePathState(savePaths_t pathIndex, prefShowOpt_t Opt) {
else
PrintAndLogEx(NORMAL, " %s %s "_GREEN_("%s"), prefShowMsg(Opt), tempStr, session.defaultPaths[pathIndex]);
}
-*/
-void showPlotPosState(void) {
+
+static void showPlotPosState(void) {
PrintAndLogEx(NORMAL, " Plot window............ X "_GREEN_("%4d")" Y "_GREEN_("%4d")" H "_GREEN_("%4d")" W "_GREEN_("%4d"),
session.plot.x, session.plot.y, session.plot.h, session.plot.w);
}
-void showOverlayPosState(void) {
+static void showOverlayPosState(void) {
PrintAndLogEx(NORMAL, " Slider/Overlay window.. X "_GREEN_("%4d")" Y "_GREEN_("%4d")" H "_GREEN_("%4d")" W "_GREEN_("%4d"),
session.overlay.x, session.overlay.y, session.overlay.h, session.overlay.w);
}
+*/
-void showHintsState(prefShowOpt_t Opt) {
+static void showHintsState(prefShowOpt_t Opt) {
if (session.show_hints)
PrintAndLogEx(NORMAL, " %s hints.................. "_GREEN_("on"), prefShowMsg(Opt));
else
@@ -850,28 +851,28 @@ static int setCmdSavePaths (const char *Cmd) {
return PM3_SUCCESS;
}
-*/
-int getCmdHelp(const char *Cmd) {
+static int getCmdHelp(const char *Cmd) {
return PM3_SUCCESS;
}
+*/
-int getCmdEmoji(const char *Cmd) {
+static int getCmdEmoji(const char *Cmd) {
showEmojiState(prefShowNone);
return PM3_SUCCESS;
}
-int getCmdHint(const char *Cmd) {
+static int getCmdHint(const char *Cmd) {
showHintsState(prefShowNone);
return PM3_SUCCESS;
}
-int getCmdColor(const char *Cmd) {
+static int getCmdColor(const char *Cmd) {
showColorState(prefShowNone);
return PM3_SUCCESS;
}
-int getCmdDebug(const char *Cmd) {
+static int getCmdDebug(const char *Cmd) {
showClientDebugState(prefShowNone);
return PM3_SUCCESS;
}
@@ -904,12 +905,12 @@ static int setCmdHelp(const char *Cmd) {
return PM3_SUCCESS;
}
-int CmdPrefGet(const char *Cmd) {
+static int CmdPrefGet(const char *Cmd) {
clearCommandBuffer();
return CmdsParse(getCommandTable, Cmd);
}
-int CmdPrefSet(const char *Cmd) {
+static int CmdPrefSet(const char *Cmd) {
clearCommandBuffer();
return CmdsParse(setCommandTable, Cmd);
}
diff --git a/client/src/proxgui.h b/client/src/proxgui.h
index c9cd0096d..bfcbc78e1 100644
--- a/client/src/proxgui.h
+++ b/client/src/proxgui.h
@@ -59,7 +59,6 @@ extern uint8_t g_debugMode;
#ifndef FILE_PATH_SIZE
#define FILE_PATH_SIZE 1000
#endif
-extern uint8_t gui_serial_port_name[FILE_PATH_SIZE];
#ifdef __cplusplus
}
diff --git a/client/src/proxguiqt.cpp b/client/src/proxguiqt.cpp
index 855b41c87..59bbddb69 100644
--- a/client/src/proxguiqt.cpp
+++ b/client/src/proxguiqt.cpp
@@ -27,6 +27,7 @@
#include "proxgui.h"
#include
#include "ui.h"
+#include "comms.h"
extern "C" int preferences_save(void);
diff --git a/client/src/proxmark3.c b/client/src/proxmark3.c
index 6010fb981..80fd958b1 100644
--- a/client/src/proxmark3.c
+++ b/client/src/proxmark3.c
@@ -116,8 +116,8 @@ static void showBanner(void) {
static const char *prompt_dev = "";
static const char *prompt_ctx = "";
-static void prompt_compose(char *buf, size_t buflen, const char *prompt_ctx, const char *prompt_dev) {
- snprintf(buf, buflen - 1, PROXPROMPT_COMPOSE, prompt_dev, prompt_ctx);
+static void prompt_compose(char *buf, size_t buflen, const char *promptctx, const char *promptdev) {
+ snprintf(buf, buflen - 1, PROXPROMPT_COMPOSE, promptdev, promptctx);
}
static int check_comm(void) {
@@ -155,11 +155,11 @@ int push_cmdscriptfile(char *path, bool stayafter) {
return PM3_SUCCESS;
}
-static FILE *current_cmdscriptfile() {
+static FILE *current_cmdscriptfile(void) {
return cmdscriptfile[cmdscriptfile_idx];
}
-static bool pop_cmdscriptfile() {
+static bool pop_cmdscriptfile(void) {
fclose(cmdscriptfile[cmdscriptfile_idx]);
cmdscriptfile[cmdscriptfile_idx--] = NULL;
if (cmdscriptfile_idx == 0)
diff --git a/client/src/util.c b/client/src/util.c
index 3d0c6bd87..fb131e987 100644
--- a/client/src/util.c
+++ b/client/src/util.c
@@ -823,12 +823,6 @@ void wiegand_add_parity_swapped(uint8_t *target, uint8_t *source, uint8_t length
*(target) = GetParity(source + length / 2, EVEN, length / 2);
}
-// xor two arrays together for len items. The dst array contains the new xored values.
-void xor(unsigned char *dst, unsigned char *src, size_t len) {
- for (; len > 0; len--, dst++, src++)
- *dst ^= *src;
-}
-
// Pack a bitarray into a uint32_t.
uint32_t PackBits(uint8_t start, uint8_t len, uint8_t *bits) {
diff --git a/client/src/util.h b/client/src/util.h
index 59591ac24..3f67c33f4 100644
--- a/client/src/util.h
+++ b/client/src/util.h
@@ -21,8 +21,8 @@
# define FILE_PATH_SIZE 1000
#endif
-uint8_t g_debugMode;
-uint8_t g_printAndLog;
+extern uint8_t g_debugMode;
+extern uint8_t g_printAndLog;
#define PRINTANDLOG_PRINT 1
#define PRINTANDLOG_LOG 2
diff --git a/client/src/wiegand_formats.c b/client/src/wiegand_formats.c
index 0c3c09fb6..13c08f143 100644
--- a/client/src/wiegand_formats.c
+++ b/client/src/wiegand_formats.c
@@ -602,7 +602,7 @@ static const cardformat_t FormatTable[] = {
{NULL, NULL, NULL, NULL, {0, 0, 0, 0, 0}} // Must null terminate array
};
-void HIDListFormats() {
+void HIDListFormats(void) {
if (FormatTable[0].Name == NULL)
return;
diff --git a/client/src/wiegand_formats.h b/client/src/wiegand_formats.h
index 2b9b3df05..4ac36fdcf 100644
--- a/client/src/wiegand_formats.h
+++ b/client/src/wiegand_formats.h
@@ -39,7 +39,7 @@ typedef struct {
cardformatdescriptor_t Fields;
} cardformat_t;
-void HIDListFormats();
+void HIDListFormats(void);
int HIDFindCardFormat(const char *format);
cardformat_t HIDGetCardFormat(int idx);
bool HIDPack(int format_idx, wiegand_card_t *card, wiegand_message_t *packed);
diff --git a/client/src/wiegand_formatutils.c b/client/src/wiegand_formatutils.c
index 836da717d..cee0590ac 100644
--- a/client/src/wiegand_formatutils.c
+++ b/client/src/wiegand_formatutils.c
@@ -64,7 +64,7 @@ bool set_bit_by_position(wiegand_message_t *data, bool value, uint8_t pos) {
* If the definition of the wiegand_message struct changes, this function must also
* be updated to match.
*/
-void message_datacopy(wiegand_message_t *src, wiegand_message_t *dest) {
+static void message_datacopy(wiegand_message_t *src, wiegand_message_t *dest) {
dest->Bot = src->Bot;
dest->Mid = src->Mid;
dest->Top = src->Top;
From 6221d28e4328649c87b3819b715303a06bd04d82 Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Sun, 3 May 2020 12:19:42 +0200
Subject: [PATCH 050/632] cflags
---
client/Makefile | 9 +++++++--
1 file changed, 7 insertions(+), 2 deletions(-)
diff --git a/client/Makefile b/client/Makefile
index 1f857e584..1cdc18f73 100644
--- a/client/Makefile
+++ b/client/Makefile
@@ -56,8 +56,13 @@ ZLIB = $(OBJDIR)/libz.a
LIBS = -I$(LUALIBPATH) -I$(MBEDTLSLIBPATH) -I$(JANSSONLIBPATH) -I$(CBORLIBPATH) -I$(ZLIBPATH) -I$(REVENGPATH) -I$(AMIIBOLIBPATH) -I$(HARDNESTEDPATH) -I$(CLIPARSERPATH)
INCLUDES_CLIENT += -I./src -I../include -I../common -I../common_fpga $(LIBS)
#CFLAGS ?= -Wall -Werror -O3
-CFLAGS ?= -Wall -Werror -O3 -Wchar-subscripts -Wundef -Wcast-align -Wwrite-strings -Wunused -Wuninitialized -Wpointer-arith -Winline -Wformat -Wformat-security -Winit-self -Wmissing-include-dirs -Wstrict-prototypes -Wnested-externs -Wmissing-declarations
-# -Wshadow -Wmissing-prototypes -Wredundant-decls
+ifneq ($(platform),Darwin)
+# readline has strict-prototype issues
+CFLAGS ?= -Wall -Werror -O3 -Wmissing-prototypes -Wchar-subscripts -Wundef -Wcast-align -Wwrite-strings -Wunused -Wuninitialized -Wpointer-arith -Winline -Wformat -Wformat-security -Winit-self -Wmissing-include-dirs -Wnested-externs -Wmissing-declarations
+else
+CFLAGS ?= -Wall -Werror -O3 -Wmissing-prototypes -Wchar-subscripts -Wundef -Wcast-align -Wwrite-strings -Wunused -Wuninitialized -Wpointer-arith -Winline -Wformat -Wformat-security -Winit-self -Wmissing-include-dirs -Wstrict-prototypes -Wnested-externs -Wmissing-declarations
+endif
+# -Wshadow -Wredundant-decls
# -Wbad-function-cast -Wextra -Wswitch-enum -Wold-style-definition
# We cannot just use CFLAGS+=... because it has impact on sub-makes if CFLAGS is defined in env:
From 19be62f7e6a74a01dc9844d3fdc334c176b0b65d Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Sun, 3 May 2020 12:23:55 +0200
Subject: [PATCH 051/632] stricter warnings: Wredundant-decls
---
client/Makefile | 6 +++---
client/src/cmddata.h | 1 -
client/src/cmdhfmfu.h | 9 ---------
client/src/graph.h | 5 +----
client/src/proxgui.h | 19 -------------------
client/src/proxguiqt.cpp | 6 ++++--
client/src/scripting.c | 1 +
client/src/ui.h | 2 +-
common/lfdemod.c | 1 +
9 files changed, 11 insertions(+), 39 deletions(-)
diff --git a/client/Makefile b/client/Makefile
index 1cdc18f73..cbbf07e15 100644
--- a/client/Makefile
+++ b/client/Makefile
@@ -58,11 +58,11 @@ INCLUDES_CLIENT += -I./src -I../include -I../common -I../common_fpga $(LIBS)
#CFLAGS ?= -Wall -Werror -O3
ifneq ($(platform),Darwin)
# readline has strict-prototype issues
-CFLAGS ?= -Wall -Werror -O3 -Wmissing-prototypes -Wchar-subscripts -Wundef -Wcast-align -Wwrite-strings -Wunused -Wuninitialized -Wpointer-arith -Winline -Wformat -Wformat-security -Winit-self -Wmissing-include-dirs -Wnested-externs -Wmissing-declarations
+CFLAGS ?= -Wall -Werror -O3 -Wredundant-decls -Wmissing-prototypes -Wchar-subscripts -Wundef -Wcast-align -Wwrite-strings -Wunused -Wuninitialized -Wpointer-arith -Winline -Wformat -Wformat-security -Winit-self -Wmissing-include-dirs -Wnested-externs -Wmissing-declarations
else
-CFLAGS ?= -Wall -Werror -O3 -Wmissing-prototypes -Wchar-subscripts -Wundef -Wcast-align -Wwrite-strings -Wunused -Wuninitialized -Wpointer-arith -Winline -Wformat -Wformat-security -Winit-self -Wmissing-include-dirs -Wstrict-prototypes -Wnested-externs -Wmissing-declarations
+CFLAGS ?= -Wall -Werror -O3 -Wredundant-decls -Wmissing-prototypes -Wchar-subscripts -Wundef -Wcast-align -Wwrite-strings -Wunused -Wuninitialized -Wpointer-arith -Winline -Wformat -Wformat-security -Winit-self -Wmissing-include-dirs -Wstrict-prototypes -Wnested-externs -Wmissing-declarations
endif
-# -Wshadow -Wredundant-decls
+# -Wshadow
# -Wbad-function-cast -Wextra -Wswitch-enum -Wold-style-definition
# We cannot just use CFLAGS+=... because it has impact on sub-makes if CFLAGS is defined in env:
diff --git a/client/src/cmddata.h b/client/src/cmddata.h
index a19bead27..4a740f8a2 100644
--- a/client/src/cmddata.h
+++ b/client/src/cmddata.h
@@ -81,6 +81,5 @@ extern size_t DemodBufferLen;
extern int g_DemodClock;
extern size_t g_DemodStartIdx;
-extern uint8_t g_debugMode;
#endif
diff --git a/client/src/cmdhfmfu.h b/client/src/cmdhfmfu.h
index be52b1ed8..0f87cb3f6 100644
--- a/client/src/cmdhfmfu.h
+++ b/client/src/cmdhfmfu.h
@@ -29,15 +29,6 @@ void printMFUdumpEx(mfu_dump_t *card, uint16_t pages, uint8_t startpage);
int CmdHFMFUltra(const char *Cmd);
-uint32_t ul_ev1_pwdgenA(uint8_t *uid);
-uint32_t ul_ev1_pwdgenB(uint8_t *uid);
-uint32_t ul_ev1_pwdgenC(uint8_t *uid);
-uint32_t ul_ev1_pwdgenD(uint8_t *uid);
-
-uint16_t ul_ev1_packgenA(uint8_t *uid);
-uint16_t ul_ev1_packgenB(uint8_t *uid);
-uint16_t ul_ev1_packgenC(uint8_t *uid);
-uint16_t ul_ev1_packgenD(uint8_t *uid);
uint16_t ul_ev1_packgen_VCNEW(uint8_t *uid, uint32_t pwd);
uint32_t ul_ev1_otpgenA(uint8_t *uid);
diff --git a/client/src/graph.h b/client/src/graph.h
index 01b20c7e2..b753f418d 100644
--- a/client/src/graph.h
+++ b/client/src/graph.h
@@ -30,10 +30,7 @@ int GetNrzClock(const char *str, bool printAns);
int GetFskClock(const char *str, bool printAns);
bool fskClocks(uint8_t *fc1, uint8_t *fc2, uint8_t *rf1, int *firstClockEdge);
-// Max graph trace len: 40000 (bigbuf) * 8 (at 1 bit per sample)
-#ifndef MAX_GRAPH_TRACE_LEN
-#define MAX_GRAPH_TRACE_LEN (40000 * 8 )
-#endif
+#define MAX_GRAPH_TRACE_LEN (40000 * 8)
#define GRAPH_SAVE 1
#define GRAPH_RESTORE 0
diff --git a/client/src/proxgui.h b/client/src/proxgui.h
index bfcbc78e1..4666cccc3 100644
--- a/client/src/proxgui.h
+++ b/client/src/proxgui.h
@@ -26,12 +26,6 @@ void RepaintGraphWindow(void);
void MainGraphics(void);
void InitGraphics(int argc, char **argv, char *script_cmds_file, char *script_cmd, bool stayInCommandLoop);
void ExitGraphics(void);
-#ifndef MAX_GRAPH_TRACE_LEN
-#define MAX_GRAPH_TRACE_LEN (40000 * 8)
-#endif
-extern int GraphBuffer[MAX_GRAPH_TRACE_LEN];
-extern size_t GraphTraceLen;
-extern int s_Buff[MAX_GRAPH_TRACE_LEN];
extern double CursorScaleFactor;
extern int PlotGridX, PlotGridY, PlotGridXdefault, PlotGridYdefault, GridOffset;
@@ -40,21 +34,8 @@ extern int CommandFinished;
extern int offline;
extern bool GridLocked;
-//Operations defined in data_operations
-//int autoCorr(const int* in, int *out, size_t len, int window);
-int AskEdgeDetect(const int *in, int *out, int len, int threshold);
-int AutoCorrelate(const int *in, int *out, size_t len, size_t window, bool SaveGrph, bool verbose);
-int directionalThreshold(const int *in, int *out, size_t len, int8_t up, int8_t down);
-void save_restoreGB(uint8_t saveOpt);
-
#define GRAPH_SAVE 1
#define GRAPH_RESTORE 0
-#define MAX_DEMOD_BUF_LEN (1024*128)
-extern uint8_t DemodBuffer[MAX_DEMOD_BUF_LEN];
-extern size_t DemodBufferLen;
-extern size_t g_DemodStartIdx;
-extern bool showDemod;
-extern uint8_t g_debugMode;
#ifndef FILE_PATH_SIZE
#define FILE_PATH_SIZE 1000
diff --git a/client/src/proxguiqt.cpp b/client/src/proxguiqt.cpp
index 59bbddb69..7f0dcb8a8 100644
--- a/client/src/proxguiqt.cpp
+++ b/client/src/proxguiqt.cpp
@@ -26,12 +26,14 @@
#include
#include "proxgui.h"
#include
-#include "ui.h"
-#include "comms.h"
extern "C" int preferences_save(void);
extern "C" {
+#include "ui.h"
+#include "comms.h"
+#include "graph.h"
+#include "cmddata.h"
#include "util_darwin.h"
}
diff --git a/client/src/scripting.c b/client/src/scripting.c
index 756799626..25bda6322 100644
--- a/client/src/scripting.c
+++ b/client/src/scripting.c
@@ -33,6 +33,7 @@
#include "protocols.h"
#include "fileutils.h" // searchfile
#include "cmdlf.h" // lf_config
+#include "generator.h"
static int returnToLuaWithError(lua_State *L, const char *fmt, ...) {
char buffer[200];
diff --git a/client/src/ui.h b/client/src/ui.h
index ee101601e..8ba9c06a4 100644
--- a/client/src/ui.h
+++ b/client/src/ui.h
@@ -42,7 +42,7 @@ typedef struct {
} session_arg_t;
extern session_arg_t session;
-
+extern bool showDemod;
#ifndef M_PI
#define M_PI 3.14159265358979323846264338327
#endif
diff --git a/common/lfdemod.c b/common/lfdemod.c
index 8b10b2fb3..ee6d6afe0 100644
--- a/common/lfdemod.c
+++ b/common/lfdemod.c
@@ -51,6 +51,7 @@
#ifndef ON_DEVICE
#include "ui.h"
+#include "util.h"
# include "cmddata.h"
# define prnt(args...) PrintAndLogEx(DEBUG, ## args );
#else
From ed1fb14f5f00fe65d76a8b1057b4a6eac9030bf9 Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Sun, 3 May 2020 12:46:46 +0200
Subject: [PATCH 052/632] rework C includes in C++
---
client/src/cmddata.h | 7 +++++++
client/src/comms.h | 7 +++++++
client/src/graph.h | 7 +++++++
client/src/proxgui.h | 1 -
client/src/proxguiqt.cpp | 9 +++------
client/src/ui.h | 9 ++++++++-
client/src/util_darwin.h | 7 +++++++
7 files changed, 39 insertions(+), 8 deletions(-)
diff --git a/client/src/cmddata.h b/client/src/cmddata.h
index 4a740f8a2..a7a69e430 100644
--- a/client/src/cmddata.h
+++ b/client/src/cmddata.h
@@ -13,6 +13,10 @@
#include "common.h"
+#ifdef __cplusplus
+extern "C" {
+#endif
+
//#include //size_t
int CmdData(const char *Cmd);
@@ -82,4 +86,7 @@ extern size_t DemodBufferLen;
extern int g_DemodClock;
extern size_t g_DemodStartIdx;
+#ifdef __cplusplus
+}
+#endif
#endif
diff --git a/client/src/comms.h b/client/src/comms.h
index 288e8a326..42f5580a6 100644
--- a/client/src/comms.h
+++ b/client/src/comms.h
@@ -16,6 +16,10 @@
#include "pm3_cmd.h" // Packet structs
#include "util.h" // FILE_PATH_SIZE
+#ifdef __cplusplus
+extern "C" {
+#endif
+
#ifndef DropField
#define DropField() { \
clearCommandBuffer(); SendCommandNG(CMD_HF_DROPFIELD, NULL, 0); \
@@ -83,6 +87,9 @@ bool WaitForResponse(uint32_t cmd, PacketResponseNG *response);
//bool GetFromDevice(DeviceMemType_t memtype, uint8_t *dest, uint32_t bytes, uint32_t start_index, PacketResponseNG *response, size_t ms_timeout, bool show_warning);
bool GetFromDevice(DeviceMemType_t memtype, uint8_t *dest, uint32_t bytes, uint32_t start_index, uint8_t *data, uint32_t datalen, PacketResponseNG *response, size_t ms_timeout, bool show_warning);
+#ifdef __cplusplus
+}
+#endif
#endif
diff --git a/client/src/graph.h b/client/src/graph.h
index b753f418d..a53d65c06 100644
--- a/client/src/graph.h
+++ b/client/src/graph.h
@@ -13,6 +13,10 @@
#include "common.h"
+#ifdef __cplusplus
+extern "C" {
+#endif
+
void AppendGraph(bool redraw, uint16_t clock, int bit);
size_t ClearGraph(bool redraw);
bool HasGraphData(void);
@@ -38,4 +42,7 @@ extern int GraphBuffer[MAX_GRAPH_TRACE_LEN];
extern size_t GraphTraceLen;
extern int s_Buff[MAX_GRAPH_TRACE_LEN];
+#ifdef __cplusplus
+}
+#endif
#endif
diff --git a/client/src/proxgui.h b/client/src/proxgui.h
index 4666cccc3..cc9c9e118 100644
--- a/client/src/proxgui.h
+++ b/client/src/proxgui.h
@@ -18,7 +18,6 @@ extern "C" {
#include
#include
#include
-//#include "comms.h"
void ShowGraphWindow(void);
void HideGraphWindow(void);
diff --git a/client/src/proxguiqt.cpp b/client/src/proxguiqt.cpp
index 7f0dcb8a8..f3f49b9a0 100644
--- a/client/src/proxguiqt.cpp
+++ b/client/src/proxguiqt.cpp
@@ -24,18 +24,15 @@
#include
#include
#include
-#include "proxgui.h"
#include
-
-extern "C" int preferences_save(void);
-
-extern "C" {
+#include "proxgui.h"
#include "ui.h"
#include "comms.h"
#include "graph.h"
#include "cmddata.h"
#include "util_darwin.h"
-}
+
+extern "C" int preferences_save(void);
bool g_useOverlays = false;
int g_absVMax = 0;
diff --git a/client/src/ui.h b/client/src/ui.h
index 8ba9c06a4..7a2c90659 100644
--- a/client/src/ui.h
+++ b/client/src/ui.h
@@ -11,10 +11,14 @@
#ifndef UI_H__
#define UI_H__
-#include "common.h"
#include
+#include "common.h"
#include "ansi.h"
+#ifdef __cplusplus
+extern "C" {
+#endif
+
#define _USE_MATH_DEFINES
typedef enum logLevel {NORMAL, SUCCESS, INFO, FAILED, WARNING, ERR, DEBUG, INPLACE, HINT} logLevel_t;
@@ -60,4 +64,7 @@ extern pthread_mutex_t print_lock;
void iceIIR_Butterworth(int *data, const size_t len);
void iceSimple_Filter(int *data, const size_t len, uint8_t k);
+#ifdef __cplusplus
+}
+#endif
#endif
diff --git a/client/src/util_darwin.h b/client/src/util_darwin.h
index 709680cdc..001282578 100644
--- a/client/src/util_darwin.h
+++ b/client/src/util_darwin.h
@@ -11,9 +11,16 @@
#ifndef UTIL_DARWIN_H__
#define UTIL_DARWIN_H__
+#ifdef __cplusplus
+extern "C" {
+#endif
+
void disableAppNap(const char *reason);
void enableAppNap(void);
void makeUnfocusable(void);
void makeFocusable(void);
+#ifdef __cplusplus
+}
+#endif
#endif
From 82ad1b683a9a2ace84a53d228204d8387e102070 Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Sun, 3 May 2020 12:50:33 +0200
Subject: [PATCH 053/632] bug ifneq <> ifeq
---
client/Makefile | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/client/Makefile b/client/Makefile
index cbbf07e15..48a1a3591 100644
--- a/client/Makefile
+++ b/client/Makefile
@@ -56,7 +56,7 @@ ZLIB = $(OBJDIR)/libz.a
LIBS = -I$(LUALIBPATH) -I$(MBEDTLSLIBPATH) -I$(JANSSONLIBPATH) -I$(CBORLIBPATH) -I$(ZLIBPATH) -I$(REVENGPATH) -I$(AMIIBOLIBPATH) -I$(HARDNESTEDPATH) -I$(CLIPARSERPATH)
INCLUDES_CLIENT += -I./src -I../include -I../common -I../common_fpga $(LIBS)
#CFLAGS ?= -Wall -Werror -O3
-ifneq ($(platform),Darwin)
+ifeq ($(platform),Darwin)
# readline has strict-prototype issues
CFLAGS ?= -Wall -Werror -O3 -Wredundant-decls -Wmissing-prototypes -Wchar-subscripts -Wundef -Wcast-align -Wwrite-strings -Wunused -Wuninitialized -Wpointer-arith -Winline -Wformat -Wformat-security -Winit-self -Wmissing-include-dirs -Wnested-externs -Wmissing-declarations
else
From c94eae0046c90af02ba3f3c0b53d0f7a53de1183 Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Sun, 3 May 2020 15:15:02 +0200
Subject: [PATCH 054/632] fix warning about cast realignment, WIP
---
client/Makefile | 4 ++--
client/deps/cliparser/Makefile | 2 +-
client/deps/jansson/Makefile | 2 +-
client/deps/liblua/Makefile | 2 +-
client/src/mifare/mfkey.c | 25 +++++++++++++------------
client/src/mifare/mifarehost.c | 11 +++++++----
common/crc32.c | 6 ++++--
common/mbedtls/Makefile | 2 +-
8 files changed, 30 insertions(+), 24 deletions(-)
diff --git a/client/Makefile b/client/Makefile
index 48a1a3591..9904e8b27 100644
--- a/client/Makefile
+++ b/client/Makefile
@@ -58,9 +58,9 @@ INCLUDES_CLIENT += -I./src -I../include -I../common -I../common_fpga $(LIBS)
#CFLAGS ?= -Wall -Werror -O3
ifeq ($(platform),Darwin)
# readline has strict-prototype issues
-CFLAGS ?= -Wall -Werror -O3 -Wredundant-decls -Wmissing-prototypes -Wchar-subscripts -Wundef -Wcast-align -Wwrite-strings -Wunused -Wuninitialized -Wpointer-arith -Winline -Wformat -Wformat-security -Winit-self -Wmissing-include-dirs -Wnested-externs -Wmissing-declarations
+CFLAGS ?= -Wall -Werror -O3 -Wredundant-decls -Wmissing-prototypes -Wchar-subscripts -Wundef -Wcast-align -Wno-error=cast-align -Wwrite-strings -Wunused -Wuninitialized -Wpointer-arith -Winline -Wformat -Wformat-security -Winit-self -Wmissing-include-dirs -Wnested-externs -Wmissing-declarations
else
-CFLAGS ?= -Wall -Werror -O3 -Wredundant-decls -Wmissing-prototypes -Wchar-subscripts -Wundef -Wcast-align -Wwrite-strings -Wunused -Wuninitialized -Wpointer-arith -Winline -Wformat -Wformat-security -Winit-self -Wmissing-include-dirs -Wstrict-prototypes -Wnested-externs -Wmissing-declarations
+CFLAGS ?= -Wall -Werror -O3 -Wredundant-decls -Wmissing-prototypes -Wchar-subscripts -Wundef -Wcast-align -Wno-error=cast-align -Wwrite-strings -Wunused -Wuninitialized -Wpointer-arith -Winline -Wformat -Wformat-security -Winit-self -Wmissing-include-dirs -Wstrict-prototypes -Wnested-externs -Wmissing-declarations
endif
# -Wshadow
# -Wbad-function-cast -Wextra -Wswitch-enum -Wold-style-definition
diff --git a/client/deps/cliparser/Makefile b/client/deps/cliparser/Makefile
index 7f4409de0..4873372c4 100644
--- a/client/deps/cliparser/Makefile
+++ b/client/deps/cliparser/Makefile
@@ -1,6 +1,6 @@
MYSRCPATHS =
MYINCLUDES = -I../../../common -I../../../include -I../../src
-MYCFLAGS =
+MYCFLAGS = -Wno-cast-align
MYDEFS =
MYSRCS = \
argtable3.c \
diff --git a/client/deps/jansson/Makefile b/client/deps/jansson/Makefile
index 152e8bcb9..c0d16d6a3 100644
--- a/client/deps/jansson/Makefile
+++ b/client/deps/jansson/Makefile
@@ -1,6 +1,6 @@
MYSRCPATHS =
MYINCLUDES = -I.
-MYCFLAGS = -Wno-unused-function
+MYCFLAGS = -Wno-unused-function -Wno-cast-align
MYDEFS = -DHAVE_STDINT_H
MYSRCS = \
dump.c \
diff --git a/client/deps/liblua/Makefile b/client/deps/liblua/Makefile
index 54e45185b..0b05279b7 100644
--- a/client/deps/liblua/Makefile
+++ b/client/deps/liblua/Makefile
@@ -1,7 +1,7 @@
MYSRCPATHS =
MYINCLUDES = -I.
# Lua lib requires GNU extensions (implicit declarations of functions): -std=gnu99 or -std=gnu11
-MYCFLAGS =
+MYCFLAGS = -Wno-cast-align
MYDEFS = -DLUA_COMPAT_ALL $(SYSCFLAGS)
MYSRCS = lapi.c lcode.c lctype.c ldebug.c ldo.c ldump.c lfunc.c lgc.c llex.c \
lmem.c lobject.c lopcodes.c lparser.c lstate.c lstring.c ltable.c \
diff --git a/client/src/mifare/mfkey.c b/client/src/mifare/mfkey.c
index 7d04762b8..710bba449 100644
--- a/client/src/mifare/mfkey.c
+++ b/client/src/mifare/mfkey.c
@@ -45,11 +45,14 @@ uint32_t intersection(uint64_t *listA, uint64_t *listB) {
// Darkside attack (hf mf mifare)
// if successful it will return a list of keys, not just one.
uint32_t nonce2key(uint32_t uid, uint32_t nt, uint32_t nr, uint32_t ar, uint64_t par_info, uint64_t ks_info, uint64_t **keys) {
- struct Crypto1State *states;
+ union {
+ struct Crypto1State *states;
+ uint64_t *keylist;
+ } unionstate;
+
uint32_t i, pos;
uint8_t ks3x[8], par[8][8];
uint64_t key_recovered;
- uint64_t *keylist;
// Reset the last three significant bits of the reader nonce
nr &= 0xFFFFFF1F;
@@ -68,23 +71,21 @@ uint32_t nonce2key(uint32_t uid, uint32_t nt, uint32_t nr, uint32_t ar, uint64_t
par[7 - pos][7] = (bt >> 7) & 1;
}
- states = lfsr_common_prefix(nr, ar, ks3x, par, (par_info == 0));
+ unionstate.states = lfsr_common_prefix(nr, ar, ks3x, par, (par_info == 0));
- if (!states) {
+ if (!unionstate.states) {
*keys = NULL;
return 0;
}
- keylist = (uint64_t *)states;
-
- for (i = 0; keylist[i]; i++) {
- lfsr_rollback_word(states + i, uid ^ nt, 0);
- crypto1_get_lfsr(states + i, &key_recovered);
- keylist[i] = key_recovered;
+ for (i = 0; unionstate.keylist[i]; i++) {
+ lfsr_rollback_word(unionstate.states + i, uid ^ nt, 0);
+ crypto1_get_lfsr(unionstate.states + i, &key_recovered);
+ unionstate.keylist[i] = key_recovered;
}
- keylist[i] = -1;
+ unionstate.keylist[i] = -1;
- *keys = keylist;
+ *keys = unionstate.keylist;
return i;
}
diff --git a/client/src/mifare/mifarehost.c b/client/src/mifare/mifarehost.c
index 8b57604f9..c3ad1b0a0 100644
--- a/client/src/mifare/mifarehost.c
+++ b/client/src/mifare/mifarehost.c
@@ -378,7 +378,7 @@ __attribute__((force_align_arg_pointer))
StateList_t *statelist = arg;
statelist->head.slhead = lfsr_recovery32(statelist->ks1, statelist->nt_enc ^ statelist->uid);
- for (p1 = statelist->head.slhead; * (uint64_t *)p1 != 0; p1++) {};
+ for (p1 = statelist->head.slhead; p1->odd | p1->even; p1++) {};
statelist->len = p1 - statelist->head.slhead;
statelist->tail.sltail = --p1;
@@ -492,8 +492,10 @@ int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo,
}
}
- *(uint64_t *)p3 = -1;
- *(uint64_t *)p4 = -1;
+ p3->odd = -1;
+ p3->even = -1;
+ p4->odd = -1;
+ p4->even = -1;
statelists[0].len = p3 - statelists[0].head.slhead;
statelists[1].len = p4 - statelists[1].head.slhead;
statelists[0].tail.sltail = --p3;
@@ -637,7 +639,8 @@ int mfStaticNested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBl
}
}
- *(uint64_t *)p3 = -1;
+ p3->odd = -1;
+ p3->even = -1;
statelists[0].len = p3 - statelists[0].head.slhead;
statelists[0].tail.sltail = --p3;
diff --git a/common/crc32.c b/common/crc32.c
index 440bed910..b539baa05 100644
--- a/common/crc32.c
+++ b/common/crc32.c
@@ -23,8 +23,10 @@ void crc32_ex(const uint8_t *data, const size_t len, uint8_t *crc) {
for (size_t i = 0; i < len; i++) {
crc32_byte(&desfire_crc, data[i]);
}
-
- *((uint32_t *)(crc)) = htole32(desfire_crc);
+ uint32_t crctmp = htole32(desfire_crc);
+ for (size_t i=0; i < sizeof(uint32_t); i++) {
+ crc[i] = ((uint8_t *) &crctmp)[i];
+ }
}
void crc32_append(uint8_t *data, const size_t len) {
diff --git a/common/mbedtls/Makefile b/common/mbedtls/Makefile
index be5f08a0a..880f6bcc8 100644
--- a/common/mbedtls/Makefile
+++ b/common/mbedtls/Makefile
@@ -1,6 +1,6 @@
MYSRCPATHS =
MYINCLUDES = -I. -I..
-MYCFLAGS =
+MYCFLAGS = -Wno-cast-align
MYDEFS =
MYSRCS = \
aes.c \
From 4d4984657eba9dfb58ce3a87877a137ac6438cf5 Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Sun, 3 May 2020 19:25:14 +0200
Subject: [PATCH 055/632] activate more warnings and ease their mgmt
---
Makefile.defs | 15 +++++++++++++++
Makefile.host | 3 +--
client/Makefile | 10 +---------
client/deps/jansson/Makefile | 2 +-
client/deps/liblua/Makefile | 2 +-
5 files changed, 19 insertions(+), 13 deletions(-)
diff --git a/Makefile.defs b/Makefile.defs
index 4068d7516..1fc794def 100644
--- a/Makefile.defs
+++ b/Makefile.defs
@@ -44,3 +44,18 @@ else
AR= ar rcs
RANLIB= ranlib
endif
+
+DEFCFLAGS = -Wall -Werror -O3
+# Some more warnings we want as errors:
+DEFCFLAGS += -Wredundant-decls -Wmissing-prototypes -Wchar-subscripts -Wundef -Wwrite-strings -Wunused -Wuninitialized -Wpointer-arith -Winline -Wformat -Wformat-security -Winit-self -Wmissing-include-dirs -Wnested-externs -Wmissing-declarations
+# Some more warnings we need first to eliminate, so temporarely tolerated:
+DEFCFLAGS += -Wbad-function-cast -Wno-error=bad-function-cast -Wshadow -Wno-error=shadow -Wcast-align -Wno-error=cast-align
+# TODO?:
+#DEFCFLAGS += -Wextra -Wswitch-enum -Wold-style-definition
+
+ifeq ($(platform),Darwin)
+# their readline has strict-prototype issues
+DEFCFLAGS += -Wstrict-prototypes -Wno-error=strict-prototypes
+else
+DEFCFLAGS += -Wstrict-prototypes
+endif
diff --git a/Makefile.host b/Makefile.host
index 7ed942401..c95f4bb4f 100644
--- a/Makefile.host
+++ b/Makefile.host
@@ -15,8 +15,7 @@ ifeq ($(DEFSBEENHERE),)
$(error Can't find Makefile.defs)
endif
-CFLAGS ?= -Wall -Werror -O3 -Wchar-subscripts -Wundef -Wshadow -Wcast-align -Wwrite-strings -Wunused -Wuninitialized -Wpointer-arith -Wredundant-decls -Winline -Wformat -Wformat-security -Winit-self -Wmissing-include-dirs -Wmissing-prototypes -Wstrict-prototypes -Wnested-externs -Wmissing-declarations
-# -Wbad-function-cast -Wextra -Wswitch-enum -Wold-style-definition
+CFLAGS ?= $(DEFCFLAGS)
CFLAGS += $(MYDEFS) $(MYCFLAGS) $(MYINCLUDES)
vpath %.c $(MYSRCPATHS)
diff --git a/client/Makefile b/client/Makefile
index 9904e8b27..a17f57c27 100644
--- a/client/Makefile
+++ b/client/Makefile
@@ -55,15 +55,7 @@ ZLIB = $(OBJDIR)/libz.a
LIBS = -I$(LUALIBPATH) -I$(MBEDTLSLIBPATH) -I$(JANSSONLIBPATH) -I$(CBORLIBPATH) -I$(ZLIBPATH) -I$(REVENGPATH) -I$(AMIIBOLIBPATH) -I$(HARDNESTEDPATH) -I$(CLIPARSERPATH)
INCLUDES_CLIENT += -I./src -I../include -I../common -I../common_fpga $(LIBS)
-#CFLAGS ?= -Wall -Werror -O3
-ifeq ($(platform),Darwin)
-# readline has strict-prototype issues
-CFLAGS ?= -Wall -Werror -O3 -Wredundant-decls -Wmissing-prototypes -Wchar-subscripts -Wundef -Wcast-align -Wno-error=cast-align -Wwrite-strings -Wunused -Wuninitialized -Wpointer-arith -Winline -Wformat -Wformat-security -Winit-self -Wmissing-include-dirs -Wnested-externs -Wmissing-declarations
-else
-CFLAGS ?= -Wall -Werror -O3 -Wredundant-decls -Wmissing-prototypes -Wchar-subscripts -Wundef -Wcast-align -Wno-error=cast-align -Wwrite-strings -Wunused -Wuninitialized -Wpointer-arith -Winline -Wformat -Wformat-security -Winit-self -Wmissing-include-dirs -Wstrict-prototypes -Wnested-externs -Wmissing-declarations
-endif
-# -Wshadow
-# -Wbad-function-cast -Wextra -Wswitch-enum -Wold-style-definition
+CFLAGS ?= $(DEFCFLAGS)
# We cannot just use CFLAGS+=... because it has impact on sub-makes if CFLAGS is defined in env:
PM3CFLAGS = $(CFLAGS) $(INCLUDES_CLIENT)
diff --git a/client/deps/jansson/Makefile b/client/deps/jansson/Makefile
index c0d16d6a3..487a85af8 100644
--- a/client/deps/jansson/Makefile
+++ b/client/deps/jansson/Makefile
@@ -1,6 +1,6 @@
MYSRCPATHS =
MYINCLUDES = -I.
-MYCFLAGS = -Wno-unused-function -Wno-cast-align
+MYCFLAGS = -Wno-unused-function -Wno-cast-align -Wno-bad-function-cast
MYDEFS = -DHAVE_STDINT_H
MYSRCS = \
dump.c \
diff --git a/client/deps/liblua/Makefile b/client/deps/liblua/Makefile
index 0b05279b7..296fd9e24 100644
--- a/client/deps/liblua/Makefile
+++ b/client/deps/liblua/Makefile
@@ -1,7 +1,7 @@
MYSRCPATHS =
MYINCLUDES = -I.
# Lua lib requires GNU extensions (implicit declarations of functions): -std=gnu99 or -std=gnu11
-MYCFLAGS = -Wno-cast-align
+MYCFLAGS = -Wno-cast-align -Wno-bad-function-cast
MYDEFS = -DLUA_COMPAT_ALL $(SYSCFLAGS)
MYSRCS = lapi.c lcode.c lctype.c ldebug.c ldo.c ldump.c lfunc.c lgc.c llex.c \
lmem.c lobject.c lopcodes.c lparser.c lstate.c lstring.c ltable.c \
From 723503b74ee1fd47cc36be1716696690edb866f0 Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Sun, 3 May 2020 21:43:03 +0200
Subject: [PATCH 056/632] unshadow vars
---
Makefile.defs | 4 +-
client/src/cmdhfmfdes.c | 4 +-
client/src/cmdhfmfhard.c | 38 ++++++-------
client/src/cmdtrace.c | 58 ++++++++++----------
client/src/mifare/mifare4.c | 104 ++++++++++++++++++------------------
5 files changed, 104 insertions(+), 104 deletions(-)
diff --git a/Makefile.defs b/Makefile.defs
index 1fc794def..a9d9328d3 100644
--- a/Makefile.defs
+++ b/Makefile.defs
@@ -47,9 +47,9 @@ endif
DEFCFLAGS = -Wall -Werror -O3
# Some more warnings we want as errors:
-DEFCFLAGS += -Wredundant-decls -Wmissing-prototypes -Wchar-subscripts -Wundef -Wwrite-strings -Wunused -Wuninitialized -Wpointer-arith -Winline -Wformat -Wformat-security -Winit-self -Wmissing-include-dirs -Wnested-externs -Wmissing-declarations
+DEFCFLAGS += -Wredundant-decls -Wmissing-prototypes -Wchar-subscripts -Wshadow -Wundef -Wwrite-strings -Wunused -Wuninitialized -Wpointer-arith -Winline -Wformat -Wformat-security -Winit-self -Wmissing-include-dirs -Wnested-externs -Wmissing-declarations
# Some more warnings we need first to eliminate, so temporarely tolerated:
-DEFCFLAGS += -Wbad-function-cast -Wno-error=bad-function-cast -Wshadow -Wno-error=shadow -Wcast-align -Wno-error=cast-align
+DEFCFLAGS += -Wbad-function-cast -Wno-error=bad-function-cast -Wcast-align -Wno-error=cast-align
# TODO?:
#DEFCFLAGS += -Wextra -Wswitch-enum -Wold-style-definition
diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c
index c44bb4a3a..dad36ca3c 100644
--- a/client/src/cmdhfmfdes.c
+++ b/client/src/cmdhfmfdes.c
@@ -642,7 +642,7 @@ static nxp_cardtype_t getCardType(uint8_t major, uint8_t minor) {
return DESFIRE_UNKNOWN;
}
-static int handler_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rpayload, bool defaultkey) {
+static int handler_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rpayload, bool def_key) {
// 3 different way to authenticate AUTH (CRC16) , AUTH_ISO (CRC32) , AUTH_AES (CRC32)
// 4 different crypto arg1 DES, 3DES, 3K3DES, AES
// 3 different communication modes, PLAIN,MAC,CRYPTO
@@ -679,7 +679,7 @@ static int handler_desfire_auth(mfdes_authinput_t *payload, mfdes_auth_res_t *rp
// Part 1
- if (defaultkey) {
+ if (def_key) {
if (payload->algo == MFDES_AUTH_DES) {
memcpy(keybytes, PICC_MASTER_KEY8, 8);
} else if (payload->algo == MFDES_ALGO_AES || payload->algo == MFDES_ALGO_3DES) {
diff --git a/client/src/cmdhfmfhard.c b/client/src/cmdhfmfhard.c
index b8f3c0471..a32af3601 100644
--- a/client/src/cmdhfmfhard.c
+++ b/client/src/cmdhfmfhard.c
@@ -1739,24 +1739,24 @@ static void bitarray_to_list(uint8_t byte, uint32_t *bitarray, uint32_t *state_l
}
-static void add_cached_states(statelist_t *candidates, uint16_t part_sum_a0, uint16_t part_sum_a8, odd_even_t odd_even) {
- candidates->states[odd_even] = sl_cache[part_sum_a0 / 2][part_sum_a8 / 2][odd_even].sl;
- candidates->len[odd_even] = sl_cache[part_sum_a0 / 2][part_sum_a8 / 2][odd_even].len;
+static void add_cached_states(statelist_t *cands, uint16_t part_sum_a0, uint16_t part_sum_a8, odd_even_t odd_even) {
+ cands->states[odd_even] = sl_cache[part_sum_a0 / 2][part_sum_a8 / 2][odd_even].sl;
+ cands->len[odd_even] = sl_cache[part_sum_a0 / 2][part_sum_a8 / 2][odd_even].len;
return;
}
-static void add_matching_states(statelist_t *candidates, uint8_t part_sum_a0, uint8_t part_sum_a8, odd_even_t odd_even) {
+static void add_matching_states(statelist_t *cands, uint8_t part_sum_a0, uint8_t part_sum_a8, odd_even_t odd_even) {
const uint32_t worstcase_size = 1 << 20;
- candidates->states[odd_even] = (uint32_t *)malloc(sizeof(uint32_t) * worstcase_size);
- if (candidates->states[odd_even] == NULL) {
+ cands->states[odd_even] = (uint32_t *)malloc(sizeof(uint32_t) * worstcase_size);
+ if (cands->states[odd_even] == NULL) {
PrintAndLogEx(ERR, "Out of memory error in add_matching_states() - statelist.\n");
exit(4);
}
- uint32_t *candidates_bitarray = (uint32_t *)malloc_bitarray(sizeof(uint32_t) * worstcase_size);
- if (candidates_bitarray == NULL) {
+ uint32_t *cands_bitarray = (uint32_t *)malloc_bitarray(sizeof(uint32_t) * worstcase_size);
+ if (cands_bitarray == NULL) {
PrintAndLogEx(ERR, "Out of memory error in add_matching_states() - bitarray.\n");
- free(candidates->states[odd_even]);
+ free(cands->states[odd_even]);
exit(4);
}
@@ -1764,21 +1764,21 @@ static void add_matching_states(statelist_t *candidates, uint8_t part_sum_a0, ui
uint32_t *bitarray_a8 = part_sum_a8_bitarrays[odd_even][part_sum_a8 / 2];
uint32_t *bitarray_bitflips = nonces[best_first_bytes[0]].states_bitarray[odd_even];
- bitarray_AND4(candidates_bitarray, bitarray_a0, bitarray_a8, bitarray_bitflips);
+ bitarray_AND4(cands_bitarray, bitarray_a0, bitarray_a8, bitarray_bitflips);
- bitarray_to_list(best_first_bytes[0], candidates_bitarray, candidates->states[odd_even], &(candidates->len[odd_even]), odd_even);
+ bitarray_to_list(best_first_bytes[0], cands_bitarray, cands->states[odd_even], &(cands->len[odd_even]), odd_even);
- if (candidates->len[odd_even] == 0) {
- free(candidates->states[odd_even]);
- candidates->states[odd_even] = NULL;
- } else if (candidates->len[odd_even] + 1 < worstcase_size) {
- candidates->states[odd_even] = realloc(candidates->states[odd_even], sizeof(uint32_t) * (candidates->len[odd_even] + 1));
+ if (cands->len[odd_even] == 0) {
+ free(cands->states[odd_even]);
+ cands->states[odd_even] = NULL;
+ } else if (cands->len[odd_even] + 1 < worstcase_size) {
+ cands->states[odd_even] = realloc(cands->states[odd_even], sizeof(uint32_t) * (cands->len[odd_even] + 1));
}
- free_bitarray(candidates_bitarray);
+ free_bitarray(cands_bitarray);
pthread_mutex_lock(&statelist_cache_mutex);
- sl_cache[part_sum_a0 / 2][part_sum_a8 / 2][odd_even].sl = candidates->states[odd_even];
- sl_cache[part_sum_a0 / 2][part_sum_a8 / 2][odd_even].len = candidates->len[odd_even];
+ sl_cache[part_sum_a0 / 2][part_sum_a8 / 2][odd_even].sl = cands->states[odd_even];
+ sl_cache[part_sum_a0 / 2][part_sum_a8 / 2][odd_even].len = cands->len[odd_even];
sl_cache[part_sum_a0 / 2][part_sum_a8 / 2][odd_even].cache_status = COMPLETED;
pthread_mutex_unlock(&statelist_cache_mutex);
return;
diff --git a/client/src/cmdtrace.c b/client/src/cmdtrace.c
index 85d2bea09..99e5e03f2 100644
--- a/client/src/cmdtrace.c
+++ b/client/src/cmdtrace.c
@@ -22,8 +22,8 @@
static int CmdHelp(const char *Cmd);
// trace pointer
-static uint8_t *trace;
-long traceLen = 0;
+static uint8_t *g_trace;
+long g_traceLen = 0;
static int usage_trace_list(void) {
PrintAndLogEx(NORMAL, "List protocol data in trace buffer.");
@@ -491,26 +491,26 @@ static int CmdTraceLoad(const char *Cmd) {
return PM3_ESOFT;
}
- if (trace)
- free(trace);
+ if (g_trace)
+ free(g_trace);
- trace = calloc(fsize, sizeof(uint8_t));
- if (!trace) {
+ g_trace = calloc(fsize, sizeof(uint8_t));
+ if (!g_trace) {
PrintAndLogEx(FAILED, "Cannot allocate memory for trace");
fclose(f);
return PM3_EMALLOC;
}
- size_t bytes_read = fread(trace, 1, fsize, f);
- traceLen = bytes_read;
+ size_t bytes_read = fread(g_trace, 1, fsize, f);
+ g_traceLen = bytes_read;
fclose(f);
- PrintAndLogEx(SUCCESS, "Recorded Activity (TraceLen = %lu bytes) loaded from file %s", traceLen, filename);
+ PrintAndLogEx(SUCCESS, "Recorded Activity (TraceLen = %lu bytes) loaded from file %s", g_traceLen, filename);
return PM3_SUCCESS;
}
static int CmdTraceSave(const char *Cmd) {
- if (traceLen == 0) {
+ if (g_traceLen == 0) {
PrintAndLogEx(WARNING, "trace is empty, nothing to save");
return PM3_SUCCESS;
}
@@ -520,7 +520,7 @@ static int CmdTraceSave(const char *Cmd) {
if (strlen(Cmd) < 1 || cmdp == 'h') return usage_trace_save();
param_getstr(Cmd, 0, filename, sizeof(filename));
- saveFile(filename, ".bin", trace, traceLen);
+ saveFile(filename, ".bin", g_trace, g_traceLen);
return PM3_SUCCESS;
}
@@ -628,10 +628,10 @@ int CmdTraceList(const char *Cmd) {
uint16_t tracepos = 0;
- // reserv some space.
- if (!trace) {
- trace = calloc(PM3_CMD_DATA_SIZE, sizeof(uint8_t));
- if (trace == NULL) {
+ // reserve some space.
+ if (!g_trace) {
+ g_trace = calloc(PM3_CMD_DATA_SIZE, sizeof(uint8_t));
+ if (g_trace == NULL) {
PrintAndLogEx(FAILED, "Cannot allocate memory for trace");
return PM3_EMALLOC;
}
@@ -640,38 +640,38 @@ int CmdTraceList(const char *Cmd) {
if (isOnline) {
// Query for the size of the trace, downloading PM3_CMD_DATA_SIZE
PacketResponseNG response;
- if (!GetFromDevice(BIG_BUF, trace, PM3_CMD_DATA_SIZE, 0, NULL, 0, &response, 4000, true)) {
+ if (!GetFromDevice(BIG_BUF, g_trace, PM3_CMD_DATA_SIZE, 0, NULL, 0, &response, 4000, true)) {
PrintAndLogEx(WARNING, "timeout while waiting for reply.");
return PM3_ETIMEOUT;
}
- traceLen = response.oldarg[2];
- if (traceLen > PM3_CMD_DATA_SIZE) {
- uint8_t *p = realloc(trace, traceLen);
+ g_traceLen = response.oldarg[2];
+ if (g_traceLen > PM3_CMD_DATA_SIZE) {
+ uint8_t *p = realloc(g_trace, g_traceLen);
if (p == NULL) {
PrintAndLogEx(FAILED, "Cannot allocate memory for trace");
- free(trace);
+ free(g_trace);
return PM3_EMALLOC;
}
- trace = p;
- if (!GetFromDevice(BIG_BUF, trace, traceLen, 0, NULL, 0, NULL, 2500, false)) {
+ g_trace = p;
+ if (!GetFromDevice(BIG_BUF, g_trace, g_traceLen, 0, NULL, 0, NULL, 2500, false)) {
PrintAndLogEx(WARNING, "command execution time out");
- free(trace);
+ free(g_trace);
return PM3_ETIMEOUT;
}
}
}
- PrintAndLogEx(SUCCESS, "Recorded activity (trace len = " _YELLOW_("%lu") " bytes)", traceLen);
+ PrintAndLogEx(SUCCESS, "Recorded activity (trace len = " _YELLOW_("%lu") " bytes)", g_traceLen);
/*
if (protocol == FELICA) {
- printFelica(traceLen, trace);
+ printFelica(g_traceLen, g_trace);
} */
if (showHex) {
- while (tracepos < traceLen) {
- tracepos = printHexLine(tracepos, traceLen, trace, protocol);
+ while (tracepos < g_traceLen) {
+ tracepos = printHexLine(tracepos, g_traceLen, g_trace, protocol);
}
} else {
PrintAndLogEx(INFO, _YELLOW_("Start") " = Start of Start Bit, " _YELLOW_("End") " = End of last modulation. " _YELLOW_("Src") " = Source of Transfer");
@@ -700,8 +700,8 @@ int CmdTraceList(const char *Cmd) {
PrintAndLogEx(NORMAL, "------------+------------+-----+-------------------------------------------------------------------------+-----+--------------------");
ClearAuthData();
- while (tracepos < traceLen) {
- tracepos = printTraceLine(tracepos, traceLen, trace, protocol, showWaitCycles, markCRCBytes);
+ while (tracepos < g_traceLen) {
+ tracepos = printTraceLine(tracepos, g_traceLen, g_trace, protocol, showWaitCycles, markCRCBytes);
if (kbd_enter_pressed())
break;
diff --git a/client/src/mifare/mifare4.c b/client/src/mifare/mifare4.c
index 09f10d321..55961b15b 100644
--- a/client/src/mifare/mifare4.c
+++ b/client/src/mifare/mifare4.c
@@ -90,42 +90,42 @@ const char *mfGetAccessConditionsDesc(uint8_t blockn, uint8_t *data) {
return StaticNone;
}
/*
-static int CalculateEncIVCommand(mf4Session_t *session, uint8_t *iv, bool verbose) {
- memcpy(&iv[0], &session->TI, 4);
- memcpy(&iv[4], &session->R_Ctr, 2);
- memcpy(&iv[6], &session->W_Ctr, 2);
- memcpy(&iv[8], &session->R_Ctr, 2);
- memcpy(&iv[10], &session->W_Ctr, 2);
- memcpy(&iv[12], &session->R_Ctr, 2);
- memcpy(&iv[14], &session->W_Ctr, 2);
+static int CalculateEncIVCommand(mf4Session_t *mf4session, uint8_t *iv, bool verbose) {
+ memcpy(&iv[0], &mf4session->TI, 4);
+ memcpy(&iv[4], &mf4session->R_Ctr, 2);
+ memcpy(&iv[6], &mf4session->W_Ctr, 2);
+ memcpy(&iv[8], &mf4session->R_Ctr, 2);
+ memcpy(&iv[10], &mf4session->W_Ctr, 2);
+ memcpy(&iv[12], &mf4session->R_Ctr, 2);
+ memcpy(&iv[14], &mf4session->W_Ctr, 2);
return 0;
}
-static int CalculateEncIVResponse(mf4Session *session, uint8_t *iv, bool verbose) {
- memcpy(&iv[0], &session->R_Ctr, 2);
- memcpy(&iv[2], &session->W_Ctr, 2);
- memcpy(&iv[4], &session->R_Ctr, 2);
- memcpy(&iv[6], &session->W_Ctr, 2);
- memcpy(&iv[8], &session->R_Ctr, 2);
- memcpy(&iv[10], &session->W_Ctr, 2);
- memcpy(&iv[12], &session->TI, 4);
+static int CalculateEncIVResponse(mf4Session *mf4session, uint8_t *iv, bool verbose) {
+ memcpy(&iv[0], &mf4session->R_Ctr, 2);
+ memcpy(&iv[2], &mf4session->W_Ctr, 2);
+ memcpy(&iv[4], &mf4session->R_Ctr, 2);
+ memcpy(&iv[6], &mf4session->W_Ctr, 2);
+ memcpy(&iv[8], &mf4session->R_Ctr, 2);
+ memcpy(&iv[10], &mf4session->W_Ctr, 2);
+ memcpy(&iv[12], &mf4session->TI, 4);
return 0;
}
*/
-int CalculateMAC(mf4Session_t *session, MACType_t mtype, uint8_t blockNum, uint8_t blockCount, uint8_t *data, int datalen, uint8_t *mac, bool verbose) {
- if (!session || !session->Authenticated || !mac || !data || !datalen)
+int CalculateMAC(mf4Session_t *mf4session, MACType_t mtype, uint8_t blockNum, uint8_t blockCount, uint8_t *data, int datalen, uint8_t *mac, bool verbose) {
+ if (!mf4session || !mf4session->Authenticated || !mac || !data || !datalen)
return 1;
memset(mac, 0x00, 8);
- uint16_t ctr = session->R_Ctr;
+ uint16_t ctr = mf4session->R_Ctr;
switch (mtype) {
case mtypWriteCmd:
case mtypWriteResp:
- ctr = session->W_Ctr;
+ ctr = mf4session->W_Ctr;
break;
case mtypReadCmd:
case mtypReadResp:
@@ -134,7 +134,7 @@ int CalculateMAC(mf4Session_t *session, MACType_t mtype, uint8_t blockNum, uint8
uint8_t macdata[2049] = {data[0], (ctr & 0xFF), (ctr >> 8), 0};
int macdatalen = datalen;
- memcpy(&macdata[3], session->TI, 4);
+ memcpy(&macdata[3], mf4session->TI, 4);
switch (mtype) {
case mtypReadCmd:
@@ -160,10 +160,10 @@ int CalculateMAC(mf4Session_t *session, MACType_t mtype, uint8_t blockNum, uint8
if (verbose)
PrintAndLogEx(NORMAL, "MAC data[%d]: %s", macdatalen, sprint_hex(macdata, macdatalen));
- return aes_cmac8(NULL, session->Kmac, macdata, mac, macdatalen);
+ return aes_cmac8(NULL, mf4session->Kmac, macdata, mac, macdatalen);
}
-int MifareAuth4(mf4Session_t *session, uint8_t *keyn, uint8_t *key, bool activateField, bool leaveSignalON, bool dropFieldIfError, bool verbose, bool silentMode) {
+int MifareAuth4(mf4Session_t *mf4session, uint8_t *keyn, uint8_t *key, bool activateField, bool leaveSignalON, bool dropFieldIfError, bool verbose, bool silentMode) {
uint8_t data[257] = {0};
int datalen = 0;
@@ -173,8 +173,8 @@ int MifareAuth4(mf4Session_t *session, uint8_t *keyn, uint8_t *key, bool activat
if (silentMode)
verbose = false;
- if (session)
- session->Authenticated = false;
+ if (mf4session)
+ mf4session->Authenticated = false;
uint8_t cmd1[] = {0x70, keyn[1], keyn[0], 0x00};
int res = ExchangeRAW14a(cmd1, sizeof(cmd1), activateField, true, data, sizeof(data), &datalen, silentMode);
@@ -284,19 +284,19 @@ int MifareAuth4(mf4Session_t *session, uint8_t *keyn, uint8_t *key, bool activat
if (verbose)
PrintAndLogEx(NORMAL, "");
- if (session) {
- session->Authenticated = true;
- session->R_Ctr = 0;
- session->W_Ctr = 0;
- session->KeyNum = keyn[1] + (keyn[0] << 8);
- memmove(session->RndA, RndA, 16);
- memmove(session->RndB, RndB, 16);
- memmove(session->Key, key, 16);
- memmove(session->TI, raw, 4);
- memmove(session->PICCap2, &raw[20], 6);
- memmove(session->PCDCap2, &raw[26], 6);
- memmove(session->Kenc, kenc, 16);
- memmove(session->Kmac, kmac, 16);
+ if (mf4session) {
+ mf4session->Authenticated = true;
+ mf4session->R_Ctr = 0;
+ mf4session->W_Ctr = 0;
+ mf4session->KeyNum = keyn[1] + (keyn[0] << 8);
+ memmove(mf4session->RndA, RndA, 16);
+ memmove(mf4session->RndB, RndB, 16);
+ memmove(mf4session->Key, key, 16);
+ memmove(mf4session->TI, raw, 4);
+ memmove(mf4session->PICCap2, &raw[20], 6);
+ memmove(mf4session->PCDCap2, &raw[26], 6);
+ memmove(mf4session->Kenc, kenc, 16);
+ memmove(mf4session->Kmac, kmac, 16);
}
if (verbose)
@@ -330,39 +330,39 @@ int MFPCommitPerso(bool activateField, bool leaveSignalON, uint8_t *dataout, int
return intExchangeRAW14aPlus(rcmd, sizeof(rcmd), activateField, leaveSignalON, dataout, maxdataoutlen, dataoutlen);
}
-int MFPReadBlock(mf4Session_t *session, bool plain, uint8_t blockNum, uint8_t blockCount, bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen, uint8_t *mac) {
+int MFPReadBlock(mf4Session_t *mf4session, bool plain, uint8_t blockNum, uint8_t blockCount, bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen, uint8_t *mac) {
uint8_t rcmd[4 + 8] = {(plain ? (0x37) : (0x33)), blockNum, 0x00, blockCount};
- if (!plain && session)
- CalculateMAC(session, mtypReadCmd, blockNum, blockCount, rcmd, 4, &rcmd[4], VerboseMode);
+ if (!plain && mf4session)
+ CalculateMAC(mf4session, mtypReadCmd, blockNum, blockCount, rcmd, 4, &rcmd[4], VerboseMode);
int res = intExchangeRAW14aPlus(rcmd, plain ? 4 : sizeof(rcmd), activateField, leaveSignalON, dataout, maxdataoutlen, dataoutlen);
if (res)
return res;
- if (session)
- session->R_Ctr++;
+ if (mf4session)
+ mf4session->R_Ctr++;
- if (session && mac && *dataoutlen > 11)
- CalculateMAC(session, mtypReadResp, blockNum, blockCount, dataout, *dataoutlen - 8 - 2, mac, VerboseMode);
+ if (mf4session && mac && *dataoutlen > 11)
+ CalculateMAC(mf4session, mtypReadResp, blockNum, blockCount, dataout, *dataoutlen - 8 - 2, mac, VerboseMode);
return 0;
}
-int MFPWriteBlock(mf4Session_t *session, uint8_t blockNum, uint8_t *data, bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen, uint8_t *mac) {
+int MFPWriteBlock(mf4Session_t *mf4session, uint8_t blockNum, uint8_t *data, bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen, uint8_t *mac) {
uint8_t rcmd[1 + 2 + 16 + 8] = {0xA3, blockNum, 0x00};
memmove(&rcmd[3], data, 16);
- if (session)
- CalculateMAC(session, mtypWriteCmd, blockNum, 1, rcmd, 19, &rcmd[19], VerboseMode);
+ if (mf4session)
+ CalculateMAC(mf4session, mtypWriteCmd, blockNum, 1, rcmd, 19, &rcmd[19], VerboseMode);
int res = intExchangeRAW14aPlus(rcmd, sizeof(rcmd), activateField, leaveSignalON, dataout, maxdataoutlen, dataoutlen);
if (res)
return res;
- if (session)
- session->W_Ctr++;
+ if (mf4session)
+ mf4session->W_Ctr++;
- if (session && mac && *dataoutlen > 3)
- CalculateMAC(session, mtypWriteResp, blockNum, 1, dataout, *dataoutlen, mac, VerboseMode);
+ if (mf4session && mac && *dataoutlen > 3)
+ CalculateMAC(mf4session, mtypWriteResp, blockNum, 1, dataout, *dataoutlen, mac, VerboseMode);
return 0;
}
From 58f71d97f5f55d081b269c088a6d6768312f49c0 Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Mon, 4 May 2020 01:18:26 +0200
Subject: [PATCH 057/632] silent some bad-function-cast
---
Makefile.defs | 4 ++--
client/src/cmdhfmfhard.c | 3 ++-
client/src/cmdlfjablotron.c | 7 +++----
client/src/pm3_binlib.c | 3 ++-
client/src/pm3_bitlib.c | 6 ++++--
client/src/whereami.c | 3 ++-
6 files changed, 15 insertions(+), 11 deletions(-)
diff --git a/Makefile.defs b/Makefile.defs
index a9d9328d3..2de8f88a3 100644
--- a/Makefile.defs
+++ b/Makefile.defs
@@ -47,9 +47,9 @@ endif
DEFCFLAGS = -Wall -Werror -O3
# Some more warnings we want as errors:
-DEFCFLAGS += -Wredundant-decls -Wmissing-prototypes -Wchar-subscripts -Wshadow -Wundef -Wwrite-strings -Wunused -Wuninitialized -Wpointer-arith -Winline -Wformat -Wformat-security -Winit-self -Wmissing-include-dirs -Wnested-externs -Wmissing-declarations
+DEFCFLAGS += -Wcast-align -Wbad-function-cast -Wredundant-decls -Wmissing-prototypes -Wchar-subscripts -Wshadow -Wundef -Wwrite-strings -Wunused -Wuninitialized -Wpointer-arith -Winline -Wformat -Wformat-security -Winit-self -Wmissing-include-dirs -Wnested-externs -Wmissing-declarations
# Some more warnings we need first to eliminate, so temporarely tolerated:
-DEFCFLAGS += -Wbad-function-cast -Wno-error=bad-function-cast -Wcast-align -Wno-error=cast-align
+DEFCFLAGS += -Wno-error=cast-align
# TODO?:
#DEFCFLAGS += -Wextra -Wswitch-enum -Wold-style-definition
diff --git a/client/src/cmdhfmfhard.c b/client/src/cmdhfmfhard.c
index a32af3601..2a245df37 100644
--- a/client/src/cmdhfmfhard.c
+++ b/client/src/cmdhfmfhard.c
@@ -793,7 +793,8 @@ static void update_p_K(void) {
}
for (uint8_t sum_a8_idx = 0; sum_a8_idx < NUM_SUMS; sum_a8_idx++) {
uint16_t sum_a8 = sums[sum_a8_idx];
- my_p_K[sum_a8_idx] = (float)estimated_num_states_coarse(sum_a0, sum_a8) / total_count;
+ float f = estimated_num_states_coarse(sum_a0, sum_a8);
+ my_p_K[sum_a8_idx] = f / total_count;
}
// PrintAndLogEx(NORMAL, "my_p_K = [");
// for (uint8_t sum_a8_idx = 0; sum_a8_idx < NUM_SUMS; sum_a8_idx++) {
diff --git a/client/src/cmdlfjablotron.c b/client/src/cmdlfjablotron.c
index 285ddca7d..3d586215e 100644
--- a/client/src/cmdlfjablotron.c
+++ b/client/src/cmdlfjablotron.c
@@ -12,7 +12,6 @@
#include
#include
-#include
#include
#include
@@ -70,9 +69,9 @@ static uint64_t getJablontronCardId(uint64_t rawcode) {
uint64_t id = 0;
uint8_t bytes[] = {0, 0, 0, 0, 0};
num_to_bytes(rawcode, 5, bytes);
- for (int i = 4, j = 0; i > -1; --i, j += 2) {
- id += NIBBLE_LOW(bytes[i]) * (int)pow(10, j);
- id += NIBBLE_HIGH(bytes[i]) * (int)pow(10, j + 1);
+ for (int i = 0; i < 5; i++) {
+ id *= 100;
+ id += NIBBLE_HIGH(bytes[i]) * 10 + NIBBLE_LOW(bytes[i]);
}
return id;
}
diff --git a/client/src/pm3_binlib.c b/client/src/pm3_binlib.c
index f4e49c137..56d281636 100644
--- a/client/src/pm3_binlib.c
+++ b/client/src/pm3_binlib.c
@@ -203,7 +203,8 @@ static int l_unpack(lua_State *L) { /** unpack(f,s, [init]) */
#define PACKNUMBER(OP,T) \
case OP: \
{ \
- T a=(T)luaL_checknumber(L,i++); \
+ lua_Number n = luaL_checknumber(L,i++); \
+ T a=(T)n; \
doswap(swap,&a,sizeof(a)); \
luaL_addlstring(&b,(char*)&a,sizeof(a)); \
break; \
diff --git a/client/src/pm3_bitlib.c b/client/src/pm3_bitlib.c
index b5ef6e0ae..064c0f3c9 100644
--- a/client/src/pm3_bitlib.c
+++ b/client/src/pm3_bitlib.c
@@ -92,16 +92,18 @@ typedef size_t lua_UInteger;
#define LOGICAL_SHIFT(name, op) \
static int bit_ ## name(lua_State *L) { \
lua_Number f; \
+ lua_Number n = luaL_checknumber(L, 2); \
lua_pushinteger(L, BIT_TRUNCATE(BIT_TRUNCATE((lua_UInteger)TOBIT(L, 1, f)) op \
- (unsigned)luaL_checknumber(L, 2))); \
+ (unsigned)n)); \
return 1; \
}
#define ARITHMETIC_SHIFT(name, op) \
static int bit_ ## name(lua_State *L) { \
lua_Number f; \
+ lua_Number n = luaL_checknumber(L, 2); \
lua_pushinteger(L, BIT_TRUNCATE((lua_Integer)TOBIT(L, 1, f) op \
- (unsigned)luaL_checknumber(L, 2))); \
+ (unsigned)n)); \
return 1; \
}
diff --git a/client/src/whereami.c b/client/src/whereami.c
index 30d70c4d9..b725c4946 100644
--- a/client/src/whereami.c
+++ b/client/src/whereami.c
@@ -253,7 +253,8 @@ int WAI_PREFIX(getModulePath)(char *out, int capacity, int *dirname_length) {
break;
if (sscanf(buffer, "%" SCNx64 "-%" SCNx64 " %s %" SCNx64 " %x:%x %u %s\n", &low, &high, perms, &offset, &major, &minor, &inode, path) == 8) {
- uint64_t addr = (uint64_t)(uintptr_t)WAI_RETURN_ADDRESS();
+ void *addr_tmp = WAI_RETURN_ADDRESS();
+ uint64_t addr = (uint64_t)addr_tmp;
if (low <= addr && addr <= high) {
char *resolved;
From c59791d21cdc6bd1c358c54d33ee423406cef855 Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Mon, 4 May 2020 01:42:59 +0200
Subject: [PATCH 058/632] more warnings
---
Makefile.defs | 7 +++++--
1 file changed, 5 insertions(+), 2 deletions(-)
diff --git a/Makefile.defs b/Makefile.defs
index 2de8f88a3..8d090a0a6 100644
--- a/Makefile.defs
+++ b/Makefile.defs
@@ -47,11 +47,14 @@ endif
DEFCFLAGS = -Wall -Werror -O3
# Some more warnings we want as errors:
-DEFCFLAGS += -Wcast-align -Wbad-function-cast -Wredundant-decls -Wmissing-prototypes -Wchar-subscripts -Wshadow -Wundef -Wwrite-strings -Wunused -Wuninitialized -Wpointer-arith -Winline -Wformat -Wformat-security -Winit-self -Wmissing-include-dirs -Wnested-externs -Wmissing-declarations
+DEFCFLAGS += -Wcast-align -Wbad-function-cast -Wredundant-decls -Wmissing-prototypes -Wchar-subscripts -Wshadow -Wundef -Wwrite-strings -Wunused -Wuninitialized -Wpointer-arith -Winline -Wformat -Wformat-security -Winit-self -Wmissing-include-dirs -Wnested-externs -Wmissing-declarations -Wempty-body -Wignored-qualifiers -Woverride-init -Wshift-negative-value
# Some more warnings we need first to eliminate, so temporarely tolerated:
DEFCFLAGS += -Wno-error=cast-align
# TODO?:
-#DEFCFLAGS += -Wextra -Wswitch-enum -Wold-style-definition
+#DEFCFLAGS += -Wunused-parameter -Wold-style-declaration -Wsign-compare -Wimplicit-fallthrough=3 -Wtype-limits -Wmissing-field-initializers -Wunused-but-set-parameter -Wswitch-enum -Wold-style-definition
+#DEFCFLAGS += -Wno-error=unused-parameter -Wno-error=old-style-declaration -Wno-error=sign-compare -Wno-error=implicit-fallthrough -Wno-error=type-limits -Wno-error=missing-field-initializers -Wno-error=unused-but-set-parameter -Wno-error=switch-enum -Wno-error=old-style-definition
+# unknown to clang:
+# -Wclobbered -Wmissing-parameter-type -Wcast-function-type
ifeq ($(platform),Darwin)
# their readline has strict-prototype issues
From 99381b43861a72b68566e88ca48947574051c940 Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Mon, 4 May 2020 01:48:07 +0200
Subject: [PATCH 059/632] fix defined
---
client/src/proxmark3.c | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/client/src/proxmark3.c b/client/src/proxmark3.c
index 80fd958b1..1ed8bb65a 100644
--- a/client/src/proxmark3.c
+++ b/client/src/proxmark3.c
@@ -90,7 +90,7 @@ static void showBanner(void) {
g_printAndLog = PRINTANDLOG_PRINT;
PrintAndLogEx(NORMAL, "\n");
-#if defined(__linux__) || (__APPLE__) || (_WIN32)
+#if defined(__linux__) || defined(__APPLE__) || defined(_WIN32)
PrintAndLogEx(NORMAL, " " _BLUE_("██████╗ ███╗ ███╗ ████╗ "));
PrintAndLogEx(NORMAL, " " _BLUE_("██╔══██╗████╗ ████║ ══█║"));
PrintAndLogEx(NORMAL, " " _BLUE_("██████╔╝██╔████╔██║ ████╔╝"));
@@ -893,7 +893,7 @@ int main(int argc, char *argv[]) {
session.stdinOnTTY = isatty(STDIN_FILENO);
session.stdoutOnTTY = isatty(STDOUT_FILENO);
-#if defined(__linux__) || (__APPLE__)
+#if defined(__linux__) || defined(__APPLE__)
// it's okay to use color if:
// * Linux or OSX
// * Not redirected to a file but printed to term
From 00de69e57e54fa69f3eb6ee8aeb7d0c327a6215c Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Mon, 4 May 2020 02:13:11 +0200
Subject: [PATCH 060/632] adjust warning flags
---
Makefile.defs | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/Makefile.defs b/Makefile.defs
index 8d090a0a6..3c111f400 100644
--- a/Makefile.defs
+++ b/Makefile.defs
@@ -47,7 +47,7 @@ endif
DEFCFLAGS = -Wall -Werror -O3
# Some more warnings we want as errors:
-DEFCFLAGS += -Wcast-align -Wbad-function-cast -Wredundant-decls -Wmissing-prototypes -Wchar-subscripts -Wshadow -Wundef -Wwrite-strings -Wunused -Wuninitialized -Wpointer-arith -Winline -Wformat -Wformat-security -Winit-self -Wmissing-include-dirs -Wnested-externs -Wmissing-declarations -Wempty-body -Wignored-qualifiers -Woverride-init -Wshift-negative-value
+DEFCFLAGS += -Wcast-align -Wbad-function-cast -Wredundant-decls -Wmissing-prototypes -Wchar-subscripts -Wshadow -Wundef -Wwrite-strings -Wunused -Wuninitialized -Wpointer-arith -Winline -Wformat -Wformat-security -Winit-self -Wmissing-include-dirs -Wnested-externs -Wmissing-declarations -Wempty-body -Wignored-qualifiers -Woverride-init
# Some more warnings we need first to eliminate, so temporarely tolerated:
DEFCFLAGS += -Wno-error=cast-align
# TODO?:
@@ -55,6 +55,8 @@ DEFCFLAGS += -Wno-error=cast-align
#DEFCFLAGS += -Wno-error=unused-parameter -Wno-error=old-style-declaration -Wno-error=sign-compare -Wno-error=implicit-fallthrough -Wno-error=type-limits -Wno-error=missing-field-initializers -Wno-error=unused-but-set-parameter -Wno-error=switch-enum -Wno-error=old-style-definition
# unknown to clang:
# -Wclobbered -Wmissing-parameter-type -Wcast-function-type
+# requires GCC 6:
+# -Wshift-negative-value
ifeq ($(platform),Darwin)
# their readline has strict-prototype issues
From f0811de70d1a6a1f6bfb163291901e01e6bd75bc Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Mon, 4 May 2020 02:17:47 +0200
Subject: [PATCH 061/632] silent zlib warning under AppVeyor
---
common/zlib/Makefile | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/common/zlib/Makefile b/common/zlib/Makefile
index acc35bf42..9444aee9f 100644
--- a/common/zlib/Makefile
+++ b/common/zlib/Makefile
@@ -1,7 +1,7 @@
MYSRCPATHS = ../../common/zlib
MYSRCS = deflate.c adler32.c trees.c zutil.c inflate.c inffast.c inftrees.c
MYINCLUDES = -I../../common/zlib
-MYCFLAGS =
+MYCFLAGS = -Wno-error=strict-prototypes
MYDEFS = -DZ_SOLO -DNO_GZIP -DZLIB_PM3_TUNED
#-DDEBUG -Dverbose=1
From d00714d43ad7c0c5feedd458b8ce242f3f78237a Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Mon, 4 May 2020 10:38:21 +0200
Subject: [PATCH 062/632] unknown to clang < 8: -Woverride-init
---
Makefile.defs | 9 ++++-----
1 file changed, 4 insertions(+), 5 deletions(-)
diff --git a/Makefile.defs b/Makefile.defs
index 3c111f400..0cfdf85a7 100644
--- a/Makefile.defs
+++ b/Makefile.defs
@@ -47,16 +47,15 @@ endif
DEFCFLAGS = -Wall -Werror -O3
# Some more warnings we want as errors:
-DEFCFLAGS += -Wcast-align -Wbad-function-cast -Wredundant-decls -Wmissing-prototypes -Wchar-subscripts -Wshadow -Wundef -Wwrite-strings -Wunused -Wuninitialized -Wpointer-arith -Winline -Wformat -Wformat-security -Winit-self -Wmissing-include-dirs -Wnested-externs -Wmissing-declarations -Wempty-body -Wignored-qualifiers -Woverride-init
+DEFCFLAGS += -Wcast-align -Wbad-function-cast -Wredundant-decls -Wmissing-prototypes -Wchar-subscripts -Wshadow -Wundef -Wwrite-strings -Wunused -Wuninitialized -Wpointer-arith -Winline -Wformat -Wformat-security -Winit-self -Wmissing-include-dirs -Wnested-externs -Wmissing-declarations -Wempty-body -Wignored-qualifiers
# Some more warnings we need first to eliminate, so temporarely tolerated:
DEFCFLAGS += -Wno-error=cast-align
# TODO?:
#DEFCFLAGS += -Wunused-parameter -Wold-style-declaration -Wsign-compare -Wimplicit-fallthrough=3 -Wtype-limits -Wmissing-field-initializers -Wunused-but-set-parameter -Wswitch-enum -Wold-style-definition
#DEFCFLAGS += -Wno-error=unused-parameter -Wno-error=old-style-declaration -Wno-error=sign-compare -Wno-error=implicit-fallthrough -Wno-error=type-limits -Wno-error=missing-field-initializers -Wno-error=unused-but-set-parameter -Wno-error=switch-enum -Wno-error=old-style-definition
-# unknown to clang:
-# -Wclobbered -Wmissing-parameter-type -Wcast-function-type
-# requires GCC 6:
-# -Wshift-negative-value
+# unknown to clang: -Wclobbered -Wmissing-parameter-type -Wcast-function-type
+# unknown to clang < 8: -Woverride-init
+# unknown to gcc < 6: -Wshift-negative-value
ifeq ($(platform),Darwin)
# their readline has strict-prototype issues
From e68dd9e5cb8da1e1024512fb5d872326155cba7c Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Mon, 4 May 2020 23:18:00 +0200
Subject: [PATCH 063/632] update whereami and avoid compiling unnneded
troublesome parts
---
client/Makefile | 2 +-
client/src/whereami.c | 93 +++++++++++++++++++++++++++----------------
2 files changed, 60 insertions(+), 35 deletions(-)
diff --git a/client/Makefile b/client/Makefile
index a17f57c27..3a3aeedce 100644
--- a/client/Makefile
+++ b/client/Makefile
@@ -58,7 +58,7 @@ INCLUDES_CLIENT += -I./src -I../include -I../common -I../common_fpga $(LIBS)
CFLAGS ?= $(DEFCFLAGS)
# We cannot just use CFLAGS+=... because it has impact on sub-makes if CFLAGS is defined in env:
-PM3CFLAGS = $(CFLAGS) $(INCLUDES_CLIENT)
+PM3CFLAGS = $(CFLAGS) $(INCLUDES_CLIENT) -DWAI_PM3_TUNED
# WIP Testing
#PM3CFLAGS = $(CFLAGS) -std=c11 -pedantic $(INCLUDES_CLIENT)
PREFIX ?= /usr/local
diff --git a/client/src/whereami.c b/client/src/whereami.c
index b725c4946..ca2220953 100644
--- a/client/src/whereami.c
+++ b/client/src/whereami.c
@@ -3,9 +3,7 @@
// by Gregory Pakosz (@gpakosz)
// https://github.com/gpakosz/whereami
-#ifdef __cplusplus
-extern "C" {
-#endif
+#ifdef WAI_PM3_TUNED
#include "whereami.h"
@@ -14,6 +12,19 @@ extern "C" {
#define _DEFAULT_SOURCE
#endif
+#else // WAI_PM3_TUNED
+
+// in case you want to #include "whereami.c" in a larger compilation unit
+#if !defined(WHEREAMI_H)
+#include
+#endif
+
+#endif // WAI_PM3_TUNED
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
#if !defined(WAI_MALLOC) || !defined(WAI_FREE) || !defined(WAI_REALLOC)
#include
#endif
@@ -50,11 +61,14 @@ extern "C" {
#if defined(_WIN32)
+#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
+#endif
#if defined(_MSC_VER)
#pragma warning(push, 3)
#endif
#include
+#include
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
@@ -123,36 +137,36 @@ static int WAI_PREFIX(getModulePath_)(HMODULE module, char *out, int capacity, i
return length;
}
-WAI_NOINLINE
-WAI_FUNCSPEC
+WAI_NOINLINE WAI_FUNCSPEC
int WAI_PREFIX(getExecutablePath)(char *out, int capacity, int *dirname_length) {
return WAI_PREFIX(getModulePath_)(NULL, out, capacity, dirname_length);
}
// GetModuleHandleEx() is not available on old mingw environments. We don't need getModulePath() yet.
// Sacrifice it for the time being to improve backwards compatibility
-/* WAI_NOINLINE
-WAI_FUNCSPEC
-int WAI_PREFIX(getModulePath)(char* out, int capacity, int* dirname_length)
-{
- HMODULE module;
- int length = -1;
+#ifndef WAI_PM3_TUNED
+
+WAI_NOINLINE WAI_FUNCSPEC
+int WAI_PREFIX(getModulePath)(char *out, int capacity, int *dirname_length) {
+ HMODULE module;
+ int length = -1;
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable: 4054)
#endif
- if (GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCTSTR)WAI_RETURN_ADDRESS(), &module))
+ if (GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCTSTR)WAI_RETURN_ADDRESS(), &module))
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
- {
- length = WAI_PREFIX(getModulePath_)(module, out, capacity, dirname_length);
- }
+ {
+ length = WAI_PREFIX(getModulePath_)(module, out, capacity, dirname_length);
+ }
- return length;
+ return length;
}
-*/
+
+#endif // WAI_PM3_TUNED
#elif defined(__linux__) || defined(__CYGWIN__) || defined(__sun) || defined(WAI_USE_PROC_SELF_EXE)
@@ -228,14 +242,14 @@ int WAI_PREFIX(getExecutablePath)(char *out, int capacity, int *dirname_length)
#include
#endif
-WAI_NOINLINE
-WAI_FUNCSPEC
+#ifndef WAI_PM3_TUNED
+
+WAI_NOINLINE WAI_FUNCSPEC
int WAI_PREFIX(getModulePath)(char *out, int capacity, int *dirname_length) {
int length = -1;
FILE *maps = NULL;
- int i;
- for (i = 0; i < WAI_PROC_SELF_MAPS_RETRY; ++i) {
+ for (int r = 0; r < WAI_PROC_SELF_MAPS_RETRY; ++r) {
maps = fopen(WAI_PROC_SELF_MAPS, "r");
if (!maps)
break;
@@ -252,9 +266,8 @@ int WAI_PREFIX(getModulePath)(char *out, int capacity, int *dirname_length) {
if (!fgets(buffer, sizeof(buffer), maps))
break;
- if (sscanf(buffer, "%" SCNx64 "-%" SCNx64 " %s %" SCNx64 " %x:%x %u %s\n", &low, &high, perms, &offset, &major, &minor, &inode, path) == 8) {
- void *addr_tmp = WAI_RETURN_ADDRESS();
- uint64_t addr = (uint64_t)addr_tmp;
+ if (sscanf(buffer, "%" PRIx64 "-%" PRIx64 " %s %" PRIx64 " %x:%x %u %s\n", &low, &high, perms, &offset, &major, &minor, &inode, path) == 8) {
+ uint64_t addr = (uintptr_t)WAI_RETURN_ADDRESS();
if (low <= addr && addr <= high) {
char *resolved;
@@ -300,9 +313,11 @@ int WAI_PREFIX(getModulePath)(char *out, int capacity, int *dirname_length) {
memcpy(out, resolved, length);
if (dirname_length) {
- for (int j = length - 1; j >= 0; --j) {
- if (out[j] == '/') {
- *dirname_length = j;
+ int i;
+
+ for (i = length - 1; i >= 0; --i) {
+ if (out[i] == '/') {
+ *dirname_length = i;
break;
}
}
@@ -326,6 +341,7 @@ int WAI_PREFIX(getModulePath)(char *out, int capacity, int *dirname_length) {
return length;
}
+#endif // WAI_PM3_TUNED
#elif defined(__APPLE__)
@@ -381,8 +397,9 @@ int WAI_PREFIX(getExecutablePath)(char *out, int capacity, int *dirname_length)
return length;
}
-WAI_NOINLINE
-WAI_FUNCSPEC
+#ifndef WAI_PM3_TUNED
+
+WAI_NOINLINE WAI_FUNCSPEC
int WAI_PREFIX(getModulePath)(char *out, int capacity, int *dirname_length) {
char buffer[PATH_MAX];
char *resolved = NULL;
@@ -419,6 +436,8 @@ int WAI_PREFIX(getModulePath)(char *out, int capacity, int *dirname_length) {
return length;
}
+#endif // WAI_PM3_TUNED
+
#elif defined(__QNXNTO__)
#include
@@ -475,6 +494,8 @@ int WAI_PREFIX(getExecutablePath)(char *out, int capacity, int *dirname_length)
return length;
}
+#ifndef WAI_PM3_TUNED
+
WAI_FUNCSPEC
int WAI_PREFIX(getModulePath)(char *out, int capacity, int *dirname_length) {
char buffer[PATH_MAX];
@@ -512,11 +533,12 @@ int WAI_PREFIX(getModulePath)(char *out, int capacity, int *dirname_length) {
return length;
}
+#endif // WAI_PM3_TUNED
+
#elif defined(__DragonFly__) || defined(__FreeBSD__) || \
defined(__FreeBSD_kernel__) || defined(__NetBSD__)
#include
-#include
#include
#include
#include
@@ -532,8 +554,8 @@ int WAI_PREFIX(getExecutablePath)(char *out, int capacity, int *dirname_length)
int length = -1;
for (;;) {
-#ifdef KERN_PROC_ARGV
- int mib[4] = { CTL_KERN, KERN_PROC_ARGS, getpid(), KERN_PROC_ARGV };
+#if defined(__NetBSD__)
+ int mib[4] = { CTL_KERN, KERN_PROC_ARGS, -1, KERN_PROC_PATHNAME };
#else
int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 };
#endif
@@ -571,8 +593,9 @@ int WAI_PREFIX(getExecutablePath)(char *out, int capacity, int *dirname_length)
return length;
}
-WAI_NOINLINE
-WAI_FUNCSPEC
+#ifndef WAI_PM3_TUNED
+
+WAI_NOINLINE WAI_FUNCSPEC
int WAI_PREFIX(getModulePath)(char *out, int capacity, int *dirname_length) {
char buffer[PATH_MAX];
char *resolved = NULL;
@@ -609,6 +632,8 @@ int WAI_PREFIX(getModulePath)(char *out, int capacity, int *dirname_length) {
return length;
}
+#endif // WAI_PM3_TUNED
+
#else
#error unsupported platform
From 9847b77c83055870130b7198bcb8908b18b785cd Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Mon, 4 May 2020 23:31:36 +0200
Subject: [PATCH 064/632] fix cast align warning
---
common/generator.c | 15 +++++++--------
1 file changed, 7 insertions(+), 8 deletions(-)
diff --git a/common/generator.c b/common/generator.c
index 653d57061..b405fec1a 100644
--- a/common/generator.c
+++ b/common/generator.c
@@ -111,18 +111,17 @@ uint32_t ul_ev1_pwdgenB(uint8_t *uid) {
// Lego Dimension pwd generation algo nickname C.
uint32_t ul_ev1_pwdgenC(uint8_t *uid) {
uint32_t pwd = 0;
- uint8_t base[] = {
- 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x28,
- 0x63, 0x29, 0x20, 0x43, 0x6f, 0x70, 0x79, 0x72,
- 0x69, 0x67, 0x68, 0x74, 0x20, 0x4c, 0x45, 0x47,
- 0x4f, 0x20, 0x32, 0x30, 0x31, 0x34, 0xaa, 0xaa
+ uint32_t base[] = {
+ 0xffffffff, 0x28ffffff,
+ 0x43202963, 0x7279706f,
+ 0x74686769, 0x47454c20,
+ 0x3032204f, 0xaaaa3431
};
memcpy(base, uid, 7);
- for (int i = 0; i < 32; i += 4) {
- uint32_t b = *(uint32_t *)(base + i);
- pwd = b + ROTR(pwd, 25) + ROTR(pwd, 10) - pwd;
+ for (int i = 0; i < 8; i++) {
+ pwd = base[i] + ROTR(pwd, 25) + ROTR(pwd, 10) - pwd;
}
return BSWAP_32(pwd);
}
From 2c250d5d1400e3cdb7ee5a81246fe318db175c1e Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Mon, 4 May 2020 23:58:58 +0200
Subject: [PATCH 065/632] hf epa: fix cast align warning
---
client/src/cmdhfepa.c | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/client/src/cmdhfepa.c b/client/src/cmdhfepa.c
index e83ee39bf..b7c49bd83 100644
--- a/client/src/cmdhfepa.c
+++ b/client/src/cmdhfepa.c
@@ -92,8 +92,8 @@ static int CmdHFEPAPACEReplay(const char *Cmd) {
while (Cmd[skip] != ' ' && Cmd[skip] != '\0') {
// convert
scan_return = sscanf(Cmd + skip,
- "%2X%n",
- (unsigned int *)(apdus[i] + apdu_lengths[i]),
+ "%2" SCNx8 "%n",
+ apdus[i] + apdu_lengths[i],
&skip_add
);
From 30e96ece74d4dce57116a2a484f78574fba1a70c Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Tue, 5 May 2020 00:16:53 +0200
Subject: [PATCH 066/632] lf nedap: fix cast align warning
---
client/src/cmdlfnedap.c | 10 ++++++----
1 file changed, 6 insertions(+), 4 deletions(-)
diff --git a/client/src/cmdlfnedap.c b/client/src/cmdlfnedap.c
index cb0b11629..c748a262a 100644
--- a/client/src/cmdlfnedap.c
+++ b/client/src/cmdlfnedap.c
@@ -95,7 +95,9 @@ static inline uint32_t bitcount(uint32_t a) {
}
static uint8_t isEven_64_63(const uint8_t *data) { // 8
- return (bitcount(*(uint32_t *) data) + (bitcount((*(uint32_t *)(data + 4)) & 0xfeffffff))) & 1;
+ uint32_t tmp[2];
+ memcpy(tmp, data, 8);
+ return (bitcount(tmp[0]) + (bitcount(tmp[1] & 0xfeffffff))) & 1;
}
//NEDAP demod - ASK/Biphase (or Diphase), RF/64 with preamble of 1111111110 (always a 128 bit data stream)
@@ -163,14 +165,14 @@ static int CmdLFNedapDemod(const char *Cmd) {
buffer[6] = (data[3] << 7) | ((data[4] & 0xe0) >> 1) | ((data[4] & 0x01) << 3) | ((data[5] & 0xe0) >> 5);
buffer[5] = (data[5] << 7) | ((data[6] & 0xe0) >> 1) | ((data[6] & 0x01) << 3) | ((data[7] & 0xe0) >> 5);
-
- bool isValid = (checksum == *(uint16_t *)(buffer + 5));
+ uint16_t checksum2 = (buffer[6] << 8) + buffer[5];
+ bool isValid = (checksum == checksum2);
subtype = (data[1] & 0x1e) >> 1;
customerCode = ((data[1] & 0x01) << 11) | (data[2] << 3) | ((data[3] & 0xe0) >> 5);
if (isValid == false) {
- PrintAndLogEx(ERR, "Checksum : %s (calc 0x%04X != 0x%04X)", _RED_("failed"), checksum, *(uint16_t *)(buffer + 5));
+ PrintAndLogEx(ERR, "Checksum : %s (calc 0x%04X != 0x%04X)", _RED_("failed"), checksum, checksum2);
ret = PM3_ESOFT;
}
From 3fb34dd45bd38a41cb47d9c2add785d15f0aaf9a Mon Sep 17 00:00:00 2001
From: iceman1001
Date: Tue, 5 May 2020 09:15:43 +0200
Subject: [PATCH 067/632] chg: more LF demodulation tests
---
pm3test.sh | 20 ++++++++++++--------
1 file changed, 12 insertions(+), 8 deletions(-)
diff --git a/pm3test.sh b/pm3test.sh
index be9331358..0739bd7a8 100755
--- a/pm3test.sh
+++ b/pm3test.sh
@@ -110,15 +110,19 @@ while true; do
if ! CheckExecute "mfu pwdgen test" "$PM3BIN -c 'hf mfu pwdgen t'" "Selftest OK"; then break; fi
printf "\n${C_BLUE}Testing LF:${C_NC}\n"
- if ! CheckExecute "lf em4x05 test" "$PM3BIN -c 'data load traces/em4x05.pm3;lf search 1'" "FDX-B ID found"; then break; fi
- if ! CheckExecute "lf em410x test" "$PM3BIN -c 'data load traces/EM4102-1.pm3;lf search 1'" "EM410x ID found"; then break; fi
- if ! CheckExecute "lf visa2000 test" "$PM3BIN -c 'data load traces/visa2000.pm3;lf search 1'" "Visa2000 ID found"; then break; fi
- if ! CheckExecute "lf awid test" "$PM3BIN -c 'data load traces/AWID-15-259.pm3;lf search 1'" "AWID ID found"; then break; fi
- if ! CheckExecute "lf securakey test" "$PM3BIN -c 'data load traces/securakey-64169.pm3;lf search 1 '" "Securakey ID found"; then break; fi
- if ! CheckExecute "lf keri test" "$PM3BIN -c 'data load traces/keri.pm3;lf search 1'" "Pyramid ID found"; then break; fi
+ if ! CheckExecute "lf EM4x05 test" "$PM3BIN -c 'data load traces/em4x05.pm3;lf search 1'" "FDX-B ID found"; then break; fi
+ if ! CheckExecute "lf EM410x test" "$PM3BIN -c 'data load traces/EM4102-1.pm3;lf search 1'" "EM410x ID found"; then break; fi
+ if ! CheckExecute "lf VISA2000 test" "$PM3BIN -c 'data load traces/visa2000.pm3;lf search 1'" "Visa2000 ID found"; then break; fi
+ if ! CheckExecute "lf AWID test" "$PM3BIN -c 'data load traces/AWID-15-259.pm3;lf search 1'" "AWID ID found"; then break; fi
+ if ! CheckExecute "lf SECURAKEY test" "$PM3BIN -c 'data load traces/securakey-64169.pm3;lf search 1 '" "Securakey ID found"; then break; fi
+ if ! CheckExecute "lf NEXWATCH test" "$PM3BIN -c 'data load traces/quadrakey-521512301.pm3;lf search 1 '" "NexWatch ID found"; then break; fi
+ if ! CheckExecute "lf KERI test" "$PM3BIN -c 'data load traces/keri.pm3;lf search 1'" "Pyramid ID found"; then break; fi
if ! CheckExecute "lf HID Prox test" "$PM3BIN -c 'data load traces/hid-proxCardII-05512-11432784-1.pm3;lf search 1'" "HID Prox ID found"; then break; fi
- if ! CheckExecute "lf Paradox test" "$PM3BIN -c 'data load traces/Paradox-96_40426-APJN08.pm3;lf search 1'" "Paradox ID found"; then break; fi
- if ! CheckExecute "lf IO Prox test" "$PM3BIN -c 'data load traces/ioprox-XSF-01-3B-44725.pm3;lf search 1'" "IO Prox ID found"; then break; fi
+ if ! CheckExecute "lf PARADOX test" "$PM3BIN -c 'data load traces/Paradox-96_40426-APJN08.pm3;lf search 1'" "Paradox ID found"; then break; fi
+ if ! CheckExecute "lf PAC test" "$PM3BIN -c 'data load traces/pac-8E4C058E.pm3;lf search 1'" "PAC/Stanley ID found"; then break; fi
+ if ! CheckExecute "lf VIKING test" "$PM3BIN -c 'data load traces/Transit999-best.pm3;lf search 1'" "Viking ID found"; then break; fi
+ if ! CheckExecute "lf FDX-B test" "$PM3BIN -c 'data load traces/homeagain1600.pm3;lf search 1'" "FDX-B ID found"; then break; fi
+ if ! CheckExecute "lf INDALA test" "$PM3BIN -c 'data load traces/indala-504278295.pm3;lf search 1'" "Indala ID found"; then break; fi
printf "\n${C_BLUE}Testing HF:${C_NC}\n"
if ! CheckExecute "hf mf offline text" "$PM3BIN -c 'hf mf'" "at_enc"; then break; fi
From 6dadbb042390f7dcf2df4390351bf40ed81ec29e Mon Sep 17 00:00:00 2001
From: iceman1001
Date: Tue, 5 May 2020 08:19:26 +0100
Subject: [PATCH 068/632] chg: rpi aling warning
---
client/src/cmdhflegic.c | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/client/src/cmdhflegic.c b/client/src/cmdhflegic.c
index 7507e326b..b7defe904 100644
--- a/client/src/cmdhflegic.c
+++ b/client/src/cmdhflegic.c
@@ -880,7 +880,7 @@ int legic_get_type(legic_card_select_t *card) {
if (!isOK)
return PM3_ESOFT;
- memcpy(card, (legic_card_select_t *)resp.data.asBytes, sizeof(legic_card_select_t));
+ memcpy(card, resp.data.asBytes, sizeof(legic_card_select_t));
return PM3_SUCCESS;
}
void legic_chk_iv(uint32_t *iv) {
From dcb02b853c8bb269bb589510b2c0159d10dc8fa2 Mon Sep 17 00:00:00 2001
From: Iceman
Date: Tue, 5 May 2020 09:48:14 +0200
Subject: [PATCH 069/632] Update bt_manual_v10.md
updated the instructions for native bluetooth on Windows 10.
---
doc/bt_manual_v10.md | 18 ++++++++++++++++++
1 file changed, 18 insertions(+)
diff --git a/doc/bt_manual_v10.md b/doc/bt_manual_v10.md
index 8a08fcdcd..805b6ec23 100644
--- a/doc/bt_manual_v10.md
+++ b/doc/bt_manual_v10.md
@@ -65,6 +65,24 @@ To compile the client and firmware with FPC support, the easiest way is to
You are now ready to run the client with the serial port you got from your BT device on your laptop etc.
See instructions below.
+First open your bluetooth settings, click on "more options".
+
+
+
+Go to second tab and view the list of current bluetooth comports. If you don't have an outgoing com port setup, click 'add'
+
+
+
+Select `outgoing comport` and select the Proxmark3 RDV4.0 device. Click `OK` when done.
+
+
+
+Verify that you now have a outgoing comport. Remember this com port when you want to use your Proxmark3.
+
+
+
+All done!
+
#### Homebrew (macOS)
From the [homebrew-proxmark3 readme](https://github.com/RfidResearchGroup/homebrew-proxmark3)
From 9703f6412b2095800eb04dc675e05403cce5d21f Mon Sep 17 00:00:00 2001
From: Iceman
Date: Tue, 5 May 2020 09:48:27 +0200
Subject: [PATCH 070/632] Update bt_manual_v10.md
---
doc/bt_manual_v10.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/doc/bt_manual_v10.md b/doc/bt_manual_v10.md
index 805b6ec23..3290aa97a 100644
--- a/doc/bt_manual_v10.md
+++ b/doc/bt_manual_v10.md
@@ -1,6 +1,6 @@
# MANUAL
### Bluetooth / Battery add-on 'Blue Shark'
-_rev. v1.0_
+_rev. v1.1_
### 1. FEATURES
From 10abd0f2233a0680118ae8769c4d65a92d4429b0 Mon Sep 17 00:00:00 2001
From: Iceman
Date: Tue, 5 May 2020 11:45:19 +0200
Subject: [PATCH 071/632] Update bt_manual_v10.md
---
doc/bt_manual_v10.md | 89 +++++++++++++++++++++-----------------------
1 file changed, 42 insertions(+), 47 deletions(-)
diff --git a/doc/bt_manual_v10.md b/doc/bt_manual_v10.md
index 3290aa97a..3f3fd4116 100644
--- a/doc/bt_manual_v10.md
+++ b/doc/bt_manual_v10.md
@@ -1,8 +1,8 @@
# MANUAL
-### Bluetooth / Battery add-on 'Blue Shark'
+## Bluetooth / Battery add-on 'Blue Shark'
_rev. v1.1_
-### 1. FEATURES
+## 1. FEATURES
* Built-in Bluetooth 2.0 with EDR Bluetooth module, default baud rate 115200.
* Built-in 400 mAh polymer lithium-ion battery, typical standby time up to 3.5 hours.
@@ -17,7 +17,7 @@ It can easily connect to Bluetooth mobile phone, portable computer, etc. Without
Built-in battery can support standalone mode, off-line sniffing, off-line reading & simulation, etc. The temperature of the device is stable.
-### 2. PARAMETERS
+## 2. PARAMETERS
* Battery capacity: 400 mAh
* Standby time: 3.5h @ StandBy; 2.9h @ LF-On; 50min @ HF-On;
@@ -29,7 +29,7 @@ Built-in battery can support standalone mode, off-line sniffing, off-line readin
* Size and weight: 54.4mm * 29.4mm * 13.5mm 24g
-### 3. ASSEMBLY STEPS
+## 3. ASSEMBLY STEPS
* Unplug your Proxmark3 RDV4.0 device from any usb cable.
* Remove the plastic upper case of Proxmark3 RDV4.0 with opener.
@@ -45,10 +45,9 @@ Built-in battery can support standalone mode, off-line sniffing, off-line readin

-### 4. COMPILATION / FLASHING
+## 4. COMPILATION / FLASHING
#### From Source
-
Please download the latest source code from Rfid Research Group's Github repo:
https://github.com/RfidResearchGroup/proxmark3
@@ -65,31 +64,14 @@ To compile the client and firmware with FPC support, the easiest way is to
You are now ready to run the client with the serial port you got from your BT device on your laptop etc.
See instructions below.
-First open your bluetooth settings, click on "more options".
-
-
-
-Go to second tab and view the list of current bluetooth comports. If you don't have an outgoing com port setup, click 'add'
-
-
-
-Select `outgoing comport` and select the Proxmark3 RDV4.0 device. Click `OK` when done.
-
-
-
-Verify that you now have a outgoing comport. Remember this com port when you want to use your Proxmark3.
-
-
-
-All done!
-
#### Homebrew (macOS)
From the [homebrew-proxmark3 readme](https://github.com/RfidResearchGroup/homebrew-proxmark3)
1. `brew tap rfidresearchgroup/proxmark3`
2. `brew install --with-blueshark proxmark3`
-### 5. CONNECT WITH BLUETOOTH
+
+## 5. CONNECT WITH BLUETOOTH
You can have both USB cable connect and BT active at the same time and connect to either serial port.
You can also switch serial port from inside the proxmark3 client using the new command `hw connect`.
@@ -100,19 +82,33 @@ You can also switch serial port from inside the proxmark3 client using the new c
2. Name: `PM3_RDV4.0`
3. Pin: `1234`
-#### Windows
-
-#### (1) Connecting your RDV4.0 with Bluetooth on mobile phone or computer
+### Windows
+#### (5.1) (win) Connecting your RDV4.0 with Bluetooth on mobile phone or computer
* Open Bluetooth and search for a device named PM3_RDV4.0.
* Enter the paired password 1234 and establish the connection.
* The blue state LED on the add-on will keep blinking after the connection is established. Only when the mobile phone or computer opens the correct COM port, the blue LED turns on solid, indicating that the connection is successful.
-
-
-
* First time you do this you might need to go into Bluetooth more settings and add a outgoing com port.
-#### (2) Fast connection using dedicated USB Bluetooth adapter under Windows
+* First open your bluetooth settings, click on "more options".
+
+
+
+* Go to second tab and view the list of current bluetooth comports. If you don't have an outgoing com port setup, click 'add'
+
+
+
+* Select `outgoing comport` and select the Proxmark3 RDV4.0 device. Click `OK` when done.
+
+
+
+* Verify that you now have a outgoing comport. Remember this com port when you want to use your Proxmark3.
+
+
+
+* done!
+
+#### (5.2) (win) Fast connection using dedicated USB Bluetooth adapter under Windows

@@ -125,9 +121,8 @@ http://www.silabs.com/products/development-tools/software/usb-to-uart-bridge-vcp
* After the connection is established, the blue state LED on add-on will turn on solid.
* look for _CP2104 USB tp UART bridge controller_ under devices in order to get the assigned serial port
-#### Linux
-
-#### (1) Connecting rdv4.0 with Bluetooth on Linux computer via native Bluetooth support in the client
+### Linux
+#### (5.1) (linux) Connecting rdv4.0 with Bluetooth on Linux computer via native Bluetooth support in the client
This requires to have compiled the client with Bluetooth support.
@@ -171,7 +166,7 @@ Discovery started
[bluetooth]# quit
```
-#### (2) Fast connection using dedicated USB Bluetooth adapter under Linux
+#### (5.2) (linux) Fast connection using dedicated USB Bluetooth adapter under Linux

@@ -194,7 +189,7 @@ turn on solid.
./proxmark3 /dev/ttyUSB0
```
-#### (1b, deprecated) Connecting rdv4.0 with Bluetooth on Linux computer via rfcomm
+#### (5.1b) (linux, deprecated) Connecting rdv4.0 with Bluetooth on Linux computer via rfcomm
rfcomm is a deprecated tool which might be unavailable in your Linux distribution.
@@ -227,9 +222,9 @@ connection is successful.
See instructions above (method 1) for initial pairing.
-#### MacOS
+### MacOS
-#### (1) Connecting rdv4.0 with Bluetooth on MacOS
+#### (5.1) (osx) Connecting rdv4.0 with Bluetooth on MacOS
With MacOS Mojave 10.14.5 you could experience some continuosly disconnecting and difficult to recconnect the device at the system wakeup, to avoid this problem do a PRAM reset before to add your Proxmark3 RDV4 Blue Shark:
@@ -248,34 +243,34 @@ After reboot you can go ahead to pairing your Proxmark3 RDV4 Blue Shark:
```sh
./proxmark3 /dev/tty.PM3_RDV40-DevB
```
-#### Android
+### Android
-#### (2) Fast connection using dedicated Bluetooth (HC-06 Master + CP2102) adapter under Android with Termux
+#### (5.1) (android) Fast connection using dedicated Bluetooth (HC-06 Master + CP2102) adapter under Android with Termux
1. Make sure you already followed this tutorial https://github.com/RfidResearchGroup/proxmark3/blob/master/doc/termux_notes.md#setup and have Termux with an running Proxmark3 client ready. You need additional the `cp210x` serial usb driver enabled and working, like the `USB_ACM` driver to communicate wireless.
2. Insert the Bluetooth adapter with an fitting USB-C/Micro-USB converter into your Android USB port and a serial port `/dev/ttyUSB0` will be created. To see if it's working, run `tsudo ls /dev/ttyU*` and it should list `/dev/ttyUSB0`.
3. The adapter will search automatically and establish the connection to BlueShark. The adapter will remember the device that was first connected and after that the same device will be connected. After the connection is established, the blue state LED on add-on will turn on solid.
4. If you see this, congratulations, you can run your Proxmark3 client in Termux with `tsudo proxmark3/client/proxmark3 /dev/ttyUSB0`
-##### Notes
+#### Notes
If you bought your Bluetooth adapter somewhere else, make sure to set the baud rate to 115200 `AT+BAUD8` and PIN `AT+PIN1234` correctly
-### 6. OTHER NOTES
+## 6. OTHER NOTES
-#### (1) UART and LED behavior
+### (6.1) UART and LED behavior
Bluetooth is connected to Proxmark3 RDV4.0 via UART. The USB and UART interfaces of RDV4.0 can coexist without conflict, and no special switching is required.
The following link has helpful notes on UART usage and baud rates:
https://github.com/RfidResearchGroup/proxmark3/blob/master/doc/uart_notes.md
-#### (2) Disassembly
+### (6.2) Disassembly
There is a heat conductive double-sided tape inside the add-on, which has strong adhesive force. Therefore, if add-on needs to be removed, it needs to be pulled out from the heat sink end with greater efforts. Each disassembly will reduce the viscidity of double-sided tape. When double-sided tape is well protected, it will not affect the second use. Thermal conductivity will be slightly worse and will therefore have a direct impact on the thermal performance of the heat sink.
-#### (3) Battery charging
+### (6.3) Battery charging
The battery charging circuit is turned on by default. Any time a USB cable is inserted, the battery will be automatically charged. The red LED will remain bright when charging.
The red LED will be extinguished when charging is completed.
-#### (4) Get better signals
+### (6.4) Get better signals
For the better heat dissipation, we have used a cast metal enclosure for the add-on. As a result Bluetooth wireless signals are sacrificed. For example, if the back of add-on is facing the Bluetooth host, the signal is very bad and the distance will be reduced. The best signal strength can be obtained when the front glass faces the Bluetooth host.
If the Proxmark3 is not responding, it may be due to a poor Bluetooth connection. To improve performance, try repositioning the Proxmark3 so the glass face is directed toward the host.
From b330b48258fd0f4b1e4c21678d23d076b2c8212b Mon Sep 17 00:00:00 2001
From: Iceman
Date: Tue, 5 May 2020 12:07:22 +0200
Subject: [PATCH 072/632] Update bt_manual_v10.md
---
doc/bt_manual_v10.md | 55 +++++++++++++++++++++++++++++++++-----------
1 file changed, 42 insertions(+), 13 deletions(-)
diff --git a/doc/bt_manual_v10.md b/doc/bt_manual_v10.md
index 3f3fd4116..b92dfe23b 100644
--- a/doc/bt_manual_v10.md
+++ b/doc/bt_manual_v10.md
@@ -2,6 +2,30 @@
## Bluetooth / Battery add-on 'Blue Shark'
_rev. v1.1_
+1. FEATURES
+2. PARAMETERS
+3. ASSEMBLY STEPS
+4. COMPILATION / FLASHING
+ * 4.1 From source
+ * 4.2 Homebrew (macOS)
+5. CONNECT WITH BLUETOOTH
+ * 5.1 WINDOWS
+ * 5.1.1 Connecting your RDV4.0 with Bluetooth on mobile phone or computer
+ * 5.1.2 Fast connection using dedicated USB Bluetooth adapter under Windows
+ * 5.2 LINUX
+ * 5.2.1 Connecting rdv4.0 with Bluetooth on Linux computer via native Bluetooth support in the client
+ * 5.2.2 Fast connection using dedicated USB Bluetooth adapter under Linux
+ * 5.2.1b *(deprecated)* Connecting rdv4.0 with Bluetooth on Linux computer via rfcomm
+ * 5.3 OS X
+ * 5.3.1 Connecting rdv4.0 with Bluetooth on MacOS
+ * 5.4 ANDROID
+ * 5.4.1 Fast connection using dedicated Bluetooth (HC-06 Master + CP2102) adapter under Android with Termux
+6. OTHER NOTES
+ * 6.1. UART and LED behavior
+ * 6.2. Disassembly
+ * 6.3. Battery charging
+ * 6.4. Get better signals
+
## 1. FEATURES
* Built-in Bluetooth 2.0 with EDR Bluetooth module, default baud rate 115200.
@@ -47,7 +71,7 @@ Built-in battery can support standalone mode, off-line sniffing, off-line readin
## 4. COMPILATION / FLASHING
-#### From Source
+#### (4.1) From Source
Please download the latest source code from Rfid Research Group's Github repo:
https://github.com/RfidResearchGroup/proxmark3
@@ -64,7 +88,7 @@ To compile the client and firmware with FPC support, the easiest way is to
You are now ready to run the client with the serial port you got from your BT device on your laptop etc.
See instructions below.
-#### Homebrew (macOS)
+#### (4.2) Homebrew (macOS)
From the [homebrew-proxmark3 readme](https://github.com/RfidResearchGroup/homebrew-proxmark3)
1. `brew tap rfidresearchgroup/proxmark3`
@@ -82,8 +106,9 @@ You can also switch serial port from inside the proxmark3 client using the new c
2. Name: `PM3_RDV4.0`
3. Pin: `1234`
-### Windows
-#### (5.1) (win) Connecting your RDV4.0 with Bluetooth on mobile phone or computer
+### (5.1) Windows
+
+#### (5.1.1) Connecting your RDV4.0 with Bluetooth on mobile phone or computer
* Open Bluetooth and search for a device named PM3_RDV4.0.
* Enter the paired password 1234 and establish the connection.
* The blue state LED on the add-on will keep blinking after the connection is established. Only when the mobile phone or computer opens the correct COM port, the blue LED turns on solid, indicating that the connection is successful.
@@ -91,6 +116,9 @@ You can also switch serial port from inside the proxmark3 client using the new c
* First time you do this you might need to go into Bluetooth more settings and add a outgoing com port.
* First open your bluetooth settings, click on "more options".
+
+
+
@@ -108,7 +136,7 @@ You can also switch serial port from inside the proxmark3 client using the new c
* done!
-#### (5.2) (win) Fast connection using dedicated USB Bluetooth adapter under Windows
+#### (5.1.2) Fast connection using dedicated USB Bluetooth adapter under Windows

@@ -121,8 +149,9 @@ http://www.silabs.com/products/development-tools/software/usb-to-uart-bridge-vcp
* After the connection is established, the blue state LED on add-on will turn on solid.
* look for _CP2104 USB tp UART bridge controller_ under devices in order to get the assigned serial port
-### Linux
-#### (5.1) (linux) Connecting rdv4.0 with Bluetooth on Linux computer via native Bluetooth support in the client
+### (5.2) Linux
+
+#### (5.2.1) Connecting rdv4.0 with Bluetooth on Linux computer via native Bluetooth support in the client
This requires to have compiled the client with Bluetooth support.
@@ -166,7 +195,7 @@ Discovery started
[bluetooth]# quit
```
-#### (5.2) (linux) Fast connection using dedicated USB Bluetooth adapter under Linux
+#### (5.2.2) Fast connection using dedicated USB Bluetooth adapter under Linux

@@ -189,7 +218,7 @@ turn on solid.
./proxmark3 /dev/ttyUSB0
```
-#### (5.1b) (linux, deprecated) Connecting rdv4.0 with Bluetooth on Linux computer via rfcomm
+#### (5.2.1b) (deprecated) Connecting rdv4.0 with Bluetooth on Linux computer via rfcomm
rfcomm is a deprecated tool which might be unavailable in your Linux distribution.
@@ -222,9 +251,9 @@ connection is successful.
See instructions above (method 1) for initial pairing.
-### MacOS
+### (5.3) MacOS
-#### (5.1) (osx) Connecting rdv4.0 with Bluetooth on MacOS
+#### (5.3.1) Connecting rdv4.0 with Bluetooth on MacOS
With MacOS Mojave 10.14.5 you could experience some continuosly disconnecting and difficult to recconnect the device at the system wakeup, to avoid this problem do a PRAM reset before to add your Proxmark3 RDV4 Blue Shark:
@@ -243,9 +272,9 @@ After reboot you can go ahead to pairing your Proxmark3 RDV4 Blue Shark:
```sh
./proxmark3 /dev/tty.PM3_RDV40-DevB
```
-### Android
+### (5.4) Android
-#### (5.1) (android) Fast connection using dedicated Bluetooth (HC-06 Master + CP2102) adapter under Android with Termux
+#### (5.4.1) Fast connection using dedicated Bluetooth (HC-06 Master + CP2102) adapter under Android with Termux
1. Make sure you already followed this tutorial https://github.com/RfidResearchGroup/proxmark3/blob/master/doc/termux_notes.md#setup and have Termux with an running Proxmark3 client ready. You need additional the `cp210x` serial usb driver enabled and working, like the `USB_ACM` driver to communicate wireless.
2. Insert the Bluetooth adapter with an fitting USB-C/Micro-USB converter into your Android USB port and a serial port `/dev/ttyUSB0` will be created. To see if it's working, run `tsudo ls /dev/ttyU*` and it should list `/dev/ttyUSB0`.
From ddfcf71d406e84195edbda70e711cf0adc8efd5c Mon Sep 17 00:00:00 2001
From: Iceman
Date: Tue, 5 May 2020 12:08:44 +0200
Subject: [PATCH 073/632] Update bt_manual_v10.md
---
doc/bt_manual_v10.md | 5 +----
1 file changed, 1 insertion(+), 4 deletions(-)
diff --git a/doc/bt_manual_v10.md b/doc/bt_manual_v10.md
index b92dfe23b..037f64ef8 100644
--- a/doc/bt_manual_v10.md
+++ b/doc/bt_manual_v10.md
@@ -113,12 +113,9 @@ You can also switch serial port from inside the proxmark3 client using the new c
* Enter the paired password 1234 and establish the connection.
* The blue state LED on the add-on will keep blinking after the connection is established. Only when the mobile phone or computer opens the correct COM port, the blue LED turns on solid, indicating that the connection is successful.
-* First time you do this you might need to go into Bluetooth more settings and add a outgoing com port.
+* First time you do this you might need to go into Bluetooth more settings and add a outgoing com port. If so, follow these steps below.
* First open your bluetooth settings, click on "more options".
-
-
-
From 2e52c476def1bea51dd42e719866d94d4888057e Mon Sep 17 00:00:00 2001
From: iceman1001
Date: Tue, 5 May 2020 12:32:46 +0200
Subject: [PATCH 074/632] check for sim module fw file
---
pm3test.sh | 2 ++
1 file changed, 2 insertions(+)
diff --git a/pm3test.sh b/pm3test.sh
index 0739bd7a8..99fe168dc 100755
--- a/pm3test.sh
+++ b/pm3test.sh
@@ -95,6 +95,8 @@ while true; do
printf "\n${C_BLUE}Testing files:${C_NC}\n"
if ! CheckFileExist "proxmark3 exists" "$PM3BIN"; then break; fi
if ! CheckFileExist "hardnested tables exists" "./client/resources/hardnested_tables/*.z"; then break; fi
+ if ! CheckFileExist "simmodule fw file exists" "./tools/simmodule/sim011.bin"; then break; fi
+
if $TESTDEVICE; then
if ! CheckFileExist "arm image exists" "./armsrc/obj/fullimage.elf"; then break; fi
if ! CheckFileExist "bootrom exists" "./bootrom/obj/bootrom.elf"; then break; fi
From c49bfa0849c4d9cc702080a8412ea10644fb1d0b Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Tue, 5 May 2020 13:45:03 +0200
Subject: [PATCH 075/632] bt manual
---
doc/bt_manual_v10.md | 107 ++++++++++++++++++++++---------------------
1 file changed, 55 insertions(+), 52 deletions(-)
diff --git a/doc/bt_manual_v10.md b/doc/bt_manual_v10.md
index 037f64ef8..d54d458c2 100644
--- a/doc/bt_manual_v10.md
+++ b/doc/bt_manual_v10.md
@@ -1,31 +1,33 @@
-# MANUAL
-## Bluetooth / Battery add-on 'Blue Shark'
+# MANUAL Bluetooth / Battery add-on 'Blue Shark'
_rev. v1.1_
-1. FEATURES
-2. PARAMETERS
-3. ASSEMBLY STEPS
-4. COMPILATION / FLASHING
- * 4.1 From source
- * 4.2 Homebrew (macOS)
-5. CONNECT WITH BLUETOOTH
- * 5.1 WINDOWS
- * 5.1.1 Connecting your RDV4.0 with Bluetooth on mobile phone or computer
- * 5.1.2 Fast connection using dedicated USB Bluetooth adapter under Windows
- * 5.2 LINUX
- * 5.2.1 Connecting rdv4.0 with Bluetooth on Linux computer via native Bluetooth support in the client
- * 5.2.2 Fast connection using dedicated USB Bluetooth adapter under Linux
- * 5.2.1b *(deprecated)* Connecting rdv4.0 with Bluetooth on Linux computer via rfcomm
- * 5.3 OS X
- * 5.3.1 Connecting rdv4.0 with Bluetooth on MacOS
- * 5.4 ANDROID
- * 5.4.1 Fast connection using dedicated Bluetooth (HC-06 Master + CP2102) adapter under Android with Termux
-6. OTHER NOTES
- * 6.1. UART and LED behavior
- * 6.2. Disassembly
- * 6.3. Battery charging
- * 6.4. Get better signals
-
+## Table of Contents
+
+ * [1. FEATURES](#1-features)
+ * [2. PARAMETERS](#2-parameters)
+ * [3. ASSEMBLY STEPS](#3-assembly-steps)
+ * [4. COMPILATION / FLASHING](#4-compilation--flashing)
+ * [4.1 From Source](#41-from-source)
+ * [4.2 Homebrew (macOS)](#42-homebrew-macos)
+ * [5. CONNECT WITH BLUETOOTH](#5-connect-with-bluetooth)
+ * [5.1 Windows](#51-windows)
+ * [5.1.1 Connecting your RDV4.0 with Bluetooth on mobile phone or computer](#511-connecting-your-rdv40-with-bluetooth-on-mobile-phone-or-computer)
+ * [5.1.2 Fast connection using dedicated USB Bluetooth adapter under Windows](#512-fast-connection-using-dedicated-usb-bluetooth-adapter-under-windows)
+ * [5.2 Linux](#52-linux)
+ * [5.2.1 Connecting rdv4.0 with Bluetooth on Linux computer via native Bluetooth support in the client](#521-connecting-rdv40-with-bluetooth-on-linux-computer-via-native-bluetooth-support-in-the-client)
+ * [5.2.2 Fast connection using dedicated USB Bluetooth adapter under Linux](#522-fast-connection-using-dedicated-usb-bluetooth-adapter-under-linux)
+ * [5.2.3 (deprecated) Connecting rdv4.0 with Bluetooth on Linux computer via rfcomm](#523-deprecated-connecting-rdv40-with-bluetooth-on-linux-computer-via-rfcomm)
+ * [5.3 MacOS](#53-macos)
+ * [5.3.1 Connecting rdv4.0 with Bluetooth on MacOS](#531-connecting-rdv40-with-bluetooth-on-macos)
+ * [5.4 Android](#54-android)
+ * [5.4.1 Fast connection using dedicated Bluetooth (HC-06 Master CP2102) adapter under Android with Termux](#541-fast-connection-using-dedicated-bluetooth-hc-06-master--cp2102-adapter-under-android-with-termux)
+ * [6. OTHER NOTES](#6-other-notes)
+ * [6.1 Default settings](#61-default-settings)
+ * [6.2 UART and LED behavior](#62-uart-and-led-behavior)
+ * [6.3 Disassembly](#63-disassembly)
+ * [6.4 Battery charging](#64-battery-charging)
+ * [6.5 Get better signals](#65-get-better-signals)
+
## 1. FEATURES
* Built-in Bluetooth 2.0 with EDR Bluetooth module, default baud rate 115200.
@@ -71,7 +73,7 @@ Built-in battery can support standalone mode, off-line sniffing, off-line readin
## 4. COMPILATION / FLASHING
-#### (4.1) From Source
+#### 4.1 From Source
Please download the latest source code from Rfid Research Group's Github repo:
https://github.com/RfidResearchGroup/proxmark3
@@ -88,7 +90,7 @@ To compile the client and firmware with FPC support, the easiest way is to
You are now ready to run the client with the serial port you got from your BT device on your laptop etc.
See instructions below.
-#### (4.2) Homebrew (macOS)
+#### 4.2 Homebrew (macOS)
From the [homebrew-proxmark3 readme](https://github.com/RfidResearchGroup/homebrew-proxmark3)
1. `brew tap rfidresearchgroup/proxmark3`
@@ -100,15 +102,9 @@ From the [homebrew-proxmark3 readme](https://github.com/RfidResearchGroup/homebr
You can have both USB cable connect and BT active at the same time and connect to either serial port.
You can also switch serial port from inside the proxmark3 client using the new command `hw connect`.
-### Default settings
+### 5.1 Windows
-1. Serial: `115200 8N1`
-2. Name: `PM3_RDV4.0`
-3. Pin: `1234`
-
-### (5.1) Windows
-
-#### (5.1.1) Connecting your RDV4.0 with Bluetooth on mobile phone or computer
+#### 5.1.1 Connecting your RDV4.0 with Bluetooth on mobile phone or computer
* Open Bluetooth and search for a device named PM3_RDV4.0.
* Enter the paired password 1234 and establish the connection.
* The blue state LED on the add-on will keep blinking after the connection is established. Only when the mobile phone or computer opens the correct COM port, the blue LED turns on solid, indicating that the connection is successful.
@@ -133,7 +129,7 @@ You can also switch serial port from inside the proxmark3 client using the new c
* done!
-#### (5.1.2) Fast connection using dedicated USB Bluetooth adapter under Windows
+#### 5.1.2 Fast connection using dedicated USB Bluetooth adapter under Windows

@@ -146,9 +142,9 @@ http://www.silabs.com/products/development-tools/software/usb-to-uart-bridge-vcp
* After the connection is established, the blue state LED on add-on will turn on solid.
* look for _CP2104 USB tp UART bridge controller_ under devices in order to get the assigned serial port
-### (5.2) Linux
+### 5.2 Linux
-#### (5.2.1) Connecting rdv4.0 with Bluetooth on Linux computer via native Bluetooth support in the client
+#### 5.2.1 Connecting rdv4.0 with Bluetooth on Linux computer via native Bluetooth support in the client
This requires to have compiled the client with Bluetooth support.
@@ -192,7 +188,7 @@ Discovery started
[bluetooth]# quit
```
-#### (5.2.2) Fast connection using dedicated USB Bluetooth adapter under Linux
+#### 5.2.2 Fast connection using dedicated USB Bluetooth adapter under Linux

@@ -215,7 +211,7 @@ turn on solid.
./proxmark3 /dev/ttyUSB0
```
-#### (5.2.1b) (deprecated) Connecting rdv4.0 with Bluetooth on Linux computer via rfcomm
+#### 5.2.3 (deprecated) Connecting rdv4.0 with Bluetooth on Linux computer via rfcomm
rfcomm is a deprecated tool which might be unavailable in your Linux distribution.
@@ -248,9 +244,9 @@ connection is successful.
See instructions above (method 1) for initial pairing.
-### (5.3) MacOS
+### 5.3 MacOS
-#### (5.3.1) Connecting rdv4.0 with Bluetooth on MacOS
+#### 5.3.1 Connecting rdv4.0 with Bluetooth on MacOS
With MacOS Mojave 10.14.5 you could experience some continuosly disconnecting and difficult to recconnect the device at the system wakeup, to avoid this problem do a PRAM reset before to add your Proxmark3 RDV4 Blue Shark:
@@ -269,34 +265,41 @@ After reboot you can go ahead to pairing your Proxmark3 RDV4 Blue Shark:
```sh
./proxmark3 /dev/tty.PM3_RDV40-DevB
```
-### (5.4) Android
+### 5.4 Android
-#### (5.4.1) Fast connection using dedicated Bluetooth (HC-06 Master + CP2102) adapter under Android with Termux
+#### 5.4.1 Fast connection using dedicated Bluetooth (HC-06 Master + CP2102) adapter under Android with Termux
1. Make sure you already followed this tutorial https://github.com/RfidResearchGroup/proxmark3/blob/master/doc/termux_notes.md#setup and have Termux with an running Proxmark3 client ready. You need additional the `cp210x` serial usb driver enabled and working, like the `USB_ACM` driver to communicate wireless.
2. Insert the Bluetooth adapter with an fitting USB-C/Micro-USB converter into your Android USB port and a serial port `/dev/ttyUSB0` will be created. To see if it's working, run `tsudo ls /dev/ttyU*` and it should list `/dev/ttyUSB0`.
3. The adapter will search automatically and establish the connection to BlueShark. The adapter will remember the device that was first connected and after that the same device will be connected. After the connection is established, the blue state LED on add-on will turn on solid.
4. If you see this, congratulations, you can run your Proxmark3 client in Termux with `tsudo proxmark3/client/proxmark3 /dev/ttyUSB0`
-#### Notes
-If you bought your Bluetooth adapter somewhere else, make sure to set the baud rate to 115200 `AT+BAUD8` and PIN `AT+PIN1234` correctly
-
## 6. OTHER NOTES
-### (6.1) UART and LED behavior
+### 6.1 Default settings
+
+Settings of the Blue Shark add-on and of the white dongle:
+
+1. Serial: `115200 8N1`
+2. Name: `PM3_RDV4.0`
+3. Pin: `1234`
+
+If you bought your Bluetooth adapter dongle somewhere else, make sure to set the baud rate to 115200 `AT+BAUD8`, the name `AT+NAMEPM3_RDV4.0` and PIN `AT+PIN1234` correctly.
+
+### 6.1 UART and LED behavior
Bluetooth is connected to Proxmark3 RDV4.0 via UART. The USB and UART interfaces of RDV4.0 can coexist without conflict, and no special switching is required.
The following link has helpful notes on UART usage and baud rates:
https://github.com/RfidResearchGroup/proxmark3/blob/master/doc/uart_notes.md
-### (6.2) Disassembly
+### 6.2 Disassembly
There is a heat conductive double-sided tape inside the add-on, which has strong adhesive force. Therefore, if add-on needs to be removed, it needs to be pulled out from the heat sink end with greater efforts. Each disassembly will reduce the viscidity of double-sided tape. When double-sided tape is well protected, it will not affect the second use. Thermal conductivity will be slightly worse and will therefore have a direct impact on the thermal performance of the heat sink.
-### (6.3) Battery charging
+### 6.3 Battery charging
The battery charging circuit is turned on by default. Any time a USB cable is inserted, the battery will be automatically charged. The red LED will remain bright when charging.
The red LED will be extinguished when charging is completed.
-### (6.4) Get better signals
+### 6.4 Get better signals
For the better heat dissipation, we have used a cast metal enclosure for the add-on. As a result Bluetooth wireless signals are sacrificed. For example, if the back of add-on is facing the Bluetooth host, the signal is very bad and the distance will be reduced. The best signal strength can be obtained when the front glass faces the Bluetooth host.
If the Proxmark3 is not responding, it may be due to a poor Bluetooth connection. To improve performance, try repositioning the Proxmark3 so the glass face is directed toward the host.
From 70add3fabe8afe9e2c83e2c3eceec7435c9a910a Mon Sep 17 00:00:00 2001
From: iceman1001
Date: Wed, 6 May 2020 12:14:05 +0200
Subject: [PATCH 076/632] fix: "trace list" too short array for explanation
---
client/src/cmdtrace.c | 12 ++++++------
1 file changed, 6 insertions(+), 6 deletions(-)
diff --git a/client/src/cmdtrace.c b/client/src/cmdtrace.c
index 99e5e03f2..2da9ce675 100644
--- a/client/src/cmdtrace.c
+++ b/client/src/cmdtrace.c
@@ -211,7 +211,7 @@ static uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *tr
uint16_t data_len, parity_len;
uint32_t duration, timestamp, first_timestamp, EndOfTransmissionTimestamp;
uint8_t topaz_reader_command[9];
- char explanation[30] = {0};
+ char explanation[40] = {0};
uint8_t mfData[32] = {0};
size_t mfDataLen = 0;
@@ -296,7 +296,7 @@ static uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *tr
//2 Not crc-command
//--- Draw the data column
- char line[18][110] = {{0}};
+ char line[18][120] = {{0}};
for (int j = 0; j < data_len && j / 18 < 18; j++) {
@@ -315,20 +315,20 @@ static uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *tr
&& (isResponse || protocol == ISO_14443A)
&& (oddparity8(frame[j]) != ((parityBits >> (7 - (j & 0x0007))) & 0x01))) {
- snprintf(line[j / 18] + ((j % 18) * 4), 110, "%02x! ", frame[j]);
+ snprintf(line[j / 18] + ((j % 18) * 4), 120, "%02x! ", frame[j]);
} else if (protocol == ICLASS && isResponse == false) {
uint8_t parity = 0;
for (int i = 0; i < 6; i++) {
parity ^= ((frame[0] >> i) & 1);
}
if (parity == ((frame[0] >> 7) & 1)) {
- snprintf(line[j / 18] + ((j % 18) * 4), 110, "%02x ", frame[j]);
+ snprintf(line[j / 18] + ((j % 18) * 4), 120, "%02x ", frame[j]);
} else {
- snprintf(line[j / 18] + ((j % 18) * 4), 110, "%02x! ", frame[j]);
+ snprintf(line[j / 18] + ((j % 18) * 4), 120, "%02x! ", frame[j]);
}
} else {
- snprintf(line[j / 18] + ((j % 18) * 4), 110, "%02x ", frame[j]);
+ snprintf(line[j / 18] + ((j % 18) * 4), 120, "%02x ", frame[j]);
}
}
From 021ee95e07599c0fe80d7a03cc1bb4053d7c4afe Mon Sep 17 00:00:00 2001
From: dxl <64101226@qq.com>
Date: Wed, 6 May 2020 12:05:14 +0200
Subject: [PATCH 077/632] don't mix ifdef and defined
---
client/deps/tinycbor/open_memstream.c | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/client/deps/tinycbor/open_memstream.c b/client/deps/tinycbor/open_memstream.c
index 098bf90fe..7a134286f 100644
--- a/client/deps/tinycbor/open_memstream.c
+++ b/client/deps/tinycbor/open_memstream.c
@@ -36,7 +36,7 @@
# include
#endif
-#ifdef __APPLE__ || defined(__ANDROID__) || defined(ANDROID)
+#if defined(__APPLE__) || defined(__ANDROID__) || defined(ANDROID)
typedef int RetType;
typedef int LenType;
#elif __GLIBC__
@@ -102,7 +102,7 @@ FILE *open_memstream(char **bufptr, size_t *lenptr) {
*bufptr = NULL;
*lenptr = 0;
-#ifdef __APPLE__ || defined(__ANDROID__) || defined(ANDROID)
+#if defined(__APPLE__) || defined(__ANDROID__) || defined(ANDROID)
return funopen(b, NULL, write_to_buffer, NULL, close_buffer);
#elif __GLIBC__
static const cookie_io_functions_t vtable = {
From fcf0265704d3c5004d14f5e1fadff5dfc36460cc Mon Sep 17 00:00:00 2001
From: dxl <64101226@qq.com>
Date: Wed, 6 May 2020 12:44:34 +0200
Subject: [PATCH 078/632] missing include
---
client/src/cmdhflegic.c | 1 +
1 file changed, 1 insertion(+)
diff --git a/client/src/cmdhflegic.c b/client/src/cmdhflegic.c
index b7defe904..fabe926fa 100644
--- a/client/src/cmdhflegic.c
+++ b/client/src/cmdhflegic.c
@@ -10,6 +10,7 @@
#include "cmdhflegic.h"
#include // for Mingw readline
+#include // tolower
#include
#include "cmdparser.h" // command_t
From d118ba9e0685f4d7dff55ab462b195ac0ff1af8a Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Wed, 6 May 2020 13:01:07 +0200
Subject: [PATCH 079/632] comment out unused iceIIR_Butterworth
---
client/src/ui.c | 3 +++
1 file changed, 3 insertions(+)
diff --git a/client/src/ui.c b/client/src/ui.c
index 5d0e28aec..0b0ffdb56 100644
--- a/client/src/ui.c
+++ b/client/src/ui.c
@@ -485,6 +485,8 @@ void memcpy_filter_emoji(void *dest, const void *src, size_t n, emojiMode_t mode
}
}
+/*
+// If reactivated, beware it doesn't compile on Android (DXL)
void iceIIR_Butterworth(int *data, const size_t len) {
int *output = (int *) calloc(sizeof(int) * len, sizeof(uint8_t));
@@ -533,6 +535,7 @@ void iceIIR_Butterworth(int *data, const size_t len) {
free(output);
}
+*/
void iceSimple_Filter(int *data, const size_t len, uint8_t k) {
// ref: http://www.edn.com/design/systems-design/4320010/A-simple-software-lowpass-filter-suits-embedded-system-applications
From 78ee43c9c4f91e22c40e06b58e3e6d6c8909c01d Mon Sep 17 00:00:00 2001
From: dxl <64101226@qq.com>
Date: Wed, 6 May 2020 12:03:37 +0200
Subject: [PATCH 080/632] Android platform adaptation(dxl)
---
client/android/CMakeLists.txt | 403 ++++++++++++++++++++++++++++++++++
client/android/jni_tools.c | 97 ++++++++
client/android/jni_tools.h | 40 ++++
client/android/pm3_main.c | 175 +++++++++++++++
4 files changed, 715 insertions(+)
create mode 100644 client/android/CMakeLists.txt
create mode 100644 client/android/jni_tools.c
create mode 100644 client/android/jni_tools.h
create mode 100644 client/android/pm3_main.c
diff --git a/client/android/CMakeLists.txt b/client/android/CMakeLists.txt
new file mode 100644
index 000000000..a4e04b8ca
--- /dev/null
+++ b/client/android/CMakeLists.txt
@@ -0,0 +1,403 @@
+#需要的最cmake版本
+cmake_minimum_required(VERSION 3.4.1)
+
+#添加预编译宏定义参数,此次的作用是开启配置文件的引入!
+add_definitions(-DANDROID -D"getlocaledecpoint()='.'" -DZ_SOLO)
+
+set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99 -O3 -fvisibility=hidden -w")
+
+#缩短路径定义
+set(PM3_ROOT ../../)
+
+#添加动态库定义
+add_library(pm3rrg_rdv4 SHARED
+ ${PM3_ROOT}/common/util_posix.c
+ ${PM3_ROOT}/common/crapto1/crapto1.c
+ ${PM3_ROOT}/common/crapto1/crypto1.c
+ ${PM3_ROOT}/common/crc.c
+ ${PM3_ROOT}/common/crc16.c
+ ${PM3_ROOT}/common/crc32.c
+ ${PM3_ROOT}/common/crc64.c
+ ${PM3_ROOT}/common/cardhelper.c
+ ${PM3_ROOT}/common/parity.c
+ ${PM3_ROOT}/common/commonutil.c
+ ${PM3_ROOT}/common/generator.c
+ ${PM3_ROOT}/common/lfdemod.c
+ ${PM3_ROOT}/common/iso15693tools.c
+ ${PM3_ROOT}/common/bucketsort.c
+ ${PM3_ROOT}/common/legic_prng.c
+ ${PM3_ROOT}/common/mbedtls/aes.c
+ ${PM3_ROOT}/common/mbedtls/base64.c
+ ${PM3_ROOT}/common/mbedtls/rsa.c
+ ${PM3_ROOT}/common/mbedtls/rsa_internal.c
+ ${PM3_ROOT}/common/mbedtls/arc4.c
+ ${PM3_ROOT}/common/mbedtls/bignum.c
+ ${PM3_ROOT}/common/mbedtls/asn1parse.c
+ ${PM3_ROOT}/common/mbedtls/asn1write.c
+ ${PM3_ROOT}/common/mbedtls/blowfish.c
+ ${PM3_ROOT}/common/mbedtls/camellia.c
+ ${PM3_ROOT}/common/mbedtls/certs.c
+ ${PM3_ROOT}/common/mbedtls/des.c
+ ${PM3_ROOT}/common/mbedtls/ecdsa.c
+ ${PM3_ROOT}/common/mbedtls/ecp.c
+ ${PM3_ROOT}/common/mbedtls/ecp_curves.c
+ ${PM3_ROOT}/common/mbedtls/entropy.c
+ ${PM3_ROOT}/common/mbedtls/entropy_poll.c
+ ${PM3_ROOT}/common/mbedtls/error.c
+ ${PM3_ROOT}/common/mbedtls/md.c
+ ${PM3_ROOT}/common/mbedtls/md5.c
+ ${PM3_ROOT}/common/mbedtls/md_wrap.c
+ ${PM3_ROOT}/common/mbedtls/sha1.c
+ ${PM3_ROOT}/common/mbedtls/sha256.c
+ ${PM3_ROOT}/common/mbedtls/sha512.c
+ ${PM3_ROOT}/common/mbedtls/timing.c
+ ${PM3_ROOT}/common/mbedtls/cmac.c
+ ${PM3_ROOT}/common/mbedtls/oid.c
+ ${PM3_ROOT}/common/mbedtls/pem.c
+ ${PM3_ROOT}/common/mbedtls/pk.c
+ ${PM3_ROOT}/common/mbedtls/pk_wrap.c
+ ${PM3_ROOT}/common/mbedtls/pkcs5.c
+ ${PM3_ROOT}/common/mbedtls/pkcs12.c
+ ${PM3_ROOT}/common/mbedtls/pkparse.c
+ ${PM3_ROOT}/common/mbedtls/pkwrite.c
+ ${PM3_ROOT}/common/mbedtls/x509.c
+ ${PM3_ROOT}/common/mbedtls/x509_crl.c
+ ${PM3_ROOT}/common/mbedtls/x509_crt.c
+ ${PM3_ROOT}/common/mbedtls/ctr_drbg.c
+ ${PM3_ROOT}/common/mbedtls/cipher_wrap.c
+ ${PM3_ROOT}/common/mbedtls/cipher.c
+ ${PM3_ROOT}/common/mbedtls/platform_util.c
+ ${PM3_ROOT}/common//zlib/inflate.c
+ ${PM3_ROOT}/common/zlib/inffast.c
+ ${PM3_ROOT}/common/zlib/zutil.c
+ ${PM3_ROOT}/common/zlib/inftrees.c
+ ${PM3_ROOT}/common//zlib/adler32.c
+ # client inside
+ ${PM3_ROOT}/client/src/fileutils.c
+ ${PM3_ROOT}/client/src/uart/uart_posix.c
+ ${PM3_ROOT}/client/src/loclass/cipherutils.c
+ ${PM3_ROOT}/client/src/loclass/cipher.c
+ ${PM3_ROOT}/client/src/loclass/ikeys.c
+ ${PM3_ROOT}/client/src/loclass/elite_crack.c
+ ${PM3_ROOT}/client/src/emv/emvcore.c
+ ${PM3_ROOT}/client/src/emv/cmdemv.c
+ ${PM3_ROOT}/client/src/emv/tlv.c
+ ${PM3_ROOT}/client/src/emv/dol.c
+ ${PM3_ROOT}/client/src/emv/emv_tags.c
+ ${PM3_ROOT}/client/src/emv/emv_roca.c
+ ${PM3_ROOT}/client/src/emv/dump.c
+ ${PM3_ROOT}/client/src/emv/crypto_polarssl.c
+ ${PM3_ROOT}/client/src/emv/crypto.c
+ ${PM3_ROOT}/client/src/emv/emv_pk.c
+ ${PM3_ROOT}/client/src/emv/emv_pki.c
+ ${PM3_ROOT}/client/src/emv/emvjson.c
+ ${PM3_ROOT}/client/src/emv/apduinfo.c
+ ${PM3_ROOT}/client/src/emv/test/cryptotest.c
+ ${PM3_ROOT}/client/src/emv/test/sda_test.c
+ ${PM3_ROOT}/client/src/emv/test/dda_test.c
+ ${PM3_ROOT}/client/src/emv/test/cda_test.c
+ ${PM3_ROOT}/client/src/emv/test/crypto_test.c
+ ${PM3_ROOT}/client/src/emv/test/cryptotest.c
+ ${PM3_ROOT}/client/src/emv/test/sda_test.c
+ ${PM3_ROOT}/client/src/emv/test/dda_test.c
+ ${PM3_ROOT}/client/src/emv/test/cda_test.c
+ ${PM3_ROOT}/client/src/emv/test/crypto_test.c
+ ${PM3_ROOT}/client/src/crypto/libpcrypto.c
+ ${PM3_ROOT}/client/src/crypto/asn1utils.c
+ ${PM3_ROOT}/client/src/crypto/asn1dump.c
+ ${PM3_ROOT}/client/src/mifare/mad.c
+ ${PM3_ROOT}/client/src/mifare/mfkey.c
+ ${PM3_ROOT}/client/src/mifare/mifare4.c
+ ${PM3_ROOT}/client/src/mifare/mifarehost.c
+ ${PM3_ROOT}/client/src/mifare/ndef.c
+ ${PM3_ROOT}/client/src/mifare/desfire_crypto.c
+ ${PM3_ROOT}/client/src/mifare/mifaredefault.c
+ ${PM3_ROOT}/client/src/fido/cose.c
+ ${PM3_ROOT}/client/src/fido/fidocore.c
+ ${PM3_ROOT}/client/src/fido/cbortools.c
+ ${PM3_ROOT}/client/src/fido/additional_ca.c
+ ${PM3_ROOT}/client/src/preferences.c
+ ${PM3_ROOT}/client/src/graph.c
+ ${PM3_ROOT}/client/src/ui.c
+ ${PM3_ROOT}/client/src/tea.c
+ ${PM3_ROOT}/client/src/util.c
+ ${PM3_ROOT}/client/src/comms.c
+ ${PM3_ROOT}/client/src/cmdcrc.c
+ ${PM3_ROOT}/client/src/cmdanalyse.c
+ ${PM3_ROOT}/client/src/cmddata.c
+ ${PM3_ROOT}/client/src/cmdtrace.c
+ ${PM3_ROOT}/client/src/cmdhf.c
+ ${PM3_ROOT}/client/src/cmdhflto.c
+ ${PM3_ROOT}/client/src/aidsearch.c
+ ${PM3_ROOT}/client/src/cmdhf14a.c
+ ${PM3_ROOT}/client/src/cmdhf14b.c
+ ${PM3_ROOT}/client/src/cmdwiegand.c
+ ${PM3_ROOT}/client/src/wiegand_formatutils.c
+ ${PM3_ROOT}/client/src/wiegand_formats.c
+ ${PM3_ROOT}/client/src/cmdlfmotorola.c
+ ${PM3_ROOT}/client/src/cmdlfgallagher.c
+ ${PM3_ROOT}/client/src/cmdhf15.c
+ ${PM3_ROOT}/client/src/cmdhfepa.c
+ ${PM3_ROOT}/client/src/cmdhflegic.c
+ ${PM3_ROOT}/client/src/cmdhfthinfilm.c
+ ${PM3_ROOT}/client/src/cmdflashmemspiffs.c
+ ${PM3_ROOT}/client/src/cmdhffelica.c
+ ${PM3_ROOT}/client/src/cmdhficlass.c
+ ${PM3_ROOT}/client/src/cmdhflist.c
+ ${PM3_ROOT}/client/src/cmdhfmf.c
+ ${PM3_ROOT}/client/src/cmdhfmfdes.c
+ ${PM3_ROOT}/client/src/cmdhfmfu.c
+ ${PM3_ROOT}/client/src/cmdhfmfp.c
+ ${PM3_ROOT}/client/src/cmdhffido.c
+ ${PM3_ROOT}/client/src/cmdhftopaz.c
+ ${PM3_ROOT}/client/src/cmdhw.c
+ ${PM3_ROOT}/client/src/cmdlf.c
+ ${PM3_ROOT}/client/src/cmdlfkeri.c
+ ${PM3_ROOT}/client/src/cmdlffdx.c
+ ${PM3_ROOT}/client/src/cmdlfio.c
+ ${PM3_ROOT}/client/src/cmdlfem4x.c
+ ${PM3_ROOT}/client/src/cmdlfhid.c
+ ${PM3_ROOT}/client/src/cmdlfnedap.c
+ ${PM3_ROOT}/client/src/cmdlfguard.c
+ ${PM3_ROOT}/client/src/cmdlfhitag.c
+ ${PM3_ROOT}/client/src/cmdlfjablotron.c
+ ${PM3_ROOT}/client/src/cmdsmartcard.c
+ ${PM3_ROOT}/client/src/cmdlfti.c
+ ${PM3_ROOT}/client/src/cmdlfpac.c
+ ${PM3_ROOT}/client/src/cmdlfnoralsy.c
+ ${PM3_ROOT}/client/src/cmdlfnexwatch.c
+ ${PM3_ROOT}/client/src/cmdlfpresco.c
+ ${PM3_ROOT}/client/src/cmdlfindala.c
+ ${PM3_ROOT}/client/src/cmdlfviking.c
+ ${PM3_ROOT}/client/src/cmdlfsecurakey.c
+ ${PM3_ROOT}/client/src/cmdlfpyramid.c
+ ${PM3_ROOT}/client/src/cmdlfparadox.c
+ ${PM3_ROOT}/client/src/cmdlfcotag.c
+ ${PM3_ROOT}/client/src/cmdlfawid.c
+ ${PM3_ROOT}/client/src/cmdparser.c
+ ${PM3_ROOT}/client/src/cmdscript.c
+ ${PM3_ROOT}/client/src/cmdlfvisa2000.c
+ ${PM3_ROOT}/client/src/whereami.c
+ ${PM3_ROOT}/client/src/cmdmain.c
+ ${PM3_ROOT}/client/src/cmdflashmem.c
+ ${PM3_ROOT}/client/src/scripting.c
+ ${PM3_ROOT}/client/src/pm3_binlib.c
+ ${PM3_ROOT}/client/src/pm3_bitlib.c
+ ${PM3_ROOT}/client/src/cmdlft55xx.c
+ ${PM3_ROOT}/client/src/cmdlfpcf7931.c
+ ${PM3_ROOT}/client/src/cmdhfmfhard.c
+ ${PM3_ROOT}/client/src/cmdusart.c
+ # deps ouside
+ ${PM3_ROOT}/client/deps/jansson/utf.c
+ ${PM3_ROOT}/client/deps/jansson/dump.c
+ ${PM3_ROOT}/client/deps/jansson/path.c
+ ${PM3_ROOT}/client/deps/jansson/load.c
+ ${PM3_ROOT}/client/deps/jansson/error.c
+ ${PM3_ROOT}/client/deps/jansson/value.c
+ ${PM3_ROOT}/client/deps/jansson/memory.c
+ ${PM3_ROOT}/client/deps/jansson/pack_unpack.c
+ ${PM3_ROOT}/client/deps/jansson/hashtable_seed.c
+ ${PM3_ROOT}/client/deps/jansson/strbuffer.c
+ ${PM3_ROOT}/client/deps/jansson/strconv.c
+ ${PM3_ROOT}/client/deps/jansson/hashtable.c
+ ${PM3_ROOT}/client/deps/jansson/hashtable.c
+ # cliparser
+ ${PM3_ROOT}/client/deps/cliparser/cliparser.c
+ ${PM3_ROOT}/client/deps/cliparser/argtable3.c
+ # tinycbor
+ ${PM3_ROOT}/client/deps/tinycbor/cborencoder.c
+ ${PM3_ROOT}/client/deps/tinycbor/cborencoder_close_container_checked.c
+ ${PM3_ROOT}/client/deps/tinycbor/cborerrorstrings.c
+ ${PM3_ROOT}/client/deps/tinycbor/cborparser.c
+ ${PM3_ROOT}/client/deps/tinycbor/cborparser_dup_string.c
+ ${PM3_ROOT}/client/deps/tinycbor/cborpretty.c
+ ${PM3_ROOT}/client/deps/tinycbor/cborpretty_stdio.c
+ ${PM3_ROOT}/client/deps/tinycbor/cbortojson.c
+ ${PM3_ROOT}/client/deps/tinycbor/cborvalidation.c
+ ${PM3_ROOT}/client/deps/tinycbor/open_memstream.c
+ # reveng
+ ${PM3_ROOT}/client/deps/reveng/cli.c
+ ${PM3_ROOT}/client/deps/reveng/bmpbit.c
+ ${PM3_ROOT}/client/deps/reveng/preset.c
+ ${PM3_ROOT}/client/deps/reveng/model.c
+ ${PM3_ROOT}/client/deps/reveng/poly.c
+ ${PM3_ROOT}/client/deps/reveng/reveng.c
+ # liblua
+ ${PM3_ROOT}/client/deps/liblua/lapi.c
+ ${PM3_ROOT}/client/deps/liblua/ldo.c
+ ${PM3_ROOT}/client/deps/liblua/lgc.c
+ ${PM3_ROOT}/client/deps/liblua/ltm.c
+ ${PM3_ROOT}/client/deps/liblua/lvm.c
+ ${PM3_ROOT}/client/deps/liblua/lzio.c
+ ${PM3_ROOT}/client/deps/liblua/lcode.c
+ ${PM3_ROOT}/client/deps/liblua/llex.c
+ ${PM3_ROOT}/client/deps/liblua/liolib.c
+ ${PM3_ROOT}/client/deps/liblua/loslib.c
+ ${PM3_ROOT}/client/deps/liblua/lopcodes.c
+ ${PM3_ROOT}/client/deps/liblua/lmem.c
+ ${PM3_ROOT}/client/deps/liblua/lmathlib.c
+ ${PM3_ROOT}/client/deps/liblua/ldump.c
+ ${PM3_ROOT}/client/deps/liblua/ldblib.c
+ ${PM3_ROOT}/client/deps/liblua/lundump.c
+ ${PM3_ROOT}/client/deps/liblua/lcorolib.c
+ ${PM3_ROOT}/client/deps/liblua/lauxlib.c
+ ${PM3_ROOT}/client/deps/liblua/ltablib.c
+ ${PM3_ROOT}/client/deps/liblua/linit.c
+ ${PM3_ROOT}/client/deps/liblua/lstring.c
+ ${PM3_ROOT}/client/deps/liblua/lctype.c
+ ${PM3_ROOT}/client/deps/liblua/ltable.c
+ ${PM3_ROOT}/client/deps/liblua/ldebug.c
+ ${PM3_ROOT}/client/deps/liblua/lstate.c
+ ${PM3_ROOT}/client/deps/liblua/lstrlib.c
+ ${PM3_ROOT}/client/deps/liblua/lfunc.c
+ ${PM3_ROOT}/client/deps/liblua/lparser.c
+ ${PM3_ROOT}/client/deps/liblua/lobject.c
+ ${PM3_ROOT}/client/deps/liblua/loadlib.c
+ ${PM3_ROOT}/client/deps/liblua/lbaselib.c
+ ${PM3_ROOT}/client/deps/liblua/lbitlib.c
+ ${PM3_ROOT}/client/deps/hardnested/hardnested_bruteforce.c
+ # android source
+ jni_tools.c
+ pm3_main.c
+ )
+
+#添加头文件配置
+target_include_directories(pm3rrg_rdv4 PRIVATE
+ ${CMAKE_CURRENT_SOURCE_DIR}
+ ${PM3_ROOT}/
+ ${PM3_ROOT}/include/
+ ${PM3_ROOT}/common
+ ${PM3_ROOT}/common/zlib
+ ${PM3_ROOT}/common_fpga
+ ${PM3_ROOT}/common/mbedtls
+ ${PM3_ROOT}/client/src
+ ${PM3_ROOT}/client/src/fido
+ ${PM3_ROOT}/client/src/uart
+ ${PM3_ROOT}/client/deps/liblua
+ ${PM3_ROOT}/client/deps/reveng
+ ${PM3_ROOT}/client/deps/jansson
+ ${PM3_ROOT}/client/deps/tinycbor
+ ${PM3_ROOT}/client/deps/cliparser
+ ${PM3_ROOT}/client/deps/hardnested)
+
+## CPU-specific code
+## These are mostly for x86-based architectures, which is not useful for many Android devices.
+add_library(pm3rrg_rdv4_hardnested_nosimd OBJECT
+ ${PM3_ROOT}/client/deps/hardnested/hardnested_bf_core.c
+ ${PM3_ROOT}/client/deps/hardnested/hardnested_bitarray_core.c)
+
+target_include_directories(pm3rrg_rdv4_hardnested_nosimd PRIVATE
+ ${PM3_ROOT}/common
+ ${PM3_ROOT}/client
+ ${PM3_ROOT}/include/
+ ${PM3_ROOT}/client/deps/hardnested)
+
+set(X86_CPUS x86 x86_64 i686)
+
+message(STATUS "CMAKE_SYSTEM_PROCESSOR := ${CMAKE_SYSTEM_PROCESSOR}")
+
+if ("${CMAKE_SYSTEM_PROCESSOR}" IN_LIST X86_CPUS)
+ message(STATUS "Building optimised x86/x86_64 binaries")
+ target_compile_options(pm3rrg_rdv4_hardnested_nosimd BEFORE PRIVATE
+ -mno-mmx -mno-sse2 -mno-avx -mno-avx2 -mno-avx512f)
+
+ set_property(TARGET pm3rrg_rdv4_hardnested_nosimd PROPERTY POSITION_INDEPENDENT_CODE ON)
+
+ ## x86 / MMX
+ add_library(pm3rrg_rdv4_hardnested_mmx OBJECT
+ ${PM3_ROOT}/client/deps/hardnested/hardnested_bf_core.c
+ ${PM3_ROOT}/client/deps/hardnested/hardnested_bitarray_core.c)
+
+ target_compile_options(pm3rrg_rdv4_hardnested_mmx BEFORE PRIVATE
+ -mmmx -mno-sse2 -mno-avx -mno-avx2 -mno-avx512f)
+
+ target_include_directories(pm3rrg_rdv4_hardnested_mmx PRIVATE
+ ${PM3_ROOT}/common
+ ${PM3_ROOT}/client
+ ${PM3_ROOT}/include/
+ ${PM3_ROOT}/client/deps/hardnested)
+
+ set_property(TARGET pm3rrg_rdv4_hardnested_mmx PROPERTY POSITION_INDEPENDENT_CODE ON)
+
+ ## x86 / SSE2
+ add_library(pm3rrg_rdv4_hardnested_sse2 OBJECT
+ ${PM3_ROOT}/client/deps/hardnested/hardnested_bf_core.c
+ ${PM3_ROOT}/client/deps/hardnested/hardnested_bitarray_core.c)
+
+ target_compile_options(pm3rrg_rdv4_hardnested_sse2 BEFORE PRIVATE
+ -mmmx -msse2 -mno-avx -mno-avx2 -mno-avx512f)
+
+ target_include_directories(pm3rrg_rdv4_hardnested_sse2 PRIVATE
+ ${PM3_ROOT}/common
+ ${PM3_ROOT}/client
+ ${PM3_ROOT}/include/
+ ${PM3_ROOT}/client/deps/hardnested)
+
+ set_property(TARGET pm3rrg_rdv4_hardnested_sse2 PROPERTY POSITION_INDEPENDENT_CODE ON)
+
+ ## x86 / AVX
+ add_library(pm3rrg_rdv4_hardnested_avx OBJECT
+ ${PM3_ROOT}/client/deps/hardnested/hardnested_bf_core.c
+ ${PM3_ROOT}/client/deps/hardnested/hardnested_bitarray_core.c)
+
+ target_compile_options(pm3rrg_rdv4_hardnested_avx BEFORE PRIVATE
+ -mmmx -msse2 -mavx -mno-avx2 -mno-avx512f)
+
+ target_include_directories(pm3rrg_rdv4_hardnested_avx PRIVATE
+ ${PM3_ROOT}/common
+ ${PM3_ROOT}/client
+ ${PM3_ROOT}/include/
+ ${PM3_ROOT}/client/deps/hardnested)
+
+ set_property(TARGET pm3rrg_rdv4_hardnested_avx PROPERTY POSITION_INDEPENDENT_CODE ON)
+
+ ## x86 / AVX2
+ add_library(pm3rrg_rdv4_hardnested_avx2 OBJECT
+ ${PM3_ROOT}/client/deps/hardnested/hardnested_bf_core.c
+ ${PM3_ROOT}/client/deps/hardnested/hardnested_bitarray_core.c)
+
+ target_compile_options(pm3rrg_rdv4_hardnested_avx2 BEFORE PRIVATE
+ -mmmx -msse2 -mavx -mavx2 -mno-avx512f)
+
+ target_include_directories(pm3rrg_rdv4_hardnested_avx2 PRIVATE
+ ${PM3_ROOT}/common
+ ${PM3_ROOT}/client
+ ${PM3_ROOT}/include/
+ ${PM3_ROOT}/client/deps/hardnested)
+
+ set_property(TARGET pm3rrg_rdv4_hardnested_avx2 PROPERTY POSITION_INDEPENDENT_CODE ON)
+
+ ## x86 / AVX512
+ add_library(pm3rrg_rdv4_hardnested_avx512 OBJECT
+ ${PM3_ROOT}/client/deps/hardnested/hardnested_bf_core.c
+ ${PM3_ROOT}/client/deps/hardnested/hardnested_bitarray_core.c)
+
+ target_compile_options(pm3rrg_rdv4_hardnested_avx512 BEFORE PRIVATE
+ -mmmx -msse2 -mavx -mavx2 -mavx512f)
+
+ target_include_directories(pm3rrg_rdv4_hardnested_avx512 PRIVATE
+ ${PM3_ROOT}/common
+ ${PM3_ROOT}/client
+ ${PM3_ROOT}/include/
+ ${PM3_ROOT}/client/deps/hardnested)
+
+ set_property(TARGET pm3rrg_rdv4_hardnested_avx512 PROPERTY POSITION_INDEPENDENT_CODE ON)
+
+ set(SIMD_TARGETS
+ $
+ $
+ $
+ $
+ $)
+else ()
+ message(STATUS "Not building optimised targets")
+ set(SIMD_TARGETS)
+endif ()
+
+#定义为静态库,被最终的pm3库依赖!
+add_library(pm3rrg_rdv4_hardnested STATIC
+ $
+ ${SIMD_TARGETS})
+
+#添加动态库链接!
+target_link_libraries(pm3rrg_rdv4 pm3rrg_rdv4_hardnested android log z)
\ No newline at end of file
diff --git a/client/android/jni_tools.c b/client/android/jni_tools.c
new file mode 100644
index 000000000..74e05051c
--- /dev/null
+++ b/client/android/jni_tools.c
@@ -0,0 +1,97 @@
+//
+// Created by DXL on 2017/9/1.
+//
+
+//including header
+#include
+#include
+#include "stdbool.h"
+
+//当前线程是否添加的标志位
+static bool g_IsAttach;
+
+//TODO 环境变量获取函数
+JNIEnv *getJniEnv() {
+ JNIEnv *currentThreadEnv;
+ g_IsAttach = false;
+ if ((*g_JavaVM)->GetEnv(g_JavaVM, (void **) ¤tThreadEnv, JNI_VERSION_1_4) != JNI_OK) {
+ LOGE("Get Env Fail!");
+ if ((*g_JavaVM)->AttachCurrentThread(g_JavaVM, ¤tThreadEnv, NULL) != JNI_OK) {
+ LOGE("Attach the current thread Fail!");
+ g_IsAttach = false;
+ return NULL;
+ } else {
+ g_IsAttach = true;
+ LOGE("Attach the current thread Success!");
+ return currentThreadEnv;
+ }
+ } else {
+ g_IsAttach = false;
+ //LOGE("Get Env Success!");
+ return currentThreadEnv;
+ }
+}
+
+//解绑线程env
+void deatchThread() {
+ if (g_IsAttach) {
+ LOGD("线程解绑成功!");
+ (*g_JavaVM)->DetachCurrentThread(g_JavaVM);
+ }
+}
+
+//TODO 命令行解析
+CMD *parse_command_line(const char *commandStr) {
+ //一个指针,指向传进来的命令字符串(const修饰的,我们需要复刻一份!)
+ CMD *cmd = (CMD *) malloc(sizeof(CMD));
+ if (!cmd) {
+ LOGD("申请空间失败!");
+ return NULL;
+ }
+ //拷贝字符串到堆空间!
+ char *pTmp = strdup(commandStr);
+ LOGD("拷贝参数字符串到临时堆!");
+ //返回的结果!先初始化为20个空间
+ int size = 20;
+ cmd->cmd = (char **) malloc(size * sizeof(char **));
+ if (cmd->cmd) {
+ LOGD("申请参数空间成功!");
+ } else {
+ LOGD("申请空间失败!");
+ }
+ //进行截取
+ char *pStr = strtok(pTmp, " ");
+ LOGD("第0次截取完成: %s", pStr);
+ //给结果数组进行下标为0的第一次初始化
+ cmd->cmd[0] = pStr;
+ //局部变量用于储存解析到的命令个数,下标移动为一
+ int count = 1;
+ //需要截取命令参数,以空格为限定符
+ for (; pStr != NULL; ++count) {
+ //如果容量不够,则扩容!
+ if (count == (size - 1)) {
+ size += 20;
+ cmd->cmd = (char **) realloc(cmd->cmd, size * sizeof(char **));
+ LOGD("超过初始容量,自动扩容!");
+ }
+ pStr = strtok(NULL, " ");
+ if (pStr) {
+ cmd->cmd[count] = pStr;
+ LOGD("第%d次截取完成: %s", count, pStr);
+ }
+ }
+ cmd->len = (count - 1);
+ LOGD("解析函数执行完成!");
+ return cmd;
+}
+
+//内存释放
+void free_command_line(CMD *cmd) {
+ //二级指针需要逐层释放!
+ LOGD("释放命令行字符串二级引用!");
+ free(cmd->cmd[0]);
+ LOGD("释放命令行一级引用!");
+ free(cmd->cmd);
+ LOGD("释放结构体内存");
+ free(cmd);
+}
\ No newline at end of file
diff --git a/client/android/jni_tools.h b/client/android/jni_tools.h
new file mode 100644
index 000000000..121cf043f
--- /dev/null
+++ b/client/android/jni_tools.h
@@ -0,0 +1,40 @@
+//
+// Created by dell on 2017/9/1.
+//
+
+#ifndef DXL_TOOLS_H
+#define DXL_TOOLS_H
+
+#include
+#include
+#include
+
+//JNI LOG
+#define TAG "DXL BlUESPP_PN532"
+#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE,TAG,__VA_ARGS__)
+#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,TAG,__VA_ARGS__)
+#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,TAG,__VA_ARGS__)
+#define LOGW(...) __android_log_print(ANDROID_LOG_WARN,TAG,__VA_ARGS__)
+#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,TAG,__VA_ARGS__)
+
+//全局的环境变量定义
+JavaVM *g_JavaVM;
+
+//线程环境指针获取函数
+JNIEnv *getJniEnv();
+
+//子线程释放函数,必须是native层创建的线程才可以调用
+void deatchThread();
+
+typedef struct {
+ char **cmd;
+ int len;
+} CMD;
+
+//命令行解析函数
+CMD *parse_command_line(const char *commandStr);
+
+//解析结果释放函数!
+void free_command_line(CMD *);
+
+#endif //DXL_TOOLS_H
\ No newline at end of file
diff --git a/client/android/pm3_main.c b/client/android/pm3_main.c
new file mode 100644
index 000000000..d9c2386c8
--- /dev/null
+++ b/client/android/pm3_main.c
@@ -0,0 +1,175 @@
+//-----------------------------------------------------------------------------
+// Copyright (C) 2009 Michael Gernoth
+// Copyright (C) 2010 iZsh
+//
+// This code is licensed to you under the terms of the GNU GPL, version 2 or,
+// at your option, any later version. See the LICENSE.txt file for the text of
+// the license.
+//-----------------------------------------------------------------------------
+// Main binary
+//-----------------------------------------------------------------------------
+
+#include "proxmark3.h"
+
+#include
+#include // for Mingw readline
+#include
+#include
+#include
+#include "usart_defs.h"
+#include "util_posix.h"
+#include "proxgui.h"
+#include "cmdmain.h"
+#include "ui.h"
+#include "cmdhw.h"
+#include "whereami.h"
+#include "comms.h"
+#include "fileutils.h"
+#include "jni_tools.h"
+
+#define LOCAL_SOCKET_SERVER_NAME "DXL.COM.ASL"
+
+void ShowGraphWindow() {
+
+}
+
+void HideGraphWindow(void) {
+
+}
+
+void RepaintGraphWindow() {
+
+}
+
+int push_cmdscriptfile(char *path, bool stayafter) {
+ return PM3_SUCCESS;
+}
+
+static char *my_executable_path = NULL;
+static char *my_executable_directory = NULL;
+
+const char *get_my_executable_path(void) {
+ return my_executable_path;
+}
+
+const char *get_my_executable_directory(void) {
+ return my_executable_directory;
+}
+
+static void set_my_executable_path(void) {
+
+}
+
+static const char *my_user_directory = NULL;
+
+const char *get_my_user_directory(void) {
+ return my_user_directory;
+}
+
+static void set_my_user_directory(void) {
+}
+
+static bool open() {
+ if (conn.run) {
+ return true;
+ }
+ // Open with LocalSocket(Not a tcp connection!)
+ bool ret = OpenProxmark("socket:"LOCAL_SOCKET_SERVER_NAME, false, 1000, false, 115200);
+ return ret;
+}
+
+/*
+ * 发送一条命令等待执行!
+ * */
+jint sendCMD(JNIEnv *env, jobject instance, jstring cmd_) {
+ //may be pm3 not running.
+ if (!conn.run) {
+ if (open() && TestProxmark() == PM3_SUCCESS) {
+ LOGD("Open Successfully!");
+ PrintAndLogEx(NORMAL, "Open Successfully!");
+ } else {
+ LOGD("Open failed!");
+ PrintAndLogEx(NORMAL, "Open failed!");
+ CloseProxmark();
+ }
+ }
+ //无论如何,新的命令的输入了,就要换个行!
+ PrintAndLogEx(NORMAL, "\n");
+ char *cmd = (char *) ((*env)->GetStringUTFChars(env, cmd_, 0));
+ // Many parts of the PM3 client will assume that they can read any write from pwd. So we set
+ // pwd to whatever the PM3 "executable directory" is, to get consistent behaviour.
+ /*int ret = chdir(get_my_executable_directory());
+ if (ret == -1) {
+ LOGW("Couldn't chdir(get_my_executable_directory()), errno=%s", strerror(errno));
+ }
+ char pwd[1024];
+ memset((void *) &pwd, 0, sizeof(pwd));
+ getcwd((char *) &pwd, sizeof(pwd));
+ LOGI("pwd = %s", pwd);*/
+ int ret = CommandReceived(cmd);
+ if (ret == 99) {
+ // exit / quit
+ // TODO: implement this
+ PrintAndLogEx(NORMAL, "Asked to exit, can't really do that yet...");
+ }
+ (*env)->ReleaseStringUTFChars(env, cmd_, cmd);
+ return ret;
+}
+
+/*
+ * 是否在执行命令
+ * */
+jboolean isExecuting(JNIEnv *env, jobject instance) {
+ return (jboolean) ((jboolean) conn.run);
+}
+
+/*
+ * 进行设备链接验证!
+ * */
+jboolean testPm3(JNIEnv *env, jobject instance) {
+ bool ret1 = open();
+ if (!ret1) {
+ CloseProxmark();
+ return false;
+ }
+ bool ret2 = TestProxmark() == PM3_SUCCESS;
+ return (jboolean) (ret1 && ret2);
+}
+
+void stopPm3(JNIEnv *env, jobject instance) {
+ CloseProxmark();
+}
+
+JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *reserved) {
+ JNIEnv *jniEnv = NULL;
+ if ((*vm)->GetEnv(vm, (void **) &jniEnv, JNI_VERSION_1_4) != JNI_OK) {
+ return -1;
+ }
+ (*jniEnv)->GetJavaVM(jniEnv, &g_JavaVM);
+ jclass clazz = (*jniEnv)->FindClass(jniEnv, "cn/rrg/natives/Proxmark3RRGRdv4Tools");
+ if (clazz == NULL) {
+ return -1;
+ }
+ jclass clz_test = (*jniEnv)->FindClass(jniEnv, "cn/rrg/devices/Proxmark3RRGRdv4");
+ JNINativeMethod methods[] = {
+ {"startExecute", "(Ljava/lang/String;)I", (void *) sendCMD},
+ {"stopExecute", "()V", (void *) stopPm3},
+ {"isExecuting", "()Z", (void *) isExecuting}
+ };
+ JNINativeMethod methods1[] = {
+ {"testPm3", "()Z", (void *) testPm3},
+ {"closePm3", "()V", stopPm3}
+ };
+ if ((*jniEnv)->RegisterNatives(jniEnv, clazz, methods, sizeof(methods) / sizeof(methods[0])) !=
+ JNI_OK) {
+ return -1;
+ }
+ if ((*jniEnv)->RegisterNatives(jniEnv, clz_test, methods1,
+ sizeof(methods1) / sizeof(methods1[0])) !=
+ JNI_OK) {
+ return -1;
+ }
+ (*jniEnv)->DeleteLocalRef(jniEnv, clazz);
+ (*jniEnv)->DeleteLocalRef(jniEnv, clz_test);
+ return JNI_VERSION_1_4;
+}
From 4b41e36d4951252149f67bbe6145163b7f8137c2 Mon Sep 17 00:00:00 2001
From: dxl <64101226@qq.com>
Date: Wed, 6 May 2020 12:48:46 +0200
Subject: [PATCH 081/632] Android platform adaptation(dxl)
---
client/src/cmdhflegic.c | 10 ++++++++++
1 file changed, 10 insertions(+)
diff --git a/client/src/cmdhflegic.c b/client/src/cmdhflegic.c
index fabe926fa..28138f0ea 100644
--- a/client/src/cmdhflegic.c
+++ b/client/src/cmdhflegic.c
@@ -11,7 +11,10 @@
#include // for Mingw readline
#include // tolower
+
+#ifndef ANDROID
#include
+#endif
#include "cmdparser.h" // command_t
#include "comms.h" // clearCommandBuffer
@@ -694,12 +697,19 @@ static int CmdLegicWrbl(const char *Cmd) {
PrintAndLogEx(NORMAL, "############# DANGER ################");
PrintAndLogEx(NORMAL, "# changing the DCF is irreversible #");
PrintAndLogEx(NORMAL, "#####################################");
+
+#ifndef ANDROID
char *answer = readline("do you really want to continue? y(es) n(o) : ");
bool overwrite = (answer[0] == 'y' || answer[0] == 'Y');
if (!overwrite) {
PrintAndLogEx(NORMAL, "command cancelled");
return PM3_EOPABORTED;
}
+#else
+ PrintAndLogEx(NORMAL, "\n No interactive support on Android. ");
+ PrintAndLogEx(NORMAL, " So no confirmation asked, beware! ");
+#endif
+
}
legic_chk_iv(&IV);
From eafeb4712655182434a6b0e831f0a8c0b2489ed5 Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Wed, 6 May 2020 13:38:51 +0200
Subject: [PATCH 082/632] make style
---
client/android/jni_tools.c | 2 +-
client/android/jni_tools.h | 2 +-
client/android/pm3_main.c | 20 ++++++++++----------
client/src/cmdhfmfp.c | 4 ++--
client/src/uart/uart_posix.c | 2 +-
common/crc32.c | 2 +-
6 files changed, 16 insertions(+), 16 deletions(-)
diff --git a/client/android/jni_tools.c b/client/android/jni_tools.c
index 74e05051c..1a5fc9592 100644
--- a/client/android/jni_tools.c
+++ b/client/android/jni_tools.c
@@ -94,4 +94,4 @@ void free_command_line(CMD *cmd) {
free(cmd->cmd);
LOGD("释放结构体内存");
free(cmd);
-}
\ No newline at end of file
+}
diff --git a/client/android/jni_tools.h b/client/android/jni_tools.h
index 121cf043f..3d76184b9 100644
--- a/client/android/jni_tools.h
+++ b/client/android/jni_tools.h
@@ -37,4 +37,4 @@ CMD *parse_command_line(const char *commandStr);
//解析结果释放函数!
void free_command_line(CMD *);
-#endif //DXL_TOOLS_H
\ No newline at end of file
+#endif //DXL_TOOLS_H
diff --git a/client/android/pm3_main.c b/client/android/pm3_main.c
index d9c2386c8..87c6bbd44 100644
--- a/client/android/pm3_main.c
+++ b/client/android/pm3_main.c
@@ -95,7 +95,7 @@ jint sendCMD(JNIEnv *env, jobject instance, jstring cmd_) {
}
//无论如何,新的命令的输入了,就要换个行!
PrintAndLogEx(NORMAL, "\n");
- char *cmd = (char *) ((*env)->GetStringUTFChars(env, cmd_, 0));
+ char *cmd = (char *)((*env)->GetStringUTFChars(env, cmd_, 0));
// Many parts of the PM3 client will assume that they can read any write from pwd. So we set
// pwd to whatever the PM3 "executable directory" is, to get consistent behaviour.
/*int ret = chdir(get_my_executable_directory());
@@ -120,7 +120,7 @@ jint sendCMD(JNIEnv *env, jobject instance, jstring cmd_) {
* 是否在执行命令
* */
jboolean isExecuting(JNIEnv *env, jobject instance) {
- return (jboolean) ((jboolean) conn.run);
+ return (jboolean)((jboolean) conn.run);
}
/*
@@ -133,7 +133,7 @@ jboolean testPm3(JNIEnv *env, jobject instance) {
return false;
}
bool ret2 = TestProxmark() == PM3_SUCCESS;
- return (jboolean) (ret1 && ret2);
+ return (jboolean)(ret1 && ret2);
}
void stopPm3(JNIEnv *env, jobject instance) {
@@ -152,21 +152,21 @@ JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *reserved) {
}
jclass clz_test = (*jniEnv)->FindClass(jniEnv, "cn/rrg/devices/Proxmark3RRGRdv4");
JNINativeMethod methods[] = {
- {"startExecute", "(Ljava/lang/String;)I", (void *) sendCMD},
- {"stopExecute", "()V", (void *) stopPm3},
- {"isExecuting", "()Z", (void *) isExecuting}
+ {"startExecute", "(Ljava/lang/String;)I", (void *) sendCMD},
+ {"stopExecute", "()V", (void *) stopPm3},
+ {"isExecuting", "()Z", (void *) isExecuting}
};
JNINativeMethod methods1[] = {
- {"testPm3", "()Z", (void *) testPm3},
- {"closePm3", "()V", stopPm3}
+ {"testPm3", "()Z", (void *) testPm3},
+ {"closePm3", "()V", stopPm3}
};
if ((*jniEnv)->RegisterNatives(jniEnv, clazz, methods, sizeof(methods) / sizeof(methods[0])) !=
- JNI_OK) {
+ JNI_OK) {
return -1;
}
if ((*jniEnv)->RegisterNatives(jniEnv, clz_test, methods1,
sizeof(methods1) / sizeof(methods1[0])) !=
- JNI_OK) {
+ JNI_OK) {
return -1;
}
(*jniEnv)->DeleteLocalRef(jniEnv, clazz);
diff --git a/client/src/cmdhfmfp.c b/client/src/cmdhfmfp.c
index f9d2e661a..bc6854b26 100644
--- a/client/src/cmdhfmfp.c
+++ b/client/src/cmdhfmfp.c
@@ -950,8 +950,8 @@ static int CmdHFMFPWrbl(const char *Cmd) {
#define MAX_KEYS_LIST_LEN 1024
static int MFPKeyCheck(uint8_t startSector, uint8_t endSector, uint8_t startKeyAB, uint8_t endKeyAB,
- uint8_t keyList[MAX_KEYS_LIST_LEN][AES_KEY_LEN], size_t keyListLen, uint8_t foundKeys[2][64][AES_KEY_LEN + 1],
- bool verbose) {
+ uint8_t keyList[MAX_KEYS_LIST_LEN][AES_KEY_LEN], size_t keyListLen, uint8_t foundKeys[2][64][AES_KEY_LEN + 1],
+ bool verbose) {
int res;
bool selectCard = true;
uint8_t keyn[2] = {0};
diff --git a/client/src/uart/uart_posix.c b/client/src/uart/uart_posix.c
index 076c02ddf..a846b0d78 100644
--- a/client/src/uart/uart_posix.c
+++ b/client/src/uart/uart_posix.c
@@ -184,7 +184,7 @@ serial_port uart_open(const char *pcPortName, uint32_t speed) {
}
if (memcmp(prefix, "bt:", 3) == 0) {
- free(prefix);
+ free(prefix);
#ifdef HAVE_BLUEZ
if (strlen(pcPortName) != 20) {
diff --git a/common/crc32.c b/common/crc32.c
index b539baa05..baf6ddd28 100644
--- a/common/crc32.c
+++ b/common/crc32.c
@@ -24,7 +24,7 @@ void crc32_ex(const uint8_t *data, const size_t len, uint8_t *crc) {
crc32_byte(&desfire_crc, data[i]);
}
uint32_t crctmp = htole32(desfire_crc);
- for (size_t i=0; i < sizeof(uint32_t); i++) {
+ for (size_t i = 0; i < sizeof(uint32_t); i++) {
crc[i] = ((uint8_t *) &crctmp)[i];
}
}
From 9478dbc07160c47a8e51eb72d6a37d062114cd30 Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Wed, 6 May 2020 14:39:08 +0200
Subject: [PATCH 083/632] cmake deps: add -fPIC so they can be integrated in a
pm3 shared lib
---
client/deps/amiibo.cmake | 1 +
client/deps/cliparser.cmake | 1 +
client/deps/hardnested.cmake | 7 +++++++
client/deps/jansson.cmake | 1 +
client/deps/lua.cmake | 1 +
client/deps/mbedtls.cmake | 1 +
client/deps/reveng.cmake | 1 +
client/deps/tinycbor.cmake | 1 +
client/deps/zlib.cmake | 1 +
9 files changed, 15 insertions(+)
diff --git a/client/deps/amiibo.cmake b/client/deps/amiibo.cmake
index 857074f9e..33ca39f38 100644
--- a/client/deps/amiibo.cmake
+++ b/client/deps/amiibo.cmake
@@ -14,3 +14,4 @@ add_library(amiibo STATIC
target_include_directories(amiibo PRIVATE ../../include ../../common)
target_include_directories(amiibo INTERFACE amiitool)
target_compile_options(amiibo PRIVATE -Wall -Werror -O3)
+set_property(TARGET amiibo PROPERTY POSITION_INDEPENDENT_CODE ON)
diff --git a/client/deps/cliparser.cmake b/client/deps/cliparser.cmake
index 890fd39c5..ca3e0bf6d 100644
--- a/client/deps/cliparser.cmake
+++ b/client/deps/cliparser.cmake
@@ -9,3 +9,4 @@ target_include_directories(cliparser PRIVATE
../src)
target_include_directories(cliparser INTERFACE cliparser)
target_compile_options(cliparser PRIVATE -Wall -Werror -O3)
+set_property(TARGET cliparser PROPERTY POSITION_INDEPENDENT_CODE ON)
diff --git a/client/deps/hardnested.cmake b/client/deps/hardnested.cmake
index 8945d68a8..5dbca2dbd 100644
--- a/client/deps/hardnested.cmake
+++ b/client/deps/hardnested.cmake
@@ -3,6 +3,7 @@ add_library(hardnested_nosimd OBJECT
hardnested/hardnested_bitarray_core.c)
target_compile_options(hardnested_nosimd PRIVATE -Wall -Werror -O3)
+set_property(TARGET hardnested_nosimd PROPERTY POSITION_INDEPENDENT_CODE ON)
target_include_directories(hardnested_nosimd PRIVATE
../../common
@@ -29,6 +30,7 @@ if ("${CMAKE_SYSTEM_PROCESSOR}" IN_LIST X86_CPUS)
target_compile_options(hardnested_mmx PRIVATE -Wall -Werror -O3)
target_compile_options(hardnested_mmx BEFORE PRIVATE
-mmmx -mno-sse2 -mno-avx -mno-avx2 -mno-avx512f)
+ set_property(TARGET hardnested_mmx PROPERTY POSITION_INDEPENDENT_CODE ON)
target_include_directories(hardnested_mmx PRIVATE
../../common
@@ -42,6 +44,7 @@ if ("${CMAKE_SYSTEM_PROCESSOR}" IN_LIST X86_CPUS)
target_compile_options(hardnested_sse2 PRIVATE -Wall -Werror -O3)
target_compile_options(hardnested_sse2 BEFORE PRIVATE
-mmmx -msse2 -mno-avx -mno-avx2 -mno-avx512f)
+ set_property(TARGET hardnested_sse2 PROPERTY POSITION_INDEPENDENT_CODE ON)
target_include_directories(hardnested_sse2 PRIVATE
../../common
@@ -55,6 +58,7 @@ if ("${CMAKE_SYSTEM_PROCESSOR}" IN_LIST X86_CPUS)
target_compile_options(hardnested_avx PRIVATE -Wall -Werror -O3)
target_compile_options(hardnested_avx BEFORE PRIVATE
-mmmx -msse2 -mavx -mno-avx2 -mno-avx512f)
+ set_property(TARGET hardnested_avx PROPERTY POSITION_INDEPENDENT_CODE ON)
target_include_directories(hardnested_avx PRIVATE
../../common
@@ -68,6 +72,7 @@ if ("${CMAKE_SYSTEM_PROCESSOR}" IN_LIST X86_CPUS)
target_compile_options(hardnested_avx2 PRIVATE -Wall -Werror -O3)
target_compile_options(hardnested_avx2 BEFORE PRIVATE
-mmmx -msse2 -mavx -mavx2 -mno-avx512f)
+ set_property(TARGET hardnested_avx2 PROPERTY POSITION_INDEPENDENT_CODE ON)
target_include_directories(hardnested_avx2 PRIVATE
../../common
@@ -81,6 +86,7 @@ if ("${CMAKE_SYSTEM_PROCESSOR}" IN_LIST X86_CPUS)
target_compile_options(hardnested_avx512 PRIVATE -Wall -Werror -O3)
target_compile_options(hardnested_avx512 BEFORE PRIVATE
-mmmx -msse2 -mavx -mavx2 -mavx512f)
+ set_property(TARGET hardnested_avx512 PROPERTY POSITION_INDEPENDENT_CODE ON)
target_include_directories(hardnested_avx512 PRIVATE
../../common
@@ -101,6 +107,7 @@ add_library(hardnested STATIC
hardnested/hardnested_bruteforce.c
$
${SIMD_TARGETS})
+set_property(TARGET hardnested PROPERTY POSITION_INDEPENDENT_CODE ON)
target_include_directories(hardnested PRIVATE
../../common
../../include
diff --git a/client/deps/jansson.cmake b/client/deps/jansson.cmake
index 216f7a830..d3054b158 100644
--- a/client/deps/jansson.cmake
+++ b/client/deps/jansson.cmake
@@ -16,3 +16,4 @@ add_library(jansson STATIC
target_compile_definitions(jansson PRIVATE HAVE_STDINT_H)
target_include_directories(jansson INTERFACE jansson)
target_compile_options(jansson PRIVATE -Wall -Werror -Wno-unused-function -O3)
+set_property(TARGET jansson PROPERTY POSITION_INDEPENDENT_CODE ON)
diff --git a/client/deps/lua.cmake b/client/deps/lua.cmake
index 3850863b5..b5267c561 100644
--- a/client/deps/lua.cmake
+++ b/client/deps/lua.cmake
@@ -46,3 +46,4 @@ endif (NOT MINGW)
target_include_directories(lua INTERFACE liblua)
target_compile_options(lua PRIVATE -Wall -Werror -O3)
+set_property(TARGET lua PROPERTY POSITION_INDEPENDENT_CODE ON)
diff --git a/client/deps/mbedtls.cmake b/client/deps/mbedtls.cmake
index 932c1757c..5f6cff8b5 100644
--- a/client/deps/mbedtls.cmake
+++ b/client/deps/mbedtls.cmake
@@ -46,3 +46,4 @@ add_library(mbedtls STATIC
target_include_directories(mbedtls PRIVATE ../../common)
target_compile_options(mbedtls PRIVATE -Wall -Werror -O3)
+set_property(TARGET mbedtls PROPERTY POSITION_INDEPENDENT_CODE ON)
diff --git a/client/deps/reveng.cmake b/client/deps/reveng.cmake
index 0d24c9d49..c32de008a 100644
--- a/client/deps/reveng.cmake
+++ b/client/deps/reveng.cmake
@@ -11,3 +11,4 @@ target_compile_definitions(reveng PRIVATE PRESETS)
target_include_directories(reveng PRIVATE ../cliparser)
target_include_directories(reveng INTERFACE reveng)
target_compile_options(reveng PRIVATE -Wall -Werror -O3)
+set_property(TARGET reveng PROPERTY POSITION_INDEPENDENT_CODE ON)
diff --git a/client/deps/tinycbor.cmake b/client/deps/tinycbor.cmake
index 14ebb5326..d7a51672d 100644
--- a/client/deps/tinycbor.cmake
+++ b/client/deps/tinycbor.cmake
@@ -12,3 +12,4 @@ add_library(tinycbor STATIC
target_include_directories(tinycbor INTERFACE tinycbor)
# Strange errors on Mingw when compiling with -O3
target_compile_options(tinycbor PRIVATE -Wall -Werror -O2)
+set_property(TARGET tinycbor PROPERTY POSITION_INDEPENDENT_CODE ON)
diff --git a/client/deps/zlib.cmake b/client/deps/zlib.cmake
index dc6044f80..fabfc218a 100644
--- a/client/deps/zlib.cmake
+++ b/client/deps/zlib.cmake
@@ -10,3 +10,4 @@ add_library(z STATIC
target_compile_definitions(z PRIVATE Z_SOLO NO_GZIP ZLIB_PM3_TUNED)
target_compile_options(z PRIVATE -Wall -Werror -O3)
+set_property(TARGET z PROPERTY POSITION_INDEPENDENT_CODE ON)
From 53af4304c163fabfb770c8b5a1e00ff97ab66de7 Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Wed, 6 May 2020 14:45:02 +0200
Subject: [PATCH 084/632] cmake deps: add prefix pm3rrg_rdv4_
---
client/CMakeLists.txt | 18 ++++----
client/deps/amiibo.cmake | 10 ++---
client/deps/cliparser.cmake | 10 ++---
client/deps/hardnested.cmake | 80 ++++++++++++++++++------------------
client/deps/jansson.cmake | 10 ++---
client/deps/lua.cmake | 16 ++++----
client/deps/mbedtls.cmake | 8 ++--
client/deps/reveng.cmake | 12 +++---
client/deps/tinycbor.cmake | 8 ++--
client/deps/zlib.cmake | 8 ++--
10 files changed, 90 insertions(+), 90 deletions(-)
diff --git a/client/CMakeLists.txt b/client/CMakeLists.txt
index 921e0d04b..7b17c1e36 100644
--- a/client/CMakeLists.txt
+++ b/client/CMakeLists.txt
@@ -252,16 +252,16 @@ else (APPLE)
endif (APPLE)
-find_library(cliparser REQUIRED)
-find_library(jansson REQUIRED)
-find_library(tinycbor REQUIRED)
-find_library(lua REQUIRED)
-find_library(mbedtls REQUIRED)
-find_library(reveng REQUIRED)
-find_library(z REQUIRED)
-find_library(hardnested REQUIRED)
+find_library(pm3rrg_rdv4_cliparser REQUIRED)
+find_library(pm3rrg_rdv4_jansson REQUIRED)
+find_library(pm3rrg_rdv4_tinycbor REQUIRED)
+find_library(pm3rrg_rdv4_lua REQUIRED)
+find_library(pm3rrg_rdv4_mbedtls REQUIRED)
+find_library(pm3rrg_rdv4_reveng REQUIRED)
+find_library(pm3rrg_rdv4_z REQUIRED)
+find_library(pm3rrg_rdv4_hardnested REQUIRED)
-target_link_libraries(proxmark3 PRIVATE readline pthread m mbedtls cliparser jansson lua tinycbor amiibo reveng z hardnested ${ADDITIONAL_LNK})
+target_link_libraries(proxmark3 PRIVATE readline pthread m pm3rrg_rdv4_mbedtls pm3rrg_rdv4_cliparser pm3rrg_rdv4_jansson pm3rrg_rdv4_lua pm3rrg_rdv4_tinycbor pm3rrg_rdv4_amiibo pm3rrg_rdv4_reveng pm3rrg_rdv4_z pm3rrg_rdv4_hardnested ${ADDITIONAL_LNK})
install(TARGETS proxmark3 DESTINATION "bin")
install(DIRECTORY cmdscripts lualibs luascripts resources dictionaries DESTINATION "share/proxmark3")
diff --git a/client/deps/amiibo.cmake b/client/deps/amiibo.cmake
index 33ca39f38..34780f597 100644
--- a/client/deps/amiibo.cmake
+++ b/client/deps/amiibo.cmake
@@ -5,13 +5,13 @@
#amiitool.c $(MYSRCS) ../../../../common/../../commonutil.c ../ui.c -lreadline -lm ../../../../common/mbedtls/libmbedtls.a \
#-o amiitool
-add_library(amiibo STATIC
+add_library(pm3rrg_rdv4_amiibo STATIC
amiitool/amiibo.c
amiitool/drbg.c
amiitool/keygen.c
)
-target_include_directories(amiibo PRIVATE ../../include ../../common)
-target_include_directories(amiibo INTERFACE amiitool)
-target_compile_options(amiibo PRIVATE -Wall -Werror -O3)
-set_property(TARGET amiibo PROPERTY POSITION_INDEPENDENT_CODE ON)
+target_include_directories(pm3rrg_rdv4_amiibo PRIVATE ../../include ../../common)
+target_include_directories(pm3rrg_rdv4_amiibo INTERFACE amiitool)
+target_compile_options(pm3rrg_rdv4_amiibo PRIVATE -Wall -Werror -O3)
+set_property(TARGET pm3rrg_rdv4_amiibo PROPERTY POSITION_INDEPENDENT_CODE ON)
diff --git a/client/deps/cliparser.cmake b/client/deps/cliparser.cmake
index ca3e0bf6d..b16451c07 100644
--- a/client/deps/cliparser.cmake
+++ b/client/deps/cliparser.cmake
@@ -1,12 +1,12 @@
-add_library(cliparser STATIC
+add_library(pm3rrg_rdv4_cliparser STATIC
cliparser/argtable3.c
cliparser/cliparser.c
)
-target_include_directories(cliparser PRIVATE
+target_include_directories(pm3rrg_rdv4_cliparser PRIVATE
../../common
../../include
../src)
-target_include_directories(cliparser INTERFACE cliparser)
-target_compile_options(cliparser PRIVATE -Wall -Werror -O3)
-set_property(TARGET cliparser PROPERTY POSITION_INDEPENDENT_CODE ON)
+target_include_directories(pm3rrg_rdv4_cliparser INTERFACE cliparser)
+target_compile_options(pm3rrg_rdv4_cliparser PRIVATE -Wall -Werror -O3)
+set_property(TARGET pm3rrg_rdv4_cliparser PROPERTY POSITION_INDEPENDENT_CODE ON)
diff --git a/client/deps/hardnested.cmake b/client/deps/hardnested.cmake
index 5dbca2dbd..9efff1445 100644
--- a/client/deps/hardnested.cmake
+++ b/client/deps/hardnested.cmake
@@ -1,11 +1,11 @@
-add_library(hardnested_nosimd OBJECT
+add_library(pm3rrg_rdv4_hardnested_nosimd OBJECT
hardnested/hardnested_bf_core.c
hardnested/hardnested_bitarray_core.c)
-target_compile_options(hardnested_nosimd PRIVATE -Wall -Werror -O3)
-set_property(TARGET hardnested_nosimd PROPERTY POSITION_INDEPENDENT_CODE ON)
+target_compile_options(pm3rrg_rdv4_hardnested_nosimd PRIVATE -Wall -Werror -O3)
+set_property(TARGET pm3rrg_rdv4_hardnested_nosimd PROPERTY POSITION_INDEPENDENT_CODE ON)
-target_include_directories(hardnested_nosimd PRIVATE
+target_include_directories(pm3rrg_rdv4_hardnested_nosimd PRIVATE
../../common
../../include)
@@ -19,98 +19,98 @@ message(STATUS "CMAKE_SYSTEM_PROCESSOR := ${CMAKE_SYSTEM_PROCESSOR}")
if ("${CMAKE_SYSTEM_PROCESSOR}" IN_LIST X86_CPUS)
message(STATUS "Building optimised x86/x86_64 binaries")
- target_compile_options(hardnested_nosimd BEFORE PRIVATE
+ target_compile_options(pm3rrg_rdv4_hardnested_nosimd BEFORE PRIVATE
-mno-mmx -mno-sse2 -mno-avx -mno-avx2 -mno-avx512f)
## x86 / MMX
- add_library(hardnested_mmx OBJECT
+ add_library(pm3rrg_rdv4_hardnested_mmx OBJECT
hardnested/hardnested_bf_core.c
hardnested/hardnested_bitarray_core.c)
- target_compile_options(hardnested_mmx PRIVATE -Wall -Werror -O3)
- target_compile_options(hardnested_mmx BEFORE PRIVATE
+ target_compile_options(pm3rrg_rdv4_hardnested_mmx PRIVATE -Wall -Werror -O3)
+ target_compile_options(pm3rrg_rdv4_hardnested_mmx BEFORE PRIVATE
-mmmx -mno-sse2 -mno-avx -mno-avx2 -mno-avx512f)
- set_property(TARGET hardnested_mmx PROPERTY POSITION_INDEPENDENT_CODE ON)
+ set_property(TARGET pm3rrg_rdv4_hardnested_mmx PROPERTY POSITION_INDEPENDENT_CODE ON)
- target_include_directories(hardnested_mmx PRIVATE
+ target_include_directories(pm3rrg_rdv4_hardnested_mmx PRIVATE
../../common
../../include)
## x86 / SSE2
- add_library(hardnested_sse2 OBJECT
+ add_library(pm3rrg_rdv4_hardnested_sse2 OBJECT
hardnested/hardnested_bf_core.c
hardnested/hardnested_bitarray_core.c)
- target_compile_options(hardnested_sse2 PRIVATE -Wall -Werror -O3)
- target_compile_options(hardnested_sse2 BEFORE PRIVATE
+ target_compile_options(pm3rrg_rdv4_hardnested_sse2 PRIVATE -Wall -Werror -O3)
+ target_compile_options(pm3rrg_rdv4_hardnested_sse2 BEFORE PRIVATE
-mmmx -msse2 -mno-avx -mno-avx2 -mno-avx512f)
- set_property(TARGET hardnested_sse2 PROPERTY POSITION_INDEPENDENT_CODE ON)
+ set_property(TARGET pm3rrg_rdv4_hardnested_sse2 PROPERTY POSITION_INDEPENDENT_CODE ON)
- target_include_directories(hardnested_sse2 PRIVATE
+ target_include_directories(pm3rrg_rdv4_hardnested_sse2 PRIVATE
../../common
../../include)
## x86 / AVX
- add_library(hardnested_avx OBJECT
+ add_library(pm3rrg_rdv4_hardnested_avx OBJECT
hardnested/hardnested_bf_core.c
hardnested/hardnested_bitarray_core.c)
- target_compile_options(hardnested_avx PRIVATE -Wall -Werror -O3)
- target_compile_options(hardnested_avx BEFORE PRIVATE
+ target_compile_options(pm3rrg_rdv4_hardnested_avx PRIVATE -Wall -Werror -O3)
+ target_compile_options(pm3rrg_rdv4_hardnested_avx BEFORE PRIVATE
-mmmx -msse2 -mavx -mno-avx2 -mno-avx512f)
- set_property(TARGET hardnested_avx PROPERTY POSITION_INDEPENDENT_CODE ON)
+ set_property(TARGET pm3rrg_rdv4_hardnested_avx PROPERTY POSITION_INDEPENDENT_CODE ON)
- target_include_directories(hardnested_avx PRIVATE
+ target_include_directories(pm3rrg_rdv4_hardnested_avx PRIVATE
../../common
../../include)
## x86 / AVX2
- add_library(hardnested_avx2 OBJECT
+ add_library(pm3rrg_rdv4_hardnested_avx2 OBJECT
hardnested/hardnested_bf_core.c
hardnested/hardnested_bitarray_core.c)
- target_compile_options(hardnested_avx2 PRIVATE -Wall -Werror -O3)
- target_compile_options(hardnested_avx2 BEFORE PRIVATE
+ target_compile_options(pm3rrg_rdv4_hardnested_avx2 PRIVATE -Wall -Werror -O3)
+ target_compile_options(pm3rrg_rdv4_hardnested_avx2 BEFORE PRIVATE
-mmmx -msse2 -mavx -mavx2 -mno-avx512f)
- set_property(TARGET hardnested_avx2 PROPERTY POSITION_INDEPENDENT_CODE ON)
+ set_property(TARGET pm3rrg_rdv4_hardnested_avx2 PROPERTY POSITION_INDEPENDENT_CODE ON)
- target_include_directories(hardnested_avx2 PRIVATE
+ target_include_directories(pm3rrg_rdv4_hardnested_avx2 PRIVATE
../../common
../../include)
## x86 / AVX512
- add_library(hardnested_avx512 OBJECT
+ add_library(pm3rrg_rdv4_hardnested_avx512 OBJECT
hardnested/hardnested_bf_core.c
hardnested/hardnested_bitarray_core.c)
- target_compile_options(hardnested_avx512 PRIVATE -Wall -Werror -O3)
- target_compile_options(hardnested_avx512 BEFORE PRIVATE
+ target_compile_options(pm3rrg_rdv4_hardnested_avx512 PRIVATE -Wall -Werror -O3)
+ target_compile_options(pm3rrg_rdv4_hardnested_avx512 BEFORE PRIVATE
-mmmx -msse2 -mavx -mavx2 -mavx512f)
- set_property(TARGET hardnested_avx512 PROPERTY POSITION_INDEPENDENT_CODE ON)
+ set_property(TARGET pm3rrg_rdv4_hardnested_avx512 PROPERTY POSITION_INDEPENDENT_CODE ON)
- target_include_directories(hardnested_avx512 PRIVATE
+ target_include_directories(pm3rrg_rdv4_hardnested_avx512 PRIVATE
../../common
../../include)
set(SIMD_TARGETS
- $
- $
- $
- $
- $)
+ $
+ $
+ $
+ $
+ $)
else ()
message(STATUS "Not building optimised targets")
set(SIMD_TARGETS)
endif ()
-add_library(hardnested STATIC
+add_library(pm3rrg_rdv4_hardnested STATIC
hardnested/hardnested_bruteforce.c
- $
+ $
${SIMD_TARGETS})
-set_property(TARGET hardnested PROPERTY POSITION_INDEPENDENT_CODE ON)
-target_include_directories(hardnested PRIVATE
+set_property(TARGET pm3rrg_rdv4_hardnested PROPERTY POSITION_INDEPENDENT_CODE ON)
+target_include_directories(pm3rrg_rdv4_hardnested PRIVATE
../../common
../../include
../src
jansson)
-target_include_directories(hardnested INTERFACE hardnested)
+target_include_directories(pm3rrg_rdv4_hardnested INTERFACE hardnested)
diff --git a/client/deps/jansson.cmake b/client/deps/jansson.cmake
index d3054b158..a95ff0baf 100644
--- a/client/deps/jansson.cmake
+++ b/client/deps/jansson.cmake
@@ -1,4 +1,4 @@
-add_library(jansson STATIC
+add_library(pm3rrg_rdv4_jansson STATIC
jansson/dump.c
jansson/error.c
jansson/hashtable.c
@@ -13,7 +13,7 @@ add_library(jansson STATIC
jansson/value.c
)
-target_compile_definitions(jansson PRIVATE HAVE_STDINT_H)
-target_include_directories(jansson INTERFACE jansson)
-target_compile_options(jansson PRIVATE -Wall -Werror -Wno-unused-function -O3)
-set_property(TARGET jansson PROPERTY POSITION_INDEPENDENT_CODE ON)
+target_compile_definitions(pm3rrg_rdv4_jansson PRIVATE HAVE_STDINT_H)
+target_include_directories(pm3rrg_rdv4_jansson INTERFACE jansson)
+target_compile_options(pm3rrg_rdv4_jansson PRIVATE -Wall -Werror -Wno-unused-function -O3)
+set_property(TARGET pm3rrg_rdv4_jansson PROPERTY POSITION_INDEPENDENT_CODE ON)
diff --git a/client/deps/lua.cmake b/client/deps/lua.cmake
index b5267c561..679147124 100644
--- a/client/deps/lua.cmake
+++ b/client/deps/lua.cmake
@@ -1,4 +1,4 @@
-add_library(lua STATIC
+add_library(pm3rrg_rdv4_lua STATIC
liblua/lapi.c
liblua/lcode.c
liblua/lctype.c
@@ -33,17 +33,17 @@ add_library(lua STATIC
liblua/linit.c
)
-target_compile_definitions(lua PRIVATE LUA_COMPAT_ALL)
+target_compile_definitions(pm3rrg_rdv4_lua PRIVATE LUA_COMPAT_ALL)
if (NOT MINGW)
if (APPLE)
- target_compile_definitions(lua PRIVATE LUA_USE_MACOSX)
+ target_compile_definitions(pm3rrg_rdv4_lua PRIVATE LUA_USE_MACOSX)
else (APPLE)
- target_compile_definitions(lua PRIVATE LUA_USE_LINUX)
- target_link_libraries(lua INTERFACE dl)
+ target_compile_definitions(pm3rrg_rdv4_lua PRIVATE LUA_USE_LINUX)
+ target_link_libraries(pm3rrg_rdv4_lua INTERFACE dl)
endif (APPLE)
endif (NOT MINGW)
-target_include_directories(lua INTERFACE liblua)
-target_compile_options(lua PRIVATE -Wall -Werror -O3)
-set_property(TARGET lua PROPERTY POSITION_INDEPENDENT_CODE ON)
+target_include_directories(pm3rrg_rdv4_lua INTERFACE liblua)
+target_compile_options(pm3rrg_rdv4_lua PRIVATE -Wall -Werror -O3)
+set_property(TARGET pm3rrg_rdv4_lua PROPERTY POSITION_INDEPENDENT_CODE ON)
diff --git a/client/deps/mbedtls.cmake b/client/deps/mbedtls.cmake
index 5f6cff8b5..63e706889 100644
--- a/client/deps/mbedtls.cmake
+++ b/client/deps/mbedtls.cmake
@@ -1,4 +1,4 @@
-add_library(mbedtls STATIC
+add_library(pm3rrg_rdv4_mbedtls STATIC
../../common/mbedtls/aes.c
../../common/mbedtls/asn1parse.c
../../common/mbedtls/asn1write.c
@@ -44,6 +44,6 @@ add_library(mbedtls STATIC
../../common/mbedtls/x509_crt.c
)
-target_include_directories(mbedtls PRIVATE ../../common)
-target_compile_options(mbedtls PRIVATE -Wall -Werror -O3)
-set_property(TARGET mbedtls PROPERTY POSITION_INDEPENDENT_CODE ON)
+target_include_directories(pm3rrg_rdv4_mbedtls PRIVATE ../../common)
+target_compile_options(pm3rrg_rdv4_mbedtls PRIVATE -Wall -Werror -O3)
+set_property(TARGET pm3rrg_rdv4_mbedtls PROPERTY POSITION_INDEPENDENT_CODE ON)
diff --git a/client/deps/reveng.cmake b/client/deps/reveng.cmake
index c32de008a..d5f3259ed 100644
--- a/client/deps/reveng.cmake
+++ b/client/deps/reveng.cmake
@@ -1,4 +1,4 @@
-add_library(reveng STATIC
+add_library(pm3rrg_rdv4_reveng STATIC
reveng/bmpbit.c
reveng/cli.c
reveng/model.c
@@ -7,8 +7,8 @@ add_library(reveng STATIC
reveng/reveng.c
)
-target_compile_definitions(reveng PRIVATE PRESETS)
-target_include_directories(reveng PRIVATE ../cliparser)
-target_include_directories(reveng INTERFACE reveng)
-target_compile_options(reveng PRIVATE -Wall -Werror -O3)
-set_property(TARGET reveng PROPERTY POSITION_INDEPENDENT_CODE ON)
+target_compile_definitions(pm3rrg_rdv4_reveng PRIVATE PRESETS)
+target_include_directories(pm3rrg_rdv4_reveng PRIVATE ../cliparser)
+target_include_directories(pm3rrg_rdv4_reveng INTERFACE reveng)
+target_compile_options(pm3rrg_rdv4_reveng PRIVATE -Wall -Werror -O3)
+set_property(TARGET pm3rrg_rdv4_reveng PROPERTY POSITION_INDEPENDENT_CODE ON)
diff --git a/client/deps/tinycbor.cmake b/client/deps/tinycbor.cmake
index d7a51672d..5a6abda25 100644
--- a/client/deps/tinycbor.cmake
+++ b/client/deps/tinycbor.cmake
@@ -1,4 +1,4 @@
-add_library(tinycbor STATIC
+add_library(pm3rrg_rdv4_tinycbor STATIC
tinycbor/cborencoder.c
tinycbor/cborencoder_close_container_checked.c
tinycbor/cborerrorstrings.c
@@ -9,7 +9,7 @@ add_library(tinycbor STATIC
tinycbor/cborvalidation.c
)
-target_include_directories(tinycbor INTERFACE tinycbor)
+target_include_directories(pm3rrg_rdv4_tinycbor INTERFACE tinycbor)
# Strange errors on Mingw when compiling with -O3
-target_compile_options(tinycbor PRIVATE -Wall -Werror -O2)
-set_property(TARGET tinycbor PROPERTY POSITION_INDEPENDENT_CODE ON)
+target_compile_options(pm3rrg_rdv4_tinycbor PRIVATE -Wall -Werror -O2)
+set_property(TARGET pm3rrg_rdv4_tinycbor PROPERTY POSITION_INDEPENDENT_CODE ON)
diff --git a/client/deps/zlib.cmake b/client/deps/zlib.cmake
index fabfc218a..645cbc88d 100644
--- a/client/deps/zlib.cmake
+++ b/client/deps/zlib.cmake
@@ -1,4 +1,4 @@
-add_library(z STATIC
+add_library(pm3rrg_rdv4_z STATIC
../../common/zlib/deflate.c
../../common/zlib/adler32.c
../../common/zlib/trees.c
@@ -8,6 +8,6 @@ add_library(z STATIC
../../common/zlib/inftrees.c
)
-target_compile_definitions(z PRIVATE Z_SOLO NO_GZIP ZLIB_PM3_TUNED)
-target_compile_options(z PRIVATE -Wall -Werror -O3)
-set_property(TARGET z PROPERTY POSITION_INDEPENDENT_CODE ON)
+target_compile_definitions(pm3rrg_rdv4_z PRIVATE Z_SOLO NO_GZIP ZLIB_PM3_TUNED)
+target_compile_options(pm3rrg_rdv4_z PRIVATE -Wall -Werror -O3)
+set_property(TARGET pm3rrg_rdv4_z PROPERTY POSITION_INDEPENDENT_CODE ON)
From 59453aea8b9f135cea8a0d39d1f5934dfdceb629 Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Wed, 6 May 2020 14:34:07 +0200
Subject: [PATCH 085/632] Android cmake: use common cmake files for deps
---
client/android/CMakeLists.txt | 259 ++--------------------------------
1 file changed, 13 insertions(+), 246 deletions(-)
diff --git a/client/android/CMakeLists.txt b/client/android/CMakeLists.txt
index a4e04b8ca..d320db6a1 100644
--- a/client/android/CMakeLists.txt
+++ b/client/android/CMakeLists.txt
@@ -9,6 +9,8 @@ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99 -O3 -fvisibility=hidden -w")
#缩短路径定义
set(PM3_ROOT ../../)
+add_subdirectory(../deps deps)
+
#添加动态库定义
add_library(pm3rrg_rdv4 SHARED
${PM3_ROOT}/common/util_posix.c
@@ -26,52 +28,6 @@ add_library(pm3rrg_rdv4 SHARED
${PM3_ROOT}/common/iso15693tools.c
${PM3_ROOT}/common/bucketsort.c
${PM3_ROOT}/common/legic_prng.c
- ${PM3_ROOT}/common/mbedtls/aes.c
- ${PM3_ROOT}/common/mbedtls/base64.c
- ${PM3_ROOT}/common/mbedtls/rsa.c
- ${PM3_ROOT}/common/mbedtls/rsa_internal.c
- ${PM3_ROOT}/common/mbedtls/arc4.c
- ${PM3_ROOT}/common/mbedtls/bignum.c
- ${PM3_ROOT}/common/mbedtls/asn1parse.c
- ${PM3_ROOT}/common/mbedtls/asn1write.c
- ${PM3_ROOT}/common/mbedtls/blowfish.c
- ${PM3_ROOT}/common/mbedtls/camellia.c
- ${PM3_ROOT}/common/mbedtls/certs.c
- ${PM3_ROOT}/common/mbedtls/des.c
- ${PM3_ROOT}/common/mbedtls/ecdsa.c
- ${PM3_ROOT}/common/mbedtls/ecp.c
- ${PM3_ROOT}/common/mbedtls/ecp_curves.c
- ${PM3_ROOT}/common/mbedtls/entropy.c
- ${PM3_ROOT}/common/mbedtls/entropy_poll.c
- ${PM3_ROOT}/common/mbedtls/error.c
- ${PM3_ROOT}/common/mbedtls/md.c
- ${PM3_ROOT}/common/mbedtls/md5.c
- ${PM3_ROOT}/common/mbedtls/md_wrap.c
- ${PM3_ROOT}/common/mbedtls/sha1.c
- ${PM3_ROOT}/common/mbedtls/sha256.c
- ${PM3_ROOT}/common/mbedtls/sha512.c
- ${PM3_ROOT}/common/mbedtls/timing.c
- ${PM3_ROOT}/common/mbedtls/cmac.c
- ${PM3_ROOT}/common/mbedtls/oid.c
- ${PM3_ROOT}/common/mbedtls/pem.c
- ${PM3_ROOT}/common/mbedtls/pk.c
- ${PM3_ROOT}/common/mbedtls/pk_wrap.c
- ${PM3_ROOT}/common/mbedtls/pkcs5.c
- ${PM3_ROOT}/common/mbedtls/pkcs12.c
- ${PM3_ROOT}/common/mbedtls/pkparse.c
- ${PM3_ROOT}/common/mbedtls/pkwrite.c
- ${PM3_ROOT}/common/mbedtls/x509.c
- ${PM3_ROOT}/common/mbedtls/x509_crl.c
- ${PM3_ROOT}/common/mbedtls/x509_crt.c
- ${PM3_ROOT}/common/mbedtls/ctr_drbg.c
- ${PM3_ROOT}/common/mbedtls/cipher_wrap.c
- ${PM3_ROOT}/common/mbedtls/cipher.c
- ${PM3_ROOT}/common/mbedtls/platform_util.c
- ${PM3_ROOT}/common//zlib/inflate.c
- ${PM3_ROOT}/common/zlib/inffast.c
- ${PM3_ROOT}/common/zlib/zutil.c
- ${PM3_ROOT}/common/zlib/inftrees.c
- ${PM3_ROOT}/common//zlib/adler32.c
# client inside
${PM3_ROOT}/client/src/fileutils.c
${PM3_ROOT}/client/src/uart/uart_posix.c
@@ -187,75 +143,7 @@ add_library(pm3rrg_rdv4 SHARED
${PM3_ROOT}/client/src/cmdlfpcf7931.c
${PM3_ROOT}/client/src/cmdhfmfhard.c
${PM3_ROOT}/client/src/cmdusart.c
- # deps ouside
- ${PM3_ROOT}/client/deps/jansson/utf.c
- ${PM3_ROOT}/client/deps/jansson/dump.c
- ${PM3_ROOT}/client/deps/jansson/path.c
- ${PM3_ROOT}/client/deps/jansson/load.c
- ${PM3_ROOT}/client/deps/jansson/error.c
- ${PM3_ROOT}/client/deps/jansson/value.c
- ${PM3_ROOT}/client/deps/jansson/memory.c
- ${PM3_ROOT}/client/deps/jansson/pack_unpack.c
- ${PM3_ROOT}/client/deps/jansson/hashtable_seed.c
- ${PM3_ROOT}/client/deps/jansson/strbuffer.c
- ${PM3_ROOT}/client/deps/jansson/strconv.c
- ${PM3_ROOT}/client/deps/jansson/hashtable.c
- ${PM3_ROOT}/client/deps/jansson/hashtable.c
- # cliparser
- ${PM3_ROOT}/client/deps/cliparser/cliparser.c
- ${PM3_ROOT}/client/deps/cliparser/argtable3.c
- # tinycbor
- ${PM3_ROOT}/client/deps/tinycbor/cborencoder.c
- ${PM3_ROOT}/client/deps/tinycbor/cborencoder_close_container_checked.c
- ${PM3_ROOT}/client/deps/tinycbor/cborerrorstrings.c
- ${PM3_ROOT}/client/deps/tinycbor/cborparser.c
- ${PM3_ROOT}/client/deps/tinycbor/cborparser_dup_string.c
- ${PM3_ROOT}/client/deps/tinycbor/cborpretty.c
- ${PM3_ROOT}/client/deps/tinycbor/cborpretty_stdio.c
- ${PM3_ROOT}/client/deps/tinycbor/cbortojson.c
- ${PM3_ROOT}/client/deps/tinycbor/cborvalidation.c
- ${PM3_ROOT}/client/deps/tinycbor/open_memstream.c
- # reveng
- ${PM3_ROOT}/client/deps/reveng/cli.c
- ${PM3_ROOT}/client/deps/reveng/bmpbit.c
- ${PM3_ROOT}/client/deps/reveng/preset.c
- ${PM3_ROOT}/client/deps/reveng/model.c
- ${PM3_ROOT}/client/deps/reveng/poly.c
- ${PM3_ROOT}/client/deps/reveng/reveng.c
- # liblua
- ${PM3_ROOT}/client/deps/liblua/lapi.c
- ${PM3_ROOT}/client/deps/liblua/ldo.c
- ${PM3_ROOT}/client/deps/liblua/lgc.c
- ${PM3_ROOT}/client/deps/liblua/ltm.c
- ${PM3_ROOT}/client/deps/liblua/lvm.c
- ${PM3_ROOT}/client/deps/liblua/lzio.c
- ${PM3_ROOT}/client/deps/liblua/lcode.c
- ${PM3_ROOT}/client/deps/liblua/llex.c
- ${PM3_ROOT}/client/deps/liblua/liolib.c
- ${PM3_ROOT}/client/deps/liblua/loslib.c
- ${PM3_ROOT}/client/deps/liblua/lopcodes.c
- ${PM3_ROOT}/client/deps/liblua/lmem.c
- ${PM3_ROOT}/client/deps/liblua/lmathlib.c
- ${PM3_ROOT}/client/deps/liblua/ldump.c
- ${PM3_ROOT}/client/deps/liblua/ldblib.c
- ${PM3_ROOT}/client/deps/liblua/lundump.c
- ${PM3_ROOT}/client/deps/liblua/lcorolib.c
- ${PM3_ROOT}/client/deps/liblua/lauxlib.c
- ${PM3_ROOT}/client/deps/liblua/ltablib.c
- ${PM3_ROOT}/client/deps/liblua/linit.c
- ${PM3_ROOT}/client/deps/liblua/lstring.c
- ${PM3_ROOT}/client/deps/liblua/lctype.c
- ${PM3_ROOT}/client/deps/liblua/ltable.c
- ${PM3_ROOT}/client/deps/liblua/ldebug.c
- ${PM3_ROOT}/client/deps/liblua/lstate.c
- ${PM3_ROOT}/client/deps/liblua/lstrlib.c
- ${PM3_ROOT}/client/deps/liblua/lfunc.c
- ${PM3_ROOT}/client/deps/liblua/lparser.c
- ${PM3_ROOT}/client/deps/liblua/lobject.c
- ${PM3_ROOT}/client/deps/liblua/loadlib.c
- ${PM3_ROOT}/client/deps/liblua/lbaselib.c
- ${PM3_ROOT}/client/deps/liblua/lbitlib.c
- ${PM3_ROOT}/client/deps/hardnested/hardnested_bruteforce.c
+
# android source
jni_tools.c
pm3_main.c
@@ -264,140 +152,19 @@ add_library(pm3rrg_rdv4 SHARED
#添加头文件配置
target_include_directories(pm3rrg_rdv4 PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}
- ${PM3_ROOT}/
${PM3_ROOT}/include/
${PM3_ROOT}/common
- ${PM3_ROOT}/common/zlib
${PM3_ROOT}/common_fpga
- ${PM3_ROOT}/common/mbedtls
- ${PM3_ROOT}/client/src
- ${PM3_ROOT}/client/src/fido
- ${PM3_ROOT}/client/src/uart
- ${PM3_ROOT}/client/deps/liblua
- ${PM3_ROOT}/client/deps/reveng
- ${PM3_ROOT}/client/deps/jansson
- ${PM3_ROOT}/client/deps/tinycbor
- ${PM3_ROOT}/client/deps/cliparser
- ${PM3_ROOT}/client/deps/hardnested)
+ ${PM3_ROOT}/client/src)
-## CPU-specific code
-## These are mostly for x86-based architectures, which is not useful for many Android devices.
-add_library(pm3rrg_rdv4_hardnested_nosimd OBJECT
- ${PM3_ROOT}/client/deps/hardnested/hardnested_bf_core.c
- ${PM3_ROOT}/client/deps/hardnested/hardnested_bitarray_core.c)
-
-target_include_directories(pm3rrg_rdv4_hardnested_nosimd PRIVATE
- ${PM3_ROOT}/common
- ${PM3_ROOT}/client
- ${PM3_ROOT}/include/
- ${PM3_ROOT}/client/deps/hardnested)
-
-set(X86_CPUS x86 x86_64 i686)
-
-message(STATUS "CMAKE_SYSTEM_PROCESSOR := ${CMAKE_SYSTEM_PROCESSOR}")
-
-if ("${CMAKE_SYSTEM_PROCESSOR}" IN_LIST X86_CPUS)
- message(STATUS "Building optimised x86/x86_64 binaries")
- target_compile_options(pm3rrg_rdv4_hardnested_nosimd BEFORE PRIVATE
- -mno-mmx -mno-sse2 -mno-avx -mno-avx2 -mno-avx512f)
-
- set_property(TARGET pm3rrg_rdv4_hardnested_nosimd PROPERTY POSITION_INDEPENDENT_CODE ON)
-
- ## x86 / MMX
- add_library(pm3rrg_rdv4_hardnested_mmx OBJECT
- ${PM3_ROOT}/client/deps/hardnested/hardnested_bf_core.c
- ${PM3_ROOT}/client/deps/hardnested/hardnested_bitarray_core.c)
-
- target_compile_options(pm3rrg_rdv4_hardnested_mmx BEFORE PRIVATE
- -mmmx -mno-sse2 -mno-avx -mno-avx2 -mno-avx512f)
-
- target_include_directories(pm3rrg_rdv4_hardnested_mmx PRIVATE
- ${PM3_ROOT}/common
- ${PM3_ROOT}/client
- ${PM3_ROOT}/include/
- ${PM3_ROOT}/client/deps/hardnested)
-
- set_property(TARGET pm3rrg_rdv4_hardnested_mmx PROPERTY POSITION_INDEPENDENT_CODE ON)
-
- ## x86 / SSE2
- add_library(pm3rrg_rdv4_hardnested_sse2 OBJECT
- ${PM3_ROOT}/client/deps/hardnested/hardnested_bf_core.c
- ${PM3_ROOT}/client/deps/hardnested/hardnested_bitarray_core.c)
-
- target_compile_options(pm3rrg_rdv4_hardnested_sse2 BEFORE PRIVATE
- -mmmx -msse2 -mno-avx -mno-avx2 -mno-avx512f)
-
- target_include_directories(pm3rrg_rdv4_hardnested_sse2 PRIVATE
- ${PM3_ROOT}/common
- ${PM3_ROOT}/client
- ${PM3_ROOT}/include/
- ${PM3_ROOT}/client/deps/hardnested)
-
- set_property(TARGET pm3rrg_rdv4_hardnested_sse2 PROPERTY POSITION_INDEPENDENT_CODE ON)
-
- ## x86 / AVX
- add_library(pm3rrg_rdv4_hardnested_avx OBJECT
- ${PM3_ROOT}/client/deps/hardnested/hardnested_bf_core.c
- ${PM3_ROOT}/client/deps/hardnested/hardnested_bitarray_core.c)
-
- target_compile_options(pm3rrg_rdv4_hardnested_avx BEFORE PRIVATE
- -mmmx -msse2 -mavx -mno-avx2 -mno-avx512f)
-
- target_include_directories(pm3rrg_rdv4_hardnested_avx PRIVATE
- ${PM3_ROOT}/common
- ${PM3_ROOT}/client
- ${PM3_ROOT}/include/
- ${PM3_ROOT}/client/deps/hardnested)
-
- set_property(TARGET pm3rrg_rdv4_hardnested_avx PROPERTY POSITION_INDEPENDENT_CODE ON)
-
- ## x86 / AVX2
- add_library(pm3rrg_rdv4_hardnested_avx2 OBJECT
- ${PM3_ROOT}/client/deps/hardnested/hardnested_bf_core.c
- ${PM3_ROOT}/client/deps/hardnested/hardnested_bitarray_core.c)
-
- target_compile_options(pm3rrg_rdv4_hardnested_avx2 BEFORE PRIVATE
- -mmmx -msse2 -mavx -mavx2 -mno-avx512f)
-
- target_include_directories(pm3rrg_rdv4_hardnested_avx2 PRIVATE
- ${PM3_ROOT}/common
- ${PM3_ROOT}/client
- ${PM3_ROOT}/include/
- ${PM3_ROOT}/client/deps/hardnested)
-
- set_property(TARGET pm3rrg_rdv4_hardnested_avx2 PROPERTY POSITION_INDEPENDENT_CODE ON)
-
- ## x86 / AVX512
- add_library(pm3rrg_rdv4_hardnested_avx512 OBJECT
- ${PM3_ROOT}/client/deps/hardnested/hardnested_bf_core.c
- ${PM3_ROOT}/client/deps/hardnested/hardnested_bitarray_core.c)
-
- target_compile_options(pm3rrg_rdv4_hardnested_avx512 BEFORE PRIVATE
- -mmmx -msse2 -mavx -mavx2 -mavx512f)
-
- target_include_directories(pm3rrg_rdv4_hardnested_avx512 PRIVATE
- ${PM3_ROOT}/common
- ${PM3_ROOT}/client
- ${PM3_ROOT}/include/
- ${PM3_ROOT}/client/deps/hardnested)
-
- set_property(TARGET pm3rrg_rdv4_hardnested_avx512 PROPERTY POSITION_INDEPENDENT_CODE ON)
-
- set(SIMD_TARGETS
- $
- $
- $
- $
- $)
-else ()
- message(STATUS "Not building optimised targets")
- set(SIMD_TARGETS)
-endif ()
-
-#定义为静态库,被最终的pm3库依赖!
-add_library(pm3rrg_rdv4_hardnested STATIC
- $
- ${SIMD_TARGETS})
+find_library(pm3rrg_rdv4_cliparser REQUIRED)
+find_library(pm3rrg_rdv4_jansson REQUIRED)
+find_library(pm3rrg_rdv4_tinycbor REQUIRED)
+find_library(pm3rrg_rdv4_lua REQUIRED)
+find_library(pm3rrg_rdv4_mbedtls REQUIRED)
+find_library(pm3rrg_rdv4_reveng REQUIRED)
+find_library(pm3rrg_rdv4_z REQUIRED)
+find_library(pm3rrg_rdv4_hardnested REQUIRED)
+target_link_libraries(pm3rrg_rdv4 pm3rrg_rdv4_hardnested pm3rrg_rdv4_mbedtls pm3rrg_rdv4_cliparser pm3rrg_rdv4_jansson pm3rrg_rdv4_lua pm3rrg_rdv4_tinycbor pm3rrg_rdv4_amiibo pm3rrg_rdv4_reveng pm3rrg_rdv4_z android log)
#添加动态库链接!
-target_link_libraries(pm3rrg_rdv4 pm3rrg_rdv4_hardnested android log z)
\ No newline at end of file
From f3790a89a525ac8385132ba3eb17d2e05ade35dd Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Wed, 6 May 2020 20:32:08 +0200
Subject: [PATCH 086/632] update argtable3
---
client/deps/cliparser/Makefile | 2 +-
client/deps/cliparser/argtable3.c | 4063 ++++++++++++++++++-----------
client/deps/cliparser/argtable3.h | 359 ++-
3 files changed, 2772 insertions(+), 1652 deletions(-)
diff --git a/client/deps/cliparser/Makefile b/client/deps/cliparser/Makefile
index 4873372c4..6fa13408a 100644
--- a/client/deps/cliparser/Makefile
+++ b/client/deps/cliparser/Makefile
@@ -1,6 +1,6 @@
MYSRCPATHS =
MYINCLUDES = -I../../../common -I../../../include -I../../src
-MYCFLAGS = -Wno-cast-align
+MYCFLAGS = -Wno-cast-align -Wno-discarded-qualifiers -Wno-bad-function-cast -Wno-redundant-decls
MYDEFS =
MYSRCS = \
argtable3.c \
diff --git a/client/deps/cliparser/argtable3.c b/client/deps/cliparser/argtable3.c
index f66c22d6d..c3d1bb9f7 100644
--- a/client/deps/cliparser/argtable3.c
+++ b/client/deps/cliparser/argtable3.c
@@ -30,19 +30,14 @@
#include "argtable3.h"
-// On Windows isspace crashes app in case of using Unicode character set and string to be above ASCII
-// so you have to use _istspace instead of space
-#ifdef UNICODE
-#include
-#define ISSPACE _istspace
-#else
-#define ISSPACE isspace
-#endif
+#define ARG_AMALGAMATION
/*******************************************************************************
+ * argtable3_private: Declares private types, constants, and interfaces
+ *
* This file is part of the argtable3 library.
*
- * Copyright (C) 2013 Tom G. Huang
+ * Copyright (C) 2013-2019 Tom G. Huang
*
* All rights reserved.
*
@@ -72,6 +67,8 @@
#ifndef ARG_UTILS_H
#define ARG_UTILS_H
+#include
+
#define ARG_ENABLE_TRACE 0
#define ARG_ENABLE_LOG 1
@@ -79,56 +76,199 @@
extern "C" {
#endif
-enum {
- EMINCOUNT = 1,
- EMAXCOUNT,
- EBADINT,
-
-// The same name define EOVERFLOW in errno.h on windows platform or android
-#if defined(__STDC_WANT_SECURE_LIB__) || defined(__ANDROID__) || defined(ANDROID)
- EOVERFLOW_,
-#else
- EOVERFLOW,
-#endif
- EBADDOUBLE,
- EBADDATE,
- EREGNOMATCH
-};
+enum { ARG_ERR_MINCOUNT = 1, ARG_ERR_MAXCOUNT, ARG_ERR_BADINT, ARG_ERR_OVERFLOW, ARG_ERR_BADDOUBLE, ARG_ERR_BADDATE, ARG_ERR_REGNOMATCH };
+typedef void(arg_panicfn)(const char* fmt, ...);
#if defined(_MSC_VER)
-#define ARG_TRACE(x) \
- __pragma(warning(push)) \
- __pragma(warning(disable:4127)) \
- do { if (ARG_ENABLE_TRACE) dbg_printf x; } while (0) \
- __pragma(warning(pop))
+#define ARG_TRACE(x) \
+ __pragma(warning(push)) __pragma(warning(disable : 4127)) do { \
+ if (ARG_ENABLE_TRACE) \
+ dbg_printf x; \
+ } \
+ while (0) \
+ __pragma(warning(pop))
-#define ARG_LOG(x) \
- __pragma(warning(push)) \
- __pragma(warning(disable:4127)) \
- do { if (ARG_ENABLE_LOG) dbg_printf x; } while (0) \
- __pragma(warning(pop))
+#define ARG_LOG(x) \
+ __pragma(warning(push)) __pragma(warning(disable : 4127)) do { \
+ if (ARG_ENABLE_LOG) \
+ dbg_printf x; \
+ } \
+ while (0) \
+ __pragma(warning(pop))
#else
-#define ARG_TRACE(x) \
- do { if (ARG_ENABLE_TRACE) dbg_printf x; } while (0)
+#define ARG_TRACE(x) \
+ do { \
+ if (ARG_ENABLE_TRACE) \
+ dbg_printf x; \
+ } while (0)
-#define ARG_LOG(x) \
- do { if (ARG_ENABLE_LOG) dbg_printf x; } while (0)
+#define ARG_LOG(x) \
+ do { \
+ if (ARG_ENABLE_LOG) \
+ dbg_printf x; \
+ } while (0)
#endif
-extern void dbg_printf(const char *fmt, ...);
+extern void dbg_printf(const char* fmt, ...);
+extern void arg_set_panic(arg_panicfn* proc);
+extern void* xmalloc(size_t size);
+extern void* xcalloc(size_t count, size_t size);
+extern void* xrealloc(void* ptr, size_t size);
+extern void xfree(void* ptr);
+
+struct arg_hashtable_entry {
+ void *k, *v;
+ unsigned int h;
+ struct arg_hashtable_entry* next;
+};
+
+typedef struct arg_hashtable {
+ unsigned int tablelength;
+ struct arg_hashtable_entry** table;
+ unsigned int entrycount;
+ unsigned int loadlimit;
+ unsigned int primeindex;
+ unsigned int (*hashfn)(const void* k);
+ int (*eqfn)(const void* k1, const void* k2);
+} arg_hashtable_t;
+
+/**
+ * @brief Create a hash table.
+ *
+ * @param minsize minimum initial size of hash table
+ * @param hashfn function for hashing keys
+ * @param eqfn function for determining key equality
+ * @return newly created hash table or NULL on failure
+ */
+arg_hashtable_t* arg_hashtable_create(unsigned int minsize, unsigned int (*hashfn)(const void*), int (*eqfn)(const void*, const void*));
+
+/**
+ * @brief This function will cause the table to expand if the insertion would take
+ * the ratio of entries to table size over the maximum load factor.
+ *
+ * This function does not check for repeated insertions with a duplicate key.
+ * The value returned when using a duplicate key is undefined -- when
+ * the hash table changes size, the order of retrieval of duplicate key
+ * entries is reversed.
+ * If in doubt, remove before insert.
+ *
+ * @param h the hash table to insert into
+ * @param k the key - hash table claims ownership and will free on removal
+ * @param v the value - does not claim ownership
+ * @return non-zero for successful insertion
+ */
+void arg_hashtable_insert(arg_hashtable_t* h, void* k, void* v);
+
+#define ARG_DEFINE_HASHTABLE_INSERT(fnname, keytype, valuetype) \
+ int fnname(arg_hashtable_t* h, keytype* k, valuetype* v) { return arg_hashtable_insert(h, k, v); }
+
+/**
+ * @brief Search the specified key in the hash table.
+ *
+ * @param h the hash table to search
+ * @param k the key to search for - does not claim ownership
+ * @return the value associated with the key, or NULL if none found
+ */
+void* arg_hashtable_search(arg_hashtable_t* h, const void* k);
+
+#define ARG_DEFINE_HASHTABLE_SEARCH(fnname, keytype, valuetype) \
+ valuetype* fnname(arg_hashtable_t* h, keytype* k) { return (valuetype*)(arg_hashtable_search(h, k)); }
+
+/**
+ * @brief Remove the specified key from the hash table.
+ *
+ * @param h the hash table to remove the item from
+ * @param k the key to search for - does not claim ownership
+ */
+void arg_hashtable_remove(arg_hashtable_t* h, const void* k);
+
+#define ARG_DEFINE_HASHTABLE_REMOVE(fnname, keytype, valuetype) \
+ valuetype* fnname(arg_hashtable_t* h, keytype* k) { return (valuetype*)(arg_hashtable_remove(h, k)); }
+
+/**
+ * @brief Return the number of keys in the hash table.
+ *
+ * @param h the hash table
+ * @return the number of items stored in the hash table
+ */
+unsigned int arg_hashtable_count(arg_hashtable_t* h);
+
+/**
+ * @brief Change the value associated with the key.
+ *
+ * function to change the value associated with a key, where there already
+ * exists a value bound to the key in the hash table.
+ * Source due to Holger Schemel.
+ *
+ * @name hashtable_change
+ * @param h the hash table
+ * @param key
+ * @param value
+ */
+int arg_hashtable_change(arg_hashtable_t* h, void* k, void* v);
+
+/**
+ * @brief Free the hash table and the memory allocated for each key-value pair.
+ *
+ * @param h the hash table
+ * @param free_values whether to call 'free' on the remaining values
+ */
+void arg_hashtable_destroy(arg_hashtable_t* h, int free_values);
+
+typedef struct arg_hashtable_itr {
+ arg_hashtable_t* h;
+ struct arg_hashtable_entry* e;
+ struct arg_hashtable_entry* parent;
+ unsigned int index;
+} arg_hashtable_itr_t;
+
+arg_hashtable_itr_t* arg_hashtable_itr_create(arg_hashtable_t* h);
+
+void arg_hashtable_itr_destroy(arg_hashtable_itr_t* itr);
+
+/**
+ * @brief Return the value of the (key,value) pair at the current position.
+ */
+extern void* arg_hashtable_itr_key(arg_hashtable_itr_t* i);
+
+/**
+ * @brief Return the value of the (key,value) pair at the current position.
+ */
+extern void* arg_hashtable_itr_value(arg_hashtable_itr_t* i);
+
+/**
+ * @brief Advance the iterator to the next element. Returns zero if advanced to end of table.
+ */
+int arg_hashtable_itr_advance(arg_hashtable_itr_t* itr);
+
+/**
+ * @brief Remove current element and advance the iterator to the next element.
+ */
+int arg_hashtable_itr_remove(arg_hashtable_itr_t* itr);
+
+/**
+ * @brief Search and overwrite the supplied iterator, to point to the entry matching the supplied key.
+ *
+ * @return Zero if not found.
+ */
+int arg_hashtable_itr_search(arg_hashtable_itr_t* itr, arg_hashtable_t* h, void* k);
+
+#define ARG_DEFINE_HASHTABLE_ITERATOR_SEARCH(fnname, keytype) \
+ int fnname(arg_hashtable_itr_t* i, arg_hashtable_t* h, keytype* k) { return (arg_hashtable_iterator_search(i, h, k)); }
#ifdef __cplusplus
}
#endif
#endif
-
/*******************************************************************************
+ * arg_utils: Implements memory, panic, and other utility functions
+ *
* This file is part of the argtable3 library.
*
- * Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
- *
+ * Copyright (C) 2013-2019 Tom G. Huang
+ *
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -154,22 +294,1010 @@ extern void dbg_printf(const char *fmt, ...);
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
+#include "argtable3.h"
+
+#ifndef ARG_AMALGAMATION
+#include "argtable3_private.h"
+#endif
+
#include
#include
+#include
+#include
+static void panic(const char* fmt, ...);
+static arg_panicfn* s_panic = panic;
-void dbg_printf(const char *fmt, ...) {
+void dbg_printf(const char* fmt, ...) {
va_list args;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
}
-#include "getopt.h"
+static void panic(const char* fmt, ...) {
+ va_list args;
+ char* s;
-/* $Id: getopt_long.c,v 1.1 2009/10/16 19:50:28 rodney Exp rodney $ */
-/* $OpenBSD: getopt_long.c,v 1.23 2007/10/31 12:34:57 chl Exp $ */
-/* $NetBSD: getopt_long.c,v 1.15 2002/01/31 22:43:40 tv Exp $ */
+ va_start(args, fmt);
+ vfprintf(stderr, fmt, args);
+ va_end(args);
+
+#if defined(_MSC_VER)
+#pragma warning(push)
+#pragma warning(disable : 4996)
+#endif
+ s = getenv("EF_DUMPCORE");
+#if defined(_MSC_VER)
+#pragma warning(pop)
+#endif
+
+ if (s != NULL && *s != '\0') {
+ abort();
+ } else {
+ exit(EXIT_FAILURE);
+ }
+}
+
+void arg_set_panic(arg_panicfn* proc) {
+ s_panic = proc;
+}
+
+void* xmalloc(size_t size) {
+ void* ret = malloc(size);
+ if (!ret) {
+ s_panic("Out of memory!\n");
+ }
+ return ret;
+}
+
+void* xcalloc(size_t count, size_t size) {
+ size_t allocated_count = count && size ? count : 1;
+ size_t allocated_size = count && size ? size : 1;
+ void* ret = calloc(allocated_count, allocated_size);
+ if (!ret) {
+ s_panic("Out of memory!\n");
+ }
+ return ret;
+}
+
+void* xrealloc(void* ptr, size_t size) {
+ size_t allocated_size = size ? size : 1;
+ void* ret = realloc(ptr, allocated_size);
+ if (!ret) {
+ s_panic("Out of memory!\n");
+ }
+ return ret;
+}
+
+void xfree(void* ptr) {
+ free(ptr);
+}
+
+static void merge(void* data, int esize, int i, int j, int k, arg_comparefn* comparefn) {
+ char* a = (char*)data;
+ char* m;
+ int ipos, jpos, mpos;
+
+ /* Initialize the counters used in merging. */
+ ipos = i;
+ jpos = j + 1;
+ mpos = 0;
+
+ /* Allocate storage for the merged elements. */
+ m = (char*)xmalloc(esize * ((k - i) + 1));
+
+ /* Continue while either division has elements to merge. */
+ while (ipos <= j || jpos <= k) {
+ if (ipos > j) {
+ /* The left division has no more elements to merge. */
+ while (jpos <= k) {
+ memcpy(&m[mpos * esize], &a[jpos * esize], esize);
+ jpos++;
+ mpos++;
+ }
+
+ continue;
+ } else if (jpos > k) {
+ /* The right division has no more elements to merge. */
+ while (ipos <= j) {
+ memcpy(&m[mpos * esize], &a[ipos * esize], esize);
+ ipos++;
+ mpos++;
+ }
+
+ continue;
+ }
+
+ /* Append the next ordered element to the merged elements. */
+ if (comparefn(&a[ipos * esize], &a[jpos * esize]) < 0) {
+ memcpy(&m[mpos * esize], &a[ipos * esize], esize);
+ ipos++;
+ mpos++;
+ } else {
+ memcpy(&m[mpos * esize], &a[jpos * esize], esize);
+ jpos++;
+ mpos++;
+ }
+ }
+
+ /* Prepare to pass back the merged data. */
+ memcpy(&a[i * esize], m, esize * ((k - i) + 1));
+ xfree(m);
+}
+
+void arg_mgsort(void* data, int size, int esize, int i, int k, arg_comparefn* comparefn) {
+ int j;
+
+ /* Stop the recursion when no more divisions can be made. */
+ if (i < k) {
+ /* Determine where to divide the elements. */
+ j = (int)(((i + k - 1)) / 2);
+
+ /* Recursively sort the two divisions. */
+ arg_mgsort(data, size, esize, i, j, comparefn);
+ arg_mgsort(data, size, esize, j + 1, k, comparefn);
+ merge(data, esize, i, j, k, comparefn);
+ }
+}
+/*******************************************************************************
+ * arg_hashtable: Implements the hash table utilities
+ *
+ * This file is part of the argtable3 library.
+ *
+ * Copyright (C) 2013-2019 Tom G. Huang
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * * Neither the name of STEWART HEITMANN nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ ******************************************************************************/
+
+#ifndef ARG_AMALGAMATION
+#include "argtable3_private.h"
+#endif
+
+#include
+#include
+#include
+#include
+
+/*
+ * This hash table module is adapted from the C hash table implementation by
+ * Christopher Clark. Here is the copyright notice from the library:
+ *
+ * Copyright (c) 2002, Christopher Clark
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * * Neither the name of the original author; nor the names of any contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
+ * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * Credit for primes table: Aaron Krowne
+ * http://br.endernet.org/~akrowne/
+ * http://planetmath.org/encyclopedia/GoodHashTablePrimes.html
+ */
+static const unsigned int primes[] = {53, 97, 193, 389, 769, 1543, 3079, 6151, 12289,
+ 24593, 49157, 98317, 196613, 393241, 786433, 1572869, 3145739, 6291469,
+ 12582917, 25165843, 50331653, 100663319, 201326611, 402653189, 805306457, 1610612741};
+const unsigned int prime_table_length = sizeof(primes) / sizeof(primes[0]);
+const float max_load_factor = (float)0.65;
+
+static unsigned int enhanced_hash(arg_hashtable_t* h, const void* k) {
+ /*
+ * Aim to protect against poor hash functions by adding logic here.
+ * The logic is taken from Java 1.4 hash table source.
+ */
+ unsigned int i = h->hashfn(k);
+ i += ~(i << 9);
+ i ^= ((i >> 14) | (i << 18)); /* >>> */
+ i += (i << 4);
+ i ^= ((i >> 10) | (i << 22)); /* >>> */
+ return i;
+}
+
+static unsigned int index_for(unsigned int tablelength, unsigned int hashvalue) {
+ return (hashvalue % tablelength);
+}
+
+arg_hashtable_t* arg_hashtable_create(unsigned int minsize, unsigned int (*hashfn)(const void*), int (*eqfn)(const void*, const void*)) {
+ arg_hashtable_t* h;
+ unsigned int pindex;
+ unsigned int size = primes[0];
+
+ /* Check requested hash table isn't too large */
+ if (minsize > (1u << 30))
+ return NULL;
+
+ /*
+ * Enforce size as prime. The reason is to avoid clustering of values
+ * into a small number of buckets (yes, distribution). A more even
+ * distributed hash table will perform more consistently.
+ */
+ for (pindex = 0; pindex < prime_table_length; pindex++) {
+ if (primes[pindex] > minsize) {
+ size = primes[pindex];
+ break;
+ }
+ }
+
+ h = (arg_hashtable_t*)xmalloc(sizeof(arg_hashtable_t));
+ h->table = (struct arg_hashtable_entry**)xmalloc(sizeof(struct arg_hashtable_entry*) * size);
+ memset(h->table, 0, size * sizeof(struct arg_hashtable_entry*));
+ h->tablelength = size;
+ h->primeindex = pindex;
+ h->entrycount = 0;
+ h->hashfn = hashfn;
+ h->eqfn = eqfn;
+ h->loadlimit = (unsigned int)ceil(size * max_load_factor);
+ return h;
+}
+
+static int arg_hashtable_expand(arg_hashtable_t* h) {
+ /* Double the size of the table to accommodate more entries */
+ struct arg_hashtable_entry** newtable;
+ struct arg_hashtable_entry* e;
+ unsigned int newsize;
+ unsigned int i;
+ unsigned int index;
+
+ /* Check we're not hitting max capacity */
+ if (h->primeindex == (prime_table_length - 1))
+ return 0;
+ newsize = primes[++(h->primeindex)];
+
+ newtable = (struct arg_hashtable_entry**)xmalloc(sizeof(struct arg_hashtable_entry*) * newsize);
+ memset(newtable, 0, newsize * sizeof(struct arg_hashtable_entry*));
+ /*
+ * This algorithm is not 'stable': it reverses the list
+ * when it transfers entries between the tables
+ */
+ for (i = 0; i < h->tablelength; i++) {
+ while (NULL != (e = h->table[i])) {
+ h->table[i] = e->next;
+ index = index_for(newsize, e->h);
+ e->next = newtable[index];
+ newtable[index] = e;
+ }
+ }
+
+ xfree(h->table);
+ h->table = newtable;
+ h->tablelength = newsize;
+ h->loadlimit = (unsigned int)ceil(newsize * max_load_factor);
+ return -1;
+}
+
+unsigned int arg_hashtable_count(arg_hashtable_t* h) {
+ return h->entrycount;
+}
+
+void arg_hashtable_insert(arg_hashtable_t* h, void* k, void* v) {
+ /* This method allows duplicate keys - but they shouldn't be used */
+ unsigned int index;
+ struct arg_hashtable_entry* e;
+ if ((h->entrycount + 1) > h->loadlimit) {
+ /*
+ * Ignore the return value. If expand fails, we should
+ * still try cramming just this value into the existing table
+ * -- we may not have memory for a larger table, but one more
+ * element may be ok. Next time we insert, we'll try expanding again.
+ */
+ arg_hashtable_expand(h);
+ }
+ e = (struct arg_hashtable_entry*)xmalloc(sizeof(struct arg_hashtable_entry));
+ e->h = enhanced_hash(h, k);
+ index = index_for(h->tablelength, e->h);
+ e->k = k;
+ e->v = v;
+ e->next = h->table[index];
+ h->table[index] = e;
+ h->entrycount++;
+}
+
+void* arg_hashtable_search(arg_hashtable_t* h, const void* k) {
+ struct arg_hashtable_entry* e;
+ unsigned int hashvalue;
+ unsigned int index;
+
+ hashvalue = enhanced_hash(h, k);
+ index = index_for(h->tablelength, hashvalue);
+ e = h->table[index];
+ while (e != NULL) {
+ /* Check hash value to short circuit heavier comparison */
+ if ((hashvalue == e->h) && (h->eqfn(k, e->k)))
+ return e->v;
+ e = e->next;
+ }
+ return NULL;
+}
+
+void arg_hashtable_remove(arg_hashtable_t* h, const void* k) {
+ /*
+ * TODO: consider compacting the table when the load factor drops enough,
+ * or provide a 'compact' method.
+ */
+
+ struct arg_hashtable_entry* e;
+ struct arg_hashtable_entry** pE;
+ unsigned int hashvalue;
+ unsigned int index;
+
+ hashvalue = enhanced_hash(h, k);
+ index = index_for(h->tablelength, hashvalue);
+ pE = &(h->table[index]);
+ e = *pE;
+ while (NULL != e) {
+ /* Check hash value to short circuit heavier comparison */
+ if ((hashvalue == e->h) && (h->eqfn(k, e->k))) {
+ *pE = e->next;
+ h->entrycount--;
+ xfree(e->k);
+ xfree(e->v);
+ xfree(e);
+ return;
+ }
+ pE = &(e->next);
+ e = e->next;
+ }
+}
+
+void arg_hashtable_destroy(arg_hashtable_t* h, int free_values) {
+ unsigned int i;
+ struct arg_hashtable_entry *e, *f;
+ struct arg_hashtable_entry** table = h->table;
+ if (free_values) {
+ for (i = 0; i < h->tablelength; i++) {
+ e = table[i];
+ while (NULL != e) {
+ f = e;
+ e = e->next;
+ xfree(f->k);
+ xfree(f->v);
+ xfree(f);
+ }
+ }
+ } else {
+ for (i = 0; i < h->tablelength; i++) {
+ e = table[i];
+ while (NULL != e) {
+ f = e;
+ e = e->next;
+ xfree(f->k);
+ xfree(f);
+ }
+ }
+ }
+ xfree(h->table);
+ xfree(h);
+}
+
+arg_hashtable_itr_t* arg_hashtable_itr_create(arg_hashtable_t* h) {
+ unsigned int i;
+ unsigned int tablelength;
+
+ arg_hashtable_itr_t* itr = (arg_hashtable_itr_t*)xmalloc(sizeof(arg_hashtable_itr_t));
+ itr->h = h;
+ itr->e = NULL;
+ itr->parent = NULL;
+ tablelength = h->tablelength;
+ itr->index = tablelength;
+ if (0 == h->entrycount)
+ return itr;
+
+ for (i = 0; i < tablelength; i++) {
+ if (h->table[i] != NULL) {
+ itr->e = h->table[i];
+ itr->index = i;
+ break;
+ }
+ }
+ return itr;
+}
+
+void arg_hashtable_itr_destroy(arg_hashtable_itr_t* itr) {
+ xfree(itr);
+}
+
+void* arg_hashtable_itr_key(arg_hashtable_itr_t* i) {
+ return i->e->k;
+}
+
+void* arg_hashtable_itr_value(arg_hashtable_itr_t* i) {
+ return i->e->v;
+}
+
+int arg_hashtable_itr_advance(arg_hashtable_itr_t* itr) {
+ unsigned int j;
+ unsigned int tablelength;
+ struct arg_hashtable_entry** table;
+ struct arg_hashtable_entry* next;
+
+ if (itr->e == NULL)
+ return 0; /* stupidity check */
+
+ next = itr->e->next;
+ if (NULL != next) {
+ itr->parent = itr->e;
+ itr->e = next;
+ return -1;
+ }
+
+ tablelength = itr->h->tablelength;
+ itr->parent = NULL;
+ if (tablelength <= (j = ++(itr->index))) {
+ itr->e = NULL;
+ return 0;
+ }
+
+ table = itr->h->table;
+ while (NULL == (next = table[j])) {
+ if (++j >= tablelength) {
+ itr->index = tablelength;
+ itr->e = NULL;
+ return 0;
+ }
+ }
+
+ itr->index = j;
+ itr->e = next;
+ return -1;
+}
+
+int arg_hashtable_itr_remove(arg_hashtable_itr_t* itr) {
+ struct arg_hashtable_entry* remember_e;
+ struct arg_hashtable_entry* remember_parent;
+ int ret;
+
+ /* Do the removal */
+ if ((itr->parent) == NULL) {
+ /* element is head of a chain */
+ itr->h->table[itr->index] = itr->e->next;
+ } else {
+ /* element is mid-chain */
+ itr->parent->next = itr->e->next;
+ }
+ /* itr->e is now outside the hashtable */
+ remember_e = itr->e;
+ itr->h->entrycount--;
+ xfree(remember_e->k);
+ xfree(remember_e->v);
+
+ /* Advance the iterator, correcting the parent */
+ remember_parent = itr->parent;
+ ret = arg_hashtable_itr_advance(itr);
+ if (itr->parent == remember_e) {
+ itr->parent = remember_parent;
+ }
+ xfree(remember_e);
+ return ret;
+}
+
+int arg_hashtable_itr_search(arg_hashtable_itr_t* itr, arg_hashtable_t* h, void* k) {
+ struct arg_hashtable_entry* e;
+ struct arg_hashtable_entry* parent;
+ unsigned int hashvalue;
+ unsigned int index;
+
+ hashvalue = enhanced_hash(h, k);
+ index = index_for(h->tablelength, hashvalue);
+
+ e = h->table[index];
+ parent = NULL;
+ while (e != NULL) {
+ /* Check hash value to short circuit heavier comparison */
+ if ((hashvalue == e->h) && (h->eqfn(k, e->k))) {
+ itr->index = index;
+ itr->e = e;
+ itr->parent = parent;
+ itr->h = h;
+ return -1;
+ }
+ parent = e;
+ e = e->next;
+ }
+ return 0;
+}
+
+int arg_hashtable_change(arg_hashtable_t* h, void* k, void* v) {
+ struct arg_hashtable_entry* e;
+ unsigned int hashvalue;
+ unsigned int index;
+
+ hashvalue = enhanced_hash(h, k);
+ index = index_for(h->tablelength, hashvalue);
+ e = h->table[index];
+ while (e != NULL) {
+ /* Check hash value to short circuit heavier comparison */
+ if ((hashvalue == e->h) && (h->eqfn(k, e->k))) {
+ xfree(e->v);
+ e->v = v;
+ return -1;
+ }
+ e = e->next;
+ }
+ return 0;
+}
+/*******************************************************************************
+ * arg_dstr: Implements the dynamic string utilities
+ *
+ * This file is part of the argtable3 library.
+ *
+ * Copyright (C) 2013-2019 Tom G. Huang
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * * Neither the name of STEWART HEITMANN nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ ******************************************************************************/
+
+#include "argtable3.h"
+
+#ifndef ARG_AMALGAMATION
+#include "argtable3_private.h"
+#endif
+
+#include
+#include
+#include
+
+#if defined(_MSC_VER)
+#pragma warning(push)
+#pragma warning(disable : 4996)
+#endif
+
+#define START_VSNBUFF 16
+
+/*
+ * This dynamic string module is adapted from TclResult.c in the Tcl library.
+ * Here is the copyright notice from the library:
+ *
+ * This software is copyrighted by the Regents of the University of
+ * California, Sun Microsystems, Inc., Scriptics Corporation, ActiveState
+ * Corporation and other parties. The following terms apply to all files
+ * associated with the software unless explicitly disclaimed in
+ * individual files.
+ *
+ * The authors hereby grant permission to use, copy, modify, distribute,
+ * and license this software and its documentation for any purpose, provided
+ * that existing copyright notices are retained in all copies and that this
+ * notice is included verbatim in any distributions. No written agreement,
+ * license, or royalty fee is required for any of the authorized uses.
+ * Modifications to this software may be copyrighted by their authors
+ * and need not follow the licensing terms described here, provided that
+ * the new terms are clearly indicated on the first page of each file where
+ * they apply.
+ *
+ * IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY
+ * FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
+ * ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
+ * DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE
+ * IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
+ * NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
+ * MODIFICATIONS.
+ *
+ * GOVERNMENT USE: If you are acquiring this software on behalf of the
+ * U.S. government, the Government shall have only "Restricted Rights"
+ * in the software and related documentation as defined in the Federal
+ * Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2). If you
+ * are acquiring the software on behalf of the Department of Defense, the
+ * software shall be classified as "Commercial Computer Software" and the
+ * Government shall have only "Restricted Rights" as defined in Clause
+ * 252.227-7014 (b) (3) of DFARs. Notwithstanding the foregoing, the
+ * authors grant the U.S. Government and others acting in its behalf
+ * permission to use and distribute the software in accordance with the
+ * terms specified in this license.
+ */
+
+typedef struct _internal_arg_dstr {
+ char* data;
+ arg_dstr_freefn* free_proc;
+ char sbuf[ARG_DSTR_SIZE + 1];
+ char* append_data;
+ int append_data_size;
+ int append_used;
+} _internal_arg_dstr_t;
+
+static void setup_append_buf(arg_dstr_t res, int newSpace);
+
+arg_dstr_t arg_dstr_create(void) {
+ _internal_arg_dstr_t* h = (_internal_arg_dstr_t*)xmalloc(sizeof(_internal_arg_dstr_t));
+ memset(h, 0, sizeof(_internal_arg_dstr_t));
+ h->sbuf[0] = 0;
+ h->data = h->sbuf;
+ h->free_proc = ARG_DSTR_STATIC;
+ return h;
+}
+
+void arg_dstr_destroy(arg_dstr_t ds) {
+ if (ds == NULL)
+ return;
+
+ arg_dstr_reset(ds);
+ xfree(ds);
+ return;
+}
+
+void arg_dstr_set(arg_dstr_t ds, char* str, arg_dstr_freefn* free_proc) {
+ int length;
+ register arg_dstr_freefn* old_free_proc = ds->free_proc;
+ char* old_result = ds->data;
+
+ if (str == NULL) {
+ ds->sbuf[0] = 0;
+ ds->data = ds->sbuf;
+ ds->free_proc = ARG_DSTR_STATIC;
+ } else if (free_proc == ARG_DSTR_VOLATILE) {
+ length = (int)strlen(str);
+ if (length > ARG_DSTR_SIZE) {
+ ds->data = (char*)xmalloc((unsigned)length + 1);
+ ds->free_proc = ARG_DSTR_DYNAMIC;
+ } else {
+ ds->data = ds->sbuf;
+ ds->free_proc = ARG_DSTR_STATIC;
+ }
+ strcpy(ds->data, str);
+ } else {
+ ds->data = str;
+ ds->free_proc = free_proc;
+ }
+
+ /*
+ * If the old result was dynamically-allocated, free it up. Do it here,
+ * rather than at the beginning, in case the new result value was part of
+ * the old result value.
+ */
+
+ if ((old_free_proc != 0) && (old_result != ds->data)) {
+ if (old_free_proc == ARG_DSTR_DYNAMIC) {
+ xfree(old_result);
+ } else {
+ (*old_free_proc)(old_result);
+ }
+ }
+
+ if ((ds->append_data != NULL) && (ds->append_data_size > 0)) {
+ xfree(ds->append_data);
+ ds->append_data = NULL;
+ ds->append_data_size = 0;
+ }
+}
+
+char* arg_dstr_cstr(arg_dstr_t ds) /* Interpreter whose result to return. */
+{
+ return ds->data;
+}
+
+void arg_dstr_cat(arg_dstr_t ds, const char* str) {
+ setup_append_buf(ds, (int)strlen(str) + 1);
+ memcpy(ds->data + strlen(ds->data), str, strlen(str));
+}
+
+void arg_dstr_catc(arg_dstr_t ds, char c) {
+ setup_append_buf(ds, 2);
+ memcpy(ds->data + strlen(ds->data), &c, 1);
+}
+
+/*
+ * The logic of the `arg_dstr_catf` function is adapted from the `bformat`
+ * function in The Better String Library by Paul Hsieh. Here is the copyright
+ * notice from the library:
+ *
+ * Copyright (c) 2014, Paul Hsieh
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution.
+ *
+ * * Neither the name of bstrlib nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+void arg_dstr_catf(arg_dstr_t ds, const char* fmt, ...) {
+ va_list arglist;
+ char* buff;
+ int n, r;
+ size_t slen;
+
+ if (fmt == NULL)
+ return;
+
+ /* Since the length is not determinable beforehand, a search is
+ performed using the truncating "vsnprintf" call (to avoid buffer
+ overflows) on increasing potential sizes for the output result. */
+
+ if ((n = (int)(2 * strlen(fmt))) < START_VSNBUFF)
+ n = START_VSNBUFF;
+
+ buff = (char*)xmalloc(n + 2);
+ memset(buff, 0, n + 2);
+
+ for (;;) {
+ va_start(arglist, fmt);
+ r = vsnprintf(buff, n + 1, fmt, arglist);
+ va_end(arglist);
+
+ slen = strlen(buff);
+ if (slen < (size_t)n)
+ break;
+
+ if (r > n)
+ n = r;
+ else
+ n += n;
+
+ xfree(buff);
+ buff = (char*)xmalloc(n + 2);
+ memset(buff, 0, n + 2);
+ }
+
+ arg_dstr_cat(ds, buff);
+ xfree(buff);
+}
+
+static void setup_append_buf(arg_dstr_t ds, int new_space) {
+ int total_space;
+
+ /*
+ * Make the append buffer larger, if that's necessary, then copy the
+ * data into the append buffer and make the append buffer the official
+ * data.
+ */
+ if (ds->data != ds->append_data) {
+ /*
+ * If the buffer is too big, then free it up so we go back to a
+ * smaller buffer. This avoids tying up memory forever after a large
+ * operation.
+ */
+ if (ds->append_data_size > 500) {
+ xfree(ds->append_data);
+ ds->append_data = NULL;
+ ds->append_data_size = 0;
+ }
+ ds->append_used = (int)strlen(ds->data);
+ } else if (ds->data[ds->append_used] != 0) {
+ /*
+ * Most likely someone has modified a result created by
+ * arg_dstr_cat et al. so that it has a different size. Just
+ * recompute the size.
+ */
+ ds->append_used = (int)strlen(ds->data);
+ }
+
+ total_space = new_space + ds->append_used;
+ if (total_space >= ds->append_data_size) {
+ char* newbuf;
+
+ if (total_space < 100) {
+ total_space = 200;
+ } else {
+ total_space *= 2;
+ }
+ newbuf = (char*)xmalloc((unsigned)total_space);
+ memset(newbuf, 0, total_space);
+ strcpy(newbuf, ds->data);
+ if (ds->append_data != NULL) {
+ xfree(ds->append_data);
+ }
+ ds->append_data = newbuf;
+ ds->append_data_size = total_space;
+ } else if (ds->data != ds->append_data) {
+ strcpy(ds->append_data, ds->data);
+ }
+
+ arg_dstr_free(ds);
+ ds->data = ds->append_data;
+}
+
+void arg_dstr_free(arg_dstr_t ds) {
+ if (ds->free_proc != NULL) {
+ if (ds->free_proc == ARG_DSTR_DYNAMIC) {
+ xfree(ds->data);
+ } else {
+ (*ds->free_proc)(ds->data);
+ }
+ ds->free_proc = NULL;
+ }
+}
+
+void arg_dstr_reset(arg_dstr_t ds) {
+ arg_dstr_free(ds);
+ if ((ds->append_data != NULL) && (ds->append_data_size > 0)) {
+ xfree(ds->append_data);
+ ds->append_data = NULL;
+ ds->append_data_size = 0;
+ }
+
+ ds->data = ds->sbuf;
+ ds->sbuf[0] = 0;
+}
+
+#if defined(_MSC_VER)
+#pragma warning(pop)
+#endif
+/* $Id: getopt.h,v 1.1 2009/10/16 19:50:28 rodney Exp rodney $ */
+/* $OpenBSD: getopt.h,v 1.1 2002/12/03 20:24:29 millert Exp $ */
+/* $NetBSD: getopt.h,v 1.4 2000/07/07 10:43:54 ad Exp $ */
+
+/*
+ * Copyright (c) 2000 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Dieter Baron and Thomas Klausner.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. All advertising materials mentioning features or use of this software
+ * must display the following acknowledgment:
+ * This product includes software developed by the NetBSD
+ * Foundation, Inc. and its contributors.
+ * 4. Neither the name of The NetBSD Foundation nor the names of its
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+ * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#if ARG_REPLACE_GETOPT == 1
+
+#ifndef _GETOPT_H_
+#define _GETOPT_H_
+
+/*
+ * GNU-like getopt_long() and 4.4BSD getsubopt()/optreset extensions
+ */
+#define no_argument 0
+#define required_argument 1
+#define optional_argument 2
+
+struct option {
+ /* name of long option */
+ const char* name;
+ /*
+ * one of no_argument, required_argument, and optional_argument:
+ * whether option takes an argument
+ */
+ int has_arg;
+ /* if not NULL, set *flag to val when option found */
+ int* flag;
+ /* if flag not NULL, value to set *flag to; else return value */
+ int val;
+};
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+int getopt_long(int, char* const*, const char*, const struct option*, int*);
+int getopt_long_only(int, char* const*, const char*, const struct option*, int*);
+#ifndef _GETOPT_DEFINED
+#define _GETOPT_DEFINED
+int getopt(int, char* const*, const char*);
+int getsubopt(char**, char* const*, char**);
+
+extern char* optarg; /* getopt(3) external variables */
+extern int opterr;
+extern int optind;
+extern int optopt;
+extern int optreset;
+extern char* suboptarg; /* getsubopt(3) external variable */
+#endif /* _GETOPT_DEFINED */
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* !_GETOPT_H_ */
+
+#else
+#include
+#endif /* ARG_REPLACE_GETOPT */
+/* $Id: getopt_long.c,v 1.1 2009/10/16 19:50:28 rodney Exp rodney $ */
+/* $OpenBSD: getopt_long.c,v 1.23 2007/10/31 12:34:57 chl Exp $ */
+/* $NetBSD: getopt_long.c,v 1.15 2002/01/31 22:43:40 tv Exp $ */
/*
* Copyright (c) 2002 Todd C. Miller
@@ -191,9 +1319,7 @@ void dbg_printf(const char *fmt, ...) {
* Materiel Command, USAF, under agreement number F39502-99-1-0512.
*/
-// $Id: getopt_long.c,v 1.1 2009/10/16 19:50:28 rodney Exp rodney $"
-
-/*-
+/*
* Copyright (c) 2000 The NetBSD Foundation, Inc.
* All rights reserved.
*
@@ -222,45 +1348,45 @@ void dbg_printf(const char *fmt, ...) {
* POSSIBILITY OF SUCH DAMAGE.
*/
-#if 0
-#include
+#include "argtable3.h"
+
+#ifndef ARG_AMALGAMATION
+#include "getopt.h"
#endif
+
#include
#include
#include
+#if ARG_REPLACE_GETOPT == 1
+int opterr = 1; /* if error message should be printed */
+int optind = 1; /* index into parent argv vector */
+int optopt = '?'; /* character checked for validity */
+int optreset; /* reset getopt */
+char* optarg; /* argument associated with option */
+#endif /* ARG_REPLACE_GETOPT */
-#define REPLACE_GETOPT /* use this getopt as the system getopt(3) */
+#define PRINT_ERROR ((opterr) && (*options != ':'))
-#ifdef REPLACE_GETOPT
-int opterr = 1; /* if error message should be printed */
-int optind = 1; /* index into parent argv vector */
-int optopt = '?'; /* character checked for validity */
-int optreset; /* reset getopt */
-const char *optarg; /* argument associated with option */
-#endif
-
-#define PRINT_ERROR ((opterr) && (*options != ':'))
-
-#define FLAG_PERMUTE 0x01 /* permute non-options to the end of argv */
-#define FLAG_ALLARGS 0x02 /* treat non-options as args to option "-1" */
-#define FLAG_LONGONLY 0x04 /* operate as getopt_long_only */
+#define FLAG_PERMUTE 0x01 /* permute non-options to the end of argv */
+#define FLAG_ALLARGS 0x02 /* treat non-options as args to option "-1" */
+#define FLAG_LONGONLY 0x04 /* operate as getopt_long_only */
/* return values */
-#define BADCH (int)'?'
-#define BADARG ((*options == ':') ? (int)':' : (int)'?')
-#define INORDER (int)1
+#define BADCH (int)'?'
+#define BADARG ((*options == ':') ? (int)':' : (int)'?')
+#define INORDER (int)1
-#define EMSG ""
+#define EMSG ""
-static int getopt_internal(int, char *const *, const char *,
- const struct option *, int *, int);
-static int parse_long_options(char *const *, const char *,
- const struct option *, int *, int);
+#if ARG_REPLACE_GETOPT == 1
+static int getopt_internal(int, char* const*, const char*, const struct option*, int*, int);
+#endif /* ARG_REPLACE_GETOPT */
+static int parse_long_options(char* const*, const char*, const struct option*, int*, int);
static int gcd(int, int);
-static void permute_args(int, int, int, char *const *);
+static void permute_args(int, int, int, char* const*);
-static const char *place = EMSG; /* option letter processing */
+static char* place = EMSG; /* option letter processing */
/* XXX: set optreset to 1 rather than these two */
static int nonopt_start = -1; /* first non option argument (for permute) */
@@ -274,41 +1400,45 @@ static const char noarg[] = "option doesn't take an argument -- %.*s";
static const char illoptchar[] = "unknown option -- %c";
static const char illoptstring[] = "unknown option -- %s";
-
-
#ifdef _WIN32
-/* Windows needs warnx(). We change the definition though:
+/*
+ * Windows needs warnx(). We change the definition though:
* 1. (another) global is defined, opterrmsg, which holds the error message
* 2. errors are always printed out on stderr w/o the program name
* Note that opterrmsg always gets set no matter what opterr is set to. The
* error message will not be printed if opterr is 0 as usual.
*/
-#include
#include
+#include
-#define MAX_OPTER_MSG_SIZE 128
+#define MAX_OPTERRMSG_SIZE 128
-extern char opterrmsg[MAX_OPTER_MSG_SIZE];
-char opterrmsg[MAX_OPTER_MSG_SIZE]; /* buffer for the last error message */
+extern char opterrmsg[MAX_OPTERRMSG_SIZE];
+char opterrmsg[MAX_OPTERRMSG_SIZE]; /* buffer for the last error message */
-static void warnx(const char *fmt, ...) {
+static void warnx(const char* fmt, ...) {
va_list ap;
va_start(ap, fmt);
- /*
- Make sure opterrmsg is always zero-terminated despite the _vsnprintf()
- implementation specifics and manually suppress the warning.
- */
- memset(opterrmsg, 0, sizeof opterrmsg);
+
+ /*
+ * Make sure opterrmsg is always zero-terminated despite the _vsnprintf()
+ * implementation specifics and manually suppress the warning.
+ */
+ memset(opterrmsg, 0, sizeof(opterrmsg));
if (fmt != NULL)
-#ifdef __STDC_WANT_SECURE_LIB__
- _vsnprintf_s(opterrmsg, MAX_OPTER_MSG_SIZE, sizeof(opterrmsg) - 1, fmt, ap);
+#if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || (defined(__STDC_SECURE_LIB__) && defined(__STDC_WANT_SECURE_LIB__))
+ _vsnprintf_s(opterrmsg, sizeof(opterrmsg), sizeof(opterrmsg) - 1, fmt, ap);
#else
_vsnprintf(opterrmsg, sizeof(opterrmsg) - 1, fmt, ap);
#endif
+
va_end(ap);
+#ifdef _MSC_VER
+#pragma warning(suppress : 6053)
+#endif
fprintf(stderr, "%s\n", opterrmsg);
}
@@ -316,12 +1446,10 @@ static void warnx(const char *fmt, ...) {
#include
#endif /*_WIN32*/
-
/*
* Compute the greatest common divisor of a and b.
*/
-static int
-gcd(int a, int b) {
+static int gcd(int a, int b) {
int c;
c = a % b;
@@ -339,44 +1467,42 @@ gcd(int a, int b) {
* from nonopt_end to opt_end (keeping the same order of arguments
* in each block).
*/
-static void
-permute_args(int panonopt_start, int panonopt_end, int opt_end,
- char *const *nargv) {
+static void permute_args(int panonopt_start, int panonopt_end, int opt_end, char* const* nargv) {
+ int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos;
+ char* swap;
/*
* compute lengths of blocks and number and size of cycles
*/
- int nnonopts = panonopt_end - panonopt_start;
- int nopts = opt_end - panonopt_end;
- int ncycle = gcd(nnonopts, nopts);
- int cyclelen = (opt_end - panonopt_start) / ncycle;
+ nnonopts = panonopt_end - panonopt_start;
+ nopts = opt_end - panonopt_end;
+ ncycle = gcd(nnonopts, nopts);
+ cyclelen = (opt_end - panonopt_start) / ncycle;
- for (int i = 0; i < ncycle; i++) {
- int cstart = panonopt_end + i;
- int pos = cstart;
- for (int j = 0; j < cyclelen; j++) {
+ for (i = 0; i < ncycle; i++) {
+ cstart = panonopt_end + i;
+ pos = cstart;
+ for (j = 0; j < cyclelen; j++) {
if (pos >= panonopt_end)
pos -= nnonopts;
else
pos += nopts;
- char *swap = nargv[pos];
+ swap = nargv[pos];
/* LINTED const cast */
- ((char **) nargv)[pos] = nargv[cstart];
+ ((char**)nargv)[pos] = nargv[cstart];
/* LINTED const cast */
- ((char **)nargv)[cstart] = swap;
+ ((char**)nargv)[cstart] = swap;
}
}
}
/*
* parse_long_options --
- * Parse long options in argc/argv argument vector.
+ * Parse long options in argc/argv argument vector.
* Returns -1 if short_too is set and the option does not match long_options.
*/
-static int
-parse_long_options(char *const *nargv, const char *options,
- const struct option *long_options, int *idx, int short_too) {
- const char *current_argv, *has_equal;
+static int parse_long_options(char* const* nargv, const char* options, const struct option* long_options, int* idx, int short_too) {
+ char *current_argv, *has_equal;
size_t current_argv_len;
int i, match;
@@ -394,8 +1520,7 @@ parse_long_options(char *const *nargv, const char *options,
for (i = 0; long_options[i].name; i++) {
/* find matching long option */
- if (strncmp(current_argv, long_options[i].name,
- current_argv_len))
+ if (strncmp(current_argv, long_options[i].name, current_argv_len))
continue;
if (strlen(long_options[i].name) == current_argv_len) {
@@ -415,18 +1540,15 @@ parse_long_options(char *const *nargv, const char *options,
else {
/* ambiguous abbreviation */
if (PRINT_ERROR)
- warnx(ambig, (int)current_argv_len,
- current_argv);
+ warnx(ambig, (int)current_argv_len, current_argv);
optopt = 0;
return (BADCH);
}
}
if (match != -1) { /* option found */
- if (long_options[match].has_arg == no_argument
- && has_equal) {
+ if (long_options[match].has_arg == no_argument && has_equal) {
if (PRINT_ERROR)
- warnx(noarg, (int)current_argv_len,
- current_argv);
+ warnx(noarg, (int)current_argv_len, current_argv);
/*
* XXX: GNU sets optopt to val regardless of flag
*/
@@ -436,27 +1558,23 @@ parse_long_options(char *const *nargv, const char *options,
optopt = 0;
return (BADARG);
}
- if (long_options[match].has_arg == required_argument ||
- long_options[match].has_arg == optional_argument) {
+ if (long_options[match].has_arg == required_argument || long_options[match].has_arg == optional_argument) {
if (has_equal)
optarg = has_equal;
- else if (long_options[match].has_arg ==
- required_argument) {
+ else if (long_options[match].has_arg == required_argument) {
/*
* optional argument doesn't use next nargv
*/
optarg = nargv[optind++];
}
}
- if ((long_options[match].has_arg == required_argument)
- && (optarg == NULL)) {
+ if ((long_options[match].has_arg == required_argument) && (optarg == NULL)) {
/*
* Missing argument; leading ':' indicates no error
* should be generated.
*/
if (PRINT_ERROR)
- warnx(recargstring,
- current_argv);
+ warnx(recargstring, current_argv);
/*
* XXX: GNU sets optopt to val regardless of flag
*/
@@ -486,21 +1604,15 @@ parse_long_options(char *const *nargv, const char *options,
return (long_options[match].val);
}
+#if ARG_REPLACE_GETOPT == 1
/*
* getopt_internal --
- * Parse argc/argv argument vector. Called by user level routines.
+ * Parse argc/argv argument vector. Called by user level routines.
*/
-static int
-getopt_internal(int nargc, char *const *nargv, const char *options,
- const struct option *long_options, int *idx, int flags) {
- char *oli; /* option letter list index */
+static int getopt_internal(int nargc, char* const* nargv, const char* options, const struct option* long_options, int* idx, int flags) {
+ char* oli; /* option letter list index */
int optchar, short_too;
static int posixly_correct = -1;
-#ifdef __STDC_WANT_SECURE_LIB__
- char *buffer = NULL;
- size_t buffer_size = 0;
- errno_t err = 0;
-#endif
if (options == NULL)
return (-1);
@@ -509,18 +1621,14 @@ getopt_internal(int nargc, char *const *nargv, const char *options,
* Disable GNU extensions if POSIXLY_CORRECT is set or options
* string begins with a '+'.
*/
-
-#ifdef __STDC_WANT_SECURE_LIB__
- if (posixly_correct == -1) {
- err = _dupenv_s(&buffer, &buffer_size, "POSIXLY_CORRECT") == 0;
- posixly_correct = buffer != NULL;
- if (buffer != NULL && err == 0) {
- free(buffer);
- }
- }
-#else
if (posixly_correct == -1)
+#if defined(_MSC_VER)
+#pragma warning(push)
+#pragma warning(disable : 4996)
+#endif
posixly_correct = (getenv("POSIXLY_CORRECT") != NULL);
+#if defined(_MSC_VER)
+#pragma warning(pop)
#endif
if (posixly_correct || *options == '+')
flags &= ~FLAG_PERMUTE;
@@ -546,8 +1654,7 @@ start:
place = EMSG;
if (nonopt_end != -1) {
/* do permutation, if we have to */
- permute_args(nonopt_start, nonopt_end,
- optind, nargv);
+ permute_args(nonopt_start, nonopt_end, optind, nargv);
optind -= nonopt_end - nonopt_start;
} else if (nonopt_start != -1) {
/*
@@ -559,8 +1666,7 @@ start:
nonopt_start = nonopt_end = -1;
return (-1);
}
- if (*(place = nargv[optind]) != '-' ||
- (place[1] == '\0' && strchr(options, '-') == NULL)) {
+ if (*(place = nargv[optind]) != '-' || (place[1] == '\0' && strchr(options, '-') == NULL)) {
place = EMSG; /* found non-option */
if (flags & FLAG_ALLARGS) {
/*
@@ -581,10 +1687,8 @@ start:
if (nonopt_start == -1)
nonopt_start = optind;
else if (nonopt_end != -1) {
- permute_args(nonopt_start, nonopt_end,
- optind, nargv);
- nonopt_start = optind -
- (nonopt_end - nonopt_start);
+ permute_args(nonopt_start, nonopt_end, optind, nargv);
+ nonopt_start = optind - (nonopt_end - nonopt_start);
nonopt_end = -1;
}
optind++;
@@ -605,8 +1709,7 @@ start:
* non-options, we have to permute.
*/
if (nonopt_end != -1) {
- permute_args(nonopt_start, nonopt_end,
- optind, nargv);
+ permute_args(nonopt_start, nonopt_end, optind, nargv);
optind -= nonopt_end - nonopt_start;
}
nonopt_start = nonopt_end = -1;
@@ -620,25 +1723,21 @@ start:
* 2) the arg is not just "-"
* 3) either the arg starts with -- we are getopt_long_only()
*/
- if (long_options != NULL && place != nargv[optind] &&
- (*place == '-' || (flags & FLAG_LONGONLY))) {
+ if (long_options != NULL && place != nargv[optind] && (*place == '-' || (flags & FLAG_LONGONLY))) {
short_too = 0;
if (*place == '-')
place++; /* --foo long option */
else if (*place != ':' && strchr(options, *place) != NULL)
short_too = 1; /* could be short option too */
- optchar = parse_long_options(nargv, options, long_options,
- idx, short_too);
+ optchar = parse_long_options(nargv, options, long_options, idx, short_too);
if (optchar != -1) {
place = EMSG;
return (optchar);
}
}
- if ((optchar = (int) * place++) == (int)':' ||
- (optchar == (int)'-' && *place != '\0') ||
- (oli = strchr(options, optchar)) == NULL) {
+ if ((optchar = (int)*place++) == (int)':' || (optchar == (int)'-' && *place != '\0') || (oli = strchr(options, optchar)) == NULL) {
/*
* If the user specified "-" and '-' isn't listed in
* options, return -1 (non-option) as per POSIX.
@@ -655,7 +1754,7 @@ start:
}
if (long_options != NULL && optchar == 'W' && oli[1] == ';') {
/* -W long-option */
- if (*place) /* no space */
+ if (*place) /* no space */
/* NOTHING */;
else if (++optind >= nargc) { /* no arg */
place = EMSG;
@@ -663,22 +1762,21 @@ start:
warnx(recargchar, optchar);
optopt = optchar;
return (BADARG);
- } else /* white space */
+ } else /* white space */
place = nargv[optind];
- optchar = parse_long_options(nargv, options, long_options,
- idx, 0);
+ optchar = parse_long_options(nargv, options, long_options, idx, 0);
place = EMSG;
return (optchar);
}
- if (*++oli != ':') { /* doesn't take argument */
+ if (*++oli != ':') { /* doesn't take argument */
if (!*place)
++optind;
- } else { /* takes (optional) argument */
+ } else { /* takes (optional) argument */
optarg = NULL;
- if (*place) /* no white space */
+ if (*place) /* no white space */
optarg = place;
- else if (oli[1] != ':') { /* arg not optional */
- if (++optind >= nargc) { /* no arg */
+ else if (oli[1] != ':') { /* arg not optional */
+ if (++optind >= nargc) { /* no arg */
place = EMSG;
if (PRINT_ERROR)
warnx(recargchar, optchar);
@@ -694,16 +1792,13 @@ start:
return (optchar);
}
-#ifdef REPLACE_GETOPT
/*
* getopt --
- * Parse argc/argv argument vector.
+ * Parse argc/argv argument vector.
*
* [eventually this will replace the BSD getopt]
*/
-int
-getopt(int nargc, char *const *nargv, const char *options) {
-
+int getopt(int nargc, char* const* nargv, const char* options) {
/*
* We don't pass FLAG_PERMUTE to getopt_internal() since
* the BSD getopt(3) (unlike GNU) has never done this.
@@ -714,32 +1809,26 @@ getopt(int nargc, char *const *nargv, const char *options) {
*/
return (getopt_internal(nargc, nargv, options, NULL, NULL, 0));
}
-#endif /* REPLACE_GETOPT */
+#endif /* ARG_REPLACE_GETOPT */
/*
* getopt_long --
- * Parse argc/argv argument vector.
+ * Parse argc/argv argument vector.
*/
-int
-getopt_long(int nargc, char *const *nargv, const char *options,
- const struct option *long_options, int *idx) {
-
- return (getopt_internal(nargc, nargv, options, long_options, idx,
- FLAG_PERMUTE));
+int getopt_long(int nargc, char* const* nargv, const char* options, const struct option* long_options, int* idx) {
+ return (getopt_internal(nargc, nargv, options, long_options, idx, FLAG_PERMUTE));
}
/*
* getopt_long_only --
- * Parse argc/argv argument vector.
+ * Parse argc/argv argument vector.
*/
-int
-getopt_long_only(int nargc, char *const *nargv, const char *options,
- const struct option *long_options, int *idx) {
-
- return (getopt_internal(nargc, nargv, options, long_options, idx,
- FLAG_PERMUTE | FLAG_LONGONLY));
+int getopt_long_only(int nargc, char* const* nargv, const char* options, const struct option* long_options, int* idx) {
+ return (getopt_internal(nargc, nargv, options, long_options, idx, FLAG_PERMUTE | FLAG_LONGONLY));
}
/*******************************************************************************
+ * arg_date: Implements the date command-line option
+ *
* This file is part of the argtable3 library.
*
* Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
@@ -769,31 +1858,32 @@ getopt_long_only(int nargc, char *const *nargv, const char *options,
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
+#include "argtable3.h"
+
+#ifndef ARG_AMALGAMATION
+#include "argtable3_private.h"
+#endif
+
#include
#include
-#include "argtable3.h"
+char* arg_strptime(const char* buf, const char* fmt, struct tm* tm);
-
-char *arg_strptime(const char *buf, const char *fmt, struct tm *tm);
-
-
-static void arg_date_resetfn(struct arg_date *parent) {
+static void arg_date_resetfn(struct arg_date* parent) {
ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent));
parent->count = 0;
}
-
-static int arg_date_scanfn(struct arg_date *parent, const char *argval) {
+static int arg_date_scanfn(struct arg_date* parent, const char* argval) {
int errorcode = 0;
if (parent->count == parent->hdr.maxcount) {
- errorcode = EMAXCOUNT;
+ errorcode = ARG_ERR_MAXCOUNT;
} else if (!argval) {
/* no argument value was given, leave parent->tmval[] unaltered but still count it */
parent->count++;
} else {
- const char *pend;
+ const char* pend;
struct tm tm = parent->tmval[parent->count];
/* parse the given argument value, store result in parent->tmval[] */
@@ -801,92 +1891,66 @@ static int arg_date_scanfn(struct arg_date *parent, const char *argval) {
if (pend && pend[0] == '\0')
parent->tmval[parent->count++] = tm;
else
- errorcode = EBADDATE;
+ errorcode = ARG_ERR_BADDATE;
}
ARG_TRACE(("%s:scanfn(%p) returns %d\n", __FILE__, parent, errorcode));
return errorcode;
}
-
-static int arg_date_checkfn(struct arg_date *parent) {
- int errorcode = (parent->count < parent->hdr.mincount) ? EMINCOUNT : 0;
+static int arg_date_checkfn(struct arg_date* parent) {
+ int errorcode = (parent->count < parent->hdr.mincount) ? ARG_ERR_MINCOUNT : 0;
ARG_TRACE(("%s:checkfn(%p) returns %d\n", __FILE__, parent, errorcode));
return errorcode;
}
-
-static void arg_date_errorfn(
- struct arg_date *parent,
- FILE *fp,
- int errorcode,
- const char *argval,
- const char *progname) {
- const char *shortopts = parent->hdr.shortopts;
- const char *longopts = parent->hdr.longopts;
- const char *datatype = parent->hdr.datatype;
+static void arg_date_errorfn(struct arg_date* parent, arg_dstr_t ds, int errorcode, const char* argval, const char* progname) {
+ const char* shortopts = parent->hdr.shortopts;
+ const char* longopts = parent->hdr.longopts;
+ const char* datatype = parent->hdr.datatype;
/* make argval NULL safe */
argval = argval ? argval : "";
- fprintf(fp, "%s: ", progname);
+ arg_dstr_catf(ds, "%s: ", progname);
switch (errorcode) {
- case EMINCOUNT:
- fputs("missing option ", fp);
- arg_print_option(fp, shortopts, longopts, datatype, "\n");
+ case ARG_ERR_MINCOUNT:
+ arg_dstr_cat(ds, "missing option ");
+ arg_print_option_ds(ds, shortopts, longopts, datatype, "\n");
break;
- case EMAXCOUNT:
- fputs("excess option ", fp);
- arg_print_option(fp, shortopts, longopts, argval, "\n");
+ case ARG_ERR_MAXCOUNT:
+ arg_dstr_cat(ds, "excess option ");
+ arg_print_option_ds(ds, shortopts, longopts, argval, "\n");
break;
- case EBADDATE: {
+ case ARG_ERR_BADDATE: {
struct tm tm;
char buff[200];
- fprintf(fp, "illegal timestamp format \"%s\"\n", argval);
+ arg_dstr_catf(ds, "illegal timestamp format \"%s\"\n", argval);
memset(&tm, 0, sizeof(tm));
arg_strptime("1999-12-31 23:59:59", "%F %H:%M:%S", &tm);
strftime(buff, sizeof(buff), parent->format, &tm);
- printf("correct format is \"%s\"\n", buff);
+ arg_dstr_catf(ds, "correct format is \"%s\"\n", buff);
break;
}
}
}
-
-struct arg_date *arg_date0(
- const char *shortopts,
- const char *longopts,
- const char *format,
- const char *datatype,
- const char *glossary) {
+struct arg_date* arg_date0(const char* shortopts, const char* longopts, const char* format, const char* datatype, const char* glossary) {
return arg_daten(shortopts, longopts, format, datatype, 0, 1, glossary);
}
-
-struct arg_date *arg_date1(
- const char *shortopts,
- const char *longopts,
- const char *format,
- const char *datatype,
- const char *glossary) {
+struct arg_date* arg_date1(const char* shortopts, const char* longopts, const char* format, const char* datatype, const char* glossary) {
return arg_daten(shortopts, longopts, format, datatype, 1, 1, glossary);
}
-
-struct arg_date *arg_daten(
- const char *shortopts,
- const char *longopts,
- const char *format,
- const char *datatype,
- int mincount,
- int maxcount,
- const char *glossary) {
+struct arg_date*
+arg_daten(const char* shortopts, const char* longopts, const char* format, const char* datatype, int mincount, int maxcount, const char* glossary) {
size_t nbytes;
- struct arg_date *result;
+ struct arg_date* result;
/* foolproof things by ensuring maxcount is not less than mincount */
maxcount = (maxcount < mincount) ? mincount : maxcount;
@@ -896,39 +1960,37 @@ struct arg_date *arg_daten(
format = "%x";
nbytes = sizeof(struct arg_date) /* storage for struct arg_date */
- + maxcount * sizeof(struct tm); /* storage for tmval[maxcount] array */
+ + maxcount * sizeof(struct tm); /* storage for tmval[maxcount] array */
/* allocate storage for the arg_date struct + tmval[] array. */
/* we use calloc because we want the tmval[] array zero filled. */
- result = (struct arg_date *)calloc(1, nbytes);
- if (result) {
- /* init the arg_hdr struct */
- result->hdr.flag = ARG_HASVALUE;
- result->hdr.shortopts = shortopts;
- result->hdr.longopts = longopts;
- result->hdr.datatype = datatype ? datatype : format;
- result->hdr.glossary = glossary;
- result->hdr.mincount = mincount;
- result->hdr.maxcount = maxcount;
- result->hdr.parent = result;
- result->hdr.resetfn = (arg_resetfn *)arg_date_resetfn;
- result->hdr.scanfn = (arg_scanfn *)arg_date_scanfn;
- result->hdr.checkfn = (arg_checkfn *)arg_date_checkfn;
- result->hdr.errorfn = (arg_errorfn *)arg_date_errorfn;
+ result = (struct arg_date*)xcalloc(1, nbytes);
- /* store the tmval[maxcount] array immediately after the arg_date struct */
- result->tmval = (struct tm *)(result + 1);
+ /* init the arg_hdr struct */
+ result->hdr.flag = ARG_HASVALUE;
+ result->hdr.shortopts = shortopts;
+ result->hdr.longopts = longopts;
+ result->hdr.datatype = datatype ? datatype : format;
+ result->hdr.glossary = glossary;
+ result->hdr.mincount = mincount;
+ result->hdr.maxcount = maxcount;
+ result->hdr.parent = result;
+ result->hdr.resetfn = (arg_resetfn*)arg_date_resetfn;
+ result->hdr.scanfn = (arg_scanfn*)arg_date_scanfn;
+ result->hdr.checkfn = (arg_checkfn*)arg_date_checkfn;
+ result->hdr.errorfn = (arg_errorfn*)arg_date_errorfn;
- /* init the remaining arg_date member variables */
- result->count = 0;
- result->format = format;
- }
+ /* store the tmval[maxcount] array immediately after the arg_date struct */
+ result->tmval = (struct tm*)(result + 1);
+
+ /* init the remaining arg_date member variables */
+ result->count = 0;
+ result->format = format;
ARG_TRACE(("arg_daten() returns %p\n", result));
return result;
}
-
/*-
* Copyright (c) 1997, 1998, 2005, 2008 The NetBSD Foundation, Inc.
* All rights reserved.
@@ -966,40 +2028,31 @@ struct arg_date *arg_daten(
* We do not implement alternate representations. However, we always
* check whether a given modifier is allowed for a certain conversion.
*/
-#define ALT_E 0x01
-#define ALT_O 0x02
-#define LEGAL_ALT(x) { if (alt_format & ~(x)) return (0); }
-#define TM_YEAR_BASE (1900)
+#define ALT_E 0x01
+#define ALT_O 0x02
+#define LEGAL_ALT(x) \
+ { \
+ if (alt_format & ~(x)) \
+ return (0); \
+ }
+#define TM_YEAR_BASE (1900)
-static int conv_num(const char * *, int *, int, int);
+static int conv_num(const char**, int*, int, int);
-static const char *day[7] = {
- "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
- "Friday", "Saturday"
-};
+static const char* day[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
-static const char *abday[7] = {
- "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
-};
+static const char* abday[7] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
-static const char *mon[12] = {
- "January", "February", "March", "April", "May", "June", "July",
- "August", "September", "October", "November", "December"
-};
+static const char* mon[12] = {"January", "February", "March", "April", "May", "June",
+ "July", "August", "September", "October", "November", "December"};
-static const char *abmon[12] = {
- "Jan", "Feb", "Mar", "Apr", "May", "Jun",
- "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
-};
+static const char* abmon[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
-static const char *am_pm[2] = {
- "AM", "PM"
-};
+static const char* am_pm[2] = {"AM", "PM"};
-
-static int arg_strcasecmp(const char *s1, const char *s2) {
- const unsigned char *us1 = (const unsigned char *)s1;
- const unsigned char *us2 = (const unsigned char *)s2;
+static int arg_strcasecmp(const char* s1, const char* s2) {
+ const unsigned char* us1 = (const unsigned char*)s1;
+ const unsigned char* us2 = (const unsigned char*)s2;
while (tolower(*us1) == tolower(*us2++))
if (*us1++ == '\0')
return 0;
@@ -1007,11 +2060,10 @@ static int arg_strcasecmp(const char *s1, const char *s2) {
return tolower(*us1) - tolower(*--us2);
}
-
-static int arg_strncasecmp(const char *s1, const char *s2, size_t n) {
+static int arg_strncasecmp(const char* s1, const char* s2, size_t n) {
if (n != 0) {
- const unsigned char *us1 = (const unsigned char *)s1;
- const unsigned char *us2 = (const unsigned char *)s2;
+ const unsigned char* us1 = (const unsigned char*)s1;
+ const unsigned char* us2 = (const unsigned char*)s2;
do {
if (tolower(*us1) != tolower(*us2++))
return tolower(*us1) - tolower(*--us2);
@@ -1024,10 +2076,9 @@ static int arg_strncasecmp(const char *s1, const char *s2, size_t n) {
return 0;
}
-
-char *arg_strptime(const char *buf, const char *fmt, struct tm *tm) {
+char* arg_strptime(const char* buf, const char* fmt, struct tm* tm) {
char c;
- const char *bp;
+ const char* bp;
size_t len = 0;
int alt_format, i, split_year = 0;
@@ -1038,8 +2089,8 @@ char *arg_strptime(const char *buf, const char *fmt, struct tm *tm) {
alt_format = 0;
/* Eat up white-space. */
- if (ISSPACE(c)) {
- while (ISSPACE(*bp))
+ if (isspace(c)) {
+ while (isspace(*bp))
bp++;
fmt++;
@@ -1049,11 +2100,10 @@ char *arg_strptime(const char *buf, const char *fmt, struct tm *tm) {
if ((c = *fmt++) != '%')
goto literal;
-
-again:
+ again:
switch (c = *fmt++) {
case '%': /* "%%" is converted to "%". */
-literal:
+ literal:
if (c != *bp++)
return (0);
break;
@@ -1312,24 +2362,20 @@ literal:
case 'n': /* Any kind of white-space. */
case 't':
LEGAL_ALT(0);
- while (ISSPACE(*bp))
+ while (isspace(*bp))
bp++;
break;
-
default: /* Unknown/unsupported conversion. */
return (0);
}
-
-
}
/* LINTED functional specification */
- return ((char *)bp);
+ return ((char*)bp);
}
-
-static int conv_num(const char * *buf, int *dest, int llim, int ulim) {
+static int conv_num(const char** buf, int* dest, int llim, int ulim) {
int result = 0;
/* The limit also determines the number of valid digits. */
@@ -1351,6 +2397,8 @@ static int conv_num(const char * *buf, int *dest, int llim, int ulim) {
return (1);
}
/*******************************************************************************
+ * arg_dbl: Implements the double command-line option
+ *
* This file is part of the argtable3 library.
*
* Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
@@ -1380,23 +2428,25 @@ static int conv_num(const char * *buf, int *dest, int llim, int ulim) {
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
-#include
-
#include "argtable3.h"
+#ifndef ARG_AMALGAMATION
+#include "argtable3_private.h"
+#endif
-static void arg_dbl_resetfn(struct arg_dbl *parent) {
+#include
+
+static void arg_dbl_resetfn(struct arg_dbl* parent) {
ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent));
parent->count = 0;
}
-
-static int arg_dbl_scanfn(struct arg_dbl *parent, const char *argval) {
+static int arg_dbl_scanfn(struct arg_dbl* parent, const char* argval) {
int errorcode = 0;
if (parent->count == parent->hdr.maxcount) {
/* maximum number of arguments exceeded */
- errorcode = EMAXCOUNT;
+ errorcode = ARG_ERR_MAXCOUNT;
} else if (!argval) {
/* a valid argument with no argument value was given. */
/* This happens when an optional argument value was invoked. */
@@ -1404,7 +2454,7 @@ static int arg_dbl_scanfn(struct arg_dbl *parent, const char *argval) {
parent->count++;
} else {
double val;
- char *end;
+ char* end;
/* extract double from argval into val */
val = strtod(argval, &end);
@@ -1413,125 +2463,101 @@ static int arg_dbl_scanfn(struct arg_dbl *parent, const char *argval) {
if (*end == 0)
parent->dval[parent->count++] = val;
else
- errorcode = EBADDOUBLE;
+ errorcode = ARG_ERR_BADDOUBLE;
}
ARG_TRACE(("%s:scanfn(%p) returns %d\n", __FILE__, parent, errorcode));
return errorcode;
}
-
-static int arg_dbl_checkfn(struct arg_dbl *parent) {
- int errorcode = (parent->count < parent->hdr.mincount) ? EMINCOUNT : 0;
+static int arg_dbl_checkfn(struct arg_dbl* parent) {
+ int errorcode = (parent->count < parent->hdr.mincount) ? ARG_ERR_MINCOUNT : 0;
ARG_TRACE(("%s:checkfn(%p) returns %d\n", __FILE__, parent, errorcode));
return errorcode;
}
-
-static void arg_dbl_errorfn(
- struct arg_dbl *parent,
- FILE *fp,
- int errorcode,
- const char *argval,
- const char *progname) {
- const char *shortopts = parent->hdr.shortopts;
- const char *longopts = parent->hdr.longopts;
- const char *datatype = parent->hdr.datatype;
+static void arg_dbl_errorfn(struct arg_dbl* parent, arg_dstr_t ds, int errorcode, const char* argval, const char* progname) {
+ const char* shortopts = parent->hdr.shortopts;
+ const char* longopts = parent->hdr.longopts;
+ const char* datatype = parent->hdr.datatype;
/* make argval NULL safe */
argval = argval ? argval : "";
- fprintf(fp, "%s: ", progname);
+ arg_dstr_catf(ds, "%s: ", progname);
switch (errorcode) {
- case EMINCOUNT:
- fputs("missing option ", fp);
- arg_print_option(fp, shortopts, longopts, datatype, "\n");
+ case ARG_ERR_MINCOUNT:
+ arg_dstr_cat(ds, "missing option ");
+ arg_print_option_ds(ds, shortopts, longopts, datatype, "\n");
break;
- case EMAXCOUNT:
- fputs("excess option ", fp);
- arg_print_option(fp, shortopts, longopts, argval, "\n");
+ case ARG_ERR_MAXCOUNT:
+ arg_dstr_cat(ds, "excess option ");
+ arg_print_option_ds(ds, shortopts, longopts, argval, "\n");
break;
- case EBADDOUBLE:
- fprintf(fp, "invalid argument \"%s\" to option ", argval);
- arg_print_option(fp, shortopts, longopts, datatype, "\n");
+ case ARG_ERR_BADDOUBLE:
+ arg_dstr_catf(ds, "invalid argument \"%s\" to option ", argval);
+ arg_print_option_ds(ds, shortopts, longopts, datatype, "\n");
break;
}
}
-
-struct arg_dbl *arg_dbl0(
- const char *shortopts,
- const char *longopts,
- const char *datatype,
- const char *glossary) {
+struct arg_dbl* arg_dbl0(const char* shortopts, const char* longopts, const char* datatype, const char* glossary) {
return arg_dbln(shortopts, longopts, datatype, 0, 1, glossary);
}
-
-struct arg_dbl *arg_dbl1(
- const char *shortopts,
- const char *longopts,
- const char *datatype,
- const char *glossary) {
+struct arg_dbl* arg_dbl1(const char* shortopts, const char* longopts, const char* datatype, const char* glossary) {
return arg_dbln(shortopts, longopts, datatype, 1, 1, glossary);
}
-
-struct arg_dbl *arg_dbln(
- const char *shortopts,
- const char *longopts,
- const char *datatype,
- int mincount,
- int maxcount,
- const char *glossary) {
+struct arg_dbl* arg_dbln(const char* shortopts, const char* longopts, const char* datatype, int mincount, int maxcount, const char* glossary) {
size_t nbytes;
- struct arg_dbl *result;
+ struct arg_dbl* result;
+ size_t addr;
+ size_t rem;
/* foolproof things by ensuring maxcount is not less than mincount */
maxcount = (maxcount < mincount) ? mincount : maxcount;
- nbytes = sizeof(struct arg_dbl) /* storage for struct arg_dbl */
+ nbytes = sizeof(struct arg_dbl) /* storage for struct arg_dbl */
+ (maxcount + 1) * sizeof(double); /* storage for dval[maxcount] array plus one extra for padding to memory boundary */
- result = (struct arg_dbl *)malloc(nbytes);
- if (result) {
- size_t addr;
- size_t rem;
+ result = (struct arg_dbl*)xmalloc(nbytes);
- /* init the arg_hdr struct */
- result->hdr.flag = ARG_HASVALUE;
- result->hdr.shortopts = shortopts;
- result->hdr.longopts = longopts;
- result->hdr.datatype = datatype ? datatype : "";
- result->hdr.glossary = glossary;
- result->hdr.mincount = mincount;
- result->hdr.maxcount = maxcount;
- result->hdr.parent = result;
- result->hdr.resetfn = (arg_resetfn *)arg_dbl_resetfn;
- result->hdr.scanfn = (arg_scanfn *)arg_dbl_scanfn;
- result->hdr.checkfn = (arg_checkfn *)arg_dbl_checkfn;
- result->hdr.errorfn = (arg_errorfn *)arg_dbl_errorfn;
+ /* init the arg_hdr struct */
+ result->hdr.flag = ARG_HASVALUE;
+ result->hdr.shortopts = shortopts;
+ result->hdr.longopts = longopts;
+ result->hdr.datatype = datatype ? datatype : "";
+ result->hdr.glossary = glossary;
+ result->hdr.mincount = mincount;
+ result->hdr.maxcount = maxcount;
+ result->hdr.parent = result;
+ result->hdr.resetfn = (arg_resetfn*)arg_dbl_resetfn;
+ result->hdr.scanfn = (arg_scanfn*)arg_dbl_scanfn;
+ result->hdr.checkfn = (arg_checkfn*)arg_dbl_checkfn;
+ result->hdr.errorfn = (arg_errorfn*)arg_dbl_errorfn;
- /* Store the dval[maxcount] array on the first double boundary that
- * immediately follows the arg_dbl struct. We do the memory alignment
- * purely for SPARC and Motorola systems. They require floats and
- * doubles to be aligned on natural boundaries.
- */
- addr = (size_t)(result + 1);
- rem = addr % sizeof(double);
- result->dval = (double *)(addr + sizeof(double) - rem);
- ARG_TRACE(("addr=%zu, dval=%p, sizeof(double)=%d rem=%d\n", addr, result->dval, (int)sizeof(double), (int)rem));
+ /* Store the dval[maxcount] array on the first double boundary that
+ * immediately follows the arg_dbl struct. We do the memory alignment
+ * purely for SPARC and Motorola systems. They require floats and
+ * doubles to be aligned on natural boundaries.
+ */
+ addr = (size_t)(result + 1);
+ rem = addr % sizeof(double);
+ result->dval = (double*)(addr + sizeof(double) - rem);
+ ARG_TRACE(("addr=%p, dval=%p, sizeof(double)=%d rem=%d\n", addr, result->dval, (int)sizeof(double), (int)rem));
- result->count = 0;
- }
+ result->count = 0;
ARG_TRACE(("arg_dbln() returns %p\n", result));
return result;
}
/*******************************************************************************
+ * arg_end: Implements the error handling utilities
+ *
* This file is part of the argtable3 library.
*
* Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
@@ -1561,108 +2587,107 @@ struct arg_dbl *arg_dbln(
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
-#include
-
#include "argtable3.h"
+#ifndef ARG_AMALGAMATION
+#include "argtable3_private.h"
+#endif
-static void arg_end_resetfn(struct arg_end *parent) {
+#include
+
+static void arg_end_resetfn(struct arg_end* parent) {
ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent));
parent->count = 0;
}
-static void arg_end_errorfn(
- void *parent,
- FILE *fp,
- int error,
- const char *argval,
- const char *progname) {
+static void arg_end_errorfn(void* parent, arg_dstr_t ds, int error, const char* argval, const char* progname) {
/* suppress unreferenced formal parameter warning */
(void)parent;
progname = progname ? progname : "";
argval = argval ? argval : "";
- fprintf(fp, "%s: ", progname);
+ arg_dstr_catf(ds, "%s: ", progname);
switch (error) {
case ARG_ELIMIT:
- fputs("too many errors to display", fp);
+ arg_dstr_cat(ds, "too many errors to display");
break;
case ARG_EMALLOC:
- fputs("insufficent memory", fp);
+ arg_dstr_cat(ds, "insufficient memory");
break;
case ARG_ENOMATCH:
- fprintf(fp, "unexpected argument \"%s\"", argval);
+ arg_dstr_catf(ds, "unexpected argument \"%s\"", argval);
break;
case ARG_EMISSARG:
- fprintf(fp, "option \"%s\" requires an argument", argval);
+ arg_dstr_catf(ds, "option \"%s\" requires an argument", argval);
break;
case ARG_ELONGOPT:
- fprintf(fp, "invalid option \"%s\"", argval);
+ arg_dstr_catf(ds, "invalid option \"%s\"", argval);
break;
default:
- fprintf(fp, "invalid option \"-%c\"", error);
+ arg_dstr_catf(ds, "invalid option \"-%c\"", error);
break;
}
- fputc('\n', fp);
+ arg_dstr_cat(ds, "\n");
}
-
-struct arg_end *arg_end(int maxcount) {
+struct arg_end* arg_end(int maxcount) {
size_t nbytes;
- struct arg_end *result;
+ struct arg_end* result;
- nbytes = sizeof(struct arg_end)
- + maxcount * sizeof(int) /* storage for int error[maxcount] array*/
- + maxcount * sizeof(void *) /* storage for void* parent[maxcount] array */
- + maxcount * sizeof(char *); /* storage for char* argval[maxcount] array */
+ nbytes = sizeof(struct arg_end) + maxcount * sizeof(int) /* storage for int error[maxcount] array*/
+ + maxcount * sizeof(void*) /* storage for void* parent[maxcount] array */
+ + maxcount * sizeof(char*); /* storage for char* argval[maxcount] array */
- result = (struct arg_end *)malloc(nbytes);
- if (result) {
- /* init the arg_hdr struct */
- result->hdr.flag = ARG_TERMINATOR;
- result->hdr.shortopts = NULL;
- result->hdr.longopts = NULL;
- result->hdr.datatype = NULL;
- result->hdr.glossary = NULL;
- result->hdr.mincount = 1;
- result->hdr.maxcount = maxcount;
- result->hdr.parent = result;
- result->hdr.resetfn = (arg_resetfn *)arg_end_resetfn;
- result->hdr.scanfn = NULL;
- result->hdr.checkfn = NULL;
- result->hdr.errorfn = (arg_errorfn *)arg_end_errorfn;
+ result = (struct arg_end*)xmalloc(nbytes);
- /* store error[maxcount] array immediately after struct arg_end */
- result->error = (int *)(result + 1);
+ /* init the arg_hdr struct */
+ result->hdr.flag = ARG_TERMINATOR;
+ result->hdr.shortopts = NULL;
+ result->hdr.longopts = NULL;
+ result->hdr.datatype = NULL;
+ result->hdr.glossary = NULL;
+ result->hdr.mincount = 1;
+ result->hdr.maxcount = maxcount;
+ result->hdr.parent = result;
+ result->hdr.resetfn = (arg_resetfn*)arg_end_resetfn;
+ result->hdr.scanfn = NULL;
+ result->hdr.checkfn = NULL;
+ result->hdr.errorfn = (arg_errorfn*)arg_end_errorfn;
- /* store parent[maxcount] array immediately after error[] array */
- result->parent = (void * *)(result->error + maxcount);
+ /* store error[maxcount] array immediately after struct arg_end */
+ result->error = (int*)(result + 1);
- /* store argval[maxcount] array immediately after parent[] array */
- result->argval = (const char * *)(result->parent + maxcount);
- }
+ /* store parent[maxcount] array immediately after error[] array */
+ result->parent = (void**)(result->error + maxcount);
+
+ /* store argval[maxcount] array immediately after parent[] array */
+ result->argval = (const char**)(result->parent + maxcount);
ARG_TRACE(("arg_end(%d) returns %p\n", maxcount, result));
return result;
}
-
-void arg_print_errors(FILE *fp, struct arg_end *end, const char *progname) {
+void arg_print_errors_ds(arg_dstr_t ds, struct arg_end* end, const char* progname) {
int i;
ARG_TRACE(("arg_errors()\n"));
for (i = 0; i < end->count; i++) {
- struct arg_hdr *errorparent = (struct arg_hdr *)(end->parent[i]);
+ struct arg_hdr* errorparent = (struct arg_hdr*)(end->parent[i]);
if (errorparent->errorfn)
- errorparent->errorfn(end->parent[i],
- fp,
- end->error[i],
- end->argval[i],
- progname);
+ errorparent->errorfn(end->parent[i], ds, end->error[i], end->argval[i], progname);
}
}
+
+void arg_print_errors(FILE* fp, struct arg_end* end, const char* progname) {
+ arg_dstr_t ds = arg_dstr_create();
+ arg_print_errors_ds(ds, end, progname);
+ fputs(arg_dstr_cstr(ds), fp);
+ arg_dstr_destroy(ds);
+}
/*******************************************************************************
+ * arg_file: Implements the file command-line option
+ *
* This file is part of the argtable3 library.
*
* Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
@@ -1692,28 +2717,30 @@ void arg_print_errors(FILE *fp, struct arg_end *end, const char *progname) {
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
-#include
-#include
-
#include "argtable3.h"
-#ifdef WIN32
-# define FILESEPARATOR1 '\\'
-# define FILESEPARATOR2 '/'
-#else
-# define FILESEPARATOR1 '/'
-# define FILESEPARATOR2 '/'
+#ifndef ARG_AMALGAMATION
+#include "argtable3_private.h"
#endif
+#include
+#include
-static void arg_file_resetfn(struct arg_file *parent) {
+#ifdef WIN32
+#define FILESEPARATOR1 '\\'
+#define FILESEPARATOR2 '/'
+#else
+#define FILESEPARATOR1 '/'
+#define FILESEPARATOR2 '/'
+#endif
+
+static void arg_file_resetfn(struct arg_file* parent) {
ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent));
parent->count = 0;
}
-
/* Returns ptr to the base filename within *filename */
-static const char *arg_basename(const char *filename) {
+static const char* arg_basename(const char* filename) {
const char *result = NULL, *result1, *result2;
/* Find the last occurrence of eother file separator character. */
@@ -1723,13 +2750,13 @@ static const char *arg_basename(const char *filename) {
result2 = (filename ? strrchr(filename, FILESEPARATOR2) : NULL);
if (result2)
- result = result2 + 1; /* using FILESEPARATOR2 (the alternative file separator) */
+ result = result2 + 1; /* using FILESEPARATOR2 (the alternative file separator) */
if (result1)
- result = result1 + 1; /* using FILESEPARATOR1 (the preferred file separator) */
+ result = result1 + 1; /* using FILESEPARATOR1 (the preferred file separator) */
if (!result)
- result = filename; /* neither file separator was found so basename is the whole filename */
+ result = filename; /* neither file separator was found so basename is the whole filename */
/* special cases of "." and ".." are not considered basenames */
if (result && (strcmp(".", result) == 0 || strcmp("..", result) == 0))
@@ -1738,11 +2765,10 @@ static const char *arg_basename(const char *filename) {
return result;
}
-
/* Returns ptr to the file extension within *basename */
-static const char *arg_extension(const char *basename) {
+static const char* arg_extension(const char* basename) {
/* find the last occurrence of '.' in basename */
- const char *result = (basename ? strrchr(basename, '.') : NULL);
+ const char* result = (basename ? strrchr(basename, '.') : NULL);
/* if no '.' was found then return pointer to end of basename */
if (basename && !result)
@@ -1759,23 +2785,22 @@ static const char *arg_extension(const char *basename) {
return result;
}
-
-static int arg_file_scanfn(struct arg_file *parent, const char *argval) {
+static int arg_file_scanfn(struct arg_file* parent, const char* argval) {
int errorcode = 0;
if (parent->count == parent->hdr.maxcount) {
/* maximum number of arguments exceeded */
- errorcode = EMAXCOUNT;
+ errorcode = ARG_ERR_MAXCOUNT;
} else if (!argval) {
/* a valid argument with no argument value was given. */
/* This happens when an optional argument value was invoked. */
/* leave parent arguiment value unaltered but still count the argument. */
parent->count++;
} else {
- parent->filename[parent->count] = argval;
- parent->basename[parent->count] = arg_basename(argval);
+ parent->filename[parent->count] = argval;
+ parent->basename[parent->count] = arg_basename(argval);
parent->extension[parent->count] =
- arg_extension(parent->basename[parent->count]); /* only seek extensions within the basename (not the file path)*/
+ arg_extension(parent->basename[parent->count]); /* only seek extensions within the basename (not the file path)*/
parent->count++;
}
@@ -1783,118 +2808,94 @@ static int arg_file_scanfn(struct arg_file *parent, const char *argval) {
return errorcode;
}
-
-static int arg_file_checkfn(struct arg_file *parent) {
- int errorcode = (parent->count < parent->hdr.mincount) ? EMINCOUNT : 0;
+static int arg_file_checkfn(struct arg_file* parent) {
+ int errorcode = (parent->count < parent->hdr.mincount) ? ARG_ERR_MINCOUNT : 0;
ARG_TRACE(("%s:checkfn(%p) returns %d\n", __FILE__, parent, errorcode));
return errorcode;
}
-
-static void arg_file_errorfn(
- struct arg_file *parent,
- FILE *fp,
- int errorcode,
- const char *argval,
- const char *progname) {
- const char *shortopts = parent->hdr.shortopts;
- const char *longopts = parent->hdr.longopts;
- const char *datatype = parent->hdr.datatype;
+static void arg_file_errorfn(struct arg_file* parent, arg_dstr_t ds, int errorcode, const char* argval, const char* progname) {
+ const char* shortopts = parent->hdr.shortopts;
+ const char* longopts = parent->hdr.longopts;
+ const char* datatype = parent->hdr.datatype;
/* make argval NULL safe */
argval = argval ? argval : "";
- fprintf(fp, "%s: ", progname);
+ arg_dstr_catf(ds, "%s: ", progname);
switch (errorcode) {
- case EMINCOUNT:
- fputs("missing option ", fp);
- arg_print_option(fp, shortopts, longopts, datatype, "\n");
+ case ARG_ERR_MINCOUNT:
+ arg_dstr_cat(ds, "missing option ");
+ arg_print_option_ds(ds, shortopts, longopts, datatype, "\n");
break;
- case EMAXCOUNT:
- fputs("excess option ", fp);
- arg_print_option(fp, shortopts, longopts, argval, "\n");
+ case ARG_ERR_MAXCOUNT:
+ arg_dstr_cat(ds, "excess option ");
+ arg_print_option_ds(ds, shortopts, longopts, argval, "\n");
break;
default:
- fprintf(fp, "unknown error at \"%s\"\n", argval);
+ arg_dstr_catf(ds, "unknown error at \"%s\"\n", argval);
}
}
-
-struct arg_file *arg_file0(
- const char *shortopts,
- const char *longopts,
- const char *datatype,
- const char *glossary) {
+struct arg_file* arg_file0(const char* shortopts, const char* longopts, const char* datatype, const char* glossary) {
return arg_filen(shortopts, longopts, datatype, 0, 1, glossary);
}
-
-struct arg_file *arg_file1(
- const char *shortopts,
- const char *longopts,
- const char *datatype,
- const char *glossary) {
+struct arg_file* arg_file1(const char* shortopts, const char* longopts, const char* datatype, const char* glossary) {
return arg_filen(shortopts, longopts, datatype, 1, 1, glossary);
}
-
-struct arg_file *arg_filen(
- const char *shortopts,
- const char *longopts,
- const char *datatype,
- int mincount,
- int maxcount,
- const char *glossary) {
+struct arg_file* arg_filen(const char* shortopts, const char* longopts, const char* datatype, int mincount, int maxcount, const char* glossary) {
size_t nbytes;
- struct arg_file *result;
+ struct arg_file* result;
+ int i;
/* foolproof things by ensuring maxcount is not less than mincount */
maxcount = (maxcount < mincount) ? mincount : maxcount;
- nbytes = sizeof(struct arg_file) /* storage for struct arg_file */
- + sizeof(char *) * maxcount /* storage for filename[maxcount] array */
- + sizeof(char *) * maxcount /* storage for basename[maxcount] array */
- + sizeof(char *) * maxcount; /* storage for extension[maxcount] array */
+ nbytes = sizeof(struct arg_file) /* storage for struct arg_file */
+ + sizeof(char*) * maxcount /* storage for filename[maxcount] array */
+ + sizeof(char*) * maxcount /* storage for basename[maxcount] array */
+ + sizeof(char*) * maxcount; /* storage for extension[maxcount] array */
- result = (struct arg_file *)malloc(nbytes);
- if (result) {
- int i;
+ result = (struct arg_file*)xmalloc(nbytes);
- /* init the arg_hdr struct */
- result->hdr.flag = ARG_HASVALUE;
- result->hdr.shortopts = shortopts;
- result->hdr.longopts = longopts;
- result->hdr.glossary = glossary;
- result->hdr.datatype = datatype ? datatype : "";
- result->hdr.mincount = mincount;
- result->hdr.maxcount = maxcount;
- result->hdr.parent = result;
- result->hdr.resetfn = (arg_resetfn *)arg_file_resetfn;
- result->hdr.scanfn = (arg_scanfn *)arg_file_scanfn;
- result->hdr.checkfn = (arg_checkfn *)arg_file_checkfn;
- result->hdr.errorfn = (arg_errorfn *)arg_file_errorfn;
+ /* init the arg_hdr struct */
+ result->hdr.flag = ARG_HASVALUE;
+ result->hdr.shortopts = shortopts;
+ result->hdr.longopts = longopts;
+ result->hdr.glossary = glossary;
+ result->hdr.datatype = datatype ? datatype : "";
+ result->hdr.mincount = mincount;
+ result->hdr.maxcount = maxcount;
+ result->hdr.parent = result;
+ result->hdr.resetfn = (arg_resetfn*)arg_file_resetfn;
+ result->hdr.scanfn = (arg_scanfn*)arg_file_scanfn;
+ result->hdr.checkfn = (arg_checkfn*)arg_file_checkfn;
+ result->hdr.errorfn = (arg_errorfn*)arg_file_errorfn;
- /* store the filename,basename,extension arrays immediately after the arg_file struct */
- result->filename = (const char * *)(result + 1);
- result->basename = result->filename + maxcount;
- result->extension = result->basename + maxcount;
- result->count = 0;
+ /* store the filename,basename,extension arrays immediately after the arg_file struct */
+ result->filename = (const char**)(result + 1);
+ result->basename = result->filename + maxcount;
+ result->extension = result->basename + maxcount;
+ result->count = 0;
- /* foolproof the string pointers by initialising them with empty strings */
- for (i = 0; i < maxcount; i++) {
- result->filename[i] = "";
- result->basename[i] = "";
- result->extension[i] = "";
- }
+ /* foolproof the string pointers by initialising them with empty strings */
+ for (i = 0; i < maxcount; i++) {
+ result->filename[i] = "";
+ result->basename[i] = "";
+ result->extension[i] = "";
}
ARG_TRACE(("arg_filen() returns %p\n", result));
return result;
}
/*******************************************************************************
+ * arg_int: Implements the int command-line option
+ *
* This file is part of the argtable3 library.
*
* Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
@@ -1924,19 +2925,21 @@ struct arg_file *arg_filen(
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
-#include
-#include
-#include
-
#include "argtable3.h"
+#ifndef ARG_AMALGAMATION
+#include "argtable3_private.h"
+#endif
-static void arg_int_resetfn(struct arg_int *parent) {
+#include
+#include
+#include
+
+static void arg_int_resetfn(struct arg_int* parent) {
ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent));
parent->count = 0;
}
-
/* strtol0x() is like strtol() except that the numeric string is */
/* expected to be prefixed by "0X" where X is a user supplied char. */
/* The string may optionally be prefixed by white space and + or - */
@@ -1947,16 +2950,13 @@ static void arg_int_resetfn(struct arg_int *parent) {
/* eg: to parse oct str="+0o12324", specify X='O' and base=8. */
/* eg: to parse bin str="-0B01010", specify X='B' and base=2. */
/* Failure of conversion is indicated by result where *endptr==str. */
-static long int strtol0X(const char *str,
- const char * *endptr,
- char X,
- int base) {
- long int val; /* stores result */
- int s = 1; /* sign is +1 or -1 */
- const char *ptr = str; /* ptr to current position in str */
+static long int strtol0X(const char* str, const char** endptr, char X, int base) {
+ long int val; /* stores result */
+ int s = 1; /* sign is +1 or -1 */
+ const char* ptr = str; /* ptr to current position in str */
/* skip leading whitespace */
- while (ISSPACE(*ptr))
+ while (isspace(*ptr))
ptr++;
/* printf("1) %s\n",ptr); */
@@ -1991,7 +2991,7 @@ static long int strtol0X(const char *str,
/* printf("4) %s\n",ptr); */
/* attempt conversion on remainder of string using strtol() */
- val = strtol(ptr, (char * *)endptr, base);
+ val = strtol(ptr, (char**)endptr, base);
if (*endptr == ptr) {
/* conversion failed */
*endptr = str;
@@ -2002,10 +3002,9 @@ static long int strtol0X(const char *str,
return s * val;
}
-
/* Returns 1 if str matches suffix (case insensitive). */
/* Str may contain trailing whitespace, but nothing else. */
-static int detectsuffix(const char *str, const char *suffix) {
+static int detectsuffix(const char* str, const char* suffix) {
/* scan pairwise through strings until mismatch detected */
while (toupper(*str) == toupper(*suffix)) {
/* printf("'%c' '%c'\n", *str, *suffix); */
@@ -2022,23 +3021,22 @@ static int detectsuffix(const char *str, const char *suffix) {
/* return 0 (fail) if the matching did not consume the entire suffix */
if (*suffix != 0)
- return 0; /* failed to consume entire suffix */
+ return 0; /* failed to consume entire suffix */
/* skip any remaining whitespace in str */
- while (ISSPACE(*str))
+ while (isspace(*str))
str++;
/* return 1 (success) if we have reached end of str else return 0 (fail) */
return (*str == '\0') ? 1 : 0;
}
-
-static int arg_int_scanfn(struct arg_int *parent, const char *argval) {
+static int arg_int_scanfn(struct arg_int* parent, const char* argval) {
int errorcode = 0;
if (parent->count == parent->hdr.maxcount) {
/* maximum number of arguments exceeded */
- errorcode = EMAXCOUNT;
+ errorcode = ARG_ERR_MAXCOUNT;
} else if (!argval) {
/* a valid argument with no argument value was given. */
/* This happens when an optional argument value was invoked. */
@@ -2046,7 +3044,7 @@ static int arg_int_scanfn(struct arg_int *parent, const char *argval) {
parent->count++;
} else {
long int val;
- const char *end;
+ const char* end;
/* attempt to extract hex integer (eg: +0x123) from argval into val conversion */
val = strtol0X(argval, &end, 'X', 16);
@@ -2058,10 +3056,10 @@ static int arg_int_scanfn(struct arg_int *parent, const char *argval) {
val = strtol0X(argval, &end, 'B', 2);
if (end == argval) {
/* binary failed, attempt decimal conversion with no prefix (eg 1234) */
- val = strtol(argval, (char * *)&end, 10);
+ val = strtol(argval, (char**)&end, 10);
if (end == argval) {
/* all supported number formats failed */
- return EBADINT;
+ return ARG_ERR_BADINT;
}
}
}
@@ -2070,131 +3068,90 @@ static int arg_int_scanfn(struct arg_int *parent, const char *argval) {
/* Safety check for integer overflow. WARNING: this check */
/* achieves nothing on machines where size(int)==size(long). */
if (val > INT_MAX || val < INT_MIN)
-#ifdef __STDC_WANT_SECURE_LIB__
- errorcode = EOVERFLOW_;
-#else
- errorcode = EOVERFLOW;
-#endif
+ errorcode = ARG_ERR_OVERFLOW;
/* Detect any suffixes (KB,MB,GB) and multiply argument value appropriately. */
/* We need to be mindful of integer overflows when using such big numbers. */
- if (detectsuffix(end, "KB")) { /* kilobytes */
+ if (detectsuffix(end, "KB")) /* kilobytes */
+ {
if (val > (INT_MAX / 1024) || val < (INT_MIN / 1024))
-#ifdef __STDC_WANT_SECURE_LIB__
- errorcode = EOVERFLOW_; /* Overflow would occur if we proceed */
-#else
- errorcode = EOVERFLOW; /* Overflow would occur if we proceed */
-#endif
+ errorcode = ARG_ERR_OVERFLOW; /* Overflow would occur if we proceed */
else
- val *= 1024; /* 1KB = 1024 */
- } else if (detectsuffix(end, "MB")) { /* megabytes */
+ val *= 1024; /* 1KB = 1024 */
+ } else if (detectsuffix(end, "MB")) /* megabytes */
+ {
if (val > (INT_MAX / 1048576) || val < (INT_MIN / 1048576))
-#ifdef __STDC_WANT_SECURE_LIB__
- errorcode = EOVERFLOW_; /* Overflow would occur if we proceed */
-#else
- errorcode = EOVERFLOW; /* Overflow would occur if we proceed */
-#endif
+ errorcode = ARG_ERR_OVERFLOW; /* Overflow would occur if we proceed */
else
- val *= 1048576; /* 1MB = 1024*1024 */
- } else if (detectsuffix(end, "GB")) { /* gigabytes */
+ val *= 1048576; /* 1MB = 1024*1024 */
+ } else if (detectsuffix(end, "GB")) /* gigabytes */
+ {
if (val > (INT_MAX / 1073741824) || val < (INT_MIN / 1073741824))
-#ifdef __STDC_WANT_SECURE_LIB__
- errorcode = EOVERFLOW_; /* Overflow would occur if we proceed */
-#else
- errorcode = EOVERFLOW; /* Overflow would occur if we proceed */
-#endif
+ errorcode = ARG_ERR_OVERFLOW; /* Overflow would occur if we proceed */
else
- val *= 1073741824; /* 1GB = 1024*1024*1024 */
+ val *= 1073741824; /* 1GB = 1024*1024*1024 */
} else if (!detectsuffix(end, ""))
- errorcode = EBADINT; /* invalid suffix detected */
+ errorcode = ARG_ERR_BADINT; /* invalid suffix detected */
/* if success then store result in parent->ival[] array */
if (errorcode == 0)
- parent->ival[parent->count++] = val;
+ parent->ival[parent->count++] = (int)val;
}
/* printf("%s:scanfn(%p,%p) returns %d\n",__FILE__,parent,argval,errorcode); */
return errorcode;
}
-
-static int arg_int_checkfn(struct arg_int *parent) {
- int errorcode = (parent->count < parent->hdr.mincount) ? EMINCOUNT : 0;
+static int arg_int_checkfn(struct arg_int* parent) {
+ int errorcode = (parent->count < parent->hdr.mincount) ? ARG_ERR_MINCOUNT : 0;
/*printf("%s:checkfn(%p) returns %d\n",__FILE__,parent,errorcode);*/
return errorcode;
}
-
-static void arg_int_errorfn(
- struct arg_int *parent,
- FILE *fp,
- int errorcode,
- const char *argval,
- const char *progname) {
- const char *shortopts = parent->hdr.shortopts;
- const char *longopts = parent->hdr.longopts;
- const char *datatype = parent->hdr.datatype;
+static void arg_int_errorfn(struct arg_int* parent, arg_dstr_t ds, int errorcode, const char* argval, const char* progname) {
+ const char* shortopts = parent->hdr.shortopts;
+ const char* longopts = parent->hdr.longopts;
+ const char* datatype = parent->hdr.datatype;
/* make argval NULL safe */
argval = argval ? argval : "";
- fprintf(fp, "%s: ", progname);
+ arg_dstr_catf(ds, "%s: ", progname);
switch (errorcode) {
- case EMINCOUNT:
- fputs("missing option ", fp);
- arg_print_option(fp, shortopts, longopts, datatype, "\n");
+ case ARG_ERR_MINCOUNT:
+ arg_dstr_cat(ds, "missing option ");
+ arg_print_option_ds(ds, shortopts, longopts, datatype, "\n");
break;
- case EMAXCOUNT:
- fputs("excess option ", fp);
- arg_print_option(fp, shortopts, longopts, argval, "\n");
+ case ARG_ERR_MAXCOUNT:
+ arg_dstr_cat(ds, "excess option ");
+ arg_print_option_ds(ds, shortopts, longopts, argval, "\n");
break;
- case EBADINT:
- fprintf(fp, "invalid argument \"%s\" to option ", argval);
- arg_print_option(fp, shortopts, longopts, datatype, "\n");
+ case ARG_ERR_BADINT:
+ arg_dstr_catf(ds, "invalid argument \"%s\" to option ", argval);
+ arg_print_option_ds(ds, shortopts, longopts, datatype, "\n");
break;
-#ifdef __STDC_WANT_SECURE_LIB__
- case EOVERFLOW_:
-#else
- case EOVERFLOW:
-#endif
- fputs("integer overflow at option ", fp);
- arg_print_option(fp, shortopts, longopts, datatype, " ");
- fprintf(fp, "(%s is too large)\n", argval);
+ case ARG_ERR_OVERFLOW:
+ arg_dstr_cat(ds, "integer overflow at option ");
+ arg_print_option_ds(ds, shortopts, longopts, datatype, " ");
+ arg_dstr_catf(ds, "(%s is too large)\n", argval);
break;
}
}
-
-struct arg_int *arg_int0(
- const char *shortopts,
- const char *longopts,
- const char *datatype,
- const char *glossary) {
+struct arg_int* arg_int0(const char* shortopts, const char* longopts, const char* datatype, const char* glossary) {
return arg_intn(shortopts, longopts, datatype, 0, 1, glossary);
}
-
-struct arg_int *arg_int1(
- const char *shortopts,
- const char *longopts,
- const char *datatype,
- const char *glossary) {
+struct arg_int* arg_int1(const char* shortopts, const char* longopts, const char* datatype, const char* glossary) {
return arg_intn(shortopts, longopts, datatype, 1, 1, glossary);
}
-
-struct arg_int *arg_intn(
- const char *shortopts,
- const char *longopts,
- const char *datatype,
- int mincount,
- int maxcount,
- const char *glossary) {
+struct arg_int* arg_intn(const char* shortopts, const char* longopts, const char* datatype, int mincount, int maxcount, const char* glossary) {
size_t nbytes;
- struct arg_int *result;
+ struct arg_int* result;
/* foolproof things by ensuring maxcount is not less than mincount */
maxcount = (maxcount < mincount) ? mincount : maxcount;
@@ -2202,31 +3159,32 @@ struct arg_int *arg_intn(
nbytes = sizeof(struct arg_int) /* storage for struct arg_int */
+ maxcount * sizeof(int); /* storage for ival[maxcount] array */
- result = (struct arg_int *)malloc(nbytes);
- if (result) {
- /* init the arg_hdr struct */
- result->hdr.flag = ARG_HASVALUE;
- result->hdr.shortopts = shortopts;
- result->hdr.longopts = longopts;
- result->hdr.datatype = datatype ? datatype : "";
- result->hdr.glossary = glossary;
- result->hdr.mincount = mincount;
- result->hdr.maxcount = maxcount;
- result->hdr.parent = result;
- result->hdr.resetfn = (arg_resetfn *)arg_int_resetfn;
- result->hdr.scanfn = (arg_scanfn *)arg_int_scanfn;
- result->hdr.checkfn = (arg_checkfn *)arg_int_checkfn;
- result->hdr.errorfn = (arg_errorfn *)arg_int_errorfn;
+ result = (struct arg_int*)xmalloc(nbytes);
- /* store the ival[maxcount] array immediately after the arg_int struct */
- result->ival = (int *)(result + 1);
- result->count = 0;
- }
+ /* init the arg_hdr struct */
+ result->hdr.flag = ARG_HASVALUE;
+ result->hdr.shortopts = shortopts;
+ result->hdr.longopts = longopts;
+ result->hdr.datatype = datatype ? datatype : "";
+ result->hdr.glossary = glossary;
+ result->hdr.mincount = mincount;
+ result->hdr.maxcount = maxcount;
+ result->hdr.parent = result;
+ result->hdr.resetfn = (arg_resetfn*)arg_int_resetfn;
+ result->hdr.scanfn = (arg_scanfn*)arg_int_scanfn;
+ result->hdr.checkfn = (arg_checkfn*)arg_int_checkfn;
+ result->hdr.errorfn = (arg_errorfn*)arg_int_errorfn;
+
+ /* store the ival[maxcount] array immediately after the arg_int struct */
+ result->ival = (int*)(result + 1);
+ result->count = 0;
ARG_TRACE(("arg_intn() returns %p\n", result));
return result;
}
/*******************************************************************************
+ * arg_lit: Implements the literature command-line option
+ *
* This file is part of the argtable3 library.
*
* Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
@@ -2256,116 +3214,96 @@ struct arg_int *arg_intn(
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
-#include
-
#include "argtable3.h"
+#ifndef ARG_AMALGAMATION
+#include "argtable3_private.h"
+#endif
-static void arg_lit_resetfn(struct arg_lit *parent) {
+#include
+
+static void arg_lit_resetfn(struct arg_lit* parent) {
ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent));
parent->count = 0;
}
-
-static int arg_lit_scanfn(struct arg_lit *parent, const char *argval) {
+static int arg_lit_scanfn(struct arg_lit* parent, const char* argval) {
int errorcode = 0;
if (parent->count < parent->hdr.maxcount)
parent->count++;
else
- errorcode = EMAXCOUNT;
+ errorcode = ARG_ERR_MAXCOUNT;
- ARG_TRACE(("%s:scanfn(%p,%s) returns %d\n", __FILE__, parent, argval,
- errorcode));
+ ARG_TRACE(("%s:scanfn(%p,%s) returns %d\n", __FILE__, parent, argval, errorcode));
return errorcode;
}
-
-static int arg_lit_checkfn(struct arg_lit *parent) {
- int errorcode = (parent->count < parent->hdr.mincount) ? EMINCOUNT : 0;
+static int arg_lit_checkfn(struct arg_lit* parent) {
+ int errorcode = (parent->count < parent->hdr.mincount) ? ARG_ERR_MINCOUNT : 0;
ARG_TRACE(("%s:checkfn(%p) returns %d\n", __FILE__, parent, errorcode));
return errorcode;
}
-
-static void arg_lit_errorfn(
- struct arg_lit *parent,
- FILE *fp,
- int errorcode,
- const char *argval,
- const char *progname) {
- const char *shortopts = parent->hdr.shortopts;
- const char *longopts = parent->hdr.longopts;
- const char *datatype = parent->hdr.datatype;
+static void arg_lit_errorfn(struct arg_lit* parent, arg_dstr_t ds, int errorcode, const char* argval, const char* progname) {
+ const char* shortopts = parent->hdr.shortopts;
+ const char* longopts = parent->hdr.longopts;
+ const char* datatype = parent->hdr.datatype;
switch (errorcode) {
- case EMINCOUNT:
- fprintf(fp, "%s: missing option ", progname);
- arg_print_option(fp, shortopts, longopts, datatype, "\n");
- fprintf(fp, "\n");
+ case ARG_ERR_MINCOUNT:
+ arg_dstr_catf(ds, "%s: missing option ", progname);
+ arg_print_option_ds(ds, shortopts, longopts, datatype, "\n");
+ arg_dstr_cat(ds, "\n");
break;
- case EMAXCOUNT:
- fprintf(fp, "%s: extraneous option ", progname);
- arg_print_option(fp, shortopts, longopts, datatype, "\n");
+ case ARG_ERR_MAXCOUNT:
+ arg_dstr_catf(ds, "%s: extraneous option ", progname);
+ arg_print_option_ds(ds, shortopts, longopts, datatype, "\n");
break;
}
- ARG_TRACE(("%s:errorfn(%p, %p, %d, %s, %s)\n", __FILE__, parent, fp,
- errorcode, argval, progname));
+ ARG_TRACE(("%s:errorfn(%p, %p, %d, %s, %s)\n", __FILE__, parent, ds, errorcode, argval, progname));
}
-
-struct arg_lit *arg_lit0(
- const char *shortopts,
- const char *longopts,
- const char *glossary) {
+struct arg_lit* arg_lit0(const char* shortopts, const char* longopts, const char* glossary) {
return arg_litn(shortopts, longopts, 0, 1, glossary);
}
-
-struct arg_lit *arg_lit1(
- const char *shortopts,
- const char *longopts,
- const char *glossary) {
+struct arg_lit* arg_lit1(const char* shortopts, const char* longopts, const char* glossary) {
return arg_litn(shortopts, longopts, 1, 1, glossary);
}
-
-struct arg_lit *arg_litn(
- const char *shortopts,
- const char *longopts,
- int mincount,
- int maxcount,
- const char *glossary) {
- struct arg_lit *result;
+struct arg_lit* arg_litn(const char* shortopts, const char* longopts, int mincount, int maxcount, const char* glossary) {
+ struct arg_lit* result;
/* foolproof things by ensuring maxcount is not less than mincount */
maxcount = (maxcount < mincount) ? mincount : maxcount;
- result = (struct arg_lit *)malloc(sizeof(struct arg_lit));
- if (result) {
- /* init the arg_hdr struct */
- result->hdr.flag = 0;
- result->hdr.shortopts = shortopts;
- result->hdr.longopts = longopts;
- result->hdr.datatype = NULL;
- result->hdr.glossary = glossary;
- result->hdr.mincount = mincount;
- result->hdr.maxcount = maxcount;
- result->hdr.parent = result;
- result->hdr.resetfn = (arg_resetfn *)arg_lit_resetfn;
- result->hdr.scanfn = (arg_scanfn *)arg_lit_scanfn;
- result->hdr.checkfn = (arg_checkfn *)arg_lit_checkfn;
- result->hdr.errorfn = (arg_errorfn *)arg_lit_errorfn;
+ result = (struct arg_lit*)xmalloc(sizeof(struct arg_lit));
- /* init local variables */
- result->count = 0;
- }
+ /* init the arg_hdr struct */
+ result->hdr.flag = 0;
+ result->hdr.shortopts = shortopts;
+ result->hdr.longopts = longopts;
+ result->hdr.datatype = NULL;
+ result->hdr.glossary = glossary;
+ result->hdr.mincount = mincount;
+ result->hdr.maxcount = maxcount;
+ result->hdr.parent = result;
+ result->hdr.resetfn = (arg_resetfn*)arg_lit_resetfn;
+ result->hdr.scanfn = (arg_scanfn*)arg_lit_scanfn;
+ result->hdr.checkfn = (arg_checkfn*)arg_lit_checkfn;
+ result->hdr.errorfn = (arg_errorfn*)arg_lit_errorfn;
+
+ /* init local variables */
+ result->count = 0;
ARG_TRACE(("arg_litn() returns %p\n", result));
return result;
}
/*******************************************************************************
+ * arg_rem: Implements the rem command-line option
+ *
* This file is part of the argtable3 library.
*
* Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
@@ -2395,32 +3333,36 @@ struct arg_lit *arg_litn(
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
-#include
-
#include "argtable3.h"
-struct arg_rem *arg_rem(const char *datatype, const char *glossary) {
- struct arg_rem *result = (struct arg_rem *)malloc(sizeof(struct arg_rem));
- if (result) {
- result->hdr.flag = 0;
- result->hdr.shortopts = NULL;
- result->hdr.longopts = NULL;
- result->hdr.datatype = datatype;
- result->hdr.glossary = glossary;
- result->hdr.mincount = 1;
- result->hdr.maxcount = 1;
- result->hdr.parent = result;
- result->hdr.resetfn = NULL;
- result->hdr.scanfn = NULL;
- result->hdr.checkfn = NULL;
- result->hdr.errorfn = NULL;
- }
+#ifndef ARG_AMALGAMATION
+#include "argtable3_private.h"
+#endif
+
+#include
+
+struct arg_rem* arg_rem(const char* datatype, const char* glossary) {
+ struct arg_rem* result = (struct arg_rem*)xmalloc(sizeof(struct arg_rem));
+
+ result->hdr.flag = 0;
+ result->hdr.shortopts = NULL;
+ result->hdr.longopts = NULL;
+ result->hdr.datatype = datatype;
+ result->hdr.glossary = glossary;
+ result->hdr.mincount = 1;
+ result->hdr.maxcount = 1;
+ result->hdr.parent = result;
+ result->hdr.resetfn = NULL;
+ result->hdr.scanfn = NULL;
+ result->hdr.checkfn = NULL;
+ result->hdr.errorfn = NULL;
ARG_TRACE(("arg_rem() returns %p\n", result));
return result;
}
-
/*******************************************************************************
+ * arg_rex: Implements the regex command-line option
+ *
* This file is part of the argtable3 library.
*
* Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
@@ -2450,58 +3392,54 @@ struct arg_rem *arg_rem(const char *datatype, const char *glossary) {
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
+#include "argtable3.h"
+
+#ifndef ARG_AMALGAMATION
+#include "argtable3_private.h"
+#endif
+
#include
#include
-#include "argtable3.h"
-
-
#ifndef _TREX_H_
#define _TREX_H_
-/***************************************************************
- T-Rex a tiny regular expression library
- Copyright (C) 2003-2006 Alberto Demichelis
-
- This software is provided 'as-is', without any express
- or implied warranty. In no event will the authors be held
- liable for any damages arising from the use of this software.
-
- Permission is granted to anyone to use this software for
- any purpose, including commercial applications, and to alter
- it and redistribute it freely, subject to the following restrictions:
-
- 1. The origin of this software must not be misrepresented;
- you must not claim that you wrote the original software.
- If you use this software in a product, an acknowledgment
- in the product documentation would be appreciated but
- is not required.
-
- 2. Altered source versions must be plainly marked as such,
- and must not be misrepresented as being the original software.
-
- 3. This notice may not be removed or altered from any
- source distribution.
-
-****************************************************************/
+/*
+ * This module uses the T-Rex regular expression library to implement the regex
+ * logic. Here is the copyright notice of the library:
+ *
+ * Copyright (C) 2003-2006 Alberto Demichelis
+ *
+ * This software is provided 'as-is', without any express
+ * or implied warranty. In no event will the authors be held
+ * liable for any damages arising from the use of this software.
+ *
+ * Permission is granted to anyone to use this software for
+ * any purpose, including commercial applications, and to alter
+ * it and redistribute it freely, subject to the following restrictions:
+ *
+ * 1. The origin of this software must not be misrepresented;
+ * you must not claim that you wrote the original software.
+ * If you use this software in a product, an acknowledgment
+ * in the product documentation would be appreciated but
+ * is not required.
+ *
+ * 2. Altered source versions must be plainly marked as such,
+ * and must not be misrepresented as being the original software.
+ *
+ * 3. This notice may not be removed or altered from any
+ * source distribution.
+ */
#ifdef __cplusplus
extern "C" {
#endif
-#ifdef _UNICODE
-#define TRexChar unsigned short
-#define MAX_CHAR 0xFFFF
-#define _TREXC(c) L##c
-#define trex_strlen wcslen
-#define trex_printf wprintf
-#else
#define TRexChar char
#define MAX_CHAR 0xFF
#define _TREXC(c) (c)
#define trex_strlen strlen
#define trex_printf printf
-#endif
#ifndef TREX_API
#define TREX_API extern
@@ -2516,17 +3454,18 @@ typedef unsigned int TRexBool;
typedef struct TRex TRex;
typedef struct {
- const TRexChar *begin;
+ const TRexChar* begin;
int len;
} TRexMatch;
-TREX_API TRex *trex_compile(const TRexChar *pattern, const TRexChar **error, int flags);
-TREX_API void trex_free(TRex *exp);
-TREX_API TRexBool trex_match(TRex *exp, const TRexChar *text);
-TREX_API TRexBool trex_search(TRex *exp, const TRexChar *text, const TRexChar **out_begin, const TRexChar **out_end);
-TREX_API TRexBool trex_searchrange(TRex *exp, const TRexChar *text_begin, const TRexChar *text_end, const TRexChar **out_begin, const TRexChar **out_end);
-TREX_API int trex_getsubexpcount(TRex *exp);
-TREX_API TRexBool trex_getsubexp(TRex *exp, int n, TRexMatch *subexp);
+TREX_API TRex* trex_compile(const TRexChar* pattern, const TRexChar** error, int flags);
+TREX_API void trex_free(TRex* exp);
+TREX_API TRexBool trex_match(TRex* exp, const TRexChar* text);
+TREX_API TRexBool trex_search(TRex* exp, const TRexChar* text, const TRexChar** out_begin, const TRexChar** out_end);
+TREX_API TRexBool
+trex_searchrange(TRex* exp, const TRexChar* text_begin, const TRexChar* text_end, const TRexChar** out_begin, const TRexChar** out_end);
+TREX_API int trex_getsubexpcount(TRex* exp);
+TREX_API TRexBool trex_getsubexp(TRex* exp, int n, TRexMatch* subexp);
#ifdef __cplusplus
}
@@ -2534,35 +3473,32 @@ TREX_API TRexBool trex_getsubexp(TRex *exp, int n, TRexMatch *subexp);
#endif
-
-
struct privhdr {
- const char *pattern;
+ const char* pattern;
int flags;
};
-
-static void arg_rex_resetfn(struct arg_rex *parent) {
+static void arg_rex_resetfn(struct arg_rex* parent) {
ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent));
parent->count = 0;
}
-static int arg_rex_scanfn(struct arg_rex *parent, const char *argval) {
+static int arg_rex_scanfn(struct arg_rex* parent, const char* argval) {
int errorcode = 0;
- const TRexChar *error = NULL;
- TRex *rex = NULL;
- TRexBool is_match;
+ const TRexChar* error = NULL;
+ TRex* rex = NULL;
+ TRexBool is_match = TRex_False;
if (parent->count == parent->hdr.maxcount) {
/* maximum number of arguments exceeded */
- errorcode = EMAXCOUNT;
+ errorcode = ARG_ERR_MAXCOUNT;
} else if (!argval) {
/* a valid argument with no argument value was given. */
/* This happens when an optional argument value was invoked. */
/* leave parent argument value unaltered but still count the argument. */
parent->count++;
} else {
- struct privhdr *priv = (struct privhdr *)parent->hdr.priv;
+ struct privhdr* priv = (struct privhdr*)parent->hdr.priv;
/* test the current argument value for a match with the regular expression */
/* if a match is detected, record the argument value in the arg_rex struct */
@@ -2570,7 +3506,7 @@ static int arg_rex_scanfn(struct arg_rex *parent, const char *argval) {
rex = trex_compile(priv->pattern, &error, priv->flags);
is_match = trex_match(rex, argval);
if (!is_match)
- errorcode = EREGNOMATCH;
+ errorcode = ARG_ERR_REGNOMATCH;
else
parent->sval[parent->count++] = argval;
@@ -2581,107 +3517,79 @@ static int arg_rex_scanfn(struct arg_rex *parent, const char *argval) {
return errorcode;
}
-static int arg_rex_checkfn(struct arg_rex *parent) {
- int errorcode = (parent->count < parent->hdr.mincount) ? EMINCOUNT : 0;
- //struct privhdr *priv = (struct privhdr*)parent->hdr.priv;
+static int arg_rex_checkfn(struct arg_rex* parent) {
+ int errorcode = (parent->count < parent->hdr.mincount) ? ARG_ERR_MINCOUNT : 0;
+#if 0
+ struct privhdr *priv = (struct privhdr*)parent->hdr.priv;
/* free the regex "program" we constructed in resetfn */
- //regfree(&(priv->regex));
+ regfree(&(priv->regex));
/*printf("%s:checkfn(%p) returns %d\n",__FILE__,parent,errorcode);*/
+#endif
return errorcode;
}
-static void arg_rex_errorfn(struct arg_rex *parent,
- FILE *fp,
- int errorcode,
- const char *argval,
- const char *progname) {
- const char *shortopts = parent->hdr.shortopts;
- const char *longopts = parent->hdr.longopts;
- const char *datatype = parent->hdr.datatype;
+static void arg_rex_errorfn(struct arg_rex* parent, arg_dstr_t ds, int errorcode, const char* argval, const char* progname) {
+ const char* shortopts = parent->hdr.shortopts;
+ const char* longopts = parent->hdr.longopts;
+ const char* datatype = parent->hdr.datatype;
/* make argval NULL safe */
argval = argval ? argval : "";
- fprintf(fp, "%s: ", progname);
+ arg_dstr_catf(ds, "%s: ", progname);
switch (errorcode) {
- case EMINCOUNT:
- fputs("missing option ", fp);
- arg_print_option(fp, shortopts, longopts, datatype, "\n");
+ case ARG_ERR_MINCOUNT:
+ arg_dstr_cat(ds, "missing option ");
+ arg_print_option_ds(ds, shortopts, longopts, datatype, "\n");
break;
- case EMAXCOUNT:
- fputs("excess option ", fp);
- arg_print_option(fp, shortopts, longopts, argval, "\n");
+ case ARG_ERR_MAXCOUNT:
+ arg_dstr_cat(ds, "excess option ");
+ arg_print_option_ds(ds, shortopts, longopts, argval, "\n");
break;
- case EREGNOMATCH:
- fputs("illegal value ", fp);
- arg_print_option(fp, shortopts, longopts, argval, "\n");
+ case ARG_ERR_REGNOMATCH:
+ arg_dstr_cat(ds, "illegal value ");
+ arg_print_option_ds(ds, shortopts, longopts, argval, "\n");
break;
default: {
- //char errbuff[256];
- //regerror(errorcode, NULL, errbuff, sizeof(errbuff));
- //printf("%s\n", errbuff);
- }
- break;
+ #if 0
+ char errbuff[256];
+ regerror(errorcode, NULL, errbuff, sizeof(errbuff));
+ printf("%s\n", errbuff);
+ #endif
+ } break;
}
}
-
-struct arg_rex *arg_rex0(const char *shortopts,
- const char *longopts,
- const char *pattern,
- const char *datatype,
- int flags,
- const char *glossary) {
- return arg_rexn(shortopts,
- longopts,
- pattern,
- datatype,
- 0,
- 1,
- flags,
- glossary);
+struct arg_rex* arg_rex0(const char* shortopts, const char* longopts, const char* pattern, const char* datatype, int flags, const char* glossary) {
+ return arg_rexn(shortopts, longopts, pattern, datatype, 0, 1, flags, glossary);
}
-struct arg_rex *arg_rex1(const char *shortopts,
- const char *longopts,
- const char *pattern,
- const char *datatype,
- int flags,
- const char *glossary) {
- return arg_rexn(shortopts,
- longopts,
- pattern,
- datatype,
- 1,
- 1,
- flags,
- glossary);
+struct arg_rex* arg_rex1(const char* shortopts, const char* longopts, const char* pattern, const char* datatype, int flags, const char* glossary) {
+ return arg_rexn(shortopts, longopts, pattern, datatype, 1, 1, flags, glossary);
}
-
-struct arg_rex *arg_rexn(const char *shortopts,
- const char *longopts,
- const char *pattern,
- const char *datatype,
+struct arg_rex* arg_rexn(const char* shortopts,
+ const char* longopts,
+ const char* pattern,
+ const char* datatype,
int mincount,
int maxcount,
int flags,
- const char *glossary) {
+ const char* glossary) {
size_t nbytes;
- struct arg_rex *result;
- struct privhdr *priv;
+ struct arg_rex* result;
+ struct privhdr* priv;
int i;
- const TRexChar *error = NULL;
- TRex *rex = NULL;
+ const TRexChar* error = NULL;
+ TRex* rex = NULL;
if (!pattern) {
- printf(
- "argtable: ERROR - illegal regular expression pattern \"(NULL)\"\n");
+ printf("argtable: ERROR - illegal regular expression pattern \"(NULL)\"\n");
printf("argtable: Bad argument table.\n");
return NULL;
}
@@ -2689,36 +3597,33 @@ struct arg_rex *arg_rexn(const char *shortopts,
/* foolproof things by ensuring maxcount is not less than mincount */
maxcount = (maxcount < mincount) ? mincount : maxcount;
- nbytes = sizeof(struct arg_rex) /* storage for struct arg_rex */
- + sizeof(struct privhdr) /* storage for private arg_rex data */
- + maxcount * sizeof(char *); /* storage for sval[maxcount] array */
-
- result = (struct arg_rex *)malloc(nbytes);
- if (result == NULL)
- return result;
+ nbytes = sizeof(struct arg_rex) /* storage for struct arg_rex */
+ + sizeof(struct privhdr) /* storage for private arg_rex data */
+ + maxcount * sizeof(char*); /* storage for sval[maxcount] array */
/* init the arg_hdr struct */
- result->hdr.flag = ARG_HASVALUE;
+ result = (struct arg_rex*)xmalloc(nbytes);
+ result->hdr.flag = ARG_HASVALUE;
result->hdr.shortopts = shortopts;
- result->hdr.longopts = longopts;
- result->hdr.datatype = datatype ? datatype : pattern;
- result->hdr.glossary = glossary;
- result->hdr.mincount = mincount;
- result->hdr.maxcount = maxcount;
- result->hdr.parent = result;
- result->hdr.resetfn = (arg_resetfn *)arg_rex_resetfn;
- result->hdr.scanfn = (arg_scanfn *)arg_rex_scanfn;
- result->hdr.checkfn = (arg_checkfn *)arg_rex_checkfn;
- result->hdr.errorfn = (arg_errorfn *)arg_rex_errorfn;
+ result->hdr.longopts = longopts;
+ result->hdr.datatype = datatype ? datatype : pattern;
+ result->hdr.glossary = glossary;
+ result->hdr.mincount = mincount;
+ result->hdr.maxcount = maxcount;
+ result->hdr.parent = result;
+ result->hdr.resetfn = (arg_resetfn*)arg_rex_resetfn;
+ result->hdr.scanfn = (arg_scanfn*)arg_rex_scanfn;
+ result->hdr.checkfn = (arg_checkfn*)arg_rex_checkfn;
+ result->hdr.errorfn = (arg_errorfn*)arg_rex_errorfn;
/* store the arg_rex_priv struct immediately after the arg_rex struct */
- result->hdr.priv = result + 1;
- priv = (struct privhdr *)(result->hdr.priv);
+ result->hdr.priv = result + 1;
+ priv = (struct privhdr*)(result->hdr.priv);
priv->pattern = pattern;
priv->flags = flags;
/* store the sval[maxcount] array immediately after the arg_rex_priv struct */
- result->sval = (const char * *)(priv + 1);
+ result->sval = (const char**)(priv + 1);
result->count = 0;
/* foolproof the string pointers by initializing them to reference empty strings */
@@ -2743,13 +3648,11 @@ struct arg_rex *arg_rexn(const char *shortopts,
return result;
}
-
-
/* see copyright notice in trex.h */
-#include
-#include
#include
#include
+#include
+#include
#ifdef _UINCODE
#define scisprint iswprint
@@ -2766,27 +3669,24 @@ struct arg_rex *arg_rexn(const char *shortopts,
#ifdef _DEBUG
#include
-static const TRexChar *g_nnames[] = {
- _SC("NONE"), _SC("OP_GREEDY"), _SC("OP_OR"),
- _SC("OP_EXPR"), _SC("OP_NOCAPEXPR"), _SC("OP_DOT"), _SC("OP_CLASS"),
- _SC("OP_CCLASS"), _SC("OP_NCLASS"), _SC("OP_RANGE"), _SC("OP_CHAR"),
- _SC("OP_EOL"), _SC("OP_BOL"), _SC("OP_WB")
-};
+static const TRexChar* g_nnames[] = {_SC("NONE"), _SC("OP_GREEDY"), _SC("OP_OR"), _SC("OP_EXPR"), _SC("OP_NOCAPEXPR"),
+ _SC("OP_DOT"), _SC("OP_CLASS"), _SC("OP_CCLASS"), _SC("OP_NCLASS"), _SC("OP_RANGE"),
+ _SC("OP_CHAR"), _SC("OP_EOL"), _SC("OP_BOL"), _SC("OP_WB")};
#endif
-#define OP_GREEDY (MAX_CHAR+1) // * + ? {n}
-#define OP_OR (MAX_CHAR+2)
-#define OP_EXPR (MAX_CHAR+3) //parentesis ()
-#define OP_NOCAPEXPR (MAX_CHAR+4) //parentesis (?:)
-#define OP_DOT (MAX_CHAR+5)
-#define OP_CLASS (MAX_CHAR+6)
-#define OP_CCLASS (MAX_CHAR+7)
-#define OP_NCLASS (MAX_CHAR+8) //negates class the [^
-#define OP_RANGE (MAX_CHAR+9)
-#define OP_CHAR (MAX_CHAR+10)
-#define OP_EOL (MAX_CHAR+11)
-#define OP_BOL (MAX_CHAR+12)
-#define OP_WB (MAX_CHAR+13)
+#define OP_GREEDY (MAX_CHAR + 1) /* * + ? {n} */
+#define OP_OR (MAX_CHAR + 2)
+#define OP_EXPR (MAX_CHAR + 3) /* parentesis () */
+#define OP_NOCAPEXPR (MAX_CHAR + 4) /* parentesis (?:) */
+#define OP_DOT (MAX_CHAR + 5)
+#define OP_CLASS (MAX_CHAR + 6)
+#define OP_CCLASS (MAX_CHAR + 7)
+#define OP_NCLASS (MAX_CHAR + 8) /* negates class the [^ */
+#define OP_RANGE (MAX_CHAR + 9)
+#define OP_CHAR (MAX_CHAR + 10)
+#define OP_EOL (MAX_CHAR + 11)
+#define OP_BOL (MAX_CHAR + 12)
+#define OP_WB (MAX_CHAR + 13)
#define TREX_SYMBOL_ANY_CHAR ('.')
#define TREX_SYMBOL_GREEDY_ONE_OR_MORE ('+')
@@ -2797,7 +3697,6 @@ static const TRexChar *g_nnames[] = {
#define TREX_SYMBOL_BEGINNING_OF_STRING ('^')
#define TREX_SYMBOL_ESCAPE_CHAR ('\\')
-
typedef int TRexNodeType;
typedef struct tagTRexNode {
@@ -2808,25 +3707,25 @@ typedef struct tagTRexNode {
} TRexNode;
struct TRex {
- const TRexChar *_eol;
- const TRexChar *_bol;
- const TRexChar *_p;
+ const TRexChar* _eol;
+ const TRexChar* _bol;
+ const TRexChar* _p;
int _first;
int _op;
- TRexNode *_nodes;
+ TRexNode* _nodes;
int _nallocated;
int _nsize;
int _nsubexpr;
- TRexMatch *_matches;
+ TRexMatch* _matches;
int _currsubexp;
- void *_jmpbuf;
- const TRexChar **_error;
+ void* _jmpbuf;
+ const TRexChar** _error;
int _flags;
};
-static int trex_list(TRex *exp);
+static int trex_list(TRex* exp);
-static int trex_newnode(TRex *exp, TRexNodeType type) {
+static int trex_newnode(TRex* exp, TRexNodeType type) {
TRexNode n;
int newid;
n.type = type;
@@ -2835,25 +3734,26 @@ static int trex_newnode(TRex *exp, TRexNodeType type) {
n.right = exp->_nsubexpr++;
if (exp->_nallocated < (exp->_nsize + 1)) {
exp->_nallocated *= 2;
- exp->_nodes = (TRexNode *)realloc(exp->_nodes, exp->_nallocated * sizeof(TRexNode));
+ exp->_nodes = (TRexNode*)xrealloc(exp->_nodes, exp->_nallocated * sizeof(TRexNode));
}
exp->_nodes[exp->_nsize++] = n;
newid = exp->_nsize - 1;
return (int)newid;
}
-static void trex_error(TRex *exp, const TRexChar *error) {
- if (exp->_error) *exp->_error = error;
- longjmp(*((jmp_buf *)exp->_jmpbuf), -1);
+static void trex_error(TRex* exp, const TRexChar* error) {
+ if (exp->_error)
+ *exp->_error = error;
+ longjmp(*((jmp_buf*)exp->_jmpbuf), -1);
}
-static void trex_expect(TRex *exp, int n) {
+static void trex_expect(TRex* exp, int n) {
if ((*exp->_p) != n)
trex_error(exp, _SC("expected paren"));
exp->_p++;
}
-static TRexChar trex_escapechar(TRex *exp) {
+static TRexChar trex_escapechar(TRex* exp) {
if (*exp->_p == TREX_SYMBOL_ESCAPE_CHAR) {
exp->_p++;
switch (*exp->_p) {
@@ -2875,17 +3775,18 @@ static TRexChar trex_escapechar(TRex *exp) {
default:
return (*exp->_p++);
}
- } else if (!scisprint(*exp->_p)) trex_error(exp, _SC("letter expected"));
+ } else if (!scisprint(*exp->_p))
+ trex_error(exp, _SC("letter expected"));
return (*exp->_p++);
}
-static int trex_charclass(TRex *exp, int classid) {
+static int trex_charclass(TRex* exp, int classid) {
int n = trex_newnode(exp, OP_CCLASS);
exp->_nodes[n].left = classid;
return n;
}
-static int trex_charnode(TRex *exp, TRexBool isclass) {
+static int trex_charnode(TRex* exp, TRexBool isclass) {
TRexChar t;
if (*exp->_p == TREX_SYMBOL_ESCAPE_CHAR) {
exp->_p++;
@@ -2932,46 +3833,42 @@ static int trex_charnode(TRex *exp, TRexBool isclass) {
exp->_nodes[node].left = *exp->_p;
exp->_p++;
return node;
- } //else default
+ }
+ /* fall through */
default:
t = *exp->_p;
exp->_p++;
return trex_newnode(exp, t);
}
} else if (!scisprint(*exp->_p)) {
-
trex_error(exp, _SC("letter expected"));
}
t = *exp->_p;
exp->_p++;
return trex_newnode(exp, t);
}
-static int trex_class(TRex *exp) {
+static int trex_class(TRex* exp) {
int ret = -1;
int first = -1, chain;
if (*exp->_p == TREX_SYMBOL_BEGINNING_OF_STRING) {
ret = trex_newnode(exp, OP_NCLASS);
exp->_p++;
- } else ret = trex_newnode(exp, OP_CLASS);
+ } else
+ ret = trex_newnode(exp, OP_CLASS);
- if (*exp->_p == ']') trex_error(exp, _SC("empty class"));
+ if (*exp->_p == ']')
+ trex_error(exp, _SC("empty class"));
chain = ret;
while (*exp->_p != ']' && exp->_p != exp->_eol) {
if (*exp->_p == '-' && first != -1) {
int r, t;
- if (*exp->_p++ == ']') {
+ if (*exp->_p++ == ']')
trex_error(exp, _SC("unfinished range"));
- }
-
r = trex_newnode(exp, OP_RANGE);
- if (first > *exp->_p) {
+ if (first > *exp->_p)
trex_error(exp, _SC("invalid range"));
- }
-
- if (exp->_nodes[first].type == OP_CCLASS) {
+ if (exp->_nodes[first].type == OP_CCLASS)
trex_error(exp, _SC("cannot use character classes in ranges"));
- }
-
exp->_nodes[r].left = exp->_nodes[first].type;
t = trex_escapechar(exp);
exp->_nodes[r].right = t;
@@ -2992,6 +3889,8 @@ static int trex_class(TRex *exp) {
if (first != -1) {
int c = first;
exp->_nodes[chain].next = c;
+ chain = c;
+ first = -1;
}
/* hack? */
exp->_nodes[ret].left = exp->_nodes[ret].next;
@@ -2999,26 +3898,26 @@ static int trex_class(TRex *exp) {
return ret;
}
-static int trex_parsenumber(TRex *exp) {
+static int trex_parsenumber(TRex* exp) {
int ret = *exp->_p - '0';
int positions = 10;
exp->_p++;
while (isdigit(*exp->_p)) {
- ret = ret * 10 + (*exp->_p++ -'0');
- if (positions == 1000000000) trex_error(exp, _SC("overflow in numeric constant"));
+ ret = ret * 10 + (*exp->_p++ - '0');
+ if (positions == 1000000000)
+ trex_error(exp, _SC("overflow in numeric constant"));
positions *= 10;
};
return ret;
}
-static int trex_element(TRex *exp) {
+static int trex_element(TRex* exp) {
int ret = -1;
switch (*exp->_p) {
case '(': {
int expr, newn;
exp->_p++;
-
if (*exp->_p == '?') {
exp->_p++;
trex_expect(exp, ':');
@@ -3029,8 +3928,7 @@ static int trex_element(TRex *exp) {
exp->_nodes[expr].left = newn;
ret = expr;
trex_expect(exp, ')');
- }
- break;
+ } break;
case '[':
exp->_p++;
ret = trex_class(exp);
@@ -3073,7 +3971,8 @@ static int trex_element(TRex *exp) {
break;
case '{':
exp->_p++;
- if (!isdigit(*exp->_p)) trex_error(exp, _SC("number expected"));
+ if (!isdigit(*exp->_p))
+ trex_error(exp, _SC("number expected"));
p0 = (unsigned short)trex_parsenumber(exp);
/*******************************/
switch (*exp->_p) {
@@ -3095,7 +3994,6 @@ static int trex_element(TRex *exp) {
/*******************************/
isgreedy = TRex_True;
break;
-
}
if (isgreedy) {
int nnode = trex_newnode(exp, OP_GREEDY);
@@ -3104,7 +4002,8 @@ static int trex_element(TRex *exp) {
ret = nnode;
}
}
- if ((*exp->_p != TREX_SYMBOL_BRANCH) && (*exp->_p != ')') && (*exp->_p != TREX_SYMBOL_GREEDY_ZERO_OR_MORE) && (*exp->_p != TREX_SYMBOL_GREEDY_ONE_OR_MORE) && (*exp->_p != '\0')) {
+ if ((*exp->_p != TREX_SYMBOL_BRANCH) && (*exp->_p != ')') && (*exp->_p != TREX_SYMBOL_GREEDY_ZERO_OR_MORE) &&
+ (*exp->_p != TREX_SYMBOL_GREEDY_ONE_OR_MORE) && (*exp->_p != '\0')) {
int nnode = trex_element(exp);
exp->_nodes[ret].next = nnode;
}
@@ -3112,7 +4011,7 @@ static int trex_element(TRex *exp) {
return ret;
}
-static int trex_list(TRex *exp) {
+static int trex_list(TRex* exp) {
int ret = -1, e;
if (*exp->_p == TREX_SYMBOL_BEGINNING_OF_STRING) {
exp->_p++;
@@ -3121,7 +4020,8 @@ static int trex_list(TRex *exp) {
e = trex_element(exp);
if (ret != -1) {
exp->_nodes[ret].next = e;
- } else ret = e;
+ } else
+ ret = e;
if (*exp->_p == TREX_SYMBOL_BRANCH) {
int temp, tright;
@@ -3146,9 +4046,9 @@ static TRexBool trex_matchcclass(int cclass, TRexChar c) {
case 'W':
return (!isalnum(c) && c != '_') ? TRex_True : TRex_False;
case 's':
- return ISSPACE(c) ? TRex_True : TRex_False;
+ return isspace(c) ? TRex_True : TRex_False;
case 'S':
- return !ISSPACE(c) ? TRex_True : TRex_False;
+ return !isspace(c) ? TRex_True : TRex_False;
case 'd':
return isdigit(c) ? TRex_True : TRex_False;
case 'D':
@@ -3173,39 +4073,43 @@ static TRexBool trex_matchcclass(int cclass, TRexChar c) {
return TRex_False; /*cannot happen*/
}
-static TRexBool trex_matchclass(TRex *exp, TRexNode *node, TRexChar c) {
+static TRexBool trex_matchclass(TRex* exp, TRexNode* node, TRexChar c) {
do {
switch (node->type) {
case OP_RANGE:
if (exp->_flags & TREX_ICASE) {
- if (c >= toupper(node->left) && c <= toupper(node->right)) return TRex_True;
- if (c >= tolower(node->left) && c <= tolower(node->right)) return TRex_True;
+ if (c >= toupper(node->left) && c <= toupper(node->right))
+ return TRex_True;
+ if (c >= tolower(node->left) && c <= tolower(node->right))
+ return TRex_True;
} else {
- if (c >= node->left && c <= node->right) return TRex_True;
+ if (c >= node->left && c <= node->right)
+ return TRex_True;
}
break;
case OP_CCLASS:
- if (trex_matchcclass(node->left, c)) return TRex_True;
+ if (trex_matchcclass(node->left, c))
+ return TRex_True;
break;
default:
if (exp->_flags & TREX_ICASE) {
- if (c == tolower(node->type) || c == toupper(node->type)) return TRex_True;
+ if (c == tolower(node->type) || c == toupper(node->type))
+ return TRex_True;
} else {
- if (c == node->type)return TRex_True;
+ if (c == node->type)
+ return TRex_True;
}
-
}
- } while ((node->next != -1) && (node = &exp->_nodes[node->next]));
+ } while ((node->next != -1) && ((node = &exp->_nodes[node->next]) != NULL));
return TRex_False;
}
-static const TRexChar *trex_matchnode(TRex *exp, TRexNode *node, const TRexChar *str, TRexNode *next) {
-
+static const TRexChar* trex_matchnode(TRex* exp, TRexNode* node, const TRexChar* str, TRexNode* next) {
TRexNodeType type = node->type;
switch (type) {
case OP_GREEDY: {
- //TRexNode *greedystop = (node->next != -1) ? &exp->_nodes[node->next] : NULL;
- TRexNode *greedystop = NULL;
+ /* TRexNode *greedystop = (node->next != -1) ? &exp->_nodes[node->next] : NULL; */
+ TRexNode* greedystop = NULL;
int p0 = (node->right >> 16) & 0x0000FFFF, p1 = node->right & 0x0000FFFF, nmaches = 0;
const TRexChar *s = str, *good = str;
@@ -3216,18 +4120,16 @@ static const TRexChar *trex_matchnode(TRex *exp, TRexNode *node, const TRexChar
}
while ((nmaches == 0xFFFF || nmaches < p1)) {
-
- const TRexChar *stop;
- if (!(s = trex_matchnode(exp, &exp->_nodes[node->left], s, greedystop)))
+ const TRexChar* stop;
+ if ((s = trex_matchnode(exp, &exp->_nodes[node->left], s, greedystop)) == NULL)
break;
nmaches++;
good = s;
if (greedystop) {
- //checks that 0 matches satisfy the expression(if so skips)
- //if not would always stop(for instance if is a '?')
- if (greedystop->type != OP_GREEDY ||
- (greedystop->type == OP_GREEDY && ((greedystop->right >> 16) & 0x0000FFFF) != 0)) {
- TRexNode *gnext = NULL;
+ /* checks that 0 matches satisfy the expression(if so skips) */
+ /* if not would always stop(for instance if is a '?') */
+ if (greedystop->type != OP_GREEDY || (greedystop->type == OP_GREEDY && ((greedystop->right >> 16) & 0x0000FFFF) != 0)) {
+ TRexNode* gnext = NULL;
if (greedystop->next != -1) {
gnext = &exp->_nodes[greedystop->next];
} else if (next && next->next != -1) {
@@ -3235,10 +4137,13 @@ static const TRexChar *trex_matchnode(TRex *exp, TRexNode *node, const TRexChar
}
stop = trex_matchnode(exp, greedystop, s, gnext);
if (stop) {
- //if satisfied stop it
- if (p0 == p1 && p0 == nmaches) break;
- else if (nmaches >= p0 && p1 == 0xFFFF) break;
- else if (nmaches >= p0 && nmaches <= p1) break;
+ /* if satisfied stop it */
+ if (p0 == p1 && p0 == nmaches)
+ break;
+ else if (nmaches >= p0 && p1 == 0xFFFF)
+ break;
+ else if (nmaches >= p0 && nmaches <= p1)
+ break;
}
}
}
@@ -3246,15 +4151,18 @@ static const TRexChar *trex_matchnode(TRex *exp, TRexNode *node, const TRexChar
if (s >= exp->_eol)
break;
}
- if (p0 == p1 && p0 == nmaches) return good;
- else if (nmaches >= p0 && p1 == 0xFFFF) return good;
- else if (nmaches >= p0 && nmaches <= p1) return good;
+ if (p0 == p1 && p0 == nmaches)
+ return good;
+ else if (nmaches >= p0 && p1 == 0xFFFF)
+ return good;
+ else if (nmaches >= p0 && nmaches <= p1)
+ return good;
return NULL;
}
case OP_OR: {
- const TRexChar *asd = str;
- TRexNode *temp = &exp->_nodes[node->left];
- while ((asd = trex_matchnode(exp, temp, asd, NULL))) {
+ const TRexChar* asd = str;
+ TRexNode* temp = &exp->_nodes[node->left];
+ while ((asd = trex_matchnode(exp, temp, asd, NULL)) != NULL) {
if (temp->next != -1)
temp = &exp->_nodes[temp->next];
else
@@ -3262,18 +4170,19 @@ static const TRexChar *trex_matchnode(TRex *exp, TRexNode *node, const TRexChar
}
asd = str;
temp = &exp->_nodes[node->right];
- while ((asd = trex_matchnode(exp, temp, asd, NULL))) {
+ while ((asd = trex_matchnode(exp, temp, asd, NULL)) != NULL) {
if (temp->next != -1)
temp = &exp->_nodes[temp->next];
else
return asd;
}
return NULL;
+ break;
}
case OP_EXPR:
case OP_NOCAPEXPR: {
- TRexNode *n = &exp->_nodes[node->left];
- const TRexChar *cur = str;
+ TRexNode* n = &exp->_nodes[node->left];
+ const TRexChar* cur = str;
int capture = -1;
if (node->type != OP_NOCAPEXPR && node->right == exp->_currsubexp) {
capture = exp->_currsubexp;
@@ -3282,45 +4191,47 @@ static const TRexChar *trex_matchnode(TRex *exp, TRexNode *node, const TRexChar
}
do {
- TRexNode *subnext = NULL;
+ TRexNode* subnext = NULL;
if (n->next != -1) {
subnext = &exp->_nodes[n->next];
} else {
subnext = next;
}
- if (!(cur = trex_matchnode(exp, n, cur, subnext))) {
+ if ((cur = trex_matchnode(exp, n, cur, subnext)) == NULL) {
if (capture != -1) {
exp->_matches[capture].begin = 0;
exp->_matches[capture].len = 0;
}
return NULL;
}
- } while ((n->next != -1) && (n = &exp->_nodes[n->next]));
+ } while ((n->next != -1) && ((n = &exp->_nodes[n->next]) != NULL));
if (capture != -1)
exp->_matches[capture].len = (int)(cur - exp->_matches[capture].begin);
return cur;
}
case OP_WB:
- if ((str == exp->_bol && !ISSPACE(*str))
- || ((str == exp->_eol && !ISSPACE(*(str - 1))))
- || ((!ISSPACE(*str) && ISSPACE(*(str + 1))))
- || ((ISSPACE(*str) && !ISSPACE(*(str + 1))))) {
+ if ((str == exp->_bol && !isspace(*str)) || (str == exp->_eol && !isspace(*(str - 1))) || (!isspace(*str) && isspace(*(str + 1))) ||
+ (isspace(*str) && !isspace(*(str + 1)))) {
return (node->left == 'b') ? str : NULL;
}
return (node->left == 'b') ? NULL : str;
case OP_BOL:
- if (str == exp->_bol) return str;
+ if (str == exp->_bol)
+ return str;
return NULL;
case OP_EOL:
- if (str == exp->_eol) return str;
+ if (str == exp->_eol)
+ return str;
return NULL;
- case OP_DOT:
+ case OP_DOT: {
str++;
+ }
return str;
case OP_NCLASS:
case OP_CLASS:
- if (trex_matchclass(exp, &exp->_nodes[node->left], *str) ? (type == OP_CLASS ? TRex_True : TRex_False) : (type == OP_NCLASS ? TRex_True : TRex_False)) {
+ if (trex_matchclass(exp, &exp->_nodes[node->left], *str) ? (type == OP_CLASS ? TRex_True : TRex_False)
+ : (type == OP_NCLASS ? TRex_True : TRex_False)) {
str++;
return str;
}
@@ -3333,31 +4244,32 @@ static const TRexChar *trex_matchnode(TRex *exp, TRexNode *node, const TRexChar
return NULL;
default: /* char */
if (exp->_flags & TREX_ICASE) {
- if (*str != tolower(node->type) && *str != toupper(node->type)) return NULL;
+ if (*str != tolower(node->type) && *str != toupper(node->type))
+ return NULL;
} else {
- if (*str != node->type) return NULL;
+ if (*str != node->type)
+ return NULL;
}
str++;
return str;
}
- return NULL;
}
/* public api */
-TRex *trex_compile(const TRexChar *pattern, const TRexChar **error, int flags) {
- TRex *exp = (TRex *)malloc(sizeof(TRex));
+TRex* trex_compile(const TRexChar* pattern, const TRexChar** error, int flags) {
+ TRex* exp = (TRex*)xmalloc(sizeof(TRex));
exp->_eol = exp->_bol = NULL;
exp->_p = pattern;
exp->_nallocated = (int)scstrlen(pattern) * sizeof(TRexChar);
- exp->_nodes = (TRexNode *)malloc(exp->_nallocated * sizeof(TRexNode));
+ exp->_nodes = (TRexNode*)xmalloc(exp->_nallocated * sizeof(TRexNode));
exp->_nsize = 0;
exp->_matches = 0;
exp->_nsubexpr = 0;
exp->_first = trex_newnode(exp, OP_EXPR);
exp->_error = error;
- exp->_jmpbuf = malloc(sizeof(jmp_buf));
+ exp->_jmpbuf = xmalloc(sizeof(jmp_buf));
exp->_flags = flags;
- if (setjmp(*((jmp_buf *)exp->_jmpbuf)) == 0) {
+ if (setjmp(*((jmp_buf*)exp->_jmpbuf)) == 0) {
int res = trex_list(exp);
exp->_nodes[exp->_first].left = res;
if (*exp->_p != '\0')
@@ -3365,7 +4277,7 @@ TRex *trex_compile(const TRexChar *pattern, const TRexChar **error, int flags) {
#ifdef _DEBUG
{
int nsize, i;
- TRexNode *t;
+ TRexNode* t;
nsize = exp->_nsize;
t = &exp->_nodes[0];
scprintf(_SC("\n"));
@@ -3379,7 +4291,7 @@ TRex *trex_compile(const TRexChar *pattern, const TRexChar **error, int flags) {
scprintf(_SC("\n"));
}
#endif
- exp->_matches = (TRexMatch *) malloc(exp->_nsubexpr * sizeof(TRexMatch));
+ exp->_matches = (TRexMatch*)xmalloc(exp->_nsubexpr * sizeof(TRexMatch));
memset(exp->_matches, 0, exp->_nsubexpr * sizeof(TRexMatch));
} else {
trex_free(exp);
@@ -3388,17 +4300,17 @@ TRex *trex_compile(const TRexChar *pattern, const TRexChar **error, int flags) {
return exp;
}
-void trex_free(TRex *exp) {
+void trex_free(TRex* exp) {
if (exp) {
- if (exp->_nodes) free(exp->_nodes);
- if (exp->_jmpbuf) free(exp->_jmpbuf);
- if (exp->_matches) free(exp->_matches);
- free(exp);
+ xfree(exp->_nodes);
+ xfree(exp->_jmpbuf);
+ xfree(exp->_matches);
+ xfree(exp);
}
}
-TRexBool trex_match(TRex *exp, const TRexChar *text) {
- const TRexChar *res = NULL;
+TRexBool trex_match(TRex* exp, const TRexChar* text) {
+ const TRexChar* res = NULL;
exp->_bol = text;
exp->_eol = text + scstrlen(text);
exp->_currsubexp = 0;
@@ -3408,10 +4320,11 @@ TRexBool trex_match(TRex *exp, const TRexChar *text) {
return TRex_True;
}
-TRexBool trex_searchrange(TRex *exp, const TRexChar *text_begin, const TRexChar *text_end, const TRexChar **out_begin, const TRexChar **out_end) {
- const TRexChar *cur = NULL;
+TRexBool trex_searchrange(TRex* exp, const TRexChar* text_begin, const TRexChar* text_end, const TRexChar** out_begin, const TRexChar** out_end) {
+ const TRexChar* cur = NULL;
int node = exp->_first;
- if (text_begin >= text_end) return TRex_False;
+ if (text_begin >= text_end)
+ return TRex_False;
exp->_bol = text_begin;
exp->_eol = text_end;
do {
@@ -3431,25 +4344,30 @@ TRexBool trex_searchrange(TRex *exp, const TRexChar *text_begin, const TRexChar
--text_begin;
- if (out_begin) *out_begin = text_begin;
- if (out_end) *out_end = cur;
+ if (out_begin)
+ *out_begin = text_begin;
+ if (out_end)
+ *out_end = cur;
return TRex_True;
}
-TRexBool trex_search(TRex *exp, const TRexChar *text, const TRexChar **out_begin, const TRexChar **out_end) {
+TRexBool trex_search(TRex* exp, const TRexChar* text, const TRexChar** out_begin, const TRexChar** out_end) {
return trex_searchrange(exp, text, text + scstrlen(text), out_begin, out_end);
}
-int trex_getsubexpcount(TRex *exp) {
+int trex_getsubexpcount(TRex* exp) {
return exp->_nsubexpr;
}
-TRexBool trex_getsubexp(TRex *exp, int n, TRexMatch *subexp) {
- if (n < 0 || n >= exp->_nsubexpr) return TRex_False;
+TRexBool trex_getsubexp(TRex* exp, int n, TRexMatch* subexp) {
+ if (n < 0 || n >= exp->_nsubexpr)
+ return TRex_False;
*subexp = exp->_matches[n];
return TRex_True;
}
/*******************************************************************************
+ * arg_str: Implements the str command-line option
+ *
* This file is part of the argtable3 library.
*
* Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
@@ -3479,31 +4397,34 @@ TRexBool trex_getsubexp(TRex *exp, int n, TRexMatch *subexp) {
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
-#include
-
#include "argtable3.h"
+#ifndef ARG_AMALGAMATION
+#include "argtable3_private.h"
+#endif
-static void arg_str_resetfn(struct arg_str *parent) {
+#include
+
+static void arg_str_resetfn(struct arg_str* parent) {
int i;
+
ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent));
- parent->count = 0;
for (i = 0; i < parent->count; i++) {
parent->sval[i] = "";
}
+ parent->count = 0;
}
-
-static int arg_str_scanfn(struct arg_str *parent, const char *argval) {
+static int arg_str_scanfn(struct arg_str* parent, const char* argval) {
int errorcode = 0;
if (parent->count == parent->hdr.maxcount) {
/* maximum number of arguments exceeded */
- errorcode = EMAXCOUNT;
+ errorcode = ARG_ERR_MAXCOUNT;
} else if (!argval) {
/* a valid argument with no argument value was given. */
/* This happens when an optional argument value was invoked. */
- /* leave parent arguiment value unaltered but still count the argument. */
+ /* leave parent argument value unaltered but still count the argument. */
parent->count++;
} else {
parent->sval[parent->count++] = argval;
@@ -3513,110 +4434,366 @@ static int arg_str_scanfn(struct arg_str *parent, const char *argval) {
return errorcode;
}
-
-static int arg_str_checkfn(struct arg_str *parent) {
- int errorcode = (parent->count < parent->hdr.mincount) ? EMINCOUNT : 0;
+static int arg_str_checkfn(struct arg_str* parent) {
+ int errorcode = (parent->count < parent->hdr.mincount) ? ARG_ERR_MINCOUNT : 0;
ARG_TRACE(("%s:checkfn(%p) returns %d\n", __FILE__, parent, errorcode));
return errorcode;
}
-
-static void arg_str_errorfn(
- struct arg_str *parent,
- FILE *fp,
- int errorcode,
- const char *argval,
- const char *progname) {
- const char *shortopts = parent->hdr.shortopts;
- const char *longopts = parent->hdr.longopts;
- const char *datatype = parent->hdr.datatype;
+static void arg_str_errorfn(struct arg_str* parent, arg_dstr_t ds, int errorcode, const char* argval, const char* progname) {
+ const char* shortopts = parent->hdr.shortopts;
+ const char* longopts = parent->hdr.longopts;
+ const char* datatype = parent->hdr.datatype;
/* make argval NULL safe */
argval = argval ? argval : "";
- fprintf(fp, "%s: ", progname);
+ arg_dstr_catf(ds, "%s: ", progname);
switch (errorcode) {
- case EMINCOUNT:
- fputs("missing option ", fp);
- arg_print_option(fp, shortopts, longopts, datatype, "\n");
+ case ARG_ERR_MINCOUNT:
+ arg_dstr_cat(ds, "missing option ");
+ arg_print_option_ds(ds, shortopts, longopts, datatype, "\n");
break;
- case EMAXCOUNT:
- fputs("excess option ", fp);
- arg_print_option(fp, shortopts, longopts, argval, "\n");
+ case ARG_ERR_MAXCOUNT:
+ arg_dstr_cat(ds, "excess option ");
+ arg_print_option_ds(ds, shortopts, longopts, argval, "\n");
break;
}
}
-
-struct arg_str *arg_str0(
- const char *shortopts,
- const char *longopts,
- const char *datatype,
- const char *glossary) {
+struct arg_str* arg_str0(const char* shortopts, const char* longopts, const char* datatype, const char* glossary) {
return arg_strn(shortopts, longopts, datatype, 0, 1, glossary);
}
-
-struct arg_str *arg_str1(
- const char *shortopts,
- const char *longopts,
- const char *datatype,
- const char *glossary) {
+struct arg_str* arg_str1(const char* shortopts, const char* longopts, const char* datatype, const char* glossary) {
return arg_strn(shortopts, longopts, datatype, 1, 1, glossary);
}
-
-struct arg_str *arg_strn(
- const char *shortopts,
- const char *longopts,
- const char *datatype,
- int mincount,
- int maxcount,
- const char *glossary) {
+struct arg_str* arg_strn(const char* shortopts, const char* longopts, const char* datatype, int mincount, int maxcount, const char* glossary) {
size_t nbytes;
- struct arg_str *result;
+ struct arg_str* result;
+ int i;
/* should not allow this stupid error */
/* we should return an error code warning this logic error */
/* foolproof things by ensuring maxcount is not less than mincount */
maxcount = (maxcount < mincount) ? mincount : maxcount;
- nbytes = sizeof(struct arg_str) /* storage for struct arg_str */
- + maxcount * sizeof(char *); /* storage for sval[maxcount] array */
+ nbytes = sizeof(struct arg_str) /* storage for struct arg_str */
+ + maxcount * sizeof(char*); /* storage for sval[maxcount] array */
- result = (struct arg_str *)malloc(nbytes);
- if (result) {
- int i;
+ result = (struct arg_str*)xmalloc(nbytes);
- /* init the arg_hdr struct */
- result->hdr.flag = ARG_HASVALUE;
- result->hdr.shortopts = shortopts;
- result->hdr.longopts = longopts;
- result->hdr.datatype = datatype ? datatype : "";
- result->hdr.glossary = glossary;
- result->hdr.mincount = mincount;
- result->hdr.maxcount = maxcount;
- result->hdr.parent = result;
- result->hdr.resetfn = (arg_resetfn *)arg_str_resetfn;
- result->hdr.scanfn = (arg_scanfn *)arg_str_scanfn;
- result->hdr.checkfn = (arg_checkfn *)arg_str_checkfn;
- result->hdr.errorfn = (arg_errorfn *)arg_str_errorfn;
+ /* init the arg_hdr struct */
+ result->hdr.flag = ARG_HASVALUE;
+ result->hdr.shortopts = shortopts;
+ result->hdr.longopts = longopts;
+ result->hdr.datatype = datatype ? datatype : "";
+ result->hdr.glossary = glossary;
+ result->hdr.mincount = mincount;
+ result->hdr.maxcount = maxcount;
+ result->hdr.parent = result;
+ result->hdr.resetfn = (arg_resetfn*)arg_str_resetfn;
+ result->hdr.scanfn = (arg_scanfn*)arg_str_scanfn;
+ result->hdr.checkfn = (arg_checkfn*)arg_str_checkfn;
+ result->hdr.errorfn = (arg_errorfn*)arg_str_errorfn;
- /* store the sval[maxcount] array immediately after the arg_str struct */
- result->sval = (const char * *)(result + 1);
- result->count = 0;
+ /* store the sval[maxcount] array immediately after the arg_str struct */
+ result->sval = (const char**)(result + 1);
+ result->count = 0;
- /* foolproof the string pointers by initialising them to reference empty strings */
- for (i = 0; i < maxcount; i++)
- result->sval[i] = "";
- }
+ /* foolproof the string pointers by initializing them to reference empty strings */
+ for (i = 0; i < maxcount; i++)
+ result->sval[i] = "";
ARG_TRACE(("arg_strn() returns %p\n", result));
return result;
}
/*******************************************************************************
+ * arg_cmd: Provides the sub-command mechanism
+ *
+ * This file is part of the argtable3 library.
+ *
+ * Copyright (C) 2013-2019 Tom G. Huang
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * * Neither the name of STEWART HEITMANN nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ ******************************************************************************/
+
+#include "argtable3.h"
+
+#ifndef ARG_AMALGAMATION
+#include "argtable3_private.h"
+#endif
+
+#include
+#include
+#include
+
+#define MAX_MODULE_VERSION_SIZE 128
+
+static arg_hashtable_t* s_hashtable = NULL;
+static char* s_module_name = NULL;
+static int s_mod_ver_major = 0;
+static int s_mod_ver_minor = 0;
+static int s_mod_ver_patch = 0;
+static char* s_mod_ver_tag = NULL;
+static char* s_mod_ver = NULL;
+
+void arg_set_module_name(const char* name) {
+ size_t slen;
+
+ xfree(s_module_name);
+ slen = strlen(name);
+ s_module_name = (char*)xmalloc(slen + 1);
+ memset(s_module_name, 0, slen + 1);
+
+#if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || (defined(__STDC_SECURE_LIB__) && defined(__STDC_WANT_SECURE_LIB__))
+ strncpy_s(s_module_name, slen + 1, name, slen);
+#else
+ memcpy(s_module_name, name, slen);
+#endif
+}
+
+void arg_set_module_version(int major, int minor, int patch, const char* tag) {
+ size_t slen_tag, slen_ds;
+ arg_dstr_t ds;
+
+ s_mod_ver_major = major;
+ s_mod_ver_minor = minor;
+ s_mod_ver_patch = patch;
+
+ xfree(s_mod_ver_tag);
+ slen_tag = strlen(tag);
+ s_mod_ver_tag = (char*)xmalloc(slen_tag + 1);
+ memset(s_mod_ver_tag, 0, slen_tag + 1);
+
+#if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || (defined(__STDC_SECURE_LIB__) && defined(__STDC_WANT_SECURE_LIB__))
+ strncpy_s(s_mod_ver_tag, slen_tag + 1, tag, slen_tag);
+#else
+ memcpy(s_mod_ver_tag, tag, slen_tag);
+#endif
+
+ ds = arg_dstr_create();
+ arg_dstr_catf(ds, "%d.", s_mod_ver_major);
+ arg_dstr_catf(ds, "%d.", s_mod_ver_minor);
+ arg_dstr_catf(ds, "%d.", s_mod_ver_patch);
+ arg_dstr_cat(ds, s_mod_ver_tag);
+
+ xfree(s_mod_ver);
+ slen_ds = strlen(arg_dstr_cstr(ds));
+ s_mod_ver = (char*)xmalloc(slen_ds + 1);
+ memset(s_mod_ver, 0, slen_ds + 1);
+
+#if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || (defined(__STDC_SECURE_LIB__) && defined(__STDC_WANT_SECURE_LIB__))
+ strncpy_s(s_mod_ver, slen_ds + 1, arg_dstr_cstr(ds), slen_ds);
+#else
+ memcpy(s_mod_ver, arg_dstr_cstr(ds), slen_ds);
+#endif
+
+ arg_dstr_destroy(ds);
+}
+
+static unsigned int hash_key(const void* key) {
+ const char* str = (const char*)key;
+ int c;
+ unsigned int hash = 5381;
+
+ while ((c = *str++) != 0)
+ hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
+
+ return hash;
+}
+
+static int equal_keys(const void* key1, const void* key2) {
+ char* k1 = (char*)key1;
+ char* k2 = (char*)key2;
+ return (0 == strcmp(k1, k2));
+}
+
+void arg_cmd_init(void) {
+ s_hashtable = arg_hashtable_create(32, hash_key, equal_keys);
+}
+
+void arg_cmd_uninit(void) {
+ arg_hashtable_destroy(s_hashtable, 1);
+}
+
+void arg_cmd_register(const char* name, arg_cmdfn* proc, const char* description) {
+ arg_cmd_info_t* cmd_info;
+ size_t slen_name;
+ void* k;
+
+ assert(strlen(name) < ARG_CMD_NAME_LEN);
+ assert(strlen(description) < ARG_CMD_DESCRIPTION_LEN);
+
+ /* Check if the command already exists. */
+ /* If the command exists, replace the existing command. */
+ /* If the command doesn't exist, insert the command. */
+ cmd_info = (arg_cmd_info_t*)arg_hashtable_search(s_hashtable, name);
+ if (cmd_info) {
+ arg_hashtable_remove(s_hashtable, name);
+ cmd_info = NULL;
+ }
+
+ cmd_info = (arg_cmd_info_t*)xmalloc(sizeof(arg_cmd_info_t));
+ memset(cmd_info, 0, sizeof(arg_cmd_info_t));
+
+#if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || (defined(__STDC_SECURE_LIB__) && defined(__STDC_WANT_SECURE_LIB__))
+ strncpy_s(cmd_info->name, ARG_CMD_NAME_LEN, name, strlen(name));
+ strncpy_s(cmd_info->description, ARG_CMD_DESCRIPTION_LEN, description, strlen(description));
+#else
+ memcpy(cmd_info->name, name, strlen(name));
+ memcpy(cmd_info->description, description, strlen(description));
+#endif
+
+ cmd_info->proc = proc;
+
+ slen_name = strlen(name);
+ k = xmalloc(slen_name + 1);
+ memset(k, 0, slen_name + 1);
+
+#if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || (defined(__STDC_SECURE_LIB__) && defined(__STDC_WANT_SECURE_LIB__))
+ strncpy_s((char*)k, slen_name + 1, name, slen_name);
+#else
+ memcpy((char*)k, name, slen_name);
+#endif
+
+ arg_hashtable_insert(s_hashtable, k, cmd_info);
+}
+
+void arg_cmd_unregister(const char* name) {
+ arg_hashtable_remove(s_hashtable, name);
+}
+
+int arg_cmd_dispatch(const char* name, int argc, char* argv[], arg_dstr_t res) {
+ arg_cmd_info_t* cmd_info = arg_cmd_info(name);
+
+ assert(cmd_info != NULL);
+ assert(cmd_info->proc != NULL);
+
+ return cmd_info->proc(argc, argv, res);
+}
+
+arg_cmd_info_t* arg_cmd_info(const char* name) {
+ return (arg_cmd_info_t*)arg_hashtable_search(s_hashtable, name);
+}
+
+unsigned int arg_cmd_count(void) {
+ return arg_hashtable_count(s_hashtable);
+}
+
+arg_cmd_itr_t arg_cmd_itr_create(void) {
+ return (arg_cmd_itr_t)arg_hashtable_itr_create(s_hashtable);
+}
+
+int arg_cmd_itr_advance(arg_cmd_itr_t itr) {
+ return arg_hashtable_itr_advance((arg_hashtable_itr_t*)itr);
+}
+
+char* arg_cmd_itr_key(arg_cmd_itr_t itr) {
+ return (char*)arg_hashtable_itr_key((arg_hashtable_itr_t*)itr);
+}
+
+arg_cmd_info_t* arg_cmd_itr_value(arg_cmd_itr_t itr) {
+ return (arg_cmd_info_t*)arg_hashtable_itr_value((arg_hashtable_itr_t*)itr);
+}
+
+void arg_cmd_itr_destroy(arg_cmd_itr_t itr) {
+ arg_hashtable_itr_destroy((arg_hashtable_itr_t*)itr);
+}
+
+int arg_cmd_itr_search(arg_cmd_itr_t itr, void* k) {
+ return arg_hashtable_itr_search((arg_hashtable_itr_t*)itr, s_hashtable, k);
+}
+
+static const char* module_name(void) {
+ if (s_module_name == NULL || strlen(s_module_name) == 0)
+ return "";
+
+ return s_module_name;
+}
+
+static const char* module_version(void) {
+ if (s_mod_ver == NULL || strlen(s_mod_ver) == 0)
+ return "0.0.0.0";
+
+ return s_mod_ver;
+}
+
+void arg_make_get_help_msg(arg_dstr_t res) {
+ arg_dstr_catf(res, "%s v%s\n", module_name(), module_version());
+ arg_dstr_catf(res, "Please type '%s help' to get more information.\n", module_name());
+}
+
+void arg_make_help_msg(arg_dstr_t ds, char* cmd_name, void** argtable) {
+ arg_cmd_info_t* cmd_info = (arg_cmd_info_t*)arg_hashtable_search(s_hashtable, cmd_name);
+ if (cmd_info) {
+ arg_dstr_catf(ds, "%s: %s\n", cmd_name, cmd_info->description);
+ }
+
+ arg_dstr_cat(ds, "Usage:\n");
+ arg_dstr_catf(ds, " %s", module_name());
+
+ arg_print_syntaxv_ds(ds, argtable, "\n \nAvailable options:\n");
+ arg_print_glossary_ds(ds, argtable, " %-23s %s\n");
+
+ arg_dstr_cat(ds, "\n");
+}
+
+void arg_make_syntax_err_msg(arg_dstr_t ds, void** argtable, struct arg_end* end) {
+ arg_print_errors_ds(ds, end, module_name());
+ arg_dstr_cat(ds, "Usage: \n");
+ arg_dstr_catf(ds, " %s", module_name());
+ arg_print_syntaxv_ds(ds, argtable, "\n");
+ arg_dstr_cat(ds, "\n");
+}
+
+int arg_make_syntax_err_help_msg(arg_dstr_t ds, char* name, int help, int nerrors, void** argtable, struct arg_end* end, int* exitcode) {
+ /* help handling
+ * note: '-h|--help' takes precedence over error reporting
+ */
+ if (help > 0) {
+ arg_make_help_msg(ds, name, argtable);
+ *exitcode = EXIT_SUCCESS;
+ return 1;
+ }
+
+ /* syntax error handling */
+ if (nerrors > 0) {
+ arg_make_syntax_err_msg(ds, argtable, end);
+ *exitcode = EXIT_FAILURE;
+ return 1;
+ }
+
+ return 0;
+}
+/*******************************************************************************
+ * argtable3: Implements the main interfaces of the library
+ *
* This file is part of the argtable3 library.
*
* Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
@@ -3646,18 +4823,26 @@ struct arg_str *arg_strn(
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
-#include
-#include
-#include
-#include
-
#include "argtable3.h"
-static
-void arg_register_error(struct arg_end *end,
- void *parent,
- int error,
- const char *argval) {
+#ifndef ARG_AMALGAMATION
+#include "argtable3_private.h"
+#include "getopt.h"
+#endif
+
+#ifdef _WIN32
+#define WIN32_LEAN_AND_MEAN
+#include
+#undef WIN32_LEAN_AND_MEAN
+#endif
+
+#include
+#include
+#include
+#include
+#include
+
+static void arg_register_error(struct arg_end* end, void* parent, int error, const char* argval) {
/* printf("arg_register_error(%p,%p,%d,%s)\n",end,parent,error,argval); */
if (end->count < end->hdr.maxcount) {
end->error[end->count] = error;
@@ -3665,22 +4850,20 @@ void arg_register_error(struct arg_end *end,
end->argval[end->count] = argval;
end->count++;
} else {
- end->error[end->hdr.maxcount - 1] = ARG_ELIMIT;
+ end->error[end->hdr.maxcount - 1] = ARG_ELIMIT;
end->parent[end->hdr.maxcount - 1] = end;
end->argval[end->hdr.maxcount - 1] = NULL;
}
}
-
/*
* Return index of first table entry with a matching short option
* or -1 if no match was found.
*/
-static int find_shortoption(struct arg_hdr **table, char shortopt) {
+static int find_shortoption(struct arg_hdr** table, char shortopt) {
int tabindex;
for (tabindex = 0; !(table[tabindex]->flag & ARG_TERMINATOR); tabindex++) {
- if (table[tabindex]->shortopts &&
- strchr(table[tabindex]->shortopts, shortopt))
+ if (table[tabindex]->shortopts && strchr(table[tabindex]->shortopts, shortopt))
return tabindex;
}
return -1;
@@ -3689,16 +4872,18 @@ static int find_shortoption(struct arg_hdr **table, char shortopt) {
struct longoptions {
int getoptval;
int noptions;
- struct option *options;
+ struct option* options;
};
#if 0
static
-void dump_longoptions(struct longoptions *longoptions) {
+void dump_longoptions(struct longoptions * longoptions)
+{
int i;
printf("getoptval = %d\n", longoptions->getoptval);
printf("noptions = %d\n", longoptions->noptions);
- for (i = 0; i < longoptions->noptions; i++) {
+ for (i = 0; i < longoptions->noptions; i++)
+ {
printf("options[%d].name = \"%s\"\n",
i,
longoptions->options[i].name);
@@ -3709,12 +4894,14 @@ void dump_longoptions(struct longoptions *longoptions) {
}
#endif
-static struct longoptions *alloc_longoptions(struct arg_hdr **table) {
- struct longoptions *result;
+static struct longoptions* alloc_longoptions(struct arg_hdr** table) {
+ struct longoptions* result;
size_t nbytes;
int noptions = 1;
size_t longoptlen = 0;
int tabindex;
+ int option_index = 0;
+ char* store;
/*
* Determine the total number of option structs required
@@ -3728,7 +4915,7 @@ static struct longoptions *alloc_longoptions(struct arg_hdr **table) {
*/
tabindex = 0;
do {
- const char *longopts = table[tabindex]->longopts;
+ const char* longopts = table[tabindex]->longopts;
longoptlen += (longopts ? strlen(longopts) : 0) + 1;
while (longopts) {
noptions++;
@@ -3737,130 +4924,110 @@ static struct longoptions *alloc_longoptions(struct arg_hdr **table) {
} while (!(table[tabindex++]->flag & ARG_TERMINATOR));
/*printf("%d long options consuming %d chars in total\n",noptions,longoptlen);*/
-
/* allocate storage for return data structure as: */
/* (struct longoptions) + (struct options)[noptions] + char[longoptlen] */
- nbytes = sizeof(struct longoptions)
- + sizeof(struct option) * noptions
- + longoptlen;
- result = (struct longoptions *)malloc(nbytes);
- if (result) {
- int option_index = 0;
- char *store;
+ nbytes = sizeof(struct longoptions) + sizeof(struct option) * noptions + longoptlen;
+ result = (struct longoptions*)xmalloc(nbytes);
- result->getoptval = 0;
- result->noptions = noptions;
- result->options = (struct option *)(result + 1);
- store = (char *)(result->options + noptions);
+ result->getoptval = 0;
+ result->noptions = noptions;
+ result->options = (struct option*)(result + 1);
+ store = (char*)(result->options + noptions);
- for (tabindex = 0; !(table[tabindex]->flag & ARG_TERMINATOR); tabindex++) {
- const char *longopts = table[tabindex]->longopts;
+ for (tabindex = 0; !(table[tabindex]->flag & ARG_TERMINATOR); tabindex++) {
+ const char* longopts = table[tabindex]->longopts;
- while (longopts && *longopts) {
- char *storestart = store;
+ while (longopts && *longopts) {
+ char* storestart = store;
- /* copy progressive longopt strings into the store */
- while (*longopts != 0 && *longopts != ',')
- *store++ = *longopts++;
- *store++ = 0;
- if (*longopts == ',')
- longopts++;
- /*fprintf(stderr,"storestart=\"%s\"\n",storestart);*/
+ /* copy progressive longopt strings into the store */
+ while (*longopts != 0 && *longopts != ',')
+ *store++ = *longopts++;
+ *store++ = 0;
+ if (*longopts == ',')
+ longopts++;
+ /*fprintf(stderr,"storestart=\"%s\"\n",storestart);*/
- result->options[option_index].name = storestart;
- result->options[option_index].flag = &(result->getoptval);
- result->options[option_index].val = tabindex;
- if (table[tabindex]->flag & ARG_HASOPTVALUE)
- result->options[option_index].has_arg = 2;
- else if (table[tabindex]->flag & ARG_HASVALUE)
- result->options[option_index].has_arg = 1;
- else
- result->options[option_index].has_arg = 0;
+ result->options[option_index].name = storestart;
+ result->options[option_index].flag = &(result->getoptval);
+ result->options[option_index].val = tabindex;
+ if (table[tabindex]->flag & ARG_HASOPTVALUE)
+ result->options[option_index].has_arg = 2;
+ else if (table[tabindex]->flag & ARG_HASVALUE)
+ result->options[option_index].has_arg = 1;
+ else
+ result->options[option_index].has_arg = 0;
- option_index++;
- }
+ option_index++;
}
- /* terminate the options array with a zero-filled entry */
- result->options[option_index].name = 0;
- result->options[option_index].has_arg = 0;
- result->options[option_index].flag = 0;
- result->options[option_index].val = 0;
}
+ /* terminate the options array with a zero-filled entry */
+ result->options[option_index].name = 0;
+ result->options[option_index].has_arg = 0;
+ result->options[option_index].flag = 0;
+ result->options[option_index].val = 0;
/*dump_longoptions(result);*/
return result;
}
-static char *alloc_shortoptions(struct arg_hdr **table) {
- char *result;
+static char* alloc_shortoptions(struct arg_hdr** table) {
+ char* result;
size_t len = 2;
int tabindex;
+ char* res;
/* determine the total number of option chars required */
for (tabindex = 0; !(table[tabindex]->flag & ARG_TERMINATOR); tabindex++) {
- struct arg_hdr *hdr = table[tabindex];
+ struct arg_hdr* hdr = table[tabindex];
len += 3 * (hdr->shortopts ? strlen(hdr->shortopts) : 0);
}
- result = malloc(len);
- if (result) {
- char *res = result;
+ result = xmalloc(len);
- /* add a leading ':' so getopt return codes distinguish */
- /* unrecognised option and options missing argument values */
- *res++ = ':';
+ res = result;
- for (tabindex = 0; !(table[tabindex]->flag & ARG_TERMINATOR); tabindex++) {
- struct arg_hdr *hdr = table[tabindex];
- const char *shortopts = hdr->shortopts;
- while (shortopts && *shortopts) {
- *res++ = *shortopts++;
- if (hdr->flag & ARG_HASVALUE)
- *res++ = ':';
- if (hdr->flag & ARG_HASOPTVALUE)
- *res++ = ':';
- }
+ /* add a leading ':' so getopt return codes distinguish */
+ /* unrecognised option and options missing argument values */
+ *res++ = ':';
+
+ for (tabindex = 0; !(table[tabindex]->flag & ARG_TERMINATOR); tabindex++) {
+ struct arg_hdr* hdr = table[tabindex];
+ const char* shortopts = hdr->shortopts;
+ while (shortopts && *shortopts) {
+ *res++ = *shortopts++;
+ if (hdr->flag & ARG_HASVALUE)
+ *res++ = ':';
+ if (hdr->flag & ARG_HASOPTVALUE)
+ *res++ = ':';
}
- /* null terminate the string */
- *res = 0;
}
+ /* null terminate the string */
+ *res = 0;
/*printf("alloc_shortoptions() returns \"%s\"\n",(result?result:"NULL"));*/
return result;
}
-
/* return index of the table terminator entry */
-static int arg_endindex(struct arg_hdr **table) {
+static int arg_endindex(struct arg_hdr** table) {
int tabindex = 0;
while (!(table[tabindex]->flag & ARG_TERMINATOR))
tabindex++;
return tabindex;
}
-
-static void arg_parse_tagged(int argc,
- char **argv,
- struct arg_hdr **table,
- struct arg_end *endtable) {
- struct longoptions *longoptions;
- char *shortoptions;
+static void arg_parse_tagged(int argc, char** argv, struct arg_hdr** table, struct arg_end* endtable) {
+ struct longoptions* longoptions;
+ char* shortoptions;
int copt;
/*printf("arg_parse_tagged(%d,%p,%p,%p)\n",argc,argv,table,endtable);*/
/* allocate short and long option arrays for the given opttable[]. */
/* if the allocs fail then put an error msg in the last table entry. */
- longoptions = alloc_longoptions(table);
+ longoptions = alloc_longoptions(table);
shortoptions = alloc_shortoptions(table);
- if (!longoptions || !shortoptions) {
- /* one or both memory allocs failed */
- arg_register_error(endtable, endtable, ARG_EMALLOC, NULL);
- /* free anything that was allocated (this is null safe) */
- free(shortoptions);
- free(longoptions);
- return;
- }
/*dump_longoptions(longoptions);*/
@@ -3869,9 +5036,7 @@ static void arg_parse_tagged(int argc,
opterr = 0;
/* fetch and process args using getopt_long */
- while ((copt =
- getopt_long(argc, argv, shortoptions, longoptions->options,
- NULL)) != -1) {
+ while ((copt = getopt_long(argc, argv, shortoptions, longoptions->options, NULL)) != -1) {
/*
printf("optarg='%s'\n",optarg);
printf("optind=%d\n",optind);
@@ -3881,13 +5046,11 @@ static void arg_parse_tagged(int argc,
switch (copt) {
case 0: {
int tabindex = longoptions->getoptval;
- void *parent = table[tabindex]->parent;
+ void* parent = table[tabindex]->parent;
/*printf("long option detected from argtable[%d]\n", tabindex);*/
- if (optarg && optarg[0] == 0 &&
- (table[tabindex]->flag & ARG_HASVALUE)) {
+ if (optarg && optarg[0] == 0 && (table[tabindex]->flag & ARG_HASVALUE)) {
/* printf(": long option %s requires an argument\n",argv[optind-1]); */
- arg_register_error(endtable, endtable, ARG_EMISSARG,
- argv[optind - 1]);
+ arg_register_error(endtable, endtable, ARG_EMISSARG, argv[optind - 1]);
/* continue to scan the (empty) argument value to enforce argument count checking */
}
if (table[tabindex]->scanfn) {
@@ -3895,8 +5058,7 @@ static void arg_parse_tagged(int argc,
if (errorcode != 0)
arg_register_error(endtable, parent, errorcode, optarg);
}
- }
- break;
+ } break;
case '?':
/*
@@ -3907,8 +5069,7 @@ static void arg_parse_tagged(int argc,
switch (optopt) {
case 0:
/*printf("?0 unrecognised long option %s\n",argv[optind-1]);*/
- arg_register_error(endtable, endtable, ARG_ELONGOPT,
- argv[optind - 1]);
+ arg_register_error(endtable, endtable, ARG_ELONGOPT, argv[optind - 1]);
break;
default:
/*printf("?* unrecognised short option '%c'\n",optopt);*/
@@ -3922,8 +5083,7 @@ static void arg_parse_tagged(int argc,
* getopt_long() found an option with its argument missing.
*/
/*printf(": option %s requires an argument\n",argv[optind-1]); */
- arg_register_error(endtable, endtable, ARG_EMISSARG,
- argv[optind - 1]);
+ arg_register_error(endtable, endtable, ARG_EMISSARG, argv[optind - 1]);
break;
default: {
@@ -3936,7 +5096,7 @@ static void arg_parse_tagged(int argc,
arg_register_error(endtable, endtable, copt, NULL);
} else {
if (table[tabindex]->scanfn) {
- void *parent = table[tabindex]->parent;
+ void* parent = table[tabindex]->parent;
int errorcode = table[tabindex]->scanfn(parent, optarg);
if (errorcode != 0)
arg_register_error(endtable, parent, errorcode, optarg);
@@ -3947,23 +5107,19 @@ static void arg_parse_tagged(int argc,
}
}
- free(shortoptions);
- free(longoptions);
+ xfree(shortoptions);
+ xfree(longoptions);
}
-
-static void arg_parse_untagged(int argc,
- char **argv,
- struct arg_hdr **table,
- struct arg_end *endtable) {
+static void arg_parse_untagged(int argc, char** argv, struct arg_hdr** table, struct arg_end* endtable) {
int tabindex = 0;
int errorlast = 0;
- const char *optarglast = NULL;
- void *parentlast = NULL;
+ const char* optarglast = NULL;
+ void* parentlast = NULL;
/*printf("arg_parse_untagged(%d,%p,%p,%p)\n",argc,argv,table,endtable);*/
while (!(table[tabindex]->flag & ARG_TERMINATOR)) {
- void *parent;
+ void* parent;
int errorcode;
/* if we have exhausted our argv[optind] entries then we have finished */
@@ -4026,13 +5182,12 @@ static void arg_parse_untagged(int argc,
return;
}
-
-static void arg_parse_check(struct arg_hdr **table, struct arg_end *endtable) {
+static void arg_parse_check(struct arg_hdr** table, struct arg_end* endtable) {
int tabindex = 0;
/* printf("arg_parse_check()\n"); */
do {
if (table[tabindex]->checkfn) {
- void *parent = table[tabindex]->parent;
+ void* parent = table[tabindex]->parent;
int errorcode = table[tabindex]->checkfn(parent);
if (errorcode != 0)
arg_register_error(endtable, parent, errorcode, NULL);
@@ -4040,9 +5195,8 @@ static void arg_parse_check(struct arg_hdr **table, struct arg_end *endtable) {
} while (!(table[tabindex++]->flag & ARG_TERMINATOR));
}
-
-static void arg_reset(void **argtable) {
- struct arg_hdr * *table = (struct arg_hdr * *)argtable;
+static void arg_reset(void** argtable) {
+ struct arg_hdr** table = (struct arg_hdr**)argtable;
int tabindex = 0;
/*printf("arg_reset(%p)\n",argtable);*/
do {
@@ -4051,12 +5205,12 @@ static void arg_reset(void **argtable) {
} while (!(table[tabindex++]->flag & ARG_TERMINATOR));
}
-
-int arg_parse(int argc, char * *argv, void * *argtable) {
- struct arg_hdr * *table = (struct arg_hdr * *)argtable;
- struct arg_end *endtable;
+int arg_parse(int argc, char** argv, void** argtable) {
+ struct arg_hdr** table = (struct arg_hdr**)argtable;
+ struct arg_end* endtable;
int endindex;
- char * *argvcopy = NULL;
+ char** argvcopy = NULL;
+ int i;
/*printf("arg_parse(%d,%p,%p)\n",argc,argv,argtable);*/
@@ -4065,7 +5219,7 @@ int arg_parse(int argc, char * *argv, void * *argtable) {
/* locate the first end-of-table marker within the array */
endindex = arg_endindex(table);
- endtable = (struct arg_end *)table[endindex];
+ endtable = (struct arg_end*)table[endindex];
/* Special case of argc==0. This can occur on Texas Instruments DSP. */
/* Failure to trap this case results in an unwanted NULL result from */
@@ -4078,41 +5232,34 @@ int arg_parse(int argc, char * *argv, void * *argtable) {
return endtable->count;
}
- argvcopy = (char **)malloc(sizeof(char *) * (argc + 1));
- if (argvcopy) {
- int i;
+ argvcopy = (char**)xmalloc(sizeof(char*) * (argc + 1));
- /*
- Fill in the local copy of argv[]. We need a local copy
- because getopt rearranges argv[] which adversely affects
- susbsequent parsing attempts.
- */
- for (i = 0; i < argc; i++)
- argvcopy[i] = argv[i];
+ /*
+ Fill in the local copy of argv[]. We need a local copy
+ because getopt rearranges argv[] which adversely affects
+ susbsequent parsing attempts.
+ */
+ for (i = 0; i < argc; i++)
+ argvcopy[i] = argv[i];
- argvcopy[argc] = NULL;
+ argvcopy[argc] = NULL;
- /* parse the command line (local copy) for tagged options */
- arg_parse_tagged(argc, argvcopy, table, endtable);
+ /* parse the command line (local copy) for tagged options */
+ arg_parse_tagged(argc, argvcopy, table, endtable);
- /* parse the command line (local copy) for untagged options */
- arg_parse_untagged(argc, argvcopy, table, endtable);
+ /* parse the command line (local copy) for untagged options */
+ arg_parse_untagged(argc, argvcopy, table, endtable);
- /* if no errors so far then perform post-parse checks otherwise dont bother */
- if (endtable->count == 0)
- arg_parse_check(table, endtable);
+ /* if no errors so far then perform post-parse checks otherwise dont bother */
+ if (endtable->count == 0)
+ arg_parse_check(table, endtable);
- /* release the local copt of argv[] */
- free(argvcopy);
- } else {
- /* memory alloc failed */
- arg_register_error(endtable, endtable, ARG_EMALLOC, NULL);
- }
+ /* release the local copt of argv[] */
+ xfree(argvcopy);
return endtable->count;
}
-
/*
* Concatenate contents of src[] string onto *pdest[] string.
* The *pdest pointer is altered to point to the end of the
@@ -4133,9 +5280,9 @@ int arg_parse(int argc, char * *argv, void * *argtable) {
* dest[] == "goodbye cruel world!"
* ndest == 10
*/
-static void arg_cat(char **pdest, const char *src, size_t *pndest) {
- char *dest = *pdest;
- char *end = dest + *pndest;
+static void arg_cat(char** pdest, const char* src, size_t* pndest) {
+ char* dest = *pdest;
+ char* end = dest + *pndest;
/*locate null terminator of dest string */
while (dest < end && *dest != 0)
@@ -4150,16 +5297,10 @@ static void arg_cat(char **pdest, const char *src, size_t *pndest) {
/* update *pdest and *pndest */
*pndest = end - dest;
- *pdest = dest;
+ *pdest = dest;
}
-
-static void arg_cat_option(char *dest,
- size_t ndest,
- const char *shortopts,
- const char *longopts,
- const char *datatype,
- int optvalue) {
+static void arg_cat_option(char* dest, size_t ndest, const char* shortopts, const char* longopts, const char* datatype, int optvalue) {
if (shortopts) {
char option[3];
@@ -4187,7 +5328,7 @@ static void arg_cat_option(char *dest,
/* add comma separated option tag */
ncspn = strcspn(longopts, ",");
-#ifdef __STDC_WANT_SECURE_LIB__
+#if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || (defined(__STDC_SECURE_LIB__) && defined(__STDC_WANT_SECURE_LIB__))
strncat_s(dest, ndest, longopts, (ncspn < ndest) ? ncspn : ndest);
#else
strncat(dest, longopts, (ncspn < ndest) ? ncspn : ndest);
@@ -4212,17 +5353,12 @@ static void arg_cat_option(char *dest,
}
}
-static void arg_cat_optionv(char *dest,
- size_t ndest,
- const char *shortopts,
- const char *longopts,
- const char *datatype,
- int optvalue,
- const char *separator) {
+static void
+arg_cat_optionv(char* dest, size_t ndest, const char* shortopts, const char* longopts, const char* datatype, int optvalue, const char* separator) {
separator = separator ? separator : "";
if (shortopts) {
- const char *c = shortopts;
+ const char* c = shortopts;
while (*c) {
/* "-a|-b|-c" */
char shortopt[3];
@@ -4244,7 +5380,7 @@ static void arg_cat_optionv(char *dest,
arg_cat(&dest, separator, &ndest);
if (longopts) {
- const char *c = longopts;
+ const char* c = longopts;
while (*c) {
size_t ncspn;
@@ -4253,7 +5389,7 @@ static void arg_cat_optionv(char *dest,
/* add comma separated option tag */
ncspn = strcspn(c, ",");
-#ifdef __STDC_WANT_SECURE_LIB__
+#if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || (defined(__STDC_SECURE_LIB__) && defined(__STDC_WANT_SECURE_LIB__))
strncat_s(dest, ndest, c, (ncspn < ndest) ? ncspn : ndest);
#else
strncat(dest, c, (ncspn < ndest) ? ncspn : ndest);
@@ -4283,46 +5419,38 @@ static void arg_cat_optionv(char *dest,
}
}
-
-/* this function should be deprecated because it doesnt consider optional argument values (ARG_HASOPTVALUE) */
-void arg_print_option(FILE *fp,
- const char *shortopts,
- const char *longopts,
- const char *datatype,
- const char *suffix) {
+void arg_print_option_ds(arg_dstr_t ds, const char* shortopts, const char* longopts, const char* datatype, const char* suffix) {
char syntax[200] = "";
suffix = suffix ? suffix : "";
/* there is no way of passing the proper optvalue for optional argument values here, so we must ignore it */
- arg_cat_optionv(syntax,
- sizeof(syntax),
- shortopts,
- longopts,
- datatype,
- 0,
- "|");
+ arg_cat_optionv(syntax, sizeof(syntax), shortopts, longopts, datatype, 0, "|");
- fputs(syntax, fp);
- fputs(suffix, fp);
+ arg_dstr_cat(ds, syntax);
+ arg_dstr_cat(ds, (char*)suffix);
}
+/* this function should be deprecated because it doesn't consider optional argument values (ARG_HASOPTVALUE) */
+void arg_print_option(FILE* fp, const char* shortopts, const char* longopts, const char* datatype, const char* suffix) {
+ arg_dstr_t ds = arg_dstr_create();
+ arg_print_option_ds(ds, shortopts, longopts, datatype, suffix);
+ fputs(arg_dstr_cstr(ds), fp);
+ arg_dstr_destroy(ds);
+}
/*
* Print a GNU style [OPTION] string in which all short options that
* do not take argument values are presented in abbreviated form, as
* in: -xvfsd, or -xvf[sd], or [-xvsfd]
*/
-static
-void arg_print_gnuswitch(FILE *fp, struct arg_hdr * *table) {
+static void arg_print_gnuswitch_ds(arg_dstr_t ds, struct arg_hdr** table) {
int tabindex;
- const char *format1 = " -%c";
- const char *format2 = " [-%c";
- const char *suffix = "";
+ char* format1 = " -%c";
+ char* format2 = " [-%c";
+ char* suffix = "";
/* print all mandatory switches that are without argument values */
- for (tabindex = 0;
- table[tabindex] && !(table[tabindex]->flag & ARG_TERMINATOR);
- tabindex++) {
+ for (tabindex = 0; table[tabindex] && !(table[tabindex]->flag & ARG_TERMINATOR); tabindex++) {
/* skip optional options */
if (table[tabindex]->mincount < 1)
continue;
@@ -4336,15 +5464,13 @@ void arg_print_gnuswitch(FILE *fp, struct arg_hdr * *table) {
continue;
/* print the short option (only the first short option char, ignore multiple choices)*/
- fprintf(fp, format1, table[tabindex]->shortopts[0]);
+ arg_dstr_catf(ds, format1, table[tabindex]->shortopts[0]);
format1 = "%c";
format2 = "[%c";
}
/* print all optional switches that are without argument values */
- for (tabindex = 0;
- table[tabindex] && !(table[tabindex]->flag & ARG_TERMINATOR);
- tabindex++) {
+ for (tabindex = 0; table[tabindex] && !(table[tabindex]->flag & ARG_TERMINATOR); tabindex++) {
/* skip mandatory args */
if (table[tabindex]->mincount > 0)
continue;
@@ -4358,142 +5484,161 @@ void arg_print_gnuswitch(FILE *fp, struct arg_hdr * *table) {
continue;
/* print first short option */
- fprintf(fp, format2, table[tabindex]->shortopts[0]);
+ arg_dstr_catf(ds, format2, table[tabindex]->shortopts[0]);
format2 = "%c";
suffix = "]";
}
- fprintf(fp, "%s", suffix);
+ arg_dstr_catf(ds, "%s", suffix);
}
-
-void arg_print_syntax(FILE *fp, void * *argtable, const char *suffix) {
- struct arg_hdr * *table = (struct arg_hdr * *)argtable;
+void arg_print_syntax_ds(arg_dstr_t ds, void** argtable, const char* suffix) {
+ struct arg_hdr** table = (struct arg_hdr**)argtable;
int i, tabindex;
/* print GNU style [OPTION] string */
- arg_print_gnuswitch(fp, table);
+ arg_print_gnuswitch_ds(ds, table);
/* print remaining options in abbreviated style */
- for (tabindex = 0;
- table[tabindex] && !(table[tabindex]->flag & ARG_TERMINATOR);
- tabindex++) {
+ for (tabindex = 0; table[tabindex] && !(table[tabindex]->flag & ARG_TERMINATOR); tabindex++) {
char syntax[200] = "";
const char *shortopts, *longopts, *datatype;
/* skip short options without arg values (they were printed by arg_print_gnu_switch) */
- if (table[tabindex]->shortopts &&
- !(table[tabindex]->flag & ARG_HASVALUE))
+ if (table[tabindex]->shortopts && !(table[tabindex]->flag & ARG_HASVALUE))
continue;
shortopts = table[tabindex]->shortopts;
- longopts = table[tabindex]->longopts;
- datatype = table[tabindex]->datatype;
- arg_cat_option(syntax,
- sizeof(syntax),
- shortopts,
- longopts,
- datatype,
- table[tabindex]->flag & ARG_HASOPTVALUE);
+ longopts = table[tabindex]->longopts;
+ datatype = table[tabindex]->datatype;
+ arg_cat_option(syntax, sizeof(syntax), shortopts, longopts, datatype, table[tabindex]->flag & ARG_HASOPTVALUE);
if (strlen(syntax) > 0) {
/* print mandatory instances of this option */
- for (i = 0; i < table[tabindex]->mincount; i++)
- fprintf(fp, " %s", syntax);
+ for (i = 0; i < table[tabindex]->mincount; i++) {
+ arg_dstr_cat(ds, " ");
+ arg_dstr_cat(ds, syntax);
+ }
/* print optional instances enclosed in "[..]" */
switch (table[tabindex]->maxcount - table[tabindex]->mincount) {
case 0:
break;
case 1:
- fprintf(fp, " [%s]", syntax);
+ arg_dstr_cat(ds, " [");
+ arg_dstr_cat(ds, syntax);
+ arg_dstr_cat(ds, "]");
break;
case 2:
- fprintf(fp, " [%s] [%s]", syntax, syntax);
+ arg_dstr_cat(ds, " [");
+ arg_dstr_cat(ds, syntax);
+ arg_dstr_cat(ds, "]");
+ arg_dstr_cat(ds, " [");
+ arg_dstr_cat(ds, syntax);
+ arg_dstr_cat(ds, "]");
break;
default:
- fprintf(fp, " [%s]...", syntax);
+ arg_dstr_cat(ds, " [");
+ arg_dstr_cat(ds, syntax);
+ arg_dstr_cat(ds, "]...");
break;
}
}
}
- if (suffix)
- fprintf(fp, "%s", suffix);
+ if (suffix) {
+ arg_dstr_cat(ds, (char*)suffix);
+ }
}
+void arg_print_syntax(FILE* fp, void** argtable, const char* suffix) {
+ arg_dstr_t ds = arg_dstr_create();
+ arg_print_syntax_ds(ds, argtable, suffix);
+ fputs(arg_dstr_cstr(ds), fp);
+ arg_dstr_destroy(ds);
+}
-void arg_print_syntaxv(FILE *fp, void * *argtable, const char *suffix) {
- struct arg_hdr * *table = (struct arg_hdr * *)argtable;
+void arg_print_syntaxv_ds(arg_dstr_t ds, void** argtable, const char* suffix) {
+ struct arg_hdr** table = (struct arg_hdr**)argtable;
int i, tabindex;
/* print remaining options in abbreviated style */
- for (tabindex = 0;
- table[tabindex] && !(table[tabindex]->flag & ARG_TERMINATOR);
- tabindex++) {
+ for (tabindex = 0; table[tabindex] && !(table[tabindex]->flag & ARG_TERMINATOR); tabindex++) {
char syntax[200] = "";
const char *shortopts, *longopts, *datatype;
shortopts = table[tabindex]->shortopts;
- longopts = table[tabindex]->longopts;
- datatype = table[tabindex]->datatype;
- arg_cat_optionv(syntax,
- sizeof(syntax),
- shortopts,
- longopts,
- datatype,
- table[tabindex]->flag & ARG_HASOPTVALUE,
- "|");
+ longopts = table[tabindex]->longopts;
+ datatype = table[tabindex]->datatype;
+ arg_cat_optionv(syntax, sizeof(syntax), shortopts, longopts, datatype, table[tabindex]->flag & ARG_HASOPTVALUE, "|");
/* print mandatory options */
- for (i = 0; i < table[tabindex]->mincount; i++)
- fprintf(fp, " %s", syntax);
+ for (i = 0; i < table[tabindex]->mincount; i++) {
+ arg_dstr_cat(ds, " ");
+ arg_dstr_cat(ds, syntax);
+ }
/* print optional args enclosed in "[..]" */
switch (table[tabindex]->maxcount - table[tabindex]->mincount) {
case 0:
break;
case 1:
- fprintf(fp, " [%s]", syntax);
+ arg_dstr_cat(ds, " [");
+ arg_dstr_cat(ds, syntax);
+ arg_dstr_cat(ds, "]");
break;
case 2:
- fprintf(fp, " [%s] [%s]", syntax, syntax);
+ arg_dstr_cat(ds, " [");
+ arg_dstr_cat(ds, syntax);
+ arg_dstr_cat(ds, "]");
+ arg_dstr_cat(ds, " [");
+ arg_dstr_cat(ds, syntax);
+ arg_dstr_cat(ds, "]");
break;
default:
- fprintf(fp, " [%s]...", syntax);
+ arg_dstr_cat(ds, " [");
+ arg_dstr_cat(ds, syntax);
+ arg_dstr_cat(ds, "]...");
break;
}
}
- if (suffix)
- fprintf(fp, "%s", suffix);
+ if (suffix) {
+ arg_dstr_cat(ds, (char*)suffix);
+ }
}
+void arg_print_syntaxv(FILE* fp, void** argtable, const char* suffix) {
+ arg_dstr_t ds = arg_dstr_create();
+ arg_print_syntaxv_ds(ds, argtable, suffix);
+ fputs(arg_dstr_cstr(ds), fp);
+ arg_dstr_destroy(ds);
+}
-void arg_print_glossary(FILE *fp, void * *argtable, const char *format) {
- struct arg_hdr * *table = (struct arg_hdr * *)argtable;
+void arg_print_glossary_ds(arg_dstr_t ds, void** argtable, const char* format) {
+ struct arg_hdr** table = (struct arg_hdr**)argtable;
int tabindex;
format = format ? format : " %-20s %s\n";
for (tabindex = 0; !(table[tabindex]->flag & ARG_TERMINATOR); tabindex++) {
if (table[tabindex]->glossary) {
char syntax[200] = "";
- const char *shortopts = table[tabindex]->shortopts;
- const char *longopts = table[tabindex]->longopts;
- const char *datatype = table[tabindex]->datatype;
- const char *glossary = table[tabindex]->glossary;
- arg_cat_optionv(syntax,
- sizeof(syntax),
- shortopts,
- longopts,
- datatype,
- table[tabindex]->flag & ARG_HASOPTVALUE,
- ", ");
- fprintf(fp, format, syntax, glossary);
+ const char* shortopts = table[tabindex]->shortopts;
+ const char* longopts = table[tabindex]->longopts;
+ const char* datatype = table[tabindex]->datatype;
+ const char* glossary = table[tabindex]->glossary;
+ arg_cat_optionv(syntax, sizeof(syntax), shortopts, longopts, datatype, table[tabindex]->flag & ARG_HASOPTVALUE, ", ");
+ arg_dstr_catf(ds, format, syntax, glossary);
}
}
}
+void arg_print_glossary(FILE* fp, void** argtable, const char* format) {
+ arg_dstr_t ds = arg_dstr_create();
+ arg_print_glossary_ds(ds, argtable, format);
+ fputs(arg_dstr_cstr(ds), fp);
+ arg_dstr_destroy(ds);
+}
/**
* Print a piece of text formatted, which means in a column with a
@@ -4527,62 +5672,62 @@ void arg_print_glossary(FILE *fp, void * *argtable, const char *format) {
*
* Author: Uli Fouquet
*/
-static
-void arg_print_formatted(FILE *fp,
- const unsigned lmargin,
- const unsigned rmargin,
- const char *text) {
- const unsigned textlen = (unsigned)strlen(text);
- unsigned line_start = 0;
- unsigned line_end = textlen + 1;
- const unsigned colwidth = (rmargin - lmargin) + 1;
+static void arg_print_formatted_ds(arg_dstr_t ds, const unsigned lmargin, const unsigned rmargin, const char* text) {
+ const unsigned int textlen = (unsigned int)strlen(text);
+ unsigned int line_start = 0;
+ unsigned int line_end = textlen;
+ const unsigned int colwidth = (rmargin - lmargin) + 1;
+
+ assert(strlen(text) < UINT_MAX);
/* Someone doesn't like us... */
- if (line_end == line_start) {
- fprintf(fp, "%s\n", text);
+ if (line_end < line_start) {
+ arg_dstr_catf(ds, "%s\n", text);
}
- while (line_end - 1 > line_start) {
- /* Eat leading whitespaces. This is essential because while
+ while (line_end > line_start) {
+ /* Eat leading white spaces. This is essential because while
wrapping lines, there will often be a whitespace at beginning
of line */
- while (ISSPACE(*(text + line_start)))
- { line_start++; }
-
- if ((line_end - line_start) > colwidth)
- { line_end = line_start + colwidth; }
+ while (isspace(*(text + line_start))) {
+ line_start++;
+ }
/* Find last whitespace, that fits into line */
- while ((line_end > line_start)
- && (line_end - line_start > colwidth)
- && !ISSPACE(*(text + line_end)))
- { line_end--; }
+ if (line_end - line_start > colwidth) {
+ line_end = line_start + colwidth;
- /* Do not print trailing whitespace. If this text
- has got only one line, line_end now points to the
- last char due to initialization. */
- line_end--;
+ while ((line_end > line_start) && !isspace(*(text + line_end))) {
+ line_end--;
+ }
+
+ /* Consume trailing spaces */
+ while ((line_end > line_start) && isspace(*(text + line_end))) {
+ line_end--;
+ }
+
+ /* Restore the last non-space character */
+ line_end++;
+ }
/* Output line of text */
while (line_start < line_end) {
- fputc(*(text + line_start), fp);
+ char c = *(text + line_start);
+ arg_dstr_catc(ds, c);
line_start++;
}
- fputc('\n', fp);
+ arg_dstr_cat(ds, "\n");
/* Initialize another line */
- if (line_end + 1 < textlen) {
+ if (line_end < textlen) {
unsigned i;
- for (i = 0; i < lmargin; i++)
- { fputc(' ', fp); }
+ for (i = 0; i < lmargin; i++) {
+ arg_dstr_cat(ds, " ");
+ }
line_end = textlen;
}
-
- /* If we have to print another line, get also the last char. */
- line_end++;
-
} /* lines of text */
}
@@ -4595,17 +5740,17 @@ void arg_print_formatted(FILE *fp,
*
* Contributed by Uli Fouquet
*/
-void arg_print_glossary_gnu(FILE *fp, void * *argtable) {
- struct arg_hdr * *table = (struct arg_hdr * *)argtable;
+void arg_print_glossary_gnu_ds(arg_dstr_t ds, void** argtable) {
+ struct arg_hdr** table = (struct arg_hdr**)argtable;
int tabindex;
for (tabindex = 0; !(table[tabindex]->flag & ARG_TERMINATOR); tabindex++) {
if (table[tabindex]->glossary) {
char syntax[200] = "";
- const char *shortopts = table[tabindex]->shortopts;
- const char *longopts = table[tabindex]->longopts;
- const char *datatype = table[tabindex]->datatype;
- const char *glossary = table[tabindex]->glossary;
+ const char* shortopts = table[tabindex]->shortopts;
+ const char* longopts = table[tabindex]->longopts;
+ const char* datatype = table[tabindex]->datatype;
+ const char* glossary = table[tabindex]->glossary;
if (!shortopts && longopts) {
/* Indent trailing line by 4 spaces... */
@@ -4613,35 +5758,35 @@ void arg_print_glossary_gnu(FILE *fp, void * *argtable) {
*(syntax + 4) = '\0';
}
- arg_cat_optionv(syntax,
- sizeof(syntax),
- shortopts,
- longopts,
- datatype,
- table[tabindex]->flag & ARG_HASOPTVALUE,
- ", ");
+ arg_cat_optionv(syntax, sizeof(syntax), shortopts, longopts, datatype, table[tabindex]->flag & ARG_HASOPTVALUE, ", ");
/* If syntax fits not into column, print glossary in new line... */
if (strlen(syntax) > 25) {
- fprintf(fp, " %-25s %s\n", syntax, "");
+ arg_dstr_catf(ds, " %-25s %s\n", syntax, "");
*syntax = '\0';
}
- fprintf(fp, " %-25s ", syntax);
- arg_print_formatted(fp, 28, 79, glossary);
+ arg_dstr_catf(ds, " %-25s ", syntax);
+ arg_print_formatted_ds(ds, 28, 79, glossary);
}
} /* for each table entry */
- fputc('\n', fp);
+ arg_dstr_cat(ds, "\n");
}
+void arg_print_glossary_gnu(FILE* fp, void** argtable) {
+ arg_dstr_t ds = arg_dstr_create();
+ arg_print_glossary_gnu_ds(ds, argtable);
+ fputs(arg_dstr_cstr(ds), fp);
+ arg_dstr_destroy(ds);
+}
/**
* Checks the argtable[] array for NULL entries and returns 1
* if any are found, zero otherwise.
*/
-int arg_nullcheck(void * *argtable) {
- struct arg_hdr * *table = (struct arg_hdr * *)argtable;
+int arg_nullcheck(void** argtable) {
+ struct arg_hdr** table = (struct arg_hdr**)argtable;
int tabindex;
/*printf("arg_nullcheck(%p)\n",argtable);*/
@@ -4669,8 +5814,8 @@ int arg_nullcheck(void * *argtable) {
* with the newer arg_freetable() function.
* We still keep arg_free() for backwards compatibility.
*/
-void arg_free(void * *argtable) {
- struct arg_hdr * *table = (struct arg_hdr * *)argtable;
+void arg_free(void** argtable) {
+ struct arg_hdr** table = (struct arg_hdr**)argtable;
int tabindex = 0;
int flag;
/*printf("arg_free(%p)\n",argtable);*/
@@ -4685,23 +5830,31 @@ void arg_free(void * *argtable) {
break;
flag = table[tabindex]->flag;
- free(table[tabindex]);
+ xfree(table[tabindex]);
table[tabindex++] = NULL;
} while (!(flag & ARG_TERMINATOR));
}
/* frees each non-NULL element of argtable[], where n is the size of the number of entries in the array */
-void arg_freetable(void * *argtable, size_t n) {
- struct arg_hdr * *table = (struct arg_hdr * *)argtable;
+void arg_freetable(void** argtable, size_t n) {
+ struct arg_hdr** table = (struct arg_hdr**)argtable;
size_t tabindex = 0;
/*printf("arg_freetable(%p)\n",argtable);*/
for (tabindex = 0; tabindex < n; tabindex++) {
if (table[tabindex] == NULL)
continue;
- free(table[tabindex]);
+ xfree(table[tabindex]);
table[tabindex] = NULL;
};
}
+#ifdef _WIN32
+BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) {
+ return TRUE;
+ UNREFERENCED_PARAMETER(hinstDLL);
+ UNREFERENCED_PARAMETER(fdwReason);
+ UNREFERENCED_PARAMETER(lpvReserved);
+}
+#endif
diff --git a/client/deps/cliparser/argtable3.h b/client/deps/cliparser/argtable3.h
index d8e3c53cc..204253876 100644
--- a/client/deps/cliparser/argtable3.h
+++ b/client/deps/cliparser/argtable3.h
@@ -33,8 +33,8 @@
#ifndef ARGTABLE3
#define ARGTABLE3
-#include /* FILE */
-#include /* struct tm */
+#include /* FILE */
+#include /* struct tm */
#ifdef __cplusplus
extern "C" {
@@ -50,259 +50,226 @@ extern "C" {
#endif /* ARG_REPLACE_GETOPT */
/* bit masks for arg_hdr.flag */
-enum {
- ARG_TERMINATOR = 0x1,
- ARG_HASVALUE = 0x2,
- ARG_HASOPTVALUE = 0x4
-};
+enum { ARG_TERMINATOR = 0x1, ARG_HASVALUE = 0x2, ARG_HASOPTVALUE = 0x4 };
-typedef void (arg_resetfn)(void *parent);
-typedef int (arg_scanfn)(void *parent, const char *argval);
-typedef int (arg_checkfn)(void *parent);
-typedef void (arg_errorfn)(void *parent, FILE *fp, int error, const char *argval, const char *progname);
+#if defined(_WIN32)
+ #if defined(argtable3_EXPORTS)
+ #define ARG_EXTERN __declspec(dllexport)
+ #elif defined(argtable3_IMPORTS)
+ #define ARG_EXTERN __declspec(dllimport)
+ #else
+ #define ARG_EXTERN
+ #endif
+#else
+ #define ARG_EXTERN
+#endif
+typedef struct _internal_arg_dstr* arg_dstr_t;
+typedef void* arg_cmd_itr_t;
+
+typedef void(arg_resetfn)(void* parent);
+typedef int(arg_scanfn)(void* parent, const char* argval);
+typedef int(arg_checkfn)(void* parent);
+typedef void(arg_errorfn)(void* parent, arg_dstr_t ds, int error, const char* argval, const char* progname);
+typedef void(arg_dstr_freefn)(char* buf);
+typedef int(arg_cmdfn)(int argc, char* argv[], arg_dstr_t res);
+typedef int(arg_comparefn)(const void* k1, const void* k2);
/*
-* The arg_hdr struct defines properties that are common to all arg_xxx structs.
-* The argtable library requires each arg_xxx struct to have an arg_hdr
-* struct as its first data member.
-* The argtable library functions then use this data to identify the
-* properties of the command line option, such as its option tags,
-* datatype string, and glossary strings, and so on.
-* Moreover, the arg_hdr struct contains pointers to custom functions that
-* are provided by each arg_xxx struct which perform the tasks of parsing
-* that particular arg_xxx arguments, performing post-parse checks, and
-* reporting errors.
-* These functions are private to the individual arg_xxx source code
-* and are the pointer to them are initiliased by that arg_xxx struct's
-* constructor function. The user could alter them after construction
-* if desired, but the original intention is for them to be set by the
-* constructor and left unaltered.
-*/
+ * The arg_hdr struct defines properties that are common to all arg_xxx structs.
+ * The argtable library requires each arg_xxx struct to have an arg_hdr
+ * struct as its first data member.
+ * The argtable library functions then use this data to identify the
+ * properties of the command line option, such as its option tags,
+ * datatype string, and glossary strings, and so on.
+ * Moreover, the arg_hdr struct contains pointers to custom functions that
+ * are provided by each arg_xxx struct which perform the tasks of parsing
+ * that particular arg_xxx arguments, performing post-parse checks, and
+ * reporting errors.
+ * These functions are private to the individual arg_xxx source code
+ * and are the pointer to them are initiliased by that arg_xxx struct's
+ * constructor function. The user could alter them after construction
+ * if desired, but the original intention is for them to be set by the
+ * constructor and left unaltered.
+ */
struct arg_hdr {
- char flag; /* Modifier flags: ARG_TERMINATOR, ARG_HASVALUE. */
- const char *shortopts; /* String defining the short options */
- const char *longopts; /* String defiing the long options */
- const char *datatype; /* Description of the argument data type */
- const char *glossary; /* Description of the option as shown by arg_print_glossary function */
- int mincount; /* Minimum number of occurences of this option accepted */
- int maxcount; /* Maximum number of occurences if this option accepted */
- void *parent; /* Pointer to parent arg_xxx struct */
- arg_resetfn *resetfn; /* Pointer to parent arg_xxx reset function */
- arg_scanfn *scanfn; /* Pointer to parent arg_xxx scan function */
- arg_checkfn *checkfn; /* Pointer to parent arg_xxx check function */
- arg_errorfn *errorfn; /* Pointer to parent arg_xxx error function */
- void *priv; /* Pointer to private header data for use by arg_xxx functions */
+ char flag; /* Modifier flags: ARG_TERMINATOR, ARG_HASVALUE. */
+ const char* shortopts; /* String defining the short options */
+ const char* longopts; /* String defiing the long options */
+ const char* datatype; /* Description of the argument data type */
+ const char* glossary; /* Description of the option as shown by arg_print_glossary function */
+ int mincount; /* Minimum number of occurences of this option accepted */
+ int maxcount; /* Maximum number of occurences if this option accepted */
+ void* parent; /* Pointer to parent arg_xxx struct */
+ arg_resetfn* resetfn; /* Pointer to parent arg_xxx reset function */
+ arg_scanfn* scanfn; /* Pointer to parent arg_xxx scan function */
+ arg_checkfn* checkfn; /* Pointer to parent arg_xxx check function */
+ arg_errorfn* errorfn; /* Pointer to parent arg_xxx error function */
+ void* priv; /* Pointer to private header data for use by arg_xxx functions */
};
struct arg_rem {
- struct arg_hdr hdr; /* The mandatory argtable header struct */
+ struct arg_hdr hdr; /* The mandatory argtable header struct */
};
struct arg_lit {
- struct arg_hdr hdr; /* The mandatory argtable header struct */
- int count; /* Number of matching command line args */
+ struct arg_hdr hdr; /* The mandatory argtable header struct */
+ int count; /* Number of matching command line args */
};
struct arg_int {
- struct arg_hdr hdr; /* The mandatory argtable header struct */
- int count; /* Number of matching command line args */
- int *ival; /* Array of parsed argument values */
+ struct arg_hdr hdr; /* The mandatory argtable header struct */
+ int count; /* Number of matching command line args */
+ int* ival; /* Array of parsed argument values */
};
struct arg_dbl {
- struct arg_hdr hdr; /* The mandatory argtable header struct */
- int count; /* Number of matching command line args */
- double *dval; /* Array of parsed argument values */
+ struct arg_hdr hdr; /* The mandatory argtable header struct */
+ int count; /* Number of matching command line args */
+ double* dval; /* Array of parsed argument values */
};
struct arg_str {
- struct arg_hdr hdr; /* The mandatory argtable header struct */
- int count; /* Number of matching command line args */
- const char **sval; /* Array of parsed argument values */
+ struct arg_hdr hdr; /* The mandatory argtable header struct */
+ int count; /* Number of matching command line args */
+ const char** sval; /* Array of parsed argument values */
};
struct arg_rex {
- struct arg_hdr hdr; /* The mandatory argtable header struct */
- int count; /* Number of matching command line args */
- const char **sval; /* Array of parsed argument values */
+ struct arg_hdr hdr; /* The mandatory argtable header struct */
+ int count; /* Number of matching command line args */
+ const char** sval; /* Array of parsed argument values */
};
struct arg_file {
- struct arg_hdr hdr; /* The mandatory argtable header struct */
- int count; /* Number of matching command line args*/
- const char **filename; /* Array of parsed filenames (eg: /home/foo.bar) */
- const char **basename; /* Array of parsed basenames (eg: foo.bar) */
- const char **extension; /* Array of parsed extensions (eg: .bar) */
+ struct arg_hdr hdr; /* The mandatory argtable header struct */
+ int count; /* Number of matching command line args*/
+ const char** filename; /* Array of parsed filenames (eg: /home/foo.bar) */
+ const char** basename; /* Array of parsed basenames (eg: foo.bar) */
+ const char** extension; /* Array of parsed extensions (eg: .bar) */
};
struct arg_date {
- struct arg_hdr hdr; /* The mandatory argtable header struct */
- const char *format; /* strptime format string used to parse the date */
- int count; /* Number of matching command line args */
- struct tm *tmval; /* Array of parsed time values */
+ struct arg_hdr hdr; /* The mandatory argtable header struct */
+ const char* format; /* strptime format string used to parse the date */
+ int count; /* Number of matching command line args */
+ struct tm* tmval; /* Array of parsed time values */
};
-enum {ARG_ELIMIT = 1, ARG_EMALLOC, ARG_ENOMATCH, ARG_ELONGOPT, ARG_EMISSARG};
+enum { ARG_ELIMIT = 1, ARG_EMALLOC, ARG_ENOMATCH, ARG_ELONGOPT, ARG_EMISSARG };
struct arg_end {
- struct arg_hdr hdr; /* The mandatory argtable header struct */
- int count; /* Number of errors encountered */
- int *error; /* Array of error codes */
- void **parent; /* Array of pointers to offending arg_xxx struct */
- const char **argval; /* Array of pointers to offending argv[] string */
+ struct arg_hdr hdr; /* The mandatory argtable header struct */
+ int count; /* Number of errors encountered */
+ int* error; /* Array of error codes */
+ void** parent; /* Array of pointers to offending arg_xxx struct */
+ const char** argval; /* Array of pointers to offending argv[] string */
};
-/*
typedef struct arg_cmd_info {
char name[ARG_CMD_NAME_LEN];
char description[ARG_CMD_DESCRIPTION_LEN];
arg_cmdfn* proc;
} arg_cmd_info_t;
-*/
/**** arg_xxx constructor functions *********************************/
-struct arg_rem *arg_rem(const char *datatype, const char *glossary);
+ARG_EXTERN struct arg_rem* arg_rem(const char* datatype, const char* glossary);
-struct arg_lit *arg_lit0(const char *shortopts,
- const char *longopts,
- const char *glossary);
-struct arg_lit *arg_lit1(const char *shortopts,
- const char *longopts,
- const char *glossary);
-struct arg_lit *arg_litn(const char *shortopts,
- const char *longopts,
- int mincount,
- int maxcount,
- const char *glossary);
+ARG_EXTERN struct arg_lit* arg_lit0(const char* shortopts, const char* longopts, const char* glossary);
+ARG_EXTERN struct arg_lit* arg_lit1(const char* shortopts, const char* longopts, const char* glossary);
+ARG_EXTERN struct arg_lit* arg_litn(const char* shortopts, const char* longopts, int mincount, int maxcount, const char* glossary);
-struct arg_key *arg_key0(const char *keyword,
- int flags,
- const char *glossary);
-struct arg_key *arg_key1(const char *keyword,
- int flags,
- const char *glossary);
-struct arg_key *arg_keyn(const char *keyword,
- int flags,
- int mincount,
- int maxcount,
- const char *glossary);
+ARG_EXTERN struct arg_key* arg_key0(const char* keyword, int flags, const char* glossary);
+ARG_EXTERN struct arg_key* arg_key1(const char* keyword, int flags, const char* glossary);
+ARG_EXTERN struct arg_key* arg_keyn(const char* keyword, int flags, int mincount, int maxcount, const char* glossary);
-struct arg_int *arg_int0(const char *shortopts,
- const char *longopts,
- const char *datatype,
- const char *glossary);
-struct arg_int *arg_int1(const char *shortopts,
- const char *longopts,
- const char *datatype,
- const char *glossary);
-struct arg_int *arg_intn(const char *shortopts,
- const char *longopts,
- const char *datatype,
- int mincount,
- int maxcount,
- const char *glossary);
+ARG_EXTERN struct arg_int* arg_int0(const char* shortopts, const char* longopts, const char* datatype, const char* glossary);
+ARG_EXTERN struct arg_int* arg_int1(const char* shortopts, const char* longopts, const char* datatype, const char* glossary);
+ARG_EXTERN struct arg_int* arg_intn(const char* shortopts, const char* longopts, const char* datatype, int mincount, int maxcount, const char* glossary);
-struct arg_dbl *arg_dbl0(const char *shortopts,
- const char *longopts,
- const char *datatype,
- const char *glossary);
-struct arg_dbl *arg_dbl1(const char *shortopts,
- const char *longopts,
- const char *datatype,
- const char *glossary);
-struct arg_dbl *arg_dbln(const char *shortopts,
- const char *longopts,
- const char *datatype,
- int mincount,
- int maxcount,
- const char *glossary);
+ARG_EXTERN struct arg_dbl* arg_dbl0(const char* shortopts, const char* longopts, const char* datatype, const char* glossary);
+ARG_EXTERN struct arg_dbl* arg_dbl1(const char* shortopts, const char* longopts, const char* datatype, const char* glossary);
+ARG_EXTERN struct arg_dbl* arg_dbln(const char* shortopts, const char* longopts, const char* datatype, int mincount, int maxcount, const char* glossary);
-struct arg_str *arg_str0(const char *shortopts,
- const char *longopts,
- const char *datatype,
- const char *glossary);
-struct arg_str *arg_str1(const char *shortopts,
- const char *longopts,
- const char *datatype,
- const char *glossary);
-struct arg_str *arg_strn(const char *shortopts,
- const char *longopts,
- const char *datatype,
- int mincount,
- int maxcount,
- const char *glossary);
+ARG_EXTERN struct arg_str* arg_str0(const char* shortopts, const char* longopts, const char* datatype, const char* glossary);
+ARG_EXTERN struct arg_str* arg_str1(const char* shortopts, const char* longopts, const char* datatype, const char* glossary);
+ARG_EXTERN struct arg_str* arg_strn(const char* shortopts, const char* longopts, const char* datatype, int mincount, int maxcount, const char* glossary);
-struct arg_rex *arg_rex0(const char *shortopts,
- const char *longopts,
- const char *pattern,
- const char *datatype,
- int flags,
- const char *glossary);
-struct arg_rex *arg_rex1(const char *shortopts,
- const char *longopts,
- const char *pattern,
- const char *datatype,
- int flags,
- const char *glossary);
-struct arg_rex *arg_rexn(const char *shortopts,
- const char *longopts,
- const char *pattern,
- const char *datatype,
+ARG_EXTERN struct arg_rex* arg_rex0(const char* shortopts, const char* longopts, const char* pattern, const char* datatype, int flags, const char* glossary);
+ARG_EXTERN struct arg_rex* arg_rex1(const char* shortopts, const char* longopts, const char* pattern, const char* datatype, int flags, const char* glossary);
+ARG_EXTERN struct arg_rex* arg_rexn(const char* shortopts,
+ const char* longopts,
+ const char* pattern,
+ const char* datatype,
int mincount,
int maxcount,
int flags,
- const char *glossary);
+ const char* glossary);
-struct arg_file *arg_file0(const char *shortopts,
- const char *longopts,
- const char *datatype,
- const char *glossary);
-struct arg_file *arg_file1(const char *shortopts,
- const char *longopts,
- const char *datatype,
- const char *glossary);
-struct arg_file *arg_filen(const char *shortopts,
- const char *longopts,
- const char *datatype,
- int mincount,
- int maxcount,
- const char *glossary);
+ARG_EXTERN struct arg_file* arg_file0(const char* shortopts, const char* longopts, const char* datatype, const char* glossary);
+ARG_EXTERN struct arg_file* arg_file1(const char* shortopts, const char* longopts, const char* datatype, const char* glossary);
+ARG_EXTERN struct arg_file* arg_filen(const char* shortopts, const char* longopts, const char* datatype, int mincount, int maxcount, const char* glossary);
-struct arg_date *arg_date0(const char *shortopts,
- const char *longopts,
- const char *format,
- const char *datatype,
- const char *glossary);
-struct arg_date *arg_date1(const char *shortopts,
- const char *longopts,
- const char *format,
- const char *datatype,
- const char *glossary);
-struct arg_date *arg_daten(const char *shortopts,
- const char *longopts,
- const char *format,
- const char *datatype,
- int mincount,
- int maxcount,
- const char *glossary);
+ARG_EXTERN struct arg_date* arg_date0(const char* shortopts, const char* longopts, const char* format, const char* datatype, const char* glossary);
+ARG_EXTERN struct arg_date* arg_date1(const char* shortopts, const char* longopts, const char* format, const char* datatype, const char* glossary);
+ARG_EXTERN struct arg_date* arg_daten(const char* shortopts, const char* longopts, const char* format, const char* datatype, int mincount, int maxcount, const char* glossary);
-struct arg_end *arg_end(int maxcount);
+ARG_EXTERN struct arg_end* arg_end(int maxerrors);
+#define ARG_DSTR_STATIC ((arg_dstr_freefn*)0)
+#define ARG_DSTR_VOLATILE ((arg_dstr_freefn*)1)
+#define ARG_DSTR_DYNAMIC ((arg_dstr_freefn*)3)
/**** other functions *******************************************/
-int arg_nullcheck(void **argtable);
-int arg_parse(int argc, char **argv, void **argtable);
-void arg_print_option(FILE *fp, const char *shortopts, const char *longopts, const char *datatype, const char *suffix);
-void arg_print_syntax(FILE *fp, void **argtable, const char *suffix);
-void arg_print_syntaxv(FILE *fp, void **argtable, const char *suffix);
-void arg_print_glossary(FILE *fp, void **argtable, const char *format);
-void arg_print_glossary_gnu(FILE *fp, void **argtable);
-void arg_print_errors(FILE *fp, struct arg_end *end, const char *progname);
-void arg_freetable(void **argtable, size_t n);
+ARG_EXTERN int arg_nullcheck(void** argtable);
+ARG_EXTERN int arg_parse(int argc, char** argv, void** argtable);
+ARG_EXTERN void arg_print_option(FILE* fp, const char* shortopts, const char* longopts, const char* datatype, const char* suffix);
+ARG_EXTERN void arg_print_syntax(FILE* fp, void** argtable, const char* suffix);
+ARG_EXTERN void arg_print_syntaxv(FILE* fp, void** argtable, const char* suffix);
+ARG_EXTERN void arg_print_glossary(FILE* fp, void** argtable, const char* format);
+ARG_EXTERN void arg_print_glossary_gnu(FILE* fp, void** argtable);
+ARG_EXTERN void arg_print_errors(FILE* fp, struct arg_end* end, const char* progname);
+ARG_EXTERN void arg_print_option_ds(arg_dstr_t ds, const char* shortopts, const char* longopts, const char* datatype, const char* suffix);
+ARG_EXTERN void arg_print_syntax_ds(arg_dstr_t ds, void** argtable, const char* suffix);
+ARG_EXTERN void arg_print_syntaxv_ds(arg_dstr_t ds, void** argtable, const char* suffix);
+ARG_EXTERN void arg_print_glossary_ds(arg_dstr_t ds, void** argtable, const char* format);
+ARG_EXTERN void arg_print_glossary_gnu_ds(arg_dstr_t ds, void** argtable);
+ARG_EXTERN void arg_print_errors_ds(arg_dstr_t ds, struct arg_end* end, const char* progname);
+ARG_EXTERN void arg_freetable(void** argtable, size_t n);
+
+ARG_EXTERN arg_dstr_t arg_dstr_create(void);
+ARG_EXTERN void arg_dstr_destroy(arg_dstr_t ds);
+ARG_EXTERN void arg_dstr_reset(arg_dstr_t ds);
+ARG_EXTERN void arg_dstr_free(arg_dstr_t ds);
+ARG_EXTERN void arg_dstr_set(arg_dstr_t ds, char* str, arg_dstr_freefn* free_proc);
+ARG_EXTERN void arg_dstr_cat(arg_dstr_t ds, const char* str);
+ARG_EXTERN void arg_dstr_catc(arg_dstr_t ds, char c);
+ARG_EXTERN void arg_dstr_catf(arg_dstr_t ds, const char* fmt, ...);
+ARG_EXTERN char* arg_dstr_cstr(arg_dstr_t ds);
+
+ARG_EXTERN void arg_cmd_init(void);
+ARG_EXTERN void arg_cmd_uninit(void);
+ARG_EXTERN void arg_cmd_register(const char* name, arg_cmdfn* proc, const char* description);
+ARG_EXTERN void arg_cmd_unregister(const char* name);
+ARG_EXTERN int arg_cmd_dispatch(const char* name, int argc, char* argv[], arg_dstr_t res);
+ARG_EXTERN unsigned int arg_cmd_count(void);
+ARG_EXTERN arg_cmd_info_t* arg_cmd_info(const char* name);
+ARG_EXTERN arg_cmd_itr_t arg_cmd_itr_create(void);
+ARG_EXTERN void arg_cmd_itr_destroy(arg_cmd_itr_t itr);
+ARG_EXTERN int arg_cmd_itr_advance(arg_cmd_itr_t itr);
+ARG_EXTERN char* arg_cmd_itr_key(arg_cmd_itr_t itr);
+ARG_EXTERN arg_cmd_info_t* arg_cmd_itr_value(arg_cmd_itr_t itr);
+ARG_EXTERN int arg_cmd_itr_search(arg_cmd_itr_t itr, void* k);
+ARG_EXTERN void arg_mgsort(void* data, int size, int esize, int i, int k, arg_comparefn* comparefn);
+ARG_EXTERN void arg_make_get_help_msg(arg_dstr_t res);
+ARG_EXTERN void arg_make_help_msg(arg_dstr_t ds, char* cmd_name, void** argtable);
+ARG_EXTERN void arg_make_syntax_err_msg(arg_dstr_t ds, void** argtable, struct arg_end* end);
+ARG_EXTERN int arg_make_syntax_err_help_msg(arg_dstr_t ds, char* name, int help, int nerrors, void** argtable, struct arg_end* end, int* exitcode);
+ARG_EXTERN void arg_set_module_name(const char* name);
+ARG_EXTERN void arg_set_module_version(int major, int minor, int patch, const char* tag);
/**** deprecated functions, for back-compatibility only ********/
-void arg_free(void **argtable);
+ARG_EXTERN void arg_free(void** argtable);
#ifdef __cplusplus
}
From a2a5700a8530bf4a08b6c70c2e491b47533b4648 Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Wed, 6 May 2020 23:33:55 +0200
Subject: [PATCH 087/632] fix reveng getopt bug
---
client/deps/reveng/cli.c | 1 +
1 file changed, 1 insertion(+)
diff --git a/client/deps/reveng/cli.c b/client/deps/reveng/cli.c
index 9d849dfc3..34aee6fe7 100644
--- a/client/deps/reveng/cli.c
+++ b/client/deps/reveng/cli.c
@@ -98,6 +98,7 @@ int reveng_main(int argc, char *argv[]) {
// pos=0; --- not in this ver of getopt
optind = 1;
+ optreset = 1;
do {
c = getopt(argc, argv, "?A:BDFGLMP:SVXa:bcdefhi:k:lm:p:q:rstuvw:x:yz");
switch (c) {
From 2fcad93efc3ccf4af6bd7599d9a3f4b571d436dc Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Thu, 7 May 2020 00:23:19 +0200
Subject: [PATCH 088/632] proper way to fix reveng getopt bug
---
client/deps/reveng/cli.c | 25 +++++++++++++++----------
1 file changed, 15 insertions(+), 10 deletions(-)
diff --git a/client/deps/reveng/cli.c b/client/deps/reveng/cli.c
index 34aee6fe7..88e8d3722 100644
--- a/client/deps/reveng/cli.c
+++ b/client/deps/reveng/cli.c
@@ -97,8 +97,10 @@ int reveng_main(int argc, char *argv[]) {
SETBMP();
// pos=0; --- not in this ver of getopt
+ int err = 0;
optind = 1;
- optreset = 1;
+ // Remember to consume always all the option string till getopt returns -1 !
+ // else next invocations will be corrupted
do {
c = getopt(argc, argv, "?A:BDFGLMP:SVXa:bcdefhi:k:lm:p:q:rstuvw:x:yz");
switch (c) {
@@ -106,8 +108,8 @@ int reveng_main(int argc, char *argv[]) {
case 'a': /* a: bits per character */
if ((obperhx = atoi(optarg)) > BMP_BIT) {
fprintf(stderr, "%s: argument to -%c must be between 1 and %d\n", myname, c, BMP_BIT);
- return 0;
- //exit(EXIT_FAILURE);
+ err = 1;
+ break;
}
if (c == 'a') ibperhx = obperhx;
break;
@@ -131,8 +133,8 @@ int reveng_main(int argc, char *argv[]) {
case 'v': /* v calculate reversed CRC */
if (mode) {
fprintf(stderr, "%s: more than one mode switch specified. Use %s -h for help.\n", myname, myname);
- return 0;
- //exit(EXIT_FAILURE);
+ err = 1;
+ break;
}
mode = c;
break;
@@ -152,8 +154,7 @@ int reveng_main(int argc, char *argv[]) {
case '?': /* ? get help / usage */
default:
usage();
- return 0;
- //exit(EXIT_FAILURE);
+ err = 1;
break;
case 'i': /* i: Init value */
pptr = &model.init;
@@ -185,12 +186,13 @@ int reveng_main(int argc, char *argv[]) {
case 'm': /* m: select preset CRC model */
if (!(c = mbynam(&model, optarg))) {
fprintf(stderr, "%s: preset model '%s' not found. Use %s -D to list presets.\n", myname, optarg, myname);
- return 0;
- //exit(EXIT_FAILURE);
+ err = 1;
+ break;
}
if (c < 0) {
uerror("no preset models available");
- return 0;
+ err = 1;
+ break;
}
/* must set width so that parameter to -ipx is not zeroed */
width = plen(model.spoly);
@@ -247,6 +249,9 @@ ipqx:
}
} while (c != -1);
+ if (err)
+ return 0;
+
/* canonicalise the model, so the one we dump is the one we
* calculate with (not with -s, spoly may be blank which will
* normalise to zero and clear init and xorout.)
From 3c9a19d4c1e4251c412affee210f55c3eb649e37 Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Thu, 7 May 2020 00:59:40 +0200
Subject: [PATCH 089/632] Revert "update argtable3"
It was an attempt to solve the mysterious reveng getopt bug
but it brings more troubles and throws away multi-platform pm3 tuning
This reverts commit f3790a89a525ac8385132ba3eb17d2e05ade35dd.
---
client/deps/cliparser/Makefile | 2 +-
client/deps/cliparser/argtable3.c | 4977 +++++++++++------------------
client/deps/cliparser/argtable3.h | 359 ++-
3 files changed, 2109 insertions(+), 3229 deletions(-)
diff --git a/client/deps/cliparser/Makefile b/client/deps/cliparser/Makefile
index 6fa13408a..4873372c4 100644
--- a/client/deps/cliparser/Makefile
+++ b/client/deps/cliparser/Makefile
@@ -1,6 +1,6 @@
MYSRCPATHS =
MYINCLUDES = -I../../../common -I../../../include -I../../src
-MYCFLAGS = -Wno-cast-align -Wno-discarded-qualifiers -Wno-bad-function-cast -Wno-redundant-decls
+MYCFLAGS = -Wno-cast-align
MYDEFS =
MYSRCS = \
argtable3.c \
diff --git a/client/deps/cliparser/argtable3.c b/client/deps/cliparser/argtable3.c
index c3d1bb9f7..f66c22d6d 100644
--- a/client/deps/cliparser/argtable3.c
+++ b/client/deps/cliparser/argtable3.c
@@ -30,14 +30,19 @@
#include "argtable3.h"
-#define ARG_AMALGAMATION
+// On Windows isspace crashes app in case of using Unicode character set and string to be above ASCII
+// so you have to use _istspace instead of space
+#ifdef UNICODE
+#include
+#define ISSPACE _istspace
+#else
+#define ISSPACE isspace
+#endif
/*******************************************************************************
- * argtable3_private: Declares private types, constants, and interfaces
- *
* This file is part of the argtable3 library.
*
- * Copyright (C) 2013-2019 Tom G. Huang
+ * Copyright (C) 2013 Tom G. Huang
*
* All rights reserved.
*
@@ -67,8 +72,6 @@
#ifndef ARG_UTILS_H
#define ARG_UTILS_H
-#include
-
#define ARG_ENABLE_TRACE 0
#define ARG_ENABLE_LOG 1
@@ -76,1759 +79,52 @@
extern "C" {
#endif
-enum { ARG_ERR_MINCOUNT = 1, ARG_ERR_MAXCOUNT, ARG_ERR_BADINT, ARG_ERR_OVERFLOW, ARG_ERR_BADDOUBLE, ARG_ERR_BADDATE, ARG_ERR_REGNOMATCH };
+enum {
+ EMINCOUNT = 1,
+ EMAXCOUNT,
+ EBADINT,
-typedef void(arg_panicfn)(const char* fmt, ...);
-
-#if defined(_MSC_VER)
-#define ARG_TRACE(x) \
- __pragma(warning(push)) __pragma(warning(disable : 4127)) do { \
- if (ARG_ENABLE_TRACE) \
- dbg_printf x; \
- } \
- while (0) \
- __pragma(warning(pop))
-
-#define ARG_LOG(x) \
- __pragma(warning(push)) __pragma(warning(disable : 4127)) do { \
- if (ARG_ENABLE_LOG) \
- dbg_printf x; \
- } \
- while (0) \
- __pragma(warning(pop))
+// The same name define EOVERFLOW in errno.h on windows platform or android
+#if defined(__STDC_WANT_SECURE_LIB__) || defined(__ANDROID__) || defined(ANDROID)
+ EOVERFLOW_,
#else
-#define ARG_TRACE(x) \
- do { \
- if (ARG_ENABLE_TRACE) \
- dbg_printf x; \
- } while (0)
-
-#define ARG_LOG(x) \
- do { \
- if (ARG_ENABLE_LOG) \
- dbg_printf x; \
- } while (0)
+ EOVERFLOW,
#endif
-
-extern void dbg_printf(const char* fmt, ...);
-extern void arg_set_panic(arg_panicfn* proc);
-extern void* xmalloc(size_t size);
-extern void* xcalloc(size_t count, size_t size);
-extern void* xrealloc(void* ptr, size_t size);
-extern void xfree(void* ptr);
-
-struct arg_hashtable_entry {
- void *k, *v;
- unsigned int h;
- struct arg_hashtable_entry* next;
+ EBADDOUBLE,
+ EBADDATE,
+ EREGNOMATCH
};
-typedef struct arg_hashtable {
- unsigned int tablelength;
- struct arg_hashtable_entry** table;
- unsigned int entrycount;
- unsigned int loadlimit;
- unsigned int primeindex;
- unsigned int (*hashfn)(const void* k);
- int (*eqfn)(const void* k1, const void* k2);
-} arg_hashtable_t;
-/**
- * @brief Create a hash table.
- *
- * @param minsize minimum initial size of hash table
- * @param hashfn function for hashing keys
- * @param eqfn function for determining key equality
- * @return newly created hash table or NULL on failure
- */
-arg_hashtable_t* arg_hashtable_create(unsigned int minsize, unsigned int (*hashfn)(const void*), int (*eqfn)(const void*, const void*));
+#if defined(_MSC_VER)
+#define ARG_TRACE(x) \
+ __pragma(warning(push)) \
+ __pragma(warning(disable:4127)) \
+ do { if (ARG_ENABLE_TRACE) dbg_printf x; } while (0) \
+ __pragma(warning(pop))
-/**
- * @brief This function will cause the table to expand if the insertion would take
- * the ratio of entries to table size over the maximum load factor.
- *
- * This function does not check for repeated insertions with a duplicate key.
- * The value returned when using a duplicate key is undefined -- when
- * the hash table changes size, the order of retrieval of duplicate key
- * entries is reversed.
- * If in doubt, remove before insert.
- *
- * @param h the hash table to insert into
- * @param k the key - hash table claims ownership and will free on removal
- * @param v the value - does not claim ownership
- * @return non-zero for successful insertion
- */
-void arg_hashtable_insert(arg_hashtable_t* h, void* k, void* v);
+#define ARG_LOG(x) \
+ __pragma(warning(push)) \
+ __pragma(warning(disable:4127)) \
+ do { if (ARG_ENABLE_LOG) dbg_printf x; } while (0) \
+ __pragma(warning(pop))
+#else
+#define ARG_TRACE(x) \
+ do { if (ARG_ENABLE_TRACE) dbg_printf x; } while (0)
-#define ARG_DEFINE_HASHTABLE_INSERT(fnname, keytype, valuetype) \
- int fnname(arg_hashtable_t* h, keytype* k, valuetype* v) { return arg_hashtable_insert(h, k, v); }
+#define ARG_LOG(x) \
+ do { if (ARG_ENABLE_LOG) dbg_printf x; } while (0)
+#endif
-/**
- * @brief Search the specified key in the hash table.
- *
- * @param h the hash table to search
- * @param k the key to search for - does not claim ownership
- * @return the value associated with the key, or NULL if none found
- */
-void* arg_hashtable_search(arg_hashtable_t* h, const void* k);
-
-#define ARG_DEFINE_HASHTABLE_SEARCH(fnname, keytype, valuetype) \
- valuetype* fnname(arg_hashtable_t* h, keytype* k) { return (valuetype*)(arg_hashtable_search(h, k)); }
-
-/**
- * @brief Remove the specified key from the hash table.
- *
- * @param h the hash table to remove the item from
- * @param k the key to search for - does not claim ownership
- */
-void arg_hashtable_remove(arg_hashtable_t* h, const void* k);
-
-#define ARG_DEFINE_HASHTABLE_REMOVE(fnname, keytype, valuetype) \
- valuetype* fnname(arg_hashtable_t* h, keytype* k) { return (valuetype*)(arg_hashtable_remove(h, k)); }
-
-/**
- * @brief Return the number of keys in the hash table.
- *
- * @param h the hash table
- * @return the number of items stored in the hash table
- */
-unsigned int arg_hashtable_count(arg_hashtable_t* h);
-
-/**
- * @brief Change the value associated with the key.
- *
- * function to change the value associated with a key, where there already
- * exists a value bound to the key in the hash table.
- * Source due to Holger Schemel.
- *
- * @name hashtable_change
- * @param h the hash table
- * @param key
- * @param value
- */
-int arg_hashtable_change(arg_hashtable_t* h, void* k, void* v);
-
-/**
- * @brief Free the hash table and the memory allocated for each key-value pair.
- *
- * @param h the hash table
- * @param free_values whether to call 'free' on the remaining values
- */
-void arg_hashtable_destroy(arg_hashtable_t* h, int free_values);
-
-typedef struct arg_hashtable_itr {
- arg_hashtable_t* h;
- struct arg_hashtable_entry* e;
- struct arg_hashtable_entry* parent;
- unsigned int index;
-} arg_hashtable_itr_t;
-
-arg_hashtable_itr_t* arg_hashtable_itr_create(arg_hashtable_t* h);
-
-void arg_hashtable_itr_destroy(arg_hashtable_itr_t* itr);
-
-/**
- * @brief Return the value of the (key,value) pair at the current position.
- */
-extern void* arg_hashtable_itr_key(arg_hashtable_itr_t* i);
-
-/**
- * @brief Return the value of the (key,value) pair at the current position.
- */
-extern void* arg_hashtable_itr_value(arg_hashtable_itr_t* i);
-
-/**
- * @brief Advance the iterator to the next element. Returns zero if advanced to end of table.
- */
-int arg_hashtable_itr_advance(arg_hashtable_itr_t* itr);
-
-/**
- * @brief Remove current element and advance the iterator to the next element.
- */
-int arg_hashtable_itr_remove(arg_hashtable_itr_t* itr);
-
-/**
- * @brief Search and overwrite the supplied iterator, to point to the entry matching the supplied key.
- *
- * @return Zero if not found.
- */
-int arg_hashtable_itr_search(arg_hashtable_itr_t* itr, arg_hashtable_t* h, void* k);
-
-#define ARG_DEFINE_HASHTABLE_ITERATOR_SEARCH(fnname, keytype) \
- int fnname(arg_hashtable_itr_t* i, arg_hashtable_t* h, keytype* k) { return (arg_hashtable_iterator_search(i, h, k)); }
+extern void dbg_printf(const char *fmt, ...);
#ifdef __cplusplus
}
#endif
#endif
+
/*******************************************************************************
- * arg_utils: Implements memory, panic, and other utility functions
- *
- * This file is part of the argtable3 library.
- *
- * Copyright (C) 2013-2019 Tom G. Huang
- *
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * Neither the name of STEWART HEITMANN nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT,
- * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- ******************************************************************************/
-
-#include "argtable3.h"
-
-#ifndef ARG_AMALGAMATION
-#include "argtable3_private.h"
-#endif
-
-#include
-#include
-#include
-#include
-
-static void panic(const char* fmt, ...);
-static arg_panicfn* s_panic = panic;
-
-void dbg_printf(const char* fmt, ...) {
- va_list args;
- va_start(args, fmt);
- vfprintf(stderr, fmt, args);
- va_end(args);
-}
-
-static void panic(const char* fmt, ...) {
- va_list args;
- char* s;
-
- va_start(args, fmt);
- vfprintf(stderr, fmt, args);
- va_end(args);
-
-#if defined(_MSC_VER)
-#pragma warning(push)
-#pragma warning(disable : 4996)
-#endif
- s = getenv("EF_DUMPCORE");
-#if defined(_MSC_VER)
-#pragma warning(pop)
-#endif
-
- if (s != NULL && *s != '\0') {
- abort();
- } else {
- exit(EXIT_FAILURE);
- }
-}
-
-void arg_set_panic(arg_panicfn* proc) {
- s_panic = proc;
-}
-
-void* xmalloc(size_t size) {
- void* ret = malloc(size);
- if (!ret) {
- s_panic("Out of memory!\n");
- }
- return ret;
-}
-
-void* xcalloc(size_t count, size_t size) {
- size_t allocated_count = count && size ? count : 1;
- size_t allocated_size = count && size ? size : 1;
- void* ret = calloc(allocated_count, allocated_size);
- if (!ret) {
- s_panic("Out of memory!\n");
- }
- return ret;
-}
-
-void* xrealloc(void* ptr, size_t size) {
- size_t allocated_size = size ? size : 1;
- void* ret = realloc(ptr, allocated_size);
- if (!ret) {
- s_panic("Out of memory!\n");
- }
- return ret;
-}
-
-void xfree(void* ptr) {
- free(ptr);
-}
-
-static void merge(void* data, int esize, int i, int j, int k, arg_comparefn* comparefn) {
- char* a = (char*)data;
- char* m;
- int ipos, jpos, mpos;
-
- /* Initialize the counters used in merging. */
- ipos = i;
- jpos = j + 1;
- mpos = 0;
-
- /* Allocate storage for the merged elements. */
- m = (char*)xmalloc(esize * ((k - i) + 1));
-
- /* Continue while either division has elements to merge. */
- while (ipos <= j || jpos <= k) {
- if (ipos > j) {
- /* The left division has no more elements to merge. */
- while (jpos <= k) {
- memcpy(&m[mpos * esize], &a[jpos * esize], esize);
- jpos++;
- mpos++;
- }
-
- continue;
- } else if (jpos > k) {
- /* The right division has no more elements to merge. */
- while (ipos <= j) {
- memcpy(&m[mpos * esize], &a[ipos * esize], esize);
- ipos++;
- mpos++;
- }
-
- continue;
- }
-
- /* Append the next ordered element to the merged elements. */
- if (comparefn(&a[ipos * esize], &a[jpos * esize]) < 0) {
- memcpy(&m[mpos * esize], &a[ipos * esize], esize);
- ipos++;
- mpos++;
- } else {
- memcpy(&m[mpos * esize], &a[jpos * esize], esize);
- jpos++;
- mpos++;
- }
- }
-
- /* Prepare to pass back the merged data. */
- memcpy(&a[i * esize], m, esize * ((k - i) + 1));
- xfree(m);
-}
-
-void arg_mgsort(void* data, int size, int esize, int i, int k, arg_comparefn* comparefn) {
- int j;
-
- /* Stop the recursion when no more divisions can be made. */
- if (i < k) {
- /* Determine where to divide the elements. */
- j = (int)(((i + k - 1)) / 2);
-
- /* Recursively sort the two divisions. */
- arg_mgsort(data, size, esize, i, j, comparefn);
- arg_mgsort(data, size, esize, j + 1, k, comparefn);
- merge(data, esize, i, j, k, comparefn);
- }
-}
-/*******************************************************************************
- * arg_hashtable: Implements the hash table utilities
- *
- * This file is part of the argtable3 library.
- *
- * Copyright (C) 2013-2019 Tom G. Huang
- *
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * Neither the name of STEWART HEITMANN nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT,
- * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- ******************************************************************************/
-
-#ifndef ARG_AMALGAMATION
-#include "argtable3_private.h"
-#endif
-
-#include
-#include
-#include
-#include
-
-/*
- * This hash table module is adapted from the C hash table implementation by
- * Christopher Clark. Here is the copyright notice from the library:
- *
- * Copyright (c) 2002, Christopher Clark
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * * Neither the name of the original author; nor the names of any contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
- * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-/*
- * Credit for primes table: Aaron Krowne
- * http://br.endernet.org/~akrowne/
- * http://planetmath.org/encyclopedia/GoodHashTablePrimes.html
- */
-static const unsigned int primes[] = {53, 97, 193, 389, 769, 1543, 3079, 6151, 12289,
- 24593, 49157, 98317, 196613, 393241, 786433, 1572869, 3145739, 6291469,
- 12582917, 25165843, 50331653, 100663319, 201326611, 402653189, 805306457, 1610612741};
-const unsigned int prime_table_length = sizeof(primes) / sizeof(primes[0]);
-const float max_load_factor = (float)0.65;
-
-static unsigned int enhanced_hash(arg_hashtable_t* h, const void* k) {
- /*
- * Aim to protect against poor hash functions by adding logic here.
- * The logic is taken from Java 1.4 hash table source.
- */
- unsigned int i = h->hashfn(k);
- i += ~(i << 9);
- i ^= ((i >> 14) | (i << 18)); /* >>> */
- i += (i << 4);
- i ^= ((i >> 10) | (i << 22)); /* >>> */
- return i;
-}
-
-static unsigned int index_for(unsigned int tablelength, unsigned int hashvalue) {
- return (hashvalue % tablelength);
-}
-
-arg_hashtable_t* arg_hashtable_create(unsigned int minsize, unsigned int (*hashfn)(const void*), int (*eqfn)(const void*, const void*)) {
- arg_hashtable_t* h;
- unsigned int pindex;
- unsigned int size = primes[0];
-
- /* Check requested hash table isn't too large */
- if (minsize > (1u << 30))
- return NULL;
-
- /*
- * Enforce size as prime. The reason is to avoid clustering of values
- * into a small number of buckets (yes, distribution). A more even
- * distributed hash table will perform more consistently.
- */
- for (pindex = 0; pindex < prime_table_length; pindex++) {
- if (primes[pindex] > minsize) {
- size = primes[pindex];
- break;
- }
- }
-
- h = (arg_hashtable_t*)xmalloc(sizeof(arg_hashtable_t));
- h->table = (struct arg_hashtable_entry**)xmalloc(sizeof(struct arg_hashtable_entry*) * size);
- memset(h->table, 0, size * sizeof(struct arg_hashtable_entry*));
- h->tablelength = size;
- h->primeindex = pindex;
- h->entrycount = 0;
- h->hashfn = hashfn;
- h->eqfn = eqfn;
- h->loadlimit = (unsigned int)ceil(size * max_load_factor);
- return h;
-}
-
-static int arg_hashtable_expand(arg_hashtable_t* h) {
- /* Double the size of the table to accommodate more entries */
- struct arg_hashtable_entry** newtable;
- struct arg_hashtable_entry* e;
- unsigned int newsize;
- unsigned int i;
- unsigned int index;
-
- /* Check we're not hitting max capacity */
- if (h->primeindex == (prime_table_length - 1))
- return 0;
- newsize = primes[++(h->primeindex)];
-
- newtable = (struct arg_hashtable_entry**)xmalloc(sizeof(struct arg_hashtable_entry*) * newsize);
- memset(newtable, 0, newsize * sizeof(struct arg_hashtable_entry*));
- /*
- * This algorithm is not 'stable': it reverses the list
- * when it transfers entries between the tables
- */
- for (i = 0; i < h->tablelength; i++) {
- while (NULL != (e = h->table[i])) {
- h->table[i] = e->next;
- index = index_for(newsize, e->h);
- e->next = newtable[index];
- newtable[index] = e;
- }
- }
-
- xfree(h->table);
- h->table = newtable;
- h->tablelength = newsize;
- h->loadlimit = (unsigned int)ceil(newsize * max_load_factor);
- return -1;
-}
-
-unsigned int arg_hashtable_count(arg_hashtable_t* h) {
- return h->entrycount;
-}
-
-void arg_hashtable_insert(arg_hashtable_t* h, void* k, void* v) {
- /* This method allows duplicate keys - but they shouldn't be used */
- unsigned int index;
- struct arg_hashtable_entry* e;
- if ((h->entrycount + 1) > h->loadlimit) {
- /*
- * Ignore the return value. If expand fails, we should
- * still try cramming just this value into the existing table
- * -- we may not have memory for a larger table, but one more
- * element may be ok. Next time we insert, we'll try expanding again.
- */
- arg_hashtable_expand(h);
- }
- e = (struct arg_hashtable_entry*)xmalloc(sizeof(struct arg_hashtable_entry));
- e->h = enhanced_hash(h, k);
- index = index_for(h->tablelength, e->h);
- e->k = k;
- e->v = v;
- e->next = h->table[index];
- h->table[index] = e;
- h->entrycount++;
-}
-
-void* arg_hashtable_search(arg_hashtable_t* h, const void* k) {
- struct arg_hashtable_entry* e;
- unsigned int hashvalue;
- unsigned int index;
-
- hashvalue = enhanced_hash(h, k);
- index = index_for(h->tablelength, hashvalue);
- e = h->table[index];
- while (e != NULL) {
- /* Check hash value to short circuit heavier comparison */
- if ((hashvalue == e->h) && (h->eqfn(k, e->k)))
- return e->v;
- e = e->next;
- }
- return NULL;
-}
-
-void arg_hashtable_remove(arg_hashtable_t* h, const void* k) {
- /*
- * TODO: consider compacting the table when the load factor drops enough,
- * or provide a 'compact' method.
- */
-
- struct arg_hashtable_entry* e;
- struct arg_hashtable_entry** pE;
- unsigned int hashvalue;
- unsigned int index;
-
- hashvalue = enhanced_hash(h, k);
- index = index_for(h->tablelength, hashvalue);
- pE = &(h->table[index]);
- e = *pE;
- while (NULL != e) {
- /* Check hash value to short circuit heavier comparison */
- if ((hashvalue == e->h) && (h->eqfn(k, e->k))) {
- *pE = e->next;
- h->entrycount--;
- xfree(e->k);
- xfree(e->v);
- xfree(e);
- return;
- }
- pE = &(e->next);
- e = e->next;
- }
-}
-
-void arg_hashtable_destroy(arg_hashtable_t* h, int free_values) {
- unsigned int i;
- struct arg_hashtable_entry *e, *f;
- struct arg_hashtable_entry** table = h->table;
- if (free_values) {
- for (i = 0; i < h->tablelength; i++) {
- e = table[i];
- while (NULL != e) {
- f = e;
- e = e->next;
- xfree(f->k);
- xfree(f->v);
- xfree(f);
- }
- }
- } else {
- for (i = 0; i < h->tablelength; i++) {
- e = table[i];
- while (NULL != e) {
- f = e;
- e = e->next;
- xfree(f->k);
- xfree(f);
- }
- }
- }
- xfree(h->table);
- xfree(h);
-}
-
-arg_hashtable_itr_t* arg_hashtable_itr_create(arg_hashtable_t* h) {
- unsigned int i;
- unsigned int tablelength;
-
- arg_hashtable_itr_t* itr = (arg_hashtable_itr_t*)xmalloc(sizeof(arg_hashtable_itr_t));
- itr->h = h;
- itr->e = NULL;
- itr->parent = NULL;
- tablelength = h->tablelength;
- itr->index = tablelength;
- if (0 == h->entrycount)
- return itr;
-
- for (i = 0; i < tablelength; i++) {
- if (h->table[i] != NULL) {
- itr->e = h->table[i];
- itr->index = i;
- break;
- }
- }
- return itr;
-}
-
-void arg_hashtable_itr_destroy(arg_hashtable_itr_t* itr) {
- xfree(itr);
-}
-
-void* arg_hashtable_itr_key(arg_hashtable_itr_t* i) {
- return i->e->k;
-}
-
-void* arg_hashtable_itr_value(arg_hashtable_itr_t* i) {
- return i->e->v;
-}
-
-int arg_hashtable_itr_advance(arg_hashtable_itr_t* itr) {
- unsigned int j;
- unsigned int tablelength;
- struct arg_hashtable_entry** table;
- struct arg_hashtable_entry* next;
-
- if (itr->e == NULL)
- return 0; /* stupidity check */
-
- next = itr->e->next;
- if (NULL != next) {
- itr->parent = itr->e;
- itr->e = next;
- return -1;
- }
-
- tablelength = itr->h->tablelength;
- itr->parent = NULL;
- if (tablelength <= (j = ++(itr->index))) {
- itr->e = NULL;
- return 0;
- }
-
- table = itr->h->table;
- while (NULL == (next = table[j])) {
- if (++j >= tablelength) {
- itr->index = tablelength;
- itr->e = NULL;
- return 0;
- }
- }
-
- itr->index = j;
- itr->e = next;
- return -1;
-}
-
-int arg_hashtable_itr_remove(arg_hashtable_itr_t* itr) {
- struct arg_hashtable_entry* remember_e;
- struct arg_hashtable_entry* remember_parent;
- int ret;
-
- /* Do the removal */
- if ((itr->parent) == NULL) {
- /* element is head of a chain */
- itr->h->table[itr->index] = itr->e->next;
- } else {
- /* element is mid-chain */
- itr->parent->next = itr->e->next;
- }
- /* itr->e is now outside the hashtable */
- remember_e = itr->e;
- itr->h->entrycount--;
- xfree(remember_e->k);
- xfree(remember_e->v);
-
- /* Advance the iterator, correcting the parent */
- remember_parent = itr->parent;
- ret = arg_hashtable_itr_advance(itr);
- if (itr->parent == remember_e) {
- itr->parent = remember_parent;
- }
- xfree(remember_e);
- return ret;
-}
-
-int arg_hashtable_itr_search(arg_hashtable_itr_t* itr, arg_hashtable_t* h, void* k) {
- struct arg_hashtable_entry* e;
- struct arg_hashtable_entry* parent;
- unsigned int hashvalue;
- unsigned int index;
-
- hashvalue = enhanced_hash(h, k);
- index = index_for(h->tablelength, hashvalue);
-
- e = h->table[index];
- parent = NULL;
- while (e != NULL) {
- /* Check hash value to short circuit heavier comparison */
- if ((hashvalue == e->h) && (h->eqfn(k, e->k))) {
- itr->index = index;
- itr->e = e;
- itr->parent = parent;
- itr->h = h;
- return -1;
- }
- parent = e;
- e = e->next;
- }
- return 0;
-}
-
-int arg_hashtable_change(arg_hashtable_t* h, void* k, void* v) {
- struct arg_hashtable_entry* e;
- unsigned int hashvalue;
- unsigned int index;
-
- hashvalue = enhanced_hash(h, k);
- index = index_for(h->tablelength, hashvalue);
- e = h->table[index];
- while (e != NULL) {
- /* Check hash value to short circuit heavier comparison */
- if ((hashvalue == e->h) && (h->eqfn(k, e->k))) {
- xfree(e->v);
- e->v = v;
- return -1;
- }
- e = e->next;
- }
- return 0;
-}
-/*******************************************************************************
- * arg_dstr: Implements the dynamic string utilities
- *
- * This file is part of the argtable3 library.
- *
- * Copyright (C) 2013-2019 Tom G. Huang
- *
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * Neither the name of STEWART HEITMANN nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT,
- * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- ******************************************************************************/
-
-#include "argtable3.h"
-
-#ifndef ARG_AMALGAMATION
-#include "argtable3_private.h"
-#endif
-
-#include
-#include
-#include
-
-#if defined(_MSC_VER)
-#pragma warning(push)
-#pragma warning(disable : 4996)
-#endif
-
-#define START_VSNBUFF 16
-
-/*
- * This dynamic string module is adapted from TclResult.c in the Tcl library.
- * Here is the copyright notice from the library:
- *
- * This software is copyrighted by the Regents of the University of
- * California, Sun Microsystems, Inc., Scriptics Corporation, ActiveState
- * Corporation and other parties. The following terms apply to all files
- * associated with the software unless explicitly disclaimed in
- * individual files.
- *
- * The authors hereby grant permission to use, copy, modify, distribute,
- * and license this software and its documentation for any purpose, provided
- * that existing copyright notices are retained in all copies and that this
- * notice is included verbatim in any distributions. No written agreement,
- * license, or royalty fee is required for any of the authorized uses.
- * Modifications to this software may be copyrighted by their authors
- * and need not follow the licensing terms described here, provided that
- * the new terms are clearly indicated on the first page of each file where
- * they apply.
- *
- * IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY
- * FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
- * ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
- * DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- *
- * THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE
- * IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
- * NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
- * MODIFICATIONS.
- *
- * GOVERNMENT USE: If you are acquiring this software on behalf of the
- * U.S. government, the Government shall have only "Restricted Rights"
- * in the software and related documentation as defined in the Federal
- * Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2). If you
- * are acquiring the software on behalf of the Department of Defense, the
- * software shall be classified as "Commercial Computer Software" and the
- * Government shall have only "Restricted Rights" as defined in Clause
- * 252.227-7014 (b) (3) of DFARs. Notwithstanding the foregoing, the
- * authors grant the U.S. Government and others acting in its behalf
- * permission to use and distribute the software in accordance with the
- * terms specified in this license.
- */
-
-typedef struct _internal_arg_dstr {
- char* data;
- arg_dstr_freefn* free_proc;
- char sbuf[ARG_DSTR_SIZE + 1];
- char* append_data;
- int append_data_size;
- int append_used;
-} _internal_arg_dstr_t;
-
-static void setup_append_buf(arg_dstr_t res, int newSpace);
-
-arg_dstr_t arg_dstr_create(void) {
- _internal_arg_dstr_t* h = (_internal_arg_dstr_t*)xmalloc(sizeof(_internal_arg_dstr_t));
- memset(h, 0, sizeof(_internal_arg_dstr_t));
- h->sbuf[0] = 0;
- h->data = h->sbuf;
- h->free_proc = ARG_DSTR_STATIC;
- return h;
-}
-
-void arg_dstr_destroy(arg_dstr_t ds) {
- if (ds == NULL)
- return;
-
- arg_dstr_reset(ds);
- xfree(ds);
- return;
-}
-
-void arg_dstr_set(arg_dstr_t ds, char* str, arg_dstr_freefn* free_proc) {
- int length;
- register arg_dstr_freefn* old_free_proc = ds->free_proc;
- char* old_result = ds->data;
-
- if (str == NULL) {
- ds->sbuf[0] = 0;
- ds->data = ds->sbuf;
- ds->free_proc = ARG_DSTR_STATIC;
- } else if (free_proc == ARG_DSTR_VOLATILE) {
- length = (int)strlen(str);
- if (length > ARG_DSTR_SIZE) {
- ds->data = (char*)xmalloc((unsigned)length + 1);
- ds->free_proc = ARG_DSTR_DYNAMIC;
- } else {
- ds->data = ds->sbuf;
- ds->free_proc = ARG_DSTR_STATIC;
- }
- strcpy(ds->data, str);
- } else {
- ds->data = str;
- ds->free_proc = free_proc;
- }
-
- /*
- * If the old result was dynamically-allocated, free it up. Do it here,
- * rather than at the beginning, in case the new result value was part of
- * the old result value.
- */
-
- if ((old_free_proc != 0) && (old_result != ds->data)) {
- if (old_free_proc == ARG_DSTR_DYNAMIC) {
- xfree(old_result);
- } else {
- (*old_free_proc)(old_result);
- }
- }
-
- if ((ds->append_data != NULL) && (ds->append_data_size > 0)) {
- xfree(ds->append_data);
- ds->append_data = NULL;
- ds->append_data_size = 0;
- }
-}
-
-char* arg_dstr_cstr(arg_dstr_t ds) /* Interpreter whose result to return. */
-{
- return ds->data;
-}
-
-void arg_dstr_cat(arg_dstr_t ds, const char* str) {
- setup_append_buf(ds, (int)strlen(str) + 1);
- memcpy(ds->data + strlen(ds->data), str, strlen(str));
-}
-
-void arg_dstr_catc(arg_dstr_t ds, char c) {
- setup_append_buf(ds, 2);
- memcpy(ds->data + strlen(ds->data), &c, 1);
-}
-
-/*
- * The logic of the `arg_dstr_catf` function is adapted from the `bformat`
- * function in The Better String Library by Paul Hsieh. Here is the copyright
- * notice from the library:
- *
- * Copyright (c) 2014, Paul Hsieh
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following disclaimer in the documentation
- * and/or other materials provided with the distribution.
- *
- * * Neither the name of bstrlib nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-void arg_dstr_catf(arg_dstr_t ds, const char* fmt, ...) {
- va_list arglist;
- char* buff;
- int n, r;
- size_t slen;
-
- if (fmt == NULL)
- return;
-
- /* Since the length is not determinable beforehand, a search is
- performed using the truncating "vsnprintf" call (to avoid buffer
- overflows) on increasing potential sizes for the output result. */
-
- if ((n = (int)(2 * strlen(fmt))) < START_VSNBUFF)
- n = START_VSNBUFF;
-
- buff = (char*)xmalloc(n + 2);
- memset(buff, 0, n + 2);
-
- for (;;) {
- va_start(arglist, fmt);
- r = vsnprintf(buff, n + 1, fmt, arglist);
- va_end(arglist);
-
- slen = strlen(buff);
- if (slen < (size_t)n)
- break;
-
- if (r > n)
- n = r;
- else
- n += n;
-
- xfree(buff);
- buff = (char*)xmalloc(n + 2);
- memset(buff, 0, n + 2);
- }
-
- arg_dstr_cat(ds, buff);
- xfree(buff);
-}
-
-static void setup_append_buf(arg_dstr_t ds, int new_space) {
- int total_space;
-
- /*
- * Make the append buffer larger, if that's necessary, then copy the
- * data into the append buffer and make the append buffer the official
- * data.
- */
- if (ds->data != ds->append_data) {
- /*
- * If the buffer is too big, then free it up so we go back to a
- * smaller buffer. This avoids tying up memory forever after a large
- * operation.
- */
- if (ds->append_data_size > 500) {
- xfree(ds->append_data);
- ds->append_data = NULL;
- ds->append_data_size = 0;
- }
- ds->append_used = (int)strlen(ds->data);
- } else if (ds->data[ds->append_used] != 0) {
- /*
- * Most likely someone has modified a result created by
- * arg_dstr_cat et al. so that it has a different size. Just
- * recompute the size.
- */
- ds->append_used = (int)strlen(ds->data);
- }
-
- total_space = new_space + ds->append_used;
- if (total_space >= ds->append_data_size) {
- char* newbuf;
-
- if (total_space < 100) {
- total_space = 200;
- } else {
- total_space *= 2;
- }
- newbuf = (char*)xmalloc((unsigned)total_space);
- memset(newbuf, 0, total_space);
- strcpy(newbuf, ds->data);
- if (ds->append_data != NULL) {
- xfree(ds->append_data);
- }
- ds->append_data = newbuf;
- ds->append_data_size = total_space;
- } else if (ds->data != ds->append_data) {
- strcpy(ds->append_data, ds->data);
- }
-
- arg_dstr_free(ds);
- ds->data = ds->append_data;
-}
-
-void arg_dstr_free(arg_dstr_t ds) {
- if (ds->free_proc != NULL) {
- if (ds->free_proc == ARG_DSTR_DYNAMIC) {
- xfree(ds->data);
- } else {
- (*ds->free_proc)(ds->data);
- }
- ds->free_proc = NULL;
- }
-}
-
-void arg_dstr_reset(arg_dstr_t ds) {
- arg_dstr_free(ds);
- if ((ds->append_data != NULL) && (ds->append_data_size > 0)) {
- xfree(ds->append_data);
- ds->append_data = NULL;
- ds->append_data_size = 0;
- }
-
- ds->data = ds->sbuf;
- ds->sbuf[0] = 0;
-}
-
-#if defined(_MSC_VER)
-#pragma warning(pop)
-#endif
-/* $Id: getopt.h,v 1.1 2009/10/16 19:50:28 rodney Exp rodney $ */
-/* $OpenBSD: getopt.h,v 1.1 2002/12/03 20:24:29 millert Exp $ */
-/* $NetBSD: getopt.h,v 1.4 2000/07/07 10:43:54 ad Exp $ */
-
-/*
- * Copyright (c) 2000 The NetBSD Foundation, Inc.
- * All rights reserved.
- *
- * This code is derived from software contributed to The NetBSD Foundation
- * by Dieter Baron and Thomas Klausner.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. All advertising materials mentioning features or use of this software
- * must display the following acknowledgment:
- * This product includes software developed by the NetBSD
- * Foundation, Inc. and its contributors.
- * 4. Neither the name of The NetBSD Foundation nor the names of its
- * contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
- * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
- * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#if ARG_REPLACE_GETOPT == 1
-
-#ifndef _GETOPT_H_
-#define _GETOPT_H_
-
-/*
- * GNU-like getopt_long() and 4.4BSD getsubopt()/optreset extensions
- */
-#define no_argument 0
-#define required_argument 1
-#define optional_argument 2
-
-struct option {
- /* name of long option */
- const char* name;
- /*
- * one of no_argument, required_argument, and optional_argument:
- * whether option takes an argument
- */
- int has_arg;
- /* if not NULL, set *flag to val when option found */
- int* flag;
- /* if flag not NULL, value to set *flag to; else return value */
- int val;
-};
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-int getopt_long(int, char* const*, const char*, const struct option*, int*);
-int getopt_long_only(int, char* const*, const char*, const struct option*, int*);
-#ifndef _GETOPT_DEFINED
-#define _GETOPT_DEFINED
-int getopt(int, char* const*, const char*);
-int getsubopt(char**, char* const*, char**);
-
-extern char* optarg; /* getopt(3) external variables */
-extern int opterr;
-extern int optind;
-extern int optopt;
-extern int optreset;
-extern char* suboptarg; /* getsubopt(3) external variable */
-#endif /* _GETOPT_DEFINED */
-
-#ifdef __cplusplus
-}
-#endif
-#endif /* !_GETOPT_H_ */
-
-#else
-#include
-#endif /* ARG_REPLACE_GETOPT */
-/* $Id: getopt_long.c,v 1.1 2009/10/16 19:50:28 rodney Exp rodney $ */
-/* $OpenBSD: getopt_long.c,v 1.23 2007/10/31 12:34:57 chl Exp $ */
-/* $NetBSD: getopt_long.c,v 1.15 2002/01/31 22:43:40 tv Exp $ */
-
-/*
- * Copyright (c) 2002 Todd C. Miller
- *
- * Permission to use, copy, modify, and distribute this software for any
- * purpose with or without fee is hereby granted, provided that the above
- * copyright notice and this permission notice appear in all copies.
- *
- * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
- *
- * Sponsored in part by the Defense Advanced Research Projects
- * Agency (DARPA) and Air Force Research Laboratory, Air Force
- * Materiel Command, USAF, under agreement number F39502-99-1-0512.
- */
-
-/*
- * Copyright (c) 2000 The NetBSD Foundation, Inc.
- * All rights reserved.
- *
- * This code is derived from software contributed to The NetBSD Foundation
- * by Dieter Baron and Thomas Klausner.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
- * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
- * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "argtable3.h"
-
-#ifndef ARG_AMALGAMATION
-#include "getopt.h"
-#endif
-
-#include
-#include
-#include
-
-#if ARG_REPLACE_GETOPT == 1
-int opterr = 1; /* if error message should be printed */
-int optind = 1; /* index into parent argv vector */
-int optopt = '?'; /* character checked for validity */
-int optreset; /* reset getopt */
-char* optarg; /* argument associated with option */
-#endif /* ARG_REPLACE_GETOPT */
-
-#define PRINT_ERROR ((opterr) && (*options != ':'))
-
-#define FLAG_PERMUTE 0x01 /* permute non-options to the end of argv */
-#define FLAG_ALLARGS 0x02 /* treat non-options as args to option "-1" */
-#define FLAG_LONGONLY 0x04 /* operate as getopt_long_only */
-
-/* return values */
-#define BADCH (int)'?'
-#define BADARG ((*options == ':') ? (int)':' : (int)'?')
-#define INORDER (int)1
-
-#define EMSG ""
-
-#if ARG_REPLACE_GETOPT == 1
-static int getopt_internal(int, char* const*, const char*, const struct option*, int*, int);
-#endif /* ARG_REPLACE_GETOPT */
-static int parse_long_options(char* const*, const char*, const struct option*, int*, int);
-static int gcd(int, int);
-static void permute_args(int, int, int, char* const*);
-
-static char* place = EMSG; /* option letter processing */
-
-/* XXX: set optreset to 1 rather than these two */
-static int nonopt_start = -1; /* first non option argument (for permute) */
-static int nonopt_end = -1; /* first option after non options (for permute) */
-
-/* Error messages */
-static const char recargchar[] = "option requires an argument -- %c";
-static const char recargstring[] = "option requires an argument -- %s";
-static const char ambig[] = "ambiguous option -- %.*s";
-static const char noarg[] = "option doesn't take an argument -- %.*s";
-static const char illoptchar[] = "unknown option -- %c";
-static const char illoptstring[] = "unknown option -- %s";
-
-#ifdef _WIN32
-
-/*
- * Windows needs warnx(). We change the definition though:
- * 1. (another) global is defined, opterrmsg, which holds the error message
- * 2. errors are always printed out on stderr w/o the program name
- * Note that opterrmsg always gets set no matter what opterr is set to. The
- * error message will not be printed if opterr is 0 as usual.
- */
-
-#include
-#include
-
-#define MAX_OPTERRMSG_SIZE 128
-
-extern char opterrmsg[MAX_OPTERRMSG_SIZE];
-char opterrmsg[MAX_OPTERRMSG_SIZE]; /* buffer for the last error message */
-
-static void warnx(const char* fmt, ...) {
- va_list ap;
- va_start(ap, fmt);
-
- /*
- * Make sure opterrmsg is always zero-terminated despite the _vsnprintf()
- * implementation specifics and manually suppress the warning.
- */
- memset(opterrmsg, 0, sizeof(opterrmsg));
- if (fmt != NULL)
-#if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || (defined(__STDC_SECURE_LIB__) && defined(__STDC_WANT_SECURE_LIB__))
- _vsnprintf_s(opterrmsg, sizeof(opterrmsg), sizeof(opterrmsg) - 1, fmt, ap);
-#else
- _vsnprintf(opterrmsg, sizeof(opterrmsg) - 1, fmt, ap);
-#endif
-
- va_end(ap);
-
-#ifdef _MSC_VER
-#pragma warning(suppress : 6053)
-#endif
- fprintf(stderr, "%s\n", opterrmsg);
-}
-
-#else
-#include
-#endif /*_WIN32*/
-
-/*
- * Compute the greatest common divisor of a and b.
- */
-static int gcd(int a, int b) {
- int c;
-
- c = a % b;
- while (c != 0) {
- a = b;
- b = c;
- c = a % b;
- }
-
- return (b);
-}
-
-/*
- * Exchange the block from nonopt_start to nonopt_end with the block
- * from nonopt_end to opt_end (keeping the same order of arguments
- * in each block).
- */
-static void permute_args(int panonopt_start, int panonopt_end, int opt_end, char* const* nargv) {
- int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos;
- char* swap;
-
- /*
- * compute lengths of blocks and number and size of cycles
- */
- nnonopts = panonopt_end - panonopt_start;
- nopts = opt_end - panonopt_end;
- ncycle = gcd(nnonopts, nopts);
- cyclelen = (opt_end - panonopt_start) / ncycle;
-
- for (i = 0; i < ncycle; i++) {
- cstart = panonopt_end + i;
- pos = cstart;
- for (j = 0; j < cyclelen; j++) {
- if (pos >= panonopt_end)
- pos -= nnonopts;
- else
- pos += nopts;
- swap = nargv[pos];
- /* LINTED const cast */
- ((char**)nargv)[pos] = nargv[cstart];
- /* LINTED const cast */
- ((char**)nargv)[cstart] = swap;
- }
- }
-}
-
-/*
- * parse_long_options --
- * Parse long options in argc/argv argument vector.
- * Returns -1 if short_too is set and the option does not match long_options.
- */
-static int parse_long_options(char* const* nargv, const char* options, const struct option* long_options, int* idx, int short_too) {
- char *current_argv, *has_equal;
- size_t current_argv_len;
- int i, match;
-
- current_argv = place;
- match = -1;
-
- optind++;
-
- if ((has_equal = strchr(current_argv, '=')) != NULL) {
- /* argument found (--option=arg) */
- current_argv_len = has_equal - current_argv;
- has_equal++;
- } else
- current_argv_len = strlen(current_argv);
-
- for (i = 0; long_options[i].name; i++) {
- /* find matching long option */
- if (strncmp(current_argv, long_options[i].name, current_argv_len))
- continue;
-
- if (strlen(long_options[i].name) == current_argv_len) {
- /* exact match */
- match = i;
- break;
- }
- /*
- * If this is a known short option, don't allow
- * a partial match of a single character.
- */
- if (short_too && current_argv_len == 1)
- continue;
-
- if (match == -1) /* partial match */
- match = i;
- else {
- /* ambiguous abbreviation */
- if (PRINT_ERROR)
- warnx(ambig, (int)current_argv_len, current_argv);
- optopt = 0;
- return (BADCH);
- }
- }
- if (match != -1) { /* option found */
- if (long_options[match].has_arg == no_argument && has_equal) {
- if (PRINT_ERROR)
- warnx(noarg, (int)current_argv_len, current_argv);
- /*
- * XXX: GNU sets optopt to val regardless of flag
- */
- if (long_options[match].flag == NULL)
- optopt = long_options[match].val;
- else
- optopt = 0;
- return (BADARG);
- }
- if (long_options[match].has_arg == required_argument || long_options[match].has_arg == optional_argument) {
- if (has_equal)
- optarg = has_equal;
- else if (long_options[match].has_arg == required_argument) {
- /*
- * optional argument doesn't use next nargv
- */
- optarg = nargv[optind++];
- }
- }
- if ((long_options[match].has_arg == required_argument) && (optarg == NULL)) {
- /*
- * Missing argument; leading ':' indicates no error
- * should be generated.
- */
- if (PRINT_ERROR)
- warnx(recargstring, current_argv);
- /*
- * XXX: GNU sets optopt to val regardless of flag
- */
- if (long_options[match].flag == NULL)
- optopt = long_options[match].val;
- else
- optopt = 0;
- --optind;
- return (BADARG);
- }
- } else { /* unknown option */
- if (short_too) {
- --optind;
- return (-1);
- }
- if (PRINT_ERROR)
- warnx(illoptstring, current_argv);
- optopt = 0;
- return (BADCH);
- }
- if (idx)
- *idx = match;
- if (long_options[match].flag) {
- *long_options[match].flag = long_options[match].val;
- return (0);
- } else
- return (long_options[match].val);
-}
-
-#if ARG_REPLACE_GETOPT == 1
-/*
- * getopt_internal --
- * Parse argc/argv argument vector. Called by user level routines.
- */
-static int getopt_internal(int nargc, char* const* nargv, const char* options, const struct option* long_options, int* idx, int flags) {
- char* oli; /* option letter list index */
- int optchar, short_too;
- static int posixly_correct = -1;
-
- if (options == NULL)
- return (-1);
-
- /*
- * Disable GNU extensions if POSIXLY_CORRECT is set or options
- * string begins with a '+'.
- */
- if (posixly_correct == -1)
-#if defined(_MSC_VER)
-#pragma warning(push)
-#pragma warning(disable : 4996)
-#endif
- posixly_correct = (getenv("POSIXLY_CORRECT") != NULL);
-#if defined(_MSC_VER)
-#pragma warning(pop)
-#endif
- if (posixly_correct || *options == '+')
- flags &= ~FLAG_PERMUTE;
- else if (*options == '-')
- flags |= FLAG_ALLARGS;
- if (*options == '+' || *options == '-')
- options++;
-
- /*
- * XXX Some GNU programs (like cvs) set optind to 0 instead of
- * XXX using optreset. Work around this braindamage.
- */
- if (optind == 0)
- optind = optreset = 1;
-
- optarg = NULL;
- if (optreset)
- nonopt_start = nonopt_end = -1;
-start:
- if (optreset || !*place) { /* update scanning pointer */
- optreset = 0;
- if (optind >= nargc) { /* end of argument vector */
- place = EMSG;
- if (nonopt_end != -1) {
- /* do permutation, if we have to */
- permute_args(nonopt_start, nonopt_end, optind, nargv);
- optind -= nonopt_end - nonopt_start;
- } else if (nonopt_start != -1) {
- /*
- * If we skipped non-options, set optind
- * to the first of them.
- */
- optind = nonopt_start;
- }
- nonopt_start = nonopt_end = -1;
- return (-1);
- }
- if (*(place = nargv[optind]) != '-' || (place[1] == '\0' && strchr(options, '-') == NULL)) {
- place = EMSG; /* found non-option */
- if (flags & FLAG_ALLARGS) {
- /*
- * GNU extension:
- * return non-option as argument to option 1
- */
- optarg = nargv[optind++];
- return (INORDER);
- }
- if (!(flags & FLAG_PERMUTE)) {
- /*
- * If no permutation wanted, stop parsing
- * at first non-option.
- */
- return (-1);
- }
- /* do permutation */
- if (nonopt_start == -1)
- nonopt_start = optind;
- else if (nonopt_end != -1) {
- permute_args(nonopt_start, nonopt_end, optind, nargv);
- nonopt_start = optind - (nonopt_end - nonopt_start);
- nonopt_end = -1;
- }
- optind++;
- /* process next argument */
- goto start;
- }
- if (nonopt_start != -1 && nonopt_end == -1)
- nonopt_end = optind;
-
- /*
- * If we have "-" do nothing, if "--" we are done.
- */
- if (place[1] != '\0' && *++place == '-' && place[1] == '\0') {
- optind++;
- place = EMSG;
- /*
- * We found an option (--), so if we skipped
- * non-options, we have to permute.
- */
- if (nonopt_end != -1) {
- permute_args(nonopt_start, nonopt_end, optind, nargv);
- optind -= nonopt_end - nonopt_start;
- }
- nonopt_start = nonopt_end = -1;
- return (-1);
- }
- }
-
- /*
- * Check long options if:
- * 1) we were passed some
- * 2) the arg is not just "-"
- * 3) either the arg starts with -- we are getopt_long_only()
- */
- if (long_options != NULL && place != nargv[optind] && (*place == '-' || (flags & FLAG_LONGONLY))) {
- short_too = 0;
- if (*place == '-')
- place++; /* --foo long option */
- else if (*place != ':' && strchr(options, *place) != NULL)
- short_too = 1; /* could be short option too */
-
- optchar = parse_long_options(nargv, options, long_options, idx, short_too);
- if (optchar != -1) {
- place = EMSG;
- return (optchar);
- }
- }
-
- if ((optchar = (int)*place++) == (int)':' || (optchar == (int)'-' && *place != '\0') || (oli = strchr(options, optchar)) == NULL) {
- /*
- * If the user specified "-" and '-' isn't listed in
- * options, return -1 (non-option) as per POSIX.
- * Otherwise, it is an unknown option character (or ':').
- */
- if (optchar == (int)'-' && *place == '\0')
- return (-1);
- if (!*place)
- ++optind;
- if (PRINT_ERROR)
- warnx(illoptchar, optchar);
- optopt = optchar;
- return (BADCH);
- }
- if (long_options != NULL && optchar == 'W' && oli[1] == ';') {
- /* -W long-option */
- if (*place) /* no space */
- /* NOTHING */;
- else if (++optind >= nargc) { /* no arg */
- place = EMSG;
- if (PRINT_ERROR)
- warnx(recargchar, optchar);
- optopt = optchar;
- return (BADARG);
- } else /* white space */
- place = nargv[optind];
- optchar = parse_long_options(nargv, options, long_options, idx, 0);
- place = EMSG;
- return (optchar);
- }
- if (*++oli != ':') { /* doesn't take argument */
- if (!*place)
- ++optind;
- } else { /* takes (optional) argument */
- optarg = NULL;
- if (*place) /* no white space */
- optarg = place;
- else if (oli[1] != ':') { /* arg not optional */
- if (++optind >= nargc) { /* no arg */
- place = EMSG;
- if (PRINT_ERROR)
- warnx(recargchar, optchar);
- optopt = optchar;
- return (BADARG);
- } else
- optarg = nargv[optind];
- }
- place = EMSG;
- ++optind;
- }
- /* dump back option letter */
- return (optchar);
-}
-
-/*
- * getopt --
- * Parse argc/argv argument vector.
- *
- * [eventually this will replace the BSD getopt]
- */
-int getopt(int nargc, char* const* nargv, const char* options) {
- /*
- * We don't pass FLAG_PERMUTE to getopt_internal() since
- * the BSD getopt(3) (unlike GNU) has never done this.
- *
- * Furthermore, since many privileged programs call getopt()
- * before dropping privileges it makes sense to keep things
- * as simple (and bug-free) as possible.
- */
- return (getopt_internal(nargc, nargv, options, NULL, NULL, 0));
-}
-#endif /* ARG_REPLACE_GETOPT */
-
-/*
- * getopt_long --
- * Parse argc/argv argument vector.
- */
-int getopt_long(int nargc, char* const* nargv, const char* options, const struct option* long_options, int* idx) {
- return (getopt_internal(nargc, nargv, options, long_options, idx, FLAG_PERMUTE));
-}
-
-/*
- * getopt_long_only --
- * Parse argc/argv argument vector.
- */
-int getopt_long_only(int nargc, char* const* nargv, const char* options, const struct option* long_options, int* idx) {
- return (getopt_internal(nargc, nargv, options, long_options, idx, FLAG_PERMUTE | FLAG_LONGONLY));
-}
-/*******************************************************************************
- * arg_date: Implements the date command-line option
- *
* This file is part of the argtable3 library.
*
* Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
@@ -1858,32 +154,646 @@ int getopt_long_only(int nargc, char* const* nargv, const char* options, const s
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
-#include "argtable3.h"
+#include
+#include
-#ifndef ARG_AMALGAMATION
-#include "argtable3_private.h"
+
+void dbg_printf(const char *fmt, ...) {
+ va_list args;
+ va_start(args, fmt);
+ vfprintf(stderr, fmt, args);
+ va_end(args);
+}
+
+#include "getopt.h"
+
+/* $Id: getopt_long.c,v 1.1 2009/10/16 19:50:28 rodney Exp rodney $ */
+/* $OpenBSD: getopt_long.c,v 1.23 2007/10/31 12:34:57 chl Exp $ */
+/* $NetBSD: getopt_long.c,v 1.15 2002/01/31 22:43:40 tv Exp $ */
+
+/*
+ * Copyright (c) 2002 Todd C. Miller
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ *
+ * Sponsored in part by the Defense Advanced Research Projects
+ * Agency (DARPA) and Air Force Research Laboratory, Air Force
+ * Materiel Command, USAF, under agreement number F39502-99-1-0512.
+ */
+
+// $Id: getopt_long.c,v 1.1 2009/10/16 19:50:28 rodney Exp rodney $"
+
+/*-
+ * Copyright (c) 2000 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Dieter Baron and Thomas Klausner.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+ * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#if 0
+#include
#endif
+#include
+#include
+#include
+
+
+#define REPLACE_GETOPT /* use this getopt as the system getopt(3) */
+
+#ifdef REPLACE_GETOPT
+int opterr = 1; /* if error message should be printed */
+int optind = 1; /* index into parent argv vector */
+int optopt = '?'; /* character checked for validity */
+int optreset; /* reset getopt */
+const char *optarg; /* argument associated with option */
+#endif
+
+#define PRINT_ERROR ((opterr) && (*options != ':'))
+
+#define FLAG_PERMUTE 0x01 /* permute non-options to the end of argv */
+#define FLAG_ALLARGS 0x02 /* treat non-options as args to option "-1" */
+#define FLAG_LONGONLY 0x04 /* operate as getopt_long_only */
+
+/* return values */
+#define BADCH (int)'?'
+#define BADARG ((*options == ':') ? (int)':' : (int)'?')
+#define INORDER (int)1
+
+#define EMSG ""
+
+static int getopt_internal(int, char *const *, const char *,
+ const struct option *, int *, int);
+static int parse_long_options(char *const *, const char *,
+ const struct option *, int *, int);
+static int gcd(int, int);
+static void permute_args(int, int, int, char *const *);
+
+static const char *place = EMSG; /* option letter processing */
+
+/* XXX: set optreset to 1 rather than these two */
+static int nonopt_start = -1; /* first non option argument (for permute) */
+static int nonopt_end = -1; /* first option after non options (for permute) */
+
+/* Error messages */
+static const char recargchar[] = "option requires an argument -- %c";
+static const char recargstring[] = "option requires an argument -- %s";
+static const char ambig[] = "ambiguous option -- %.*s";
+static const char noarg[] = "option doesn't take an argument -- %.*s";
+static const char illoptchar[] = "unknown option -- %c";
+static const char illoptstring[] = "unknown option -- %s";
+
+
+
+#ifdef _WIN32
+
+/* Windows needs warnx(). We change the definition though:
+ * 1. (another) global is defined, opterrmsg, which holds the error message
+ * 2. errors are always printed out on stderr w/o the program name
+ * Note that opterrmsg always gets set no matter what opterr is set to. The
+ * error message will not be printed if opterr is 0 as usual.
+ */
+
+#include
+#include
+
+#define MAX_OPTER_MSG_SIZE 128
+
+extern char opterrmsg[MAX_OPTER_MSG_SIZE];
+char opterrmsg[MAX_OPTER_MSG_SIZE]; /* buffer for the last error message */
+
+static void warnx(const char *fmt, ...) {
+ va_list ap;
+ va_start(ap, fmt);
+ /*
+ Make sure opterrmsg is always zero-terminated despite the _vsnprintf()
+ implementation specifics and manually suppress the warning.
+ */
+ memset(opterrmsg, 0, sizeof opterrmsg);
+ if (fmt != NULL)
+#ifdef __STDC_WANT_SECURE_LIB__
+ _vsnprintf_s(opterrmsg, MAX_OPTER_MSG_SIZE, sizeof(opterrmsg) - 1, fmt, ap);
+#else
+ _vsnprintf(opterrmsg, sizeof(opterrmsg) - 1, fmt, ap);
+#endif
+ va_end(ap);
+
+ fprintf(stderr, "%s\n", opterrmsg);
+}
+
+#else
+#include
+#endif /*_WIN32*/
+
+
+/*
+ * Compute the greatest common divisor of a and b.
+ */
+static int
+gcd(int a, int b) {
+ int c;
+
+ c = a % b;
+ while (c != 0) {
+ a = b;
+ b = c;
+ c = a % b;
+ }
+
+ return (b);
+}
+
+/*
+ * Exchange the block from nonopt_start to nonopt_end with the block
+ * from nonopt_end to opt_end (keeping the same order of arguments
+ * in each block).
+ */
+static void
+permute_args(int panonopt_start, int panonopt_end, int opt_end,
+ char *const *nargv) {
+
+ /*
+ * compute lengths of blocks and number and size of cycles
+ */
+ int nnonopts = panonopt_end - panonopt_start;
+ int nopts = opt_end - panonopt_end;
+ int ncycle = gcd(nnonopts, nopts);
+ int cyclelen = (opt_end - panonopt_start) / ncycle;
+
+ for (int i = 0; i < ncycle; i++) {
+ int cstart = panonopt_end + i;
+ int pos = cstart;
+ for (int j = 0; j < cyclelen; j++) {
+ if (pos >= panonopt_end)
+ pos -= nnonopts;
+ else
+ pos += nopts;
+ char *swap = nargv[pos];
+ /* LINTED const cast */
+ ((char **) nargv)[pos] = nargv[cstart];
+ /* LINTED const cast */
+ ((char **)nargv)[cstart] = swap;
+ }
+ }
+}
+
+/*
+ * parse_long_options --
+ * Parse long options in argc/argv argument vector.
+ * Returns -1 if short_too is set and the option does not match long_options.
+ */
+static int
+parse_long_options(char *const *nargv, const char *options,
+ const struct option *long_options, int *idx, int short_too) {
+ const char *current_argv, *has_equal;
+ size_t current_argv_len;
+ int i, match;
+
+ current_argv = place;
+ match = -1;
+
+ optind++;
+
+ if ((has_equal = strchr(current_argv, '=')) != NULL) {
+ /* argument found (--option=arg) */
+ current_argv_len = has_equal - current_argv;
+ has_equal++;
+ } else
+ current_argv_len = strlen(current_argv);
+
+ for (i = 0; long_options[i].name; i++) {
+ /* find matching long option */
+ if (strncmp(current_argv, long_options[i].name,
+ current_argv_len))
+ continue;
+
+ if (strlen(long_options[i].name) == current_argv_len) {
+ /* exact match */
+ match = i;
+ break;
+ }
+ /*
+ * If this is a known short option, don't allow
+ * a partial match of a single character.
+ */
+ if (short_too && current_argv_len == 1)
+ continue;
+
+ if (match == -1) /* partial match */
+ match = i;
+ else {
+ /* ambiguous abbreviation */
+ if (PRINT_ERROR)
+ warnx(ambig, (int)current_argv_len,
+ current_argv);
+ optopt = 0;
+ return (BADCH);
+ }
+ }
+ if (match != -1) { /* option found */
+ if (long_options[match].has_arg == no_argument
+ && has_equal) {
+ if (PRINT_ERROR)
+ warnx(noarg, (int)current_argv_len,
+ current_argv);
+ /*
+ * XXX: GNU sets optopt to val regardless of flag
+ */
+ if (long_options[match].flag == NULL)
+ optopt = long_options[match].val;
+ else
+ optopt = 0;
+ return (BADARG);
+ }
+ if (long_options[match].has_arg == required_argument ||
+ long_options[match].has_arg == optional_argument) {
+ if (has_equal)
+ optarg = has_equal;
+ else if (long_options[match].has_arg ==
+ required_argument) {
+ /*
+ * optional argument doesn't use next nargv
+ */
+ optarg = nargv[optind++];
+ }
+ }
+ if ((long_options[match].has_arg == required_argument)
+ && (optarg == NULL)) {
+ /*
+ * Missing argument; leading ':' indicates no error
+ * should be generated.
+ */
+ if (PRINT_ERROR)
+ warnx(recargstring,
+ current_argv);
+ /*
+ * XXX: GNU sets optopt to val regardless of flag
+ */
+ if (long_options[match].flag == NULL)
+ optopt = long_options[match].val;
+ else
+ optopt = 0;
+ --optind;
+ return (BADARG);
+ }
+ } else { /* unknown option */
+ if (short_too) {
+ --optind;
+ return (-1);
+ }
+ if (PRINT_ERROR)
+ warnx(illoptstring, current_argv);
+ optopt = 0;
+ return (BADCH);
+ }
+ if (idx)
+ *idx = match;
+ if (long_options[match].flag) {
+ *long_options[match].flag = long_options[match].val;
+ return (0);
+ } else
+ return (long_options[match].val);
+}
+
+/*
+ * getopt_internal --
+ * Parse argc/argv argument vector. Called by user level routines.
+ */
+static int
+getopt_internal(int nargc, char *const *nargv, const char *options,
+ const struct option *long_options, int *idx, int flags) {
+ char *oli; /* option letter list index */
+ int optchar, short_too;
+ static int posixly_correct = -1;
+#ifdef __STDC_WANT_SECURE_LIB__
+ char *buffer = NULL;
+ size_t buffer_size = 0;
+ errno_t err = 0;
+#endif
+
+ if (options == NULL)
+ return (-1);
+
+ /*
+ * Disable GNU extensions if POSIXLY_CORRECT is set or options
+ * string begins with a '+'.
+ */
+
+#ifdef __STDC_WANT_SECURE_LIB__
+ if (posixly_correct == -1) {
+ err = _dupenv_s(&buffer, &buffer_size, "POSIXLY_CORRECT") == 0;
+ posixly_correct = buffer != NULL;
+ if (buffer != NULL && err == 0) {
+ free(buffer);
+ }
+ }
+#else
+ if (posixly_correct == -1)
+ posixly_correct = (getenv("POSIXLY_CORRECT") != NULL);
+#endif
+ if (posixly_correct || *options == '+')
+ flags &= ~FLAG_PERMUTE;
+ else if (*options == '-')
+ flags |= FLAG_ALLARGS;
+ if (*options == '+' || *options == '-')
+ options++;
+
+ /*
+ * XXX Some GNU programs (like cvs) set optind to 0 instead of
+ * XXX using optreset. Work around this braindamage.
+ */
+ if (optind == 0)
+ optind = optreset = 1;
+
+ optarg = NULL;
+ if (optreset)
+ nonopt_start = nonopt_end = -1;
+start:
+ if (optreset || !*place) { /* update scanning pointer */
+ optreset = 0;
+ if (optind >= nargc) { /* end of argument vector */
+ place = EMSG;
+ if (nonopt_end != -1) {
+ /* do permutation, if we have to */
+ permute_args(nonopt_start, nonopt_end,
+ optind, nargv);
+ optind -= nonopt_end - nonopt_start;
+ } else if (nonopt_start != -1) {
+ /*
+ * If we skipped non-options, set optind
+ * to the first of them.
+ */
+ optind = nonopt_start;
+ }
+ nonopt_start = nonopt_end = -1;
+ return (-1);
+ }
+ if (*(place = nargv[optind]) != '-' ||
+ (place[1] == '\0' && strchr(options, '-') == NULL)) {
+ place = EMSG; /* found non-option */
+ if (flags & FLAG_ALLARGS) {
+ /*
+ * GNU extension:
+ * return non-option as argument to option 1
+ */
+ optarg = nargv[optind++];
+ return (INORDER);
+ }
+ if (!(flags & FLAG_PERMUTE)) {
+ /*
+ * If no permutation wanted, stop parsing
+ * at first non-option.
+ */
+ return (-1);
+ }
+ /* do permutation */
+ if (nonopt_start == -1)
+ nonopt_start = optind;
+ else if (nonopt_end != -1) {
+ permute_args(nonopt_start, nonopt_end,
+ optind, nargv);
+ nonopt_start = optind -
+ (nonopt_end - nonopt_start);
+ nonopt_end = -1;
+ }
+ optind++;
+ /* process next argument */
+ goto start;
+ }
+ if (nonopt_start != -1 && nonopt_end == -1)
+ nonopt_end = optind;
+
+ /*
+ * If we have "-" do nothing, if "--" we are done.
+ */
+ if (place[1] != '\0' && *++place == '-' && place[1] == '\0') {
+ optind++;
+ place = EMSG;
+ /*
+ * We found an option (--), so if we skipped
+ * non-options, we have to permute.
+ */
+ if (nonopt_end != -1) {
+ permute_args(nonopt_start, nonopt_end,
+ optind, nargv);
+ optind -= nonopt_end - nonopt_start;
+ }
+ nonopt_start = nonopt_end = -1;
+ return (-1);
+ }
+ }
+
+ /*
+ * Check long options if:
+ * 1) we were passed some
+ * 2) the arg is not just "-"
+ * 3) either the arg starts with -- we are getopt_long_only()
+ */
+ if (long_options != NULL && place != nargv[optind] &&
+ (*place == '-' || (flags & FLAG_LONGONLY))) {
+ short_too = 0;
+ if (*place == '-')
+ place++; /* --foo long option */
+ else if (*place != ':' && strchr(options, *place) != NULL)
+ short_too = 1; /* could be short option too */
+
+ optchar = parse_long_options(nargv, options, long_options,
+ idx, short_too);
+ if (optchar != -1) {
+ place = EMSG;
+ return (optchar);
+ }
+ }
+
+ if ((optchar = (int) * place++) == (int)':' ||
+ (optchar == (int)'-' && *place != '\0') ||
+ (oli = strchr(options, optchar)) == NULL) {
+ /*
+ * If the user specified "-" and '-' isn't listed in
+ * options, return -1 (non-option) as per POSIX.
+ * Otherwise, it is an unknown option character (or ':').
+ */
+ if (optchar == (int)'-' && *place == '\0')
+ return (-1);
+ if (!*place)
+ ++optind;
+ if (PRINT_ERROR)
+ warnx(illoptchar, optchar);
+ optopt = optchar;
+ return (BADCH);
+ }
+ if (long_options != NULL && optchar == 'W' && oli[1] == ';') {
+ /* -W long-option */
+ if (*place) /* no space */
+ /* NOTHING */;
+ else if (++optind >= nargc) { /* no arg */
+ place = EMSG;
+ if (PRINT_ERROR)
+ warnx(recargchar, optchar);
+ optopt = optchar;
+ return (BADARG);
+ } else /* white space */
+ place = nargv[optind];
+ optchar = parse_long_options(nargv, options, long_options,
+ idx, 0);
+ place = EMSG;
+ return (optchar);
+ }
+ if (*++oli != ':') { /* doesn't take argument */
+ if (!*place)
+ ++optind;
+ } else { /* takes (optional) argument */
+ optarg = NULL;
+ if (*place) /* no white space */
+ optarg = place;
+ else if (oli[1] != ':') { /* arg not optional */
+ if (++optind >= nargc) { /* no arg */
+ place = EMSG;
+ if (PRINT_ERROR)
+ warnx(recargchar, optchar);
+ optopt = optchar;
+ return (BADARG);
+ } else
+ optarg = nargv[optind];
+ }
+ place = EMSG;
+ ++optind;
+ }
+ /* dump back option letter */
+ return (optchar);
+}
+
+#ifdef REPLACE_GETOPT
+/*
+ * getopt --
+ * Parse argc/argv argument vector.
+ *
+ * [eventually this will replace the BSD getopt]
+ */
+int
+getopt(int nargc, char *const *nargv, const char *options) {
+
+ /*
+ * We don't pass FLAG_PERMUTE to getopt_internal() since
+ * the BSD getopt(3) (unlike GNU) has never done this.
+ *
+ * Furthermore, since many privileged programs call getopt()
+ * before dropping privileges it makes sense to keep things
+ * as simple (and bug-free) as possible.
+ */
+ return (getopt_internal(nargc, nargv, options, NULL, NULL, 0));
+}
+#endif /* REPLACE_GETOPT */
+
+/*
+ * getopt_long --
+ * Parse argc/argv argument vector.
+ */
+int
+getopt_long(int nargc, char *const *nargv, const char *options,
+ const struct option *long_options, int *idx) {
+
+ return (getopt_internal(nargc, nargv, options, long_options, idx,
+ FLAG_PERMUTE));
+}
+
+/*
+ * getopt_long_only --
+ * Parse argc/argv argument vector.
+ */
+int
+getopt_long_only(int nargc, char *const *nargv, const char *options,
+ const struct option *long_options, int *idx) {
+
+ return (getopt_internal(nargc, nargv, options, long_options, idx,
+ FLAG_PERMUTE | FLAG_LONGONLY));
+}
+/*******************************************************************************
+ * This file is part of the argtable3 library.
+ *
+ * Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * * Neither the name of STEWART HEITMANN nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ ******************************************************************************/
#include
#include
-char* arg_strptime(const char* buf, const char* fmt, struct tm* tm);
+#include "argtable3.h"
-static void arg_date_resetfn(struct arg_date* parent) {
+
+char *arg_strptime(const char *buf, const char *fmt, struct tm *tm);
+
+
+static void arg_date_resetfn(struct arg_date *parent) {
ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent));
parent->count = 0;
}
-static int arg_date_scanfn(struct arg_date* parent, const char* argval) {
+
+static int arg_date_scanfn(struct arg_date *parent, const char *argval) {
int errorcode = 0;
if (parent->count == parent->hdr.maxcount) {
- errorcode = ARG_ERR_MAXCOUNT;
+ errorcode = EMAXCOUNT;
} else if (!argval) {
/* no argument value was given, leave parent->tmval[] unaltered but still count it */
parent->count++;
} else {
- const char* pend;
+ const char *pend;
struct tm tm = parent->tmval[parent->count];
/* parse the given argument value, store result in parent->tmval[] */
@@ -1891,66 +801,92 @@ static int arg_date_scanfn(struct arg_date* parent, const char* argval) {
if (pend && pend[0] == '\0')
parent->tmval[parent->count++] = tm;
else
- errorcode = ARG_ERR_BADDATE;
+ errorcode = EBADDATE;
}
ARG_TRACE(("%s:scanfn(%p) returns %d\n", __FILE__, parent, errorcode));
return errorcode;
}
-static int arg_date_checkfn(struct arg_date* parent) {
- int errorcode = (parent->count < parent->hdr.mincount) ? ARG_ERR_MINCOUNT : 0;
+
+static int arg_date_checkfn(struct arg_date *parent) {
+ int errorcode = (parent->count < parent->hdr.mincount) ? EMINCOUNT : 0;
ARG_TRACE(("%s:checkfn(%p) returns %d\n", __FILE__, parent, errorcode));
return errorcode;
}
-static void arg_date_errorfn(struct arg_date* parent, arg_dstr_t ds, int errorcode, const char* argval, const char* progname) {
- const char* shortopts = parent->hdr.shortopts;
- const char* longopts = parent->hdr.longopts;
- const char* datatype = parent->hdr.datatype;
+
+static void arg_date_errorfn(
+ struct arg_date *parent,
+ FILE *fp,
+ int errorcode,
+ const char *argval,
+ const char *progname) {
+ const char *shortopts = parent->hdr.shortopts;
+ const char *longopts = parent->hdr.longopts;
+ const char *datatype = parent->hdr.datatype;
/* make argval NULL safe */
argval = argval ? argval : "";
- arg_dstr_catf(ds, "%s: ", progname);
+ fprintf(fp, "%s: ", progname);
switch (errorcode) {
- case ARG_ERR_MINCOUNT:
- arg_dstr_cat(ds, "missing option ");
- arg_print_option_ds(ds, shortopts, longopts, datatype, "\n");
+ case EMINCOUNT:
+ fputs("missing option ", fp);
+ arg_print_option(fp, shortopts, longopts, datatype, "\n");
break;
- case ARG_ERR_MAXCOUNT:
- arg_dstr_cat(ds, "excess option ");
- arg_print_option_ds(ds, shortopts, longopts, argval, "\n");
+ case EMAXCOUNT:
+ fputs("excess option ", fp);
+ arg_print_option(fp, shortopts, longopts, argval, "\n");
break;
- case ARG_ERR_BADDATE: {
+ case EBADDATE: {
struct tm tm;
char buff[200];
- arg_dstr_catf(ds, "illegal timestamp format \"%s\"\n", argval);
+ fprintf(fp, "illegal timestamp format \"%s\"\n", argval);
memset(&tm, 0, sizeof(tm));
arg_strptime("1999-12-31 23:59:59", "%F %H:%M:%S", &tm);
strftime(buff, sizeof(buff), parent->format, &tm);
- arg_dstr_catf(ds, "correct format is \"%s\"\n", buff);
+ printf("correct format is \"%s\"\n", buff);
break;
}
}
}
-struct arg_date* arg_date0(const char* shortopts, const char* longopts, const char* format, const char* datatype, const char* glossary) {
+
+struct arg_date *arg_date0(
+ const char *shortopts,
+ const char *longopts,
+ const char *format,
+ const char *datatype,
+ const char *glossary) {
return arg_daten(shortopts, longopts, format, datatype, 0, 1, glossary);
}
-struct arg_date* arg_date1(const char* shortopts, const char* longopts, const char* format, const char* datatype, const char* glossary) {
+
+struct arg_date *arg_date1(
+ const char *shortopts,
+ const char *longopts,
+ const char *format,
+ const char *datatype,
+ const char *glossary) {
return arg_daten(shortopts, longopts, format, datatype, 1, 1, glossary);
}
-struct arg_date*
-arg_daten(const char* shortopts, const char* longopts, const char* format, const char* datatype, int mincount, int maxcount, const char* glossary) {
+
+struct arg_date *arg_daten(
+ const char *shortopts,
+ const char *longopts,
+ const char *format,
+ const char *datatype,
+ int mincount,
+ int maxcount,
+ const char *glossary) {
size_t nbytes;
- struct arg_date* result;
+ struct arg_date *result;
/* foolproof things by ensuring maxcount is not less than mincount */
maxcount = (maxcount < mincount) ? mincount : maxcount;
@@ -1960,37 +896,39 @@ arg_daten(const char* shortopts, const char* longopts, const char* format, const
format = "%x";
nbytes = sizeof(struct arg_date) /* storage for struct arg_date */
- + maxcount * sizeof(struct tm); /* storage for tmval[maxcount] array */
+ + maxcount * sizeof(struct tm); /* storage for tmval[maxcount] array */
/* allocate storage for the arg_date struct + tmval[] array. */
/* we use calloc because we want the tmval[] array zero filled. */
- result = (struct arg_date*)xcalloc(1, nbytes);
+ result = (struct arg_date *)calloc(1, nbytes);
+ if (result) {
+ /* init the arg_hdr struct */
+ result->hdr.flag = ARG_HASVALUE;
+ result->hdr.shortopts = shortopts;
+ result->hdr.longopts = longopts;
+ result->hdr.datatype = datatype ? datatype : format;
+ result->hdr.glossary = glossary;
+ result->hdr.mincount = mincount;
+ result->hdr.maxcount = maxcount;
+ result->hdr.parent = result;
+ result->hdr.resetfn = (arg_resetfn *)arg_date_resetfn;
+ result->hdr.scanfn = (arg_scanfn *)arg_date_scanfn;
+ result->hdr.checkfn = (arg_checkfn *)arg_date_checkfn;
+ result->hdr.errorfn = (arg_errorfn *)arg_date_errorfn;
- /* init the arg_hdr struct */
- result->hdr.flag = ARG_HASVALUE;
- result->hdr.shortopts = shortopts;
- result->hdr.longopts = longopts;
- result->hdr.datatype = datatype ? datatype : format;
- result->hdr.glossary = glossary;
- result->hdr.mincount = mincount;
- result->hdr.maxcount = maxcount;
- result->hdr.parent = result;
- result->hdr.resetfn = (arg_resetfn*)arg_date_resetfn;
- result->hdr.scanfn = (arg_scanfn*)arg_date_scanfn;
- result->hdr.checkfn = (arg_checkfn*)arg_date_checkfn;
- result->hdr.errorfn = (arg_errorfn*)arg_date_errorfn;
+ /* store the tmval[maxcount] array immediately after the arg_date struct */
+ result->tmval = (struct tm *)(result + 1);
- /* store the tmval[maxcount] array immediately after the arg_date struct */
- result->tmval = (struct tm*)(result + 1);
-
- /* init the remaining arg_date member variables */
- result->count = 0;
- result->format = format;
+ /* init the remaining arg_date member variables */
+ result->count = 0;
+ result->format = format;
+ }
ARG_TRACE(("arg_daten() returns %p\n", result));
return result;
}
+
/*-
* Copyright (c) 1997, 1998, 2005, 2008 The NetBSD Foundation, Inc.
* All rights reserved.
@@ -2028,31 +966,40 @@ arg_daten(const char* shortopts, const char* longopts, const char* format, const
* We do not implement alternate representations. However, we always
* check whether a given modifier is allowed for a certain conversion.
*/
-#define ALT_E 0x01
-#define ALT_O 0x02
-#define LEGAL_ALT(x) \
- { \
- if (alt_format & ~(x)) \
- return (0); \
- }
-#define TM_YEAR_BASE (1900)
+#define ALT_E 0x01
+#define ALT_O 0x02
+#define LEGAL_ALT(x) { if (alt_format & ~(x)) return (0); }
+#define TM_YEAR_BASE (1900)
-static int conv_num(const char**, int*, int, int);
+static int conv_num(const char * *, int *, int, int);
-static const char* day[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
+static const char *day[7] = {
+ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
+ "Friday", "Saturday"
+};
-static const char* abday[7] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
+static const char *abday[7] = {
+ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
+};
-static const char* mon[12] = {"January", "February", "March", "April", "May", "June",
- "July", "August", "September", "October", "November", "December"};
+static const char *mon[12] = {
+ "January", "February", "March", "April", "May", "June", "July",
+ "August", "September", "October", "November", "December"
+};
-static const char* abmon[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
+static const char *abmon[12] = {
+ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
+ "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
+};
-static const char* am_pm[2] = {"AM", "PM"};
+static const char *am_pm[2] = {
+ "AM", "PM"
+};
-static int arg_strcasecmp(const char* s1, const char* s2) {
- const unsigned char* us1 = (const unsigned char*)s1;
- const unsigned char* us2 = (const unsigned char*)s2;
+
+static int arg_strcasecmp(const char *s1, const char *s2) {
+ const unsigned char *us1 = (const unsigned char *)s1;
+ const unsigned char *us2 = (const unsigned char *)s2;
while (tolower(*us1) == tolower(*us2++))
if (*us1++ == '\0')
return 0;
@@ -2060,10 +1007,11 @@ static int arg_strcasecmp(const char* s1, const char* s2) {
return tolower(*us1) - tolower(*--us2);
}
-static int arg_strncasecmp(const char* s1, const char* s2, size_t n) {
+
+static int arg_strncasecmp(const char *s1, const char *s2, size_t n) {
if (n != 0) {
- const unsigned char* us1 = (const unsigned char*)s1;
- const unsigned char* us2 = (const unsigned char*)s2;
+ const unsigned char *us1 = (const unsigned char *)s1;
+ const unsigned char *us2 = (const unsigned char *)s2;
do {
if (tolower(*us1) != tolower(*us2++))
return tolower(*us1) - tolower(*--us2);
@@ -2076,9 +1024,10 @@ static int arg_strncasecmp(const char* s1, const char* s2, size_t n) {
return 0;
}
-char* arg_strptime(const char* buf, const char* fmt, struct tm* tm) {
+
+char *arg_strptime(const char *buf, const char *fmt, struct tm *tm) {
char c;
- const char* bp;
+ const char *bp;
size_t len = 0;
int alt_format, i, split_year = 0;
@@ -2089,8 +1038,8 @@ char* arg_strptime(const char* buf, const char* fmt, struct tm* tm) {
alt_format = 0;
/* Eat up white-space. */
- if (isspace(c)) {
- while (isspace(*bp))
+ if (ISSPACE(c)) {
+ while (ISSPACE(*bp))
bp++;
fmt++;
@@ -2100,10 +1049,11 @@ char* arg_strptime(const char* buf, const char* fmt, struct tm* tm) {
if ((c = *fmt++) != '%')
goto literal;
- again:
+
+again:
switch (c = *fmt++) {
case '%': /* "%%" is converted to "%". */
- literal:
+literal:
if (c != *bp++)
return (0);
break;
@@ -2362,20 +1312,24 @@ char* arg_strptime(const char* buf, const char* fmt, struct tm* tm) {
case 'n': /* Any kind of white-space. */
case 't':
LEGAL_ALT(0);
- while (isspace(*bp))
+ while (ISSPACE(*bp))
bp++;
break;
+
default: /* Unknown/unsupported conversion. */
return (0);
}
+
+
}
/* LINTED functional specification */
- return ((char*)bp);
+ return ((char *)bp);
}
-static int conv_num(const char** buf, int* dest, int llim, int ulim) {
+
+static int conv_num(const char * *buf, int *dest, int llim, int ulim) {
int result = 0;
/* The limit also determines the number of valid digits. */
@@ -2397,8 +1351,6 @@ static int conv_num(const char** buf, int* dest, int llim, int ulim) {
return (1);
}
/*******************************************************************************
- * arg_dbl: Implements the double command-line option
- *
* This file is part of the argtable3 library.
*
* Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
@@ -2428,25 +1380,23 @@ static int conv_num(const char** buf, int* dest, int llim, int ulim) {
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
-#include "argtable3.h"
-
-#ifndef ARG_AMALGAMATION
-#include "argtable3_private.h"
-#endif
-
#include
-static void arg_dbl_resetfn(struct arg_dbl* parent) {
+#include "argtable3.h"
+
+
+static void arg_dbl_resetfn(struct arg_dbl *parent) {
ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent));
parent->count = 0;
}
-static int arg_dbl_scanfn(struct arg_dbl* parent, const char* argval) {
+
+static int arg_dbl_scanfn(struct arg_dbl *parent, const char *argval) {
int errorcode = 0;
if (parent->count == parent->hdr.maxcount) {
/* maximum number of arguments exceeded */
- errorcode = ARG_ERR_MAXCOUNT;
+ errorcode = EMAXCOUNT;
} else if (!argval) {
/* a valid argument with no argument value was given. */
/* This happens when an optional argument value was invoked. */
@@ -2454,7 +1404,7 @@ static int arg_dbl_scanfn(struct arg_dbl* parent, const char* argval) {
parent->count++;
} else {
double val;
- char* end;
+ char *end;
/* extract double from argval into val */
val = strtod(argval, &end);
@@ -2463,101 +1413,125 @@ static int arg_dbl_scanfn(struct arg_dbl* parent, const char* argval) {
if (*end == 0)
parent->dval[parent->count++] = val;
else
- errorcode = ARG_ERR_BADDOUBLE;
+ errorcode = EBADDOUBLE;
}
ARG_TRACE(("%s:scanfn(%p) returns %d\n", __FILE__, parent, errorcode));
return errorcode;
}
-static int arg_dbl_checkfn(struct arg_dbl* parent) {
- int errorcode = (parent->count < parent->hdr.mincount) ? ARG_ERR_MINCOUNT : 0;
+
+static int arg_dbl_checkfn(struct arg_dbl *parent) {
+ int errorcode = (parent->count < parent->hdr.mincount) ? EMINCOUNT : 0;
ARG_TRACE(("%s:checkfn(%p) returns %d\n", __FILE__, parent, errorcode));
return errorcode;
}
-static void arg_dbl_errorfn(struct arg_dbl* parent, arg_dstr_t ds, int errorcode, const char* argval, const char* progname) {
- const char* shortopts = parent->hdr.shortopts;
- const char* longopts = parent->hdr.longopts;
- const char* datatype = parent->hdr.datatype;
+
+static void arg_dbl_errorfn(
+ struct arg_dbl *parent,
+ FILE *fp,
+ int errorcode,
+ const char *argval,
+ const char *progname) {
+ const char *shortopts = parent->hdr.shortopts;
+ const char *longopts = parent->hdr.longopts;
+ const char *datatype = parent->hdr.datatype;
/* make argval NULL safe */
argval = argval ? argval : "";
- arg_dstr_catf(ds, "%s: ", progname);
+ fprintf(fp, "%s: ", progname);
switch (errorcode) {
- case ARG_ERR_MINCOUNT:
- arg_dstr_cat(ds, "missing option ");
- arg_print_option_ds(ds, shortopts, longopts, datatype, "\n");
+ case EMINCOUNT:
+ fputs("missing option ", fp);
+ arg_print_option(fp, shortopts, longopts, datatype, "\n");
break;
- case ARG_ERR_MAXCOUNT:
- arg_dstr_cat(ds, "excess option ");
- arg_print_option_ds(ds, shortopts, longopts, argval, "\n");
+ case EMAXCOUNT:
+ fputs("excess option ", fp);
+ arg_print_option(fp, shortopts, longopts, argval, "\n");
break;
- case ARG_ERR_BADDOUBLE:
- arg_dstr_catf(ds, "invalid argument \"%s\" to option ", argval);
- arg_print_option_ds(ds, shortopts, longopts, datatype, "\n");
+ case EBADDOUBLE:
+ fprintf(fp, "invalid argument \"%s\" to option ", argval);
+ arg_print_option(fp, shortopts, longopts, datatype, "\n");
break;
}
}
-struct arg_dbl* arg_dbl0(const char* shortopts, const char* longopts, const char* datatype, const char* glossary) {
+
+struct arg_dbl *arg_dbl0(
+ const char *shortopts,
+ const char *longopts,
+ const char *datatype,
+ const char *glossary) {
return arg_dbln(shortopts, longopts, datatype, 0, 1, glossary);
}
-struct arg_dbl* arg_dbl1(const char* shortopts, const char* longopts, const char* datatype, const char* glossary) {
+
+struct arg_dbl *arg_dbl1(
+ const char *shortopts,
+ const char *longopts,
+ const char *datatype,
+ const char *glossary) {
return arg_dbln(shortopts, longopts, datatype, 1, 1, glossary);
}
-struct arg_dbl* arg_dbln(const char* shortopts, const char* longopts, const char* datatype, int mincount, int maxcount, const char* glossary) {
+
+struct arg_dbl *arg_dbln(
+ const char *shortopts,
+ const char *longopts,
+ const char *datatype,
+ int mincount,
+ int maxcount,
+ const char *glossary) {
size_t nbytes;
- struct arg_dbl* result;
- size_t addr;
- size_t rem;
+ struct arg_dbl *result;
/* foolproof things by ensuring maxcount is not less than mincount */
maxcount = (maxcount < mincount) ? mincount : maxcount;
- nbytes = sizeof(struct arg_dbl) /* storage for struct arg_dbl */
+ nbytes = sizeof(struct arg_dbl) /* storage for struct arg_dbl */
+ (maxcount + 1) * sizeof(double); /* storage for dval[maxcount] array plus one extra for padding to memory boundary */
- result = (struct arg_dbl*)xmalloc(nbytes);
+ result = (struct arg_dbl *)malloc(nbytes);
+ if (result) {
+ size_t addr;
+ size_t rem;
- /* init the arg_hdr struct */
- result->hdr.flag = ARG_HASVALUE;
- result->hdr.shortopts = shortopts;
- result->hdr.longopts = longopts;
- result->hdr.datatype = datatype ? datatype : "";
- result->hdr.glossary = glossary;
- result->hdr.mincount = mincount;
- result->hdr.maxcount = maxcount;
- result->hdr.parent = result;
- result->hdr.resetfn = (arg_resetfn*)arg_dbl_resetfn;
- result->hdr.scanfn = (arg_scanfn*)arg_dbl_scanfn;
- result->hdr.checkfn = (arg_checkfn*)arg_dbl_checkfn;
- result->hdr.errorfn = (arg_errorfn*)arg_dbl_errorfn;
+ /* init the arg_hdr struct */
+ result->hdr.flag = ARG_HASVALUE;
+ result->hdr.shortopts = shortopts;
+ result->hdr.longopts = longopts;
+ result->hdr.datatype = datatype ? datatype : "";
+ result->hdr.glossary = glossary;
+ result->hdr.mincount = mincount;
+ result->hdr.maxcount = maxcount;
+ result->hdr.parent = result;
+ result->hdr.resetfn = (arg_resetfn *)arg_dbl_resetfn;
+ result->hdr.scanfn = (arg_scanfn *)arg_dbl_scanfn;
+ result->hdr.checkfn = (arg_checkfn *)arg_dbl_checkfn;
+ result->hdr.errorfn = (arg_errorfn *)arg_dbl_errorfn;
- /* Store the dval[maxcount] array on the first double boundary that
- * immediately follows the arg_dbl struct. We do the memory alignment
- * purely for SPARC and Motorola systems. They require floats and
- * doubles to be aligned on natural boundaries.
- */
- addr = (size_t)(result + 1);
- rem = addr % sizeof(double);
- result->dval = (double*)(addr + sizeof(double) - rem);
- ARG_TRACE(("addr=%p, dval=%p, sizeof(double)=%d rem=%d\n", addr, result->dval, (int)sizeof(double), (int)rem));
+ /* Store the dval[maxcount] array on the first double boundary that
+ * immediately follows the arg_dbl struct. We do the memory alignment
+ * purely for SPARC and Motorola systems. They require floats and
+ * doubles to be aligned on natural boundaries.
+ */
+ addr = (size_t)(result + 1);
+ rem = addr % sizeof(double);
+ result->dval = (double *)(addr + sizeof(double) - rem);
+ ARG_TRACE(("addr=%zu, dval=%p, sizeof(double)=%d rem=%d\n", addr, result->dval, (int)sizeof(double), (int)rem));
- result->count = 0;
+ result->count = 0;
+ }
ARG_TRACE(("arg_dbln() returns %p\n", result));
return result;
}
/*******************************************************************************
- * arg_end: Implements the error handling utilities
- *
* This file is part of the argtable3 library.
*
* Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
@@ -2587,107 +1561,108 @@ struct arg_dbl* arg_dbln(const char* shortopts, const char* longopts, const char
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
-#include "argtable3.h"
-
-#ifndef ARG_AMALGAMATION
-#include "argtable3_private.h"
-#endif
-
#include
-static void arg_end_resetfn(struct arg_end* parent) {
+#include "argtable3.h"
+
+
+static void arg_end_resetfn(struct arg_end *parent) {
ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent));
parent->count = 0;
}
-static void arg_end_errorfn(void* parent, arg_dstr_t ds, int error, const char* argval, const char* progname) {
+static void arg_end_errorfn(
+ void *parent,
+ FILE *fp,
+ int error,
+ const char *argval,
+ const char *progname) {
/* suppress unreferenced formal parameter warning */
(void)parent;
progname = progname ? progname : "";
argval = argval ? argval : "";
- arg_dstr_catf(ds, "%s: ", progname);
+ fprintf(fp, "%s: ", progname);
switch (error) {
case ARG_ELIMIT:
- arg_dstr_cat(ds, "too many errors to display");
+ fputs("too many errors to display", fp);
break;
case ARG_EMALLOC:
- arg_dstr_cat(ds, "insufficient memory");
+ fputs("insufficent memory", fp);
break;
case ARG_ENOMATCH:
- arg_dstr_catf(ds, "unexpected argument \"%s\"", argval);
+ fprintf(fp, "unexpected argument \"%s\"", argval);
break;
case ARG_EMISSARG:
- arg_dstr_catf(ds, "option \"%s\" requires an argument", argval);
+ fprintf(fp, "option \"%s\" requires an argument", argval);
break;
case ARG_ELONGOPT:
- arg_dstr_catf(ds, "invalid option \"%s\"", argval);
+ fprintf(fp, "invalid option \"%s\"", argval);
break;
default:
- arg_dstr_catf(ds, "invalid option \"-%c\"", error);
+ fprintf(fp, "invalid option \"-%c\"", error);
break;
}
- arg_dstr_cat(ds, "\n");
+ fputc('\n', fp);
}
-struct arg_end* arg_end(int maxcount) {
+
+struct arg_end *arg_end(int maxcount) {
size_t nbytes;
- struct arg_end* result;
+ struct arg_end *result;
- nbytes = sizeof(struct arg_end) + maxcount * sizeof(int) /* storage for int error[maxcount] array*/
- + maxcount * sizeof(void*) /* storage for void* parent[maxcount] array */
- + maxcount * sizeof(char*); /* storage for char* argval[maxcount] array */
+ nbytes = sizeof(struct arg_end)
+ + maxcount * sizeof(int) /* storage for int error[maxcount] array*/
+ + maxcount * sizeof(void *) /* storage for void* parent[maxcount] array */
+ + maxcount * sizeof(char *); /* storage for char* argval[maxcount] array */
- result = (struct arg_end*)xmalloc(nbytes);
+ result = (struct arg_end *)malloc(nbytes);
+ if (result) {
+ /* init the arg_hdr struct */
+ result->hdr.flag = ARG_TERMINATOR;
+ result->hdr.shortopts = NULL;
+ result->hdr.longopts = NULL;
+ result->hdr.datatype = NULL;
+ result->hdr.glossary = NULL;
+ result->hdr.mincount = 1;
+ result->hdr.maxcount = maxcount;
+ result->hdr.parent = result;
+ result->hdr.resetfn = (arg_resetfn *)arg_end_resetfn;
+ result->hdr.scanfn = NULL;
+ result->hdr.checkfn = NULL;
+ result->hdr.errorfn = (arg_errorfn *)arg_end_errorfn;
- /* init the arg_hdr struct */
- result->hdr.flag = ARG_TERMINATOR;
- result->hdr.shortopts = NULL;
- result->hdr.longopts = NULL;
- result->hdr.datatype = NULL;
- result->hdr.glossary = NULL;
- result->hdr.mincount = 1;
- result->hdr.maxcount = maxcount;
- result->hdr.parent = result;
- result->hdr.resetfn = (arg_resetfn*)arg_end_resetfn;
- result->hdr.scanfn = NULL;
- result->hdr.checkfn = NULL;
- result->hdr.errorfn = (arg_errorfn*)arg_end_errorfn;
+ /* store error[maxcount] array immediately after struct arg_end */
+ result->error = (int *)(result + 1);
- /* store error[maxcount] array immediately after struct arg_end */
- result->error = (int*)(result + 1);
+ /* store parent[maxcount] array immediately after error[] array */
+ result->parent = (void * *)(result->error + maxcount);
- /* store parent[maxcount] array immediately after error[] array */
- result->parent = (void**)(result->error + maxcount);
-
- /* store argval[maxcount] array immediately after parent[] array */
- result->argval = (const char**)(result->parent + maxcount);
+ /* store argval[maxcount] array immediately after parent[] array */
+ result->argval = (const char * *)(result->parent + maxcount);
+ }
ARG_TRACE(("arg_end(%d) returns %p\n", maxcount, result));
return result;
}
-void arg_print_errors_ds(arg_dstr_t ds, struct arg_end* end, const char* progname) {
+
+void arg_print_errors(FILE *fp, struct arg_end *end, const char *progname) {
int i;
ARG_TRACE(("arg_errors()\n"));
for (i = 0; i < end->count; i++) {
- struct arg_hdr* errorparent = (struct arg_hdr*)(end->parent[i]);
+ struct arg_hdr *errorparent = (struct arg_hdr *)(end->parent[i]);
if (errorparent->errorfn)
- errorparent->errorfn(end->parent[i], ds, end->error[i], end->argval[i], progname);
+ errorparent->errorfn(end->parent[i],
+ fp,
+ end->error[i],
+ end->argval[i],
+ progname);
}
}
-
-void arg_print_errors(FILE* fp, struct arg_end* end, const char* progname) {
- arg_dstr_t ds = arg_dstr_create();
- arg_print_errors_ds(ds, end, progname);
- fputs(arg_dstr_cstr(ds), fp);
- arg_dstr_destroy(ds);
-}
/*******************************************************************************
- * arg_file: Implements the file command-line option
- *
* This file is part of the argtable3 library.
*
* Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
@@ -2717,30 +1692,28 @@ void arg_print_errors(FILE* fp, struct arg_end* end, const char* progname) {
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
+#include
+#include
+
#include "argtable3.h"
-#ifndef ARG_AMALGAMATION
-#include "argtable3_private.h"
-#endif
-
-#include
-#include
-
#ifdef WIN32
-#define FILESEPARATOR1 '\\'
-#define FILESEPARATOR2 '/'
+# define FILESEPARATOR1 '\\'
+# define FILESEPARATOR2 '/'
#else
-#define FILESEPARATOR1 '/'
-#define FILESEPARATOR2 '/'
+# define FILESEPARATOR1 '/'
+# define FILESEPARATOR2 '/'
#endif
-static void arg_file_resetfn(struct arg_file* parent) {
+
+static void arg_file_resetfn(struct arg_file *parent) {
ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent));
parent->count = 0;
}
+
/* Returns ptr to the base filename within *filename */
-static const char* arg_basename(const char* filename) {
+static const char *arg_basename(const char *filename) {
const char *result = NULL, *result1, *result2;
/* Find the last occurrence of eother file separator character. */
@@ -2750,13 +1723,13 @@ static const char* arg_basename(const char* filename) {
result2 = (filename ? strrchr(filename, FILESEPARATOR2) : NULL);
if (result2)
- result = result2 + 1; /* using FILESEPARATOR2 (the alternative file separator) */
+ result = result2 + 1; /* using FILESEPARATOR2 (the alternative file separator) */
if (result1)
- result = result1 + 1; /* using FILESEPARATOR1 (the preferred file separator) */
+ result = result1 + 1; /* using FILESEPARATOR1 (the preferred file separator) */
if (!result)
- result = filename; /* neither file separator was found so basename is the whole filename */
+ result = filename; /* neither file separator was found so basename is the whole filename */
/* special cases of "." and ".." are not considered basenames */
if (result && (strcmp(".", result) == 0 || strcmp("..", result) == 0))
@@ -2765,10 +1738,11 @@ static const char* arg_basename(const char* filename) {
return result;
}
+
/* Returns ptr to the file extension within *basename */
-static const char* arg_extension(const char* basename) {
+static const char *arg_extension(const char *basename) {
/* find the last occurrence of '.' in basename */
- const char* result = (basename ? strrchr(basename, '.') : NULL);
+ const char *result = (basename ? strrchr(basename, '.') : NULL);
/* if no '.' was found then return pointer to end of basename */
if (basename && !result)
@@ -2785,22 +1759,23 @@ static const char* arg_extension(const char* basename) {
return result;
}
-static int arg_file_scanfn(struct arg_file* parent, const char* argval) {
+
+static int arg_file_scanfn(struct arg_file *parent, const char *argval) {
int errorcode = 0;
if (parent->count == parent->hdr.maxcount) {
/* maximum number of arguments exceeded */
- errorcode = ARG_ERR_MAXCOUNT;
+ errorcode = EMAXCOUNT;
} else if (!argval) {
/* a valid argument with no argument value was given. */
/* This happens when an optional argument value was invoked. */
/* leave parent arguiment value unaltered but still count the argument. */
parent->count++;
} else {
- parent->filename[parent->count] = argval;
- parent->basename[parent->count] = arg_basename(argval);
+ parent->filename[parent->count] = argval;
+ parent->basename[parent->count] = arg_basename(argval);
parent->extension[parent->count] =
- arg_extension(parent->basename[parent->count]); /* only seek extensions within the basename (not the file path)*/
+ arg_extension(parent->basename[parent->count]); /* only seek extensions within the basename (not the file path)*/
parent->count++;
}
@@ -2808,94 +1783,118 @@ static int arg_file_scanfn(struct arg_file* parent, const char* argval) {
return errorcode;
}
-static int arg_file_checkfn(struct arg_file* parent) {
- int errorcode = (parent->count < parent->hdr.mincount) ? ARG_ERR_MINCOUNT : 0;
+
+static int arg_file_checkfn(struct arg_file *parent) {
+ int errorcode = (parent->count < parent->hdr.mincount) ? EMINCOUNT : 0;
ARG_TRACE(("%s:checkfn(%p) returns %d\n", __FILE__, parent, errorcode));
return errorcode;
}
-static void arg_file_errorfn(struct arg_file* parent, arg_dstr_t ds, int errorcode, const char* argval, const char* progname) {
- const char* shortopts = parent->hdr.shortopts;
- const char* longopts = parent->hdr.longopts;
- const char* datatype = parent->hdr.datatype;
+
+static void arg_file_errorfn(
+ struct arg_file *parent,
+ FILE *fp,
+ int errorcode,
+ const char *argval,
+ const char *progname) {
+ const char *shortopts = parent->hdr.shortopts;
+ const char *longopts = parent->hdr.longopts;
+ const char *datatype = parent->hdr.datatype;
/* make argval NULL safe */
argval = argval ? argval : "";
- arg_dstr_catf(ds, "%s: ", progname);
+ fprintf(fp, "%s: ", progname);
switch (errorcode) {
- case ARG_ERR_MINCOUNT:
- arg_dstr_cat(ds, "missing option ");
- arg_print_option_ds(ds, shortopts, longopts, datatype, "\n");
+ case EMINCOUNT:
+ fputs("missing option ", fp);
+ arg_print_option(fp, shortopts, longopts, datatype, "\n");
break;
- case ARG_ERR_MAXCOUNT:
- arg_dstr_cat(ds, "excess option ");
- arg_print_option_ds(ds, shortopts, longopts, argval, "\n");
+ case EMAXCOUNT:
+ fputs("excess option ", fp);
+ arg_print_option(fp, shortopts, longopts, argval, "\n");
break;
default:
- arg_dstr_catf(ds, "unknown error at \"%s\"\n", argval);
+ fprintf(fp, "unknown error at \"%s\"\n", argval);
}
}
-struct arg_file* arg_file0(const char* shortopts, const char* longopts, const char* datatype, const char* glossary) {
+
+struct arg_file *arg_file0(
+ const char *shortopts,
+ const char *longopts,
+ const char *datatype,
+ const char *glossary) {
return arg_filen(shortopts, longopts, datatype, 0, 1, glossary);
}
-struct arg_file* arg_file1(const char* shortopts, const char* longopts, const char* datatype, const char* glossary) {
+
+struct arg_file *arg_file1(
+ const char *shortopts,
+ const char *longopts,
+ const char *datatype,
+ const char *glossary) {
return arg_filen(shortopts, longopts, datatype, 1, 1, glossary);
}
-struct arg_file* arg_filen(const char* shortopts, const char* longopts, const char* datatype, int mincount, int maxcount, const char* glossary) {
+
+struct arg_file *arg_filen(
+ const char *shortopts,
+ const char *longopts,
+ const char *datatype,
+ int mincount,
+ int maxcount,
+ const char *glossary) {
size_t nbytes;
- struct arg_file* result;
- int i;
+ struct arg_file *result;
/* foolproof things by ensuring maxcount is not less than mincount */
maxcount = (maxcount < mincount) ? mincount : maxcount;
- nbytes = sizeof(struct arg_file) /* storage for struct arg_file */
- + sizeof(char*) * maxcount /* storage for filename[maxcount] array */
- + sizeof(char*) * maxcount /* storage for basename[maxcount] array */
- + sizeof(char*) * maxcount; /* storage for extension[maxcount] array */
+ nbytes = sizeof(struct arg_file) /* storage for struct arg_file */
+ + sizeof(char *) * maxcount /* storage for filename[maxcount] array */
+ + sizeof(char *) * maxcount /* storage for basename[maxcount] array */
+ + sizeof(char *) * maxcount; /* storage for extension[maxcount] array */
- result = (struct arg_file*)xmalloc(nbytes);
+ result = (struct arg_file *)malloc(nbytes);
+ if (result) {
+ int i;
- /* init the arg_hdr struct */
- result->hdr.flag = ARG_HASVALUE;
- result->hdr.shortopts = shortopts;
- result->hdr.longopts = longopts;
- result->hdr.glossary = glossary;
- result->hdr.datatype = datatype ? datatype : "";
- result->hdr.mincount = mincount;
- result->hdr.maxcount = maxcount;
- result->hdr.parent = result;
- result->hdr.resetfn = (arg_resetfn*)arg_file_resetfn;
- result->hdr.scanfn = (arg_scanfn*)arg_file_scanfn;
- result->hdr.checkfn = (arg_checkfn*)arg_file_checkfn;
- result->hdr.errorfn = (arg_errorfn*)arg_file_errorfn;
+ /* init the arg_hdr struct */
+ result->hdr.flag = ARG_HASVALUE;
+ result->hdr.shortopts = shortopts;
+ result->hdr.longopts = longopts;
+ result->hdr.glossary = glossary;
+ result->hdr.datatype = datatype ? datatype : "";
+ result->hdr.mincount = mincount;
+ result->hdr.maxcount = maxcount;
+ result->hdr.parent = result;
+ result->hdr.resetfn = (arg_resetfn *)arg_file_resetfn;
+ result->hdr.scanfn = (arg_scanfn *)arg_file_scanfn;
+ result->hdr.checkfn = (arg_checkfn *)arg_file_checkfn;
+ result->hdr.errorfn = (arg_errorfn *)arg_file_errorfn;
- /* store the filename,basename,extension arrays immediately after the arg_file struct */
- result->filename = (const char**)(result + 1);
- result->basename = result->filename + maxcount;
- result->extension = result->basename + maxcount;
- result->count = 0;
+ /* store the filename,basename,extension arrays immediately after the arg_file struct */
+ result->filename = (const char * *)(result + 1);
+ result->basename = result->filename + maxcount;
+ result->extension = result->basename + maxcount;
+ result->count = 0;
- /* foolproof the string pointers by initialising them with empty strings */
- for (i = 0; i < maxcount; i++) {
- result->filename[i] = "";
- result->basename[i] = "";
- result->extension[i] = "";
+ /* foolproof the string pointers by initialising them with empty strings */
+ for (i = 0; i < maxcount; i++) {
+ result->filename[i] = "";
+ result->basename[i] = "";
+ result->extension[i] = "";
+ }
}
ARG_TRACE(("arg_filen() returns %p\n", result));
return result;
}
/*******************************************************************************
- * arg_int: Implements the int command-line option
- *
* This file is part of the argtable3 library.
*
* Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
@@ -2925,21 +1924,19 @@ struct arg_file* arg_filen(const char* shortopts, const char* longopts, const ch
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
+#include
+#include
+#include
+
#include "argtable3.h"
-#ifndef ARG_AMALGAMATION
-#include "argtable3_private.h"
-#endif
-#include
-#include
-#include
-
-static void arg_int_resetfn(struct arg_int* parent) {
+static void arg_int_resetfn(struct arg_int *parent) {
ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent));
parent->count = 0;
}
+
/* strtol0x() is like strtol() except that the numeric string is */
/* expected to be prefixed by "0X" where X is a user supplied char. */
/* The string may optionally be prefixed by white space and + or - */
@@ -2950,13 +1947,16 @@ static void arg_int_resetfn(struct arg_int* parent) {
/* eg: to parse oct str="+0o12324", specify X='O' and base=8. */
/* eg: to parse bin str="-0B01010", specify X='B' and base=2. */
/* Failure of conversion is indicated by result where *endptr==str. */
-static long int strtol0X(const char* str, const char** endptr, char X, int base) {
- long int val; /* stores result */
- int s = 1; /* sign is +1 or -1 */
- const char* ptr = str; /* ptr to current position in str */
+static long int strtol0X(const char *str,
+ const char * *endptr,
+ char X,
+ int base) {
+ long int val; /* stores result */
+ int s = 1; /* sign is +1 or -1 */
+ const char *ptr = str; /* ptr to current position in str */
/* skip leading whitespace */
- while (isspace(*ptr))
+ while (ISSPACE(*ptr))
ptr++;
/* printf("1) %s\n",ptr); */
@@ -2991,7 +1991,7 @@ static long int strtol0X(const char* str, const char** endptr, char X, int base)
/* printf("4) %s\n",ptr); */
/* attempt conversion on remainder of string using strtol() */
- val = strtol(ptr, (char**)endptr, base);
+ val = strtol(ptr, (char * *)endptr, base);
if (*endptr == ptr) {
/* conversion failed */
*endptr = str;
@@ -3002,9 +2002,10 @@ static long int strtol0X(const char* str, const char** endptr, char X, int base)
return s * val;
}
+
/* Returns 1 if str matches suffix (case insensitive). */
/* Str may contain trailing whitespace, but nothing else. */
-static int detectsuffix(const char* str, const char* suffix) {
+static int detectsuffix(const char *str, const char *suffix) {
/* scan pairwise through strings until mismatch detected */
while (toupper(*str) == toupper(*suffix)) {
/* printf("'%c' '%c'\n", *str, *suffix); */
@@ -3021,22 +2022,23 @@ static int detectsuffix(const char* str, const char* suffix) {
/* return 0 (fail) if the matching did not consume the entire suffix */
if (*suffix != 0)
- return 0; /* failed to consume entire suffix */
+ return 0; /* failed to consume entire suffix */
/* skip any remaining whitespace in str */
- while (isspace(*str))
+ while (ISSPACE(*str))
str++;
/* return 1 (success) if we have reached end of str else return 0 (fail) */
return (*str == '\0') ? 1 : 0;
}
-static int arg_int_scanfn(struct arg_int* parent, const char* argval) {
+
+static int arg_int_scanfn(struct arg_int *parent, const char *argval) {
int errorcode = 0;
if (parent->count == parent->hdr.maxcount) {
/* maximum number of arguments exceeded */
- errorcode = ARG_ERR_MAXCOUNT;
+ errorcode = EMAXCOUNT;
} else if (!argval) {
/* a valid argument with no argument value was given. */
/* This happens when an optional argument value was invoked. */
@@ -3044,7 +2046,7 @@ static int arg_int_scanfn(struct arg_int* parent, const char* argval) {
parent->count++;
} else {
long int val;
- const char* end;
+ const char *end;
/* attempt to extract hex integer (eg: +0x123) from argval into val conversion */
val = strtol0X(argval, &end, 'X', 16);
@@ -3056,10 +2058,10 @@ static int arg_int_scanfn(struct arg_int* parent, const char* argval) {
val = strtol0X(argval, &end, 'B', 2);
if (end == argval) {
/* binary failed, attempt decimal conversion with no prefix (eg 1234) */
- val = strtol(argval, (char**)&end, 10);
+ val = strtol(argval, (char * *)&end, 10);
if (end == argval) {
/* all supported number formats failed */
- return ARG_ERR_BADINT;
+ return EBADINT;
}
}
}
@@ -3068,90 +2070,131 @@ static int arg_int_scanfn(struct arg_int* parent, const char* argval) {
/* Safety check for integer overflow. WARNING: this check */
/* achieves nothing on machines where size(int)==size(long). */
if (val > INT_MAX || val < INT_MIN)
- errorcode = ARG_ERR_OVERFLOW;
+#ifdef __STDC_WANT_SECURE_LIB__
+ errorcode = EOVERFLOW_;
+#else
+ errorcode = EOVERFLOW;
+#endif
/* Detect any suffixes (KB,MB,GB) and multiply argument value appropriately. */
/* We need to be mindful of integer overflows when using such big numbers. */
- if (detectsuffix(end, "KB")) /* kilobytes */
- {
+ if (detectsuffix(end, "KB")) { /* kilobytes */
if (val > (INT_MAX / 1024) || val < (INT_MIN / 1024))
- errorcode = ARG_ERR_OVERFLOW; /* Overflow would occur if we proceed */
+#ifdef __STDC_WANT_SECURE_LIB__
+ errorcode = EOVERFLOW_; /* Overflow would occur if we proceed */
+#else
+ errorcode = EOVERFLOW; /* Overflow would occur if we proceed */
+#endif
else
- val *= 1024; /* 1KB = 1024 */
- } else if (detectsuffix(end, "MB")) /* megabytes */
- {
+ val *= 1024; /* 1KB = 1024 */
+ } else if (detectsuffix(end, "MB")) { /* megabytes */
if (val > (INT_MAX / 1048576) || val < (INT_MIN / 1048576))
- errorcode = ARG_ERR_OVERFLOW; /* Overflow would occur if we proceed */
+#ifdef __STDC_WANT_SECURE_LIB__
+ errorcode = EOVERFLOW_; /* Overflow would occur if we proceed */
+#else
+ errorcode = EOVERFLOW; /* Overflow would occur if we proceed */
+#endif
else
- val *= 1048576; /* 1MB = 1024*1024 */
- } else if (detectsuffix(end, "GB")) /* gigabytes */
- {
+ val *= 1048576; /* 1MB = 1024*1024 */
+ } else if (detectsuffix(end, "GB")) { /* gigabytes */
if (val > (INT_MAX / 1073741824) || val < (INT_MIN / 1073741824))
- errorcode = ARG_ERR_OVERFLOW; /* Overflow would occur if we proceed */
+#ifdef __STDC_WANT_SECURE_LIB__
+ errorcode = EOVERFLOW_; /* Overflow would occur if we proceed */
+#else
+ errorcode = EOVERFLOW; /* Overflow would occur if we proceed */
+#endif
else
- val *= 1073741824; /* 1GB = 1024*1024*1024 */
+ val *= 1073741824; /* 1GB = 1024*1024*1024 */
} else if (!detectsuffix(end, ""))
- errorcode = ARG_ERR_BADINT; /* invalid suffix detected */
+ errorcode = EBADINT; /* invalid suffix detected */
/* if success then store result in parent->ival[] array */
if (errorcode == 0)
- parent->ival[parent->count++] = (int)val;
+ parent->ival[parent->count++] = val;
}
/* printf("%s:scanfn(%p,%p) returns %d\n",__FILE__,parent,argval,errorcode); */
return errorcode;
}
-static int arg_int_checkfn(struct arg_int* parent) {
- int errorcode = (parent->count < parent->hdr.mincount) ? ARG_ERR_MINCOUNT : 0;
+
+static int arg_int_checkfn(struct arg_int *parent) {
+ int errorcode = (parent->count < parent->hdr.mincount) ? EMINCOUNT : 0;
/*printf("%s:checkfn(%p) returns %d\n",__FILE__,parent,errorcode);*/
return errorcode;
}
-static void arg_int_errorfn(struct arg_int* parent, arg_dstr_t ds, int errorcode, const char* argval, const char* progname) {
- const char* shortopts = parent->hdr.shortopts;
- const char* longopts = parent->hdr.longopts;
- const char* datatype = parent->hdr.datatype;
+
+static void arg_int_errorfn(
+ struct arg_int *parent,
+ FILE *fp,
+ int errorcode,
+ const char *argval,
+ const char *progname) {
+ const char *shortopts = parent->hdr.shortopts;
+ const char *longopts = parent->hdr.longopts;
+ const char *datatype = parent->hdr.datatype;
/* make argval NULL safe */
argval = argval ? argval : "";
- arg_dstr_catf(ds, "%s: ", progname);
+ fprintf(fp, "%s: ", progname);
switch (errorcode) {
- case ARG_ERR_MINCOUNT:
- arg_dstr_cat(ds, "missing option ");
- arg_print_option_ds(ds, shortopts, longopts, datatype, "\n");
+ case EMINCOUNT:
+ fputs("missing option ", fp);
+ arg_print_option(fp, shortopts, longopts, datatype, "\n");
break;
- case ARG_ERR_MAXCOUNT:
- arg_dstr_cat(ds, "excess option ");
- arg_print_option_ds(ds, shortopts, longopts, argval, "\n");
+ case EMAXCOUNT:
+ fputs("excess option ", fp);
+ arg_print_option(fp, shortopts, longopts, argval, "\n");
break;
- case ARG_ERR_BADINT:
- arg_dstr_catf(ds, "invalid argument \"%s\" to option ", argval);
- arg_print_option_ds(ds, shortopts, longopts, datatype, "\n");
+ case EBADINT:
+ fprintf(fp, "invalid argument \"%s\" to option ", argval);
+ arg_print_option(fp, shortopts, longopts, datatype, "\n");
break;
- case ARG_ERR_OVERFLOW:
- arg_dstr_cat(ds, "integer overflow at option ");
- arg_print_option_ds(ds, shortopts, longopts, datatype, " ");
- arg_dstr_catf(ds, "(%s is too large)\n", argval);
+#ifdef __STDC_WANT_SECURE_LIB__
+ case EOVERFLOW_:
+#else
+ case EOVERFLOW:
+#endif
+ fputs("integer overflow at option ", fp);
+ arg_print_option(fp, shortopts, longopts, datatype, " ");
+ fprintf(fp, "(%s is too large)\n", argval);
break;
}
}
-struct arg_int* arg_int0(const char* shortopts, const char* longopts, const char* datatype, const char* glossary) {
+
+struct arg_int *arg_int0(
+ const char *shortopts,
+ const char *longopts,
+ const char *datatype,
+ const char *glossary) {
return arg_intn(shortopts, longopts, datatype, 0, 1, glossary);
}
-struct arg_int* arg_int1(const char* shortopts, const char* longopts, const char* datatype, const char* glossary) {
+
+struct arg_int *arg_int1(
+ const char *shortopts,
+ const char *longopts,
+ const char *datatype,
+ const char *glossary) {
return arg_intn(shortopts, longopts, datatype, 1, 1, glossary);
}
-struct arg_int* arg_intn(const char* shortopts, const char* longopts, const char* datatype, int mincount, int maxcount, const char* glossary) {
+
+struct arg_int *arg_intn(
+ const char *shortopts,
+ const char *longopts,
+ const char *datatype,
+ int mincount,
+ int maxcount,
+ const char *glossary) {
size_t nbytes;
- struct arg_int* result;
+ struct arg_int *result;
/* foolproof things by ensuring maxcount is not less than mincount */
maxcount = (maxcount < mincount) ? mincount : maxcount;
@@ -3159,32 +2202,31 @@ struct arg_int* arg_intn(const char* shortopts, const char* longopts, const char
nbytes = sizeof(struct arg_int) /* storage for struct arg_int */
+ maxcount * sizeof(int); /* storage for ival[maxcount] array */
- result = (struct arg_int*)xmalloc(nbytes);
+ result = (struct arg_int *)malloc(nbytes);
+ if (result) {
+ /* init the arg_hdr struct */
+ result->hdr.flag = ARG_HASVALUE;
+ result->hdr.shortopts = shortopts;
+ result->hdr.longopts = longopts;
+ result->hdr.datatype = datatype ? datatype : "";
+ result->hdr.glossary = glossary;
+ result->hdr.mincount = mincount;
+ result->hdr.maxcount = maxcount;
+ result->hdr.parent = result;
+ result->hdr.resetfn = (arg_resetfn *)arg_int_resetfn;
+ result->hdr.scanfn = (arg_scanfn *)arg_int_scanfn;
+ result->hdr.checkfn = (arg_checkfn *)arg_int_checkfn;
+ result->hdr.errorfn = (arg_errorfn *)arg_int_errorfn;
- /* init the arg_hdr struct */
- result->hdr.flag = ARG_HASVALUE;
- result->hdr.shortopts = shortopts;
- result->hdr.longopts = longopts;
- result->hdr.datatype = datatype ? datatype : "";
- result->hdr.glossary = glossary;
- result->hdr.mincount = mincount;
- result->hdr.maxcount = maxcount;
- result->hdr.parent = result;
- result->hdr.resetfn = (arg_resetfn*)arg_int_resetfn;
- result->hdr.scanfn = (arg_scanfn*)arg_int_scanfn;
- result->hdr.checkfn = (arg_checkfn*)arg_int_checkfn;
- result->hdr.errorfn = (arg_errorfn*)arg_int_errorfn;
-
- /* store the ival[maxcount] array immediately after the arg_int struct */
- result->ival = (int*)(result + 1);
- result->count = 0;
+ /* store the ival[maxcount] array immediately after the arg_int struct */
+ result->ival = (int *)(result + 1);
+ result->count = 0;
+ }
ARG_TRACE(("arg_intn() returns %p\n", result));
return result;
}
/*******************************************************************************
- * arg_lit: Implements the literature command-line option
- *
* This file is part of the argtable3 library.
*
* Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
@@ -3214,96 +2256,116 @@ struct arg_int* arg_intn(const char* shortopts, const char* longopts, const char
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
-#include "argtable3.h"
-
-#ifndef ARG_AMALGAMATION
-#include "argtable3_private.h"
-#endif
-
#include
-static void arg_lit_resetfn(struct arg_lit* parent) {
+#include "argtable3.h"
+
+
+static void arg_lit_resetfn(struct arg_lit *parent) {
ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent));
parent->count = 0;
}
-static int arg_lit_scanfn(struct arg_lit* parent, const char* argval) {
+
+static int arg_lit_scanfn(struct arg_lit *parent, const char *argval) {
int errorcode = 0;
if (parent->count < parent->hdr.maxcount)
parent->count++;
else
- errorcode = ARG_ERR_MAXCOUNT;
+ errorcode = EMAXCOUNT;
- ARG_TRACE(("%s:scanfn(%p,%s) returns %d\n", __FILE__, parent, argval, errorcode));
+ ARG_TRACE(("%s:scanfn(%p,%s) returns %d\n", __FILE__, parent, argval,
+ errorcode));
return errorcode;
}
-static int arg_lit_checkfn(struct arg_lit* parent) {
- int errorcode = (parent->count < parent->hdr.mincount) ? ARG_ERR_MINCOUNT : 0;
+
+static int arg_lit_checkfn(struct arg_lit *parent) {
+ int errorcode = (parent->count < parent->hdr.mincount) ? EMINCOUNT : 0;
ARG_TRACE(("%s:checkfn(%p) returns %d\n", __FILE__, parent, errorcode));
return errorcode;
}
-static void arg_lit_errorfn(struct arg_lit* parent, arg_dstr_t ds, int errorcode, const char* argval, const char* progname) {
- const char* shortopts = parent->hdr.shortopts;
- const char* longopts = parent->hdr.longopts;
- const char* datatype = parent->hdr.datatype;
+
+static void arg_lit_errorfn(
+ struct arg_lit *parent,
+ FILE *fp,
+ int errorcode,
+ const char *argval,
+ const char *progname) {
+ const char *shortopts = parent->hdr.shortopts;
+ const char *longopts = parent->hdr.longopts;
+ const char *datatype = parent->hdr.datatype;
switch (errorcode) {
- case ARG_ERR_MINCOUNT:
- arg_dstr_catf(ds, "%s: missing option ", progname);
- arg_print_option_ds(ds, shortopts, longopts, datatype, "\n");
- arg_dstr_cat(ds, "\n");
+ case EMINCOUNT:
+ fprintf(fp, "%s: missing option ", progname);
+ arg_print_option(fp, shortopts, longopts, datatype, "\n");
+ fprintf(fp, "\n");
break;
- case ARG_ERR_MAXCOUNT:
- arg_dstr_catf(ds, "%s: extraneous option ", progname);
- arg_print_option_ds(ds, shortopts, longopts, datatype, "\n");
+ case EMAXCOUNT:
+ fprintf(fp, "%s: extraneous option ", progname);
+ arg_print_option(fp, shortopts, longopts, datatype, "\n");
break;
}
- ARG_TRACE(("%s:errorfn(%p, %p, %d, %s, %s)\n", __FILE__, parent, ds, errorcode, argval, progname));
+ ARG_TRACE(("%s:errorfn(%p, %p, %d, %s, %s)\n", __FILE__, parent, fp,
+ errorcode, argval, progname));
}
-struct arg_lit* arg_lit0(const char* shortopts, const char* longopts, const char* glossary) {
+
+struct arg_lit *arg_lit0(
+ const char *shortopts,
+ const char *longopts,
+ const char *glossary) {
return arg_litn(shortopts, longopts, 0, 1, glossary);
}
-struct arg_lit* arg_lit1(const char* shortopts, const char* longopts, const char* glossary) {
+
+struct arg_lit *arg_lit1(
+ const char *shortopts,
+ const char *longopts,
+ const char *glossary) {
return arg_litn(shortopts, longopts, 1, 1, glossary);
}
-struct arg_lit* arg_litn(const char* shortopts, const char* longopts, int mincount, int maxcount, const char* glossary) {
- struct arg_lit* result;
+
+struct arg_lit *arg_litn(
+ const char *shortopts,
+ const char *longopts,
+ int mincount,
+ int maxcount,
+ const char *glossary) {
+ struct arg_lit *result;
/* foolproof things by ensuring maxcount is not less than mincount */
maxcount = (maxcount < mincount) ? mincount : maxcount;
- result = (struct arg_lit*)xmalloc(sizeof(struct arg_lit));
+ result = (struct arg_lit *)malloc(sizeof(struct arg_lit));
+ if (result) {
+ /* init the arg_hdr struct */
+ result->hdr.flag = 0;
+ result->hdr.shortopts = shortopts;
+ result->hdr.longopts = longopts;
+ result->hdr.datatype = NULL;
+ result->hdr.glossary = glossary;
+ result->hdr.mincount = mincount;
+ result->hdr.maxcount = maxcount;
+ result->hdr.parent = result;
+ result->hdr.resetfn = (arg_resetfn *)arg_lit_resetfn;
+ result->hdr.scanfn = (arg_scanfn *)arg_lit_scanfn;
+ result->hdr.checkfn = (arg_checkfn *)arg_lit_checkfn;
+ result->hdr.errorfn = (arg_errorfn *)arg_lit_errorfn;
- /* init the arg_hdr struct */
- result->hdr.flag = 0;
- result->hdr.shortopts = shortopts;
- result->hdr.longopts = longopts;
- result->hdr.datatype = NULL;
- result->hdr.glossary = glossary;
- result->hdr.mincount = mincount;
- result->hdr.maxcount = maxcount;
- result->hdr.parent = result;
- result->hdr.resetfn = (arg_resetfn*)arg_lit_resetfn;
- result->hdr.scanfn = (arg_scanfn*)arg_lit_scanfn;
- result->hdr.checkfn = (arg_checkfn*)arg_lit_checkfn;
- result->hdr.errorfn = (arg_errorfn*)arg_lit_errorfn;
-
- /* init local variables */
- result->count = 0;
+ /* init local variables */
+ result->count = 0;
+ }
ARG_TRACE(("arg_litn() returns %p\n", result));
return result;
}
/*******************************************************************************
- * arg_rem: Implements the rem command-line option
- *
* This file is part of the argtable3 library.
*
* Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
@@ -3333,36 +2395,32 @@ struct arg_lit* arg_litn(const char* shortopts, const char* longopts, int mincou
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
-#include "argtable3.h"
-
-#ifndef ARG_AMALGAMATION
-#include "argtable3_private.h"
-#endif
-
#include
-struct arg_rem* arg_rem(const char* datatype, const char* glossary) {
- struct arg_rem* result = (struct arg_rem*)xmalloc(sizeof(struct arg_rem));
+#include "argtable3.h"
- result->hdr.flag = 0;
- result->hdr.shortopts = NULL;
- result->hdr.longopts = NULL;
- result->hdr.datatype = datatype;
- result->hdr.glossary = glossary;
- result->hdr.mincount = 1;
- result->hdr.maxcount = 1;
- result->hdr.parent = result;
- result->hdr.resetfn = NULL;
- result->hdr.scanfn = NULL;
- result->hdr.checkfn = NULL;
- result->hdr.errorfn = NULL;
+struct arg_rem *arg_rem(const char *datatype, const char *glossary) {
+ struct arg_rem *result = (struct arg_rem *)malloc(sizeof(struct arg_rem));
+ if (result) {
+ result->hdr.flag = 0;
+ result->hdr.shortopts = NULL;
+ result->hdr.longopts = NULL;
+ result->hdr.datatype = datatype;
+ result->hdr.glossary = glossary;
+ result->hdr.mincount = 1;
+ result->hdr.maxcount = 1;
+ result->hdr.parent = result;
+ result->hdr.resetfn = NULL;
+ result->hdr.scanfn = NULL;
+ result->hdr.checkfn = NULL;
+ result->hdr.errorfn = NULL;
+ }
ARG_TRACE(("arg_rem() returns %p\n", result));
return result;
}
+
/*******************************************************************************
- * arg_rex: Implements the regex command-line option
- *
* This file is part of the argtable3 library.
*
* Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
@@ -3392,54 +2450,58 @@ struct arg_rem* arg_rem(const char* datatype, const char* glossary) {
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
-#include "argtable3.h"
-
-#ifndef ARG_AMALGAMATION
-#include "argtable3_private.h"
-#endif
-
#include
#include
+#include "argtable3.h"
+
+
#ifndef _TREX_H_
#define _TREX_H_
+/***************************************************************
+ T-Rex a tiny regular expression library
-/*
- * This module uses the T-Rex regular expression library to implement the regex
- * logic. Here is the copyright notice of the library:
- *
- * Copyright (C) 2003-2006 Alberto Demichelis
- *
- * This software is provided 'as-is', without any express
- * or implied warranty. In no event will the authors be held
- * liable for any damages arising from the use of this software.
- *
- * Permission is granted to anyone to use this software for
- * any purpose, including commercial applications, and to alter
- * it and redistribute it freely, subject to the following restrictions:
- *
- * 1. The origin of this software must not be misrepresented;
- * you must not claim that you wrote the original software.
- * If you use this software in a product, an acknowledgment
- * in the product documentation would be appreciated but
- * is not required.
- *
- * 2. Altered source versions must be plainly marked as such,
- * and must not be misrepresented as being the original software.
- *
- * 3. This notice may not be removed or altered from any
- * source distribution.
- */
+ Copyright (C) 2003-2006 Alberto Demichelis
+
+ This software is provided 'as-is', without any express
+ or implied warranty. In no event will the authors be held
+ liable for any damages arising from the use of this software.
+
+ Permission is granted to anyone to use this software for
+ any purpose, including commercial applications, and to alter
+ it and redistribute it freely, subject to the following restrictions:
+
+ 1. The origin of this software must not be misrepresented;
+ you must not claim that you wrote the original software.
+ If you use this software in a product, an acknowledgment
+ in the product documentation would be appreciated but
+ is not required.
+
+ 2. Altered source versions must be plainly marked as such,
+ and must not be misrepresented as being the original software.
+
+ 3. This notice may not be removed or altered from any
+ source distribution.
+
+****************************************************************/
#ifdef __cplusplus
extern "C" {
#endif
+#ifdef _UNICODE
+#define TRexChar unsigned short
+#define MAX_CHAR 0xFFFF
+#define _TREXC(c) L##c
+#define trex_strlen wcslen
+#define trex_printf wprintf
+#else
#define TRexChar char
#define MAX_CHAR 0xFF
#define _TREXC(c) (c)
#define trex_strlen strlen
#define trex_printf printf
+#endif
#ifndef TREX_API
#define TREX_API extern
@@ -3454,18 +2516,17 @@ typedef unsigned int TRexBool;
typedef struct TRex TRex;
typedef struct {
- const TRexChar* begin;
+ const TRexChar *begin;
int len;
} TRexMatch;
-TREX_API TRex* trex_compile(const TRexChar* pattern, const TRexChar** error, int flags);
-TREX_API void trex_free(TRex* exp);
-TREX_API TRexBool trex_match(TRex* exp, const TRexChar* text);
-TREX_API TRexBool trex_search(TRex* exp, const TRexChar* text, const TRexChar** out_begin, const TRexChar** out_end);
-TREX_API TRexBool
-trex_searchrange(TRex* exp, const TRexChar* text_begin, const TRexChar* text_end, const TRexChar** out_begin, const TRexChar** out_end);
-TREX_API int trex_getsubexpcount(TRex* exp);
-TREX_API TRexBool trex_getsubexp(TRex* exp, int n, TRexMatch* subexp);
+TREX_API TRex *trex_compile(const TRexChar *pattern, const TRexChar **error, int flags);
+TREX_API void trex_free(TRex *exp);
+TREX_API TRexBool trex_match(TRex *exp, const TRexChar *text);
+TREX_API TRexBool trex_search(TRex *exp, const TRexChar *text, const TRexChar **out_begin, const TRexChar **out_end);
+TREX_API TRexBool trex_searchrange(TRex *exp, const TRexChar *text_begin, const TRexChar *text_end, const TRexChar **out_begin, const TRexChar **out_end);
+TREX_API int trex_getsubexpcount(TRex *exp);
+TREX_API TRexBool trex_getsubexp(TRex *exp, int n, TRexMatch *subexp);
#ifdef __cplusplus
}
@@ -3473,32 +2534,35 @@ TREX_API TRexBool trex_getsubexp(TRex* exp, int n, TRexMatch* subexp);
#endif
+
+
struct privhdr {
- const char* pattern;
+ const char *pattern;
int flags;
};
-static void arg_rex_resetfn(struct arg_rex* parent) {
+
+static void arg_rex_resetfn(struct arg_rex *parent) {
ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent));
parent->count = 0;
}
-static int arg_rex_scanfn(struct arg_rex* parent, const char* argval) {
+static int arg_rex_scanfn(struct arg_rex *parent, const char *argval) {
int errorcode = 0;
- const TRexChar* error = NULL;
- TRex* rex = NULL;
- TRexBool is_match = TRex_False;
+ const TRexChar *error = NULL;
+ TRex *rex = NULL;
+ TRexBool is_match;
if (parent->count == parent->hdr.maxcount) {
/* maximum number of arguments exceeded */
- errorcode = ARG_ERR_MAXCOUNT;
+ errorcode = EMAXCOUNT;
} else if (!argval) {
/* a valid argument with no argument value was given. */
/* This happens when an optional argument value was invoked. */
/* leave parent argument value unaltered but still count the argument. */
parent->count++;
} else {
- struct privhdr* priv = (struct privhdr*)parent->hdr.priv;
+ struct privhdr *priv = (struct privhdr *)parent->hdr.priv;
/* test the current argument value for a match with the regular expression */
/* if a match is detected, record the argument value in the arg_rex struct */
@@ -3506,7 +2570,7 @@ static int arg_rex_scanfn(struct arg_rex* parent, const char* argval) {
rex = trex_compile(priv->pattern, &error, priv->flags);
is_match = trex_match(rex, argval);
if (!is_match)
- errorcode = ARG_ERR_REGNOMATCH;
+ errorcode = EREGNOMATCH;
else
parent->sval[parent->count++] = argval;
@@ -3517,79 +2581,107 @@ static int arg_rex_scanfn(struct arg_rex* parent, const char* argval) {
return errorcode;
}
-static int arg_rex_checkfn(struct arg_rex* parent) {
- int errorcode = (parent->count < parent->hdr.mincount) ? ARG_ERR_MINCOUNT : 0;
-#if 0
- struct privhdr *priv = (struct privhdr*)parent->hdr.priv;
+static int arg_rex_checkfn(struct arg_rex *parent) {
+ int errorcode = (parent->count < parent->hdr.mincount) ? EMINCOUNT : 0;
+ //struct privhdr *priv = (struct privhdr*)parent->hdr.priv;
/* free the regex "program" we constructed in resetfn */
- regfree(&(priv->regex));
+ //regfree(&(priv->regex));
/*printf("%s:checkfn(%p) returns %d\n",__FILE__,parent,errorcode);*/
-#endif
return errorcode;
}
-static void arg_rex_errorfn(struct arg_rex* parent, arg_dstr_t ds, int errorcode, const char* argval, const char* progname) {
- const char* shortopts = parent->hdr.shortopts;
- const char* longopts = parent->hdr.longopts;
- const char* datatype = parent->hdr.datatype;
+static void arg_rex_errorfn(struct arg_rex *parent,
+ FILE *fp,
+ int errorcode,
+ const char *argval,
+ const char *progname) {
+ const char *shortopts = parent->hdr.shortopts;
+ const char *longopts = parent->hdr.longopts;
+ const char *datatype = parent->hdr.datatype;
/* make argval NULL safe */
argval = argval ? argval : "";
- arg_dstr_catf(ds, "%s: ", progname);
+ fprintf(fp, "%s: ", progname);
switch (errorcode) {
- case ARG_ERR_MINCOUNT:
- arg_dstr_cat(ds, "missing option ");
- arg_print_option_ds(ds, shortopts, longopts, datatype, "\n");
+ case EMINCOUNT:
+ fputs("missing option ", fp);
+ arg_print_option(fp, shortopts, longopts, datatype, "\n");
break;
- case ARG_ERR_MAXCOUNT:
- arg_dstr_cat(ds, "excess option ");
- arg_print_option_ds(ds, shortopts, longopts, argval, "\n");
+ case EMAXCOUNT:
+ fputs("excess option ", fp);
+ arg_print_option(fp, shortopts, longopts, argval, "\n");
break;
- case ARG_ERR_REGNOMATCH:
- arg_dstr_cat(ds, "illegal value ");
- arg_print_option_ds(ds, shortopts, longopts, argval, "\n");
+ case EREGNOMATCH:
+ fputs("illegal value ", fp);
+ arg_print_option(fp, shortopts, longopts, argval, "\n");
break;
default: {
- #if 0
- char errbuff[256];
- regerror(errorcode, NULL, errbuff, sizeof(errbuff));
- printf("%s\n", errbuff);
- #endif
- } break;
+ //char errbuff[256];
+ //regerror(errorcode, NULL, errbuff, sizeof(errbuff));
+ //printf("%s\n", errbuff);
+ }
+ break;
}
}
-struct arg_rex* arg_rex0(const char* shortopts, const char* longopts, const char* pattern, const char* datatype, int flags, const char* glossary) {
- return arg_rexn(shortopts, longopts, pattern, datatype, 0, 1, flags, glossary);
+
+struct arg_rex *arg_rex0(const char *shortopts,
+ const char *longopts,
+ const char *pattern,
+ const char *datatype,
+ int flags,
+ const char *glossary) {
+ return arg_rexn(shortopts,
+ longopts,
+ pattern,
+ datatype,
+ 0,
+ 1,
+ flags,
+ glossary);
}
-struct arg_rex* arg_rex1(const char* shortopts, const char* longopts, const char* pattern, const char* datatype, int flags, const char* glossary) {
- return arg_rexn(shortopts, longopts, pattern, datatype, 1, 1, flags, glossary);
+struct arg_rex *arg_rex1(const char *shortopts,
+ const char *longopts,
+ const char *pattern,
+ const char *datatype,
+ int flags,
+ const char *glossary) {
+ return arg_rexn(shortopts,
+ longopts,
+ pattern,
+ datatype,
+ 1,
+ 1,
+ flags,
+ glossary);
}
-struct arg_rex* arg_rexn(const char* shortopts,
- const char* longopts,
- const char* pattern,
- const char* datatype,
+
+struct arg_rex *arg_rexn(const char *shortopts,
+ const char *longopts,
+ const char *pattern,
+ const char *datatype,
int mincount,
int maxcount,
int flags,
- const char* glossary) {
+ const char *glossary) {
size_t nbytes;
- struct arg_rex* result;
- struct privhdr* priv;
+ struct arg_rex *result;
+ struct privhdr *priv;
int i;
- const TRexChar* error = NULL;
- TRex* rex = NULL;
+ const TRexChar *error = NULL;
+ TRex *rex = NULL;
if (!pattern) {
- printf("argtable: ERROR - illegal regular expression pattern \"(NULL)\"\n");
+ printf(
+ "argtable: ERROR - illegal regular expression pattern \"(NULL)\"\n");
printf("argtable: Bad argument table.\n");
return NULL;
}
@@ -3597,33 +2689,36 @@ struct arg_rex* arg_rexn(const char* shortopts,
/* foolproof things by ensuring maxcount is not less than mincount */
maxcount = (maxcount < mincount) ? mincount : maxcount;
- nbytes = sizeof(struct arg_rex) /* storage for struct arg_rex */
- + sizeof(struct privhdr) /* storage for private arg_rex data */
- + maxcount * sizeof(char*); /* storage for sval[maxcount] array */
+ nbytes = sizeof(struct arg_rex) /* storage for struct arg_rex */
+ + sizeof(struct privhdr) /* storage for private arg_rex data */
+ + maxcount * sizeof(char *); /* storage for sval[maxcount] array */
+
+ result = (struct arg_rex *)malloc(nbytes);
+ if (result == NULL)
+ return result;
/* init the arg_hdr struct */
- result = (struct arg_rex*)xmalloc(nbytes);
- result->hdr.flag = ARG_HASVALUE;
+ result->hdr.flag = ARG_HASVALUE;
result->hdr.shortopts = shortopts;
- result->hdr.longopts = longopts;
- result->hdr.datatype = datatype ? datatype : pattern;
- result->hdr.glossary = glossary;
- result->hdr.mincount = mincount;
- result->hdr.maxcount = maxcount;
- result->hdr.parent = result;
- result->hdr.resetfn = (arg_resetfn*)arg_rex_resetfn;
- result->hdr.scanfn = (arg_scanfn*)arg_rex_scanfn;
- result->hdr.checkfn = (arg_checkfn*)arg_rex_checkfn;
- result->hdr.errorfn = (arg_errorfn*)arg_rex_errorfn;
+ result->hdr.longopts = longopts;
+ result->hdr.datatype = datatype ? datatype : pattern;
+ result->hdr.glossary = glossary;
+ result->hdr.mincount = mincount;
+ result->hdr.maxcount = maxcount;
+ result->hdr.parent = result;
+ result->hdr.resetfn = (arg_resetfn *)arg_rex_resetfn;
+ result->hdr.scanfn = (arg_scanfn *)arg_rex_scanfn;
+ result->hdr.checkfn = (arg_checkfn *)arg_rex_checkfn;
+ result->hdr.errorfn = (arg_errorfn *)arg_rex_errorfn;
/* store the arg_rex_priv struct immediately after the arg_rex struct */
- result->hdr.priv = result + 1;
- priv = (struct privhdr*)(result->hdr.priv);
+ result->hdr.priv = result + 1;
+ priv = (struct privhdr *)(result->hdr.priv);
priv->pattern = pattern;
priv->flags = flags;
/* store the sval[maxcount] array immediately after the arg_rex_priv struct */
- result->sval = (const char**)(priv + 1);
+ result->sval = (const char * *)(priv + 1);
result->count = 0;
/* foolproof the string pointers by initializing them to reference empty strings */
@@ -3648,11 +2743,13 @@ struct arg_rex* arg_rexn(const char* shortopts,
return result;
}
+
+
/* see copyright notice in trex.h */
+#include
+#include
#include
#include
-#include
-#include
#ifdef _UINCODE
#define scisprint iswprint
@@ -3669,24 +2766,27 @@ struct arg_rex* arg_rexn(const char* shortopts,
#ifdef _DEBUG
#include
-static const TRexChar* g_nnames[] = {_SC("NONE"), _SC("OP_GREEDY"), _SC("OP_OR"), _SC("OP_EXPR"), _SC("OP_NOCAPEXPR"),
- _SC("OP_DOT"), _SC("OP_CLASS"), _SC("OP_CCLASS"), _SC("OP_NCLASS"), _SC("OP_RANGE"),
- _SC("OP_CHAR"), _SC("OP_EOL"), _SC("OP_BOL"), _SC("OP_WB")};
+static const TRexChar *g_nnames[] = {
+ _SC("NONE"), _SC("OP_GREEDY"), _SC("OP_OR"),
+ _SC("OP_EXPR"), _SC("OP_NOCAPEXPR"), _SC("OP_DOT"), _SC("OP_CLASS"),
+ _SC("OP_CCLASS"), _SC("OP_NCLASS"), _SC("OP_RANGE"), _SC("OP_CHAR"),
+ _SC("OP_EOL"), _SC("OP_BOL"), _SC("OP_WB")
+};
#endif
-#define OP_GREEDY (MAX_CHAR + 1) /* * + ? {n} */
-#define OP_OR (MAX_CHAR + 2)
-#define OP_EXPR (MAX_CHAR + 3) /* parentesis () */
-#define OP_NOCAPEXPR (MAX_CHAR + 4) /* parentesis (?:) */
-#define OP_DOT (MAX_CHAR + 5)
-#define OP_CLASS (MAX_CHAR + 6)
-#define OP_CCLASS (MAX_CHAR + 7)
-#define OP_NCLASS (MAX_CHAR + 8) /* negates class the [^ */
-#define OP_RANGE (MAX_CHAR + 9)
-#define OP_CHAR (MAX_CHAR + 10)
-#define OP_EOL (MAX_CHAR + 11)
-#define OP_BOL (MAX_CHAR + 12)
-#define OP_WB (MAX_CHAR + 13)
+#define OP_GREEDY (MAX_CHAR+1) // * + ? {n}
+#define OP_OR (MAX_CHAR+2)
+#define OP_EXPR (MAX_CHAR+3) //parentesis ()
+#define OP_NOCAPEXPR (MAX_CHAR+4) //parentesis (?:)
+#define OP_DOT (MAX_CHAR+5)
+#define OP_CLASS (MAX_CHAR+6)
+#define OP_CCLASS (MAX_CHAR+7)
+#define OP_NCLASS (MAX_CHAR+8) //negates class the [^
+#define OP_RANGE (MAX_CHAR+9)
+#define OP_CHAR (MAX_CHAR+10)
+#define OP_EOL (MAX_CHAR+11)
+#define OP_BOL (MAX_CHAR+12)
+#define OP_WB (MAX_CHAR+13)
#define TREX_SYMBOL_ANY_CHAR ('.')
#define TREX_SYMBOL_GREEDY_ONE_OR_MORE ('+')
@@ -3697,6 +2797,7 @@ static const TRexChar* g_nnames[] = {_SC("NONE"), _SC("OP_GREEDY"), _SC("OP_O
#define TREX_SYMBOL_BEGINNING_OF_STRING ('^')
#define TREX_SYMBOL_ESCAPE_CHAR ('\\')
+
typedef int TRexNodeType;
typedef struct tagTRexNode {
@@ -3707,25 +2808,25 @@ typedef struct tagTRexNode {
} TRexNode;
struct TRex {
- const TRexChar* _eol;
- const TRexChar* _bol;
- const TRexChar* _p;
+ const TRexChar *_eol;
+ const TRexChar *_bol;
+ const TRexChar *_p;
int _first;
int _op;
- TRexNode* _nodes;
+ TRexNode *_nodes;
int _nallocated;
int _nsize;
int _nsubexpr;
- TRexMatch* _matches;
+ TRexMatch *_matches;
int _currsubexp;
- void* _jmpbuf;
- const TRexChar** _error;
+ void *_jmpbuf;
+ const TRexChar **_error;
int _flags;
};
-static int trex_list(TRex* exp);
+static int trex_list(TRex *exp);
-static int trex_newnode(TRex* exp, TRexNodeType type) {
+static int trex_newnode(TRex *exp, TRexNodeType type) {
TRexNode n;
int newid;
n.type = type;
@@ -3734,26 +2835,25 @@ static int trex_newnode(TRex* exp, TRexNodeType type) {
n.right = exp->_nsubexpr++;
if (exp->_nallocated < (exp->_nsize + 1)) {
exp->_nallocated *= 2;
- exp->_nodes = (TRexNode*)xrealloc(exp->_nodes, exp->_nallocated * sizeof(TRexNode));
+ exp->_nodes = (TRexNode *)realloc(exp->_nodes, exp->_nallocated * sizeof(TRexNode));
}
exp->_nodes[exp->_nsize++] = n;
newid = exp->_nsize - 1;
return (int)newid;
}
-static void trex_error(TRex* exp, const TRexChar* error) {
- if (exp->_error)
- *exp->_error = error;
- longjmp(*((jmp_buf*)exp->_jmpbuf), -1);
+static void trex_error(TRex *exp, const TRexChar *error) {
+ if (exp->_error) *exp->_error = error;
+ longjmp(*((jmp_buf *)exp->_jmpbuf), -1);
}
-static void trex_expect(TRex* exp, int n) {
+static void trex_expect(TRex *exp, int n) {
if ((*exp->_p) != n)
trex_error(exp, _SC("expected paren"));
exp->_p++;
}
-static TRexChar trex_escapechar(TRex* exp) {
+static TRexChar trex_escapechar(TRex *exp) {
if (*exp->_p == TREX_SYMBOL_ESCAPE_CHAR) {
exp->_p++;
switch (*exp->_p) {
@@ -3775,18 +2875,17 @@ static TRexChar trex_escapechar(TRex* exp) {
default:
return (*exp->_p++);
}
- } else if (!scisprint(*exp->_p))
- trex_error(exp, _SC("letter expected"));
+ } else if (!scisprint(*exp->_p)) trex_error(exp, _SC("letter expected"));
return (*exp->_p++);
}
-static int trex_charclass(TRex* exp, int classid) {
+static int trex_charclass(TRex *exp, int classid) {
int n = trex_newnode(exp, OP_CCLASS);
exp->_nodes[n].left = classid;
return n;
}
-static int trex_charnode(TRex* exp, TRexBool isclass) {
+static int trex_charnode(TRex *exp, TRexBool isclass) {
TRexChar t;
if (*exp->_p == TREX_SYMBOL_ESCAPE_CHAR) {
exp->_p++;
@@ -3833,42 +2932,46 @@ static int trex_charnode(TRex* exp, TRexBool isclass) {
exp->_nodes[node].left = *exp->_p;
exp->_p++;
return node;
- }
- /* fall through */
+ } //else default
default:
t = *exp->_p;
exp->_p++;
return trex_newnode(exp, t);
}
} else if (!scisprint(*exp->_p)) {
+
trex_error(exp, _SC("letter expected"));
}
t = *exp->_p;
exp->_p++;
return trex_newnode(exp, t);
}
-static int trex_class(TRex* exp) {
+static int trex_class(TRex *exp) {
int ret = -1;
int first = -1, chain;
if (*exp->_p == TREX_SYMBOL_BEGINNING_OF_STRING) {
ret = trex_newnode(exp, OP_NCLASS);
exp->_p++;
- } else
- ret = trex_newnode(exp, OP_CLASS);
+ } else ret = trex_newnode(exp, OP_CLASS);
- if (*exp->_p == ']')
- trex_error(exp, _SC("empty class"));
+ if (*exp->_p == ']') trex_error(exp, _SC("empty class"));
chain = ret;
while (*exp->_p != ']' && exp->_p != exp->_eol) {
if (*exp->_p == '-' && first != -1) {
int r, t;
- if (*exp->_p++ == ']')
+ if (*exp->_p++ == ']') {
trex_error(exp, _SC("unfinished range"));
+ }
+
r = trex_newnode(exp, OP_RANGE);
- if (first > *exp->_p)
+ if (first > *exp->_p) {
trex_error(exp, _SC("invalid range"));
- if (exp->_nodes[first].type == OP_CCLASS)
+ }
+
+ if (exp->_nodes[first].type == OP_CCLASS) {
trex_error(exp, _SC("cannot use character classes in ranges"));
+ }
+
exp->_nodes[r].left = exp->_nodes[first].type;
t = trex_escapechar(exp);
exp->_nodes[r].right = t;
@@ -3889,8 +2992,6 @@ static int trex_class(TRex* exp) {
if (first != -1) {
int c = first;
exp->_nodes[chain].next = c;
- chain = c;
- first = -1;
}
/* hack? */
exp->_nodes[ret].left = exp->_nodes[ret].next;
@@ -3898,26 +2999,26 @@ static int trex_class(TRex* exp) {
return ret;
}
-static int trex_parsenumber(TRex* exp) {
+static int trex_parsenumber(TRex *exp) {
int ret = *exp->_p - '0';
int positions = 10;
exp->_p++;
while (isdigit(*exp->_p)) {
- ret = ret * 10 + (*exp->_p++ - '0');
- if (positions == 1000000000)
- trex_error(exp, _SC("overflow in numeric constant"));
+ ret = ret * 10 + (*exp->_p++ -'0');
+ if (positions == 1000000000) trex_error(exp, _SC("overflow in numeric constant"));
positions *= 10;
};
return ret;
}
-static int trex_element(TRex* exp) {
+static int trex_element(TRex *exp) {
int ret = -1;
switch (*exp->_p) {
case '(': {
int expr, newn;
exp->_p++;
+
if (*exp->_p == '?') {
exp->_p++;
trex_expect(exp, ':');
@@ -3928,7 +3029,8 @@ static int trex_element(TRex* exp) {
exp->_nodes[expr].left = newn;
ret = expr;
trex_expect(exp, ')');
- } break;
+ }
+ break;
case '[':
exp->_p++;
ret = trex_class(exp);
@@ -3971,8 +3073,7 @@ static int trex_element(TRex* exp) {
break;
case '{':
exp->_p++;
- if (!isdigit(*exp->_p))
- trex_error(exp, _SC("number expected"));
+ if (!isdigit(*exp->_p)) trex_error(exp, _SC("number expected"));
p0 = (unsigned short)trex_parsenumber(exp);
/*******************************/
switch (*exp->_p) {
@@ -3994,6 +3095,7 @@ static int trex_element(TRex* exp) {
/*******************************/
isgreedy = TRex_True;
break;
+
}
if (isgreedy) {
int nnode = trex_newnode(exp, OP_GREEDY);
@@ -4002,8 +3104,7 @@ static int trex_element(TRex* exp) {
ret = nnode;
}
}
- if ((*exp->_p != TREX_SYMBOL_BRANCH) && (*exp->_p != ')') && (*exp->_p != TREX_SYMBOL_GREEDY_ZERO_OR_MORE) &&
- (*exp->_p != TREX_SYMBOL_GREEDY_ONE_OR_MORE) && (*exp->_p != '\0')) {
+ if ((*exp->_p != TREX_SYMBOL_BRANCH) && (*exp->_p != ')') && (*exp->_p != TREX_SYMBOL_GREEDY_ZERO_OR_MORE) && (*exp->_p != TREX_SYMBOL_GREEDY_ONE_OR_MORE) && (*exp->_p != '\0')) {
int nnode = trex_element(exp);
exp->_nodes[ret].next = nnode;
}
@@ -4011,7 +3112,7 @@ static int trex_element(TRex* exp) {
return ret;
}
-static int trex_list(TRex* exp) {
+static int trex_list(TRex *exp) {
int ret = -1, e;
if (*exp->_p == TREX_SYMBOL_BEGINNING_OF_STRING) {
exp->_p++;
@@ -4020,8 +3121,7 @@ static int trex_list(TRex* exp) {
e = trex_element(exp);
if (ret != -1) {
exp->_nodes[ret].next = e;
- } else
- ret = e;
+ } else ret = e;
if (*exp->_p == TREX_SYMBOL_BRANCH) {
int temp, tright;
@@ -4046,9 +3146,9 @@ static TRexBool trex_matchcclass(int cclass, TRexChar c) {
case 'W':
return (!isalnum(c) && c != '_') ? TRex_True : TRex_False;
case 's':
- return isspace(c) ? TRex_True : TRex_False;
+ return ISSPACE(c) ? TRex_True : TRex_False;
case 'S':
- return !isspace(c) ? TRex_True : TRex_False;
+ return !ISSPACE(c) ? TRex_True : TRex_False;
case 'd':
return isdigit(c) ? TRex_True : TRex_False;
case 'D':
@@ -4073,43 +3173,39 @@ static TRexBool trex_matchcclass(int cclass, TRexChar c) {
return TRex_False; /*cannot happen*/
}
-static TRexBool trex_matchclass(TRex* exp, TRexNode* node, TRexChar c) {
+static TRexBool trex_matchclass(TRex *exp, TRexNode *node, TRexChar c) {
do {
switch (node->type) {
case OP_RANGE:
if (exp->_flags & TREX_ICASE) {
- if (c >= toupper(node->left) && c <= toupper(node->right))
- return TRex_True;
- if (c >= tolower(node->left) && c <= tolower(node->right))
- return TRex_True;
+ if (c >= toupper(node->left) && c <= toupper(node->right)) return TRex_True;
+ if (c >= tolower(node->left) && c <= tolower(node->right)) return TRex_True;
} else {
- if (c >= node->left && c <= node->right)
- return TRex_True;
+ if (c >= node->left && c <= node->right) return TRex_True;
}
break;
case OP_CCLASS:
- if (trex_matchcclass(node->left, c))
- return TRex_True;
+ if (trex_matchcclass(node->left, c)) return TRex_True;
break;
default:
if (exp->_flags & TREX_ICASE) {
- if (c == tolower(node->type) || c == toupper(node->type))
- return TRex_True;
+ if (c == tolower(node->type) || c == toupper(node->type)) return TRex_True;
} else {
- if (c == node->type)
- return TRex_True;
+ if (c == node->type)return TRex_True;
}
+
}
- } while ((node->next != -1) && ((node = &exp->_nodes[node->next]) != NULL));
+ } while ((node->next != -1) && (node = &exp->_nodes[node->next]));
return TRex_False;
}
-static const TRexChar* trex_matchnode(TRex* exp, TRexNode* node, const TRexChar* str, TRexNode* next) {
+static const TRexChar *trex_matchnode(TRex *exp, TRexNode *node, const TRexChar *str, TRexNode *next) {
+
TRexNodeType type = node->type;
switch (type) {
case OP_GREEDY: {
- /* TRexNode *greedystop = (node->next != -1) ? &exp->_nodes[node->next] : NULL; */
- TRexNode* greedystop = NULL;
+ //TRexNode *greedystop = (node->next != -1) ? &exp->_nodes[node->next] : NULL;
+ TRexNode *greedystop = NULL;
int p0 = (node->right >> 16) & 0x0000FFFF, p1 = node->right & 0x0000FFFF, nmaches = 0;
const TRexChar *s = str, *good = str;
@@ -4120,16 +3216,18 @@ static const TRexChar* trex_matchnode(TRex* exp, TRexNode* node, const TRexChar*
}
while ((nmaches == 0xFFFF || nmaches < p1)) {
- const TRexChar* stop;
- if ((s = trex_matchnode(exp, &exp->_nodes[node->left], s, greedystop)) == NULL)
+
+ const TRexChar *stop;
+ if (!(s = trex_matchnode(exp, &exp->_nodes[node->left], s, greedystop)))
break;
nmaches++;
good = s;
if (greedystop) {
- /* checks that 0 matches satisfy the expression(if so skips) */
- /* if not would always stop(for instance if is a '?') */
- if (greedystop->type != OP_GREEDY || (greedystop->type == OP_GREEDY && ((greedystop->right >> 16) & 0x0000FFFF) != 0)) {
- TRexNode* gnext = NULL;
+ //checks that 0 matches satisfy the expression(if so skips)
+ //if not would always stop(for instance if is a '?')
+ if (greedystop->type != OP_GREEDY ||
+ (greedystop->type == OP_GREEDY && ((greedystop->right >> 16) & 0x0000FFFF) != 0)) {
+ TRexNode *gnext = NULL;
if (greedystop->next != -1) {
gnext = &exp->_nodes[greedystop->next];
} else if (next && next->next != -1) {
@@ -4137,13 +3235,10 @@ static const TRexChar* trex_matchnode(TRex* exp, TRexNode* node, const TRexChar*
}
stop = trex_matchnode(exp, greedystop, s, gnext);
if (stop) {
- /* if satisfied stop it */
- if (p0 == p1 && p0 == nmaches)
- break;
- else if (nmaches >= p0 && p1 == 0xFFFF)
- break;
- else if (nmaches >= p0 && nmaches <= p1)
- break;
+ //if satisfied stop it
+ if (p0 == p1 && p0 == nmaches) break;
+ else if (nmaches >= p0 && p1 == 0xFFFF) break;
+ else if (nmaches >= p0 && nmaches <= p1) break;
}
}
}
@@ -4151,18 +3246,15 @@ static const TRexChar* trex_matchnode(TRex* exp, TRexNode* node, const TRexChar*
if (s >= exp->_eol)
break;
}
- if (p0 == p1 && p0 == nmaches)
- return good;
- else if (nmaches >= p0 && p1 == 0xFFFF)
- return good;
- else if (nmaches >= p0 && nmaches <= p1)
- return good;
+ if (p0 == p1 && p0 == nmaches) return good;
+ else if (nmaches >= p0 && p1 == 0xFFFF) return good;
+ else if (nmaches >= p0 && nmaches <= p1) return good;
return NULL;
}
case OP_OR: {
- const TRexChar* asd = str;
- TRexNode* temp = &exp->_nodes[node->left];
- while ((asd = trex_matchnode(exp, temp, asd, NULL)) != NULL) {
+ const TRexChar *asd = str;
+ TRexNode *temp = &exp->_nodes[node->left];
+ while ((asd = trex_matchnode(exp, temp, asd, NULL))) {
if (temp->next != -1)
temp = &exp->_nodes[temp->next];
else
@@ -4170,19 +3262,18 @@ static const TRexChar* trex_matchnode(TRex* exp, TRexNode* node, const TRexChar*
}
asd = str;
temp = &exp->_nodes[node->right];
- while ((asd = trex_matchnode(exp, temp, asd, NULL)) != NULL) {
+ while ((asd = trex_matchnode(exp, temp, asd, NULL))) {
if (temp->next != -1)
temp = &exp->_nodes[temp->next];
else
return asd;
}
return NULL;
- break;
}
case OP_EXPR:
case OP_NOCAPEXPR: {
- TRexNode* n = &exp->_nodes[node->left];
- const TRexChar* cur = str;
+ TRexNode *n = &exp->_nodes[node->left];
+ const TRexChar *cur = str;
int capture = -1;
if (node->type != OP_NOCAPEXPR && node->right == exp->_currsubexp) {
capture = exp->_currsubexp;
@@ -4191,47 +3282,45 @@ static const TRexChar* trex_matchnode(TRex* exp, TRexNode* node, const TRexChar*
}
do {
- TRexNode* subnext = NULL;
+ TRexNode *subnext = NULL;
if (n->next != -1) {
subnext = &exp->_nodes[n->next];
} else {
subnext = next;
}
- if ((cur = trex_matchnode(exp, n, cur, subnext)) == NULL) {
+ if (!(cur = trex_matchnode(exp, n, cur, subnext))) {
if (capture != -1) {
exp->_matches[capture].begin = 0;
exp->_matches[capture].len = 0;
}
return NULL;
}
- } while ((n->next != -1) && ((n = &exp->_nodes[n->next]) != NULL));
+ } while ((n->next != -1) && (n = &exp->_nodes[n->next]));
if (capture != -1)
exp->_matches[capture].len = (int)(cur - exp->_matches[capture].begin);
return cur;
}
case OP_WB:
- if ((str == exp->_bol && !isspace(*str)) || (str == exp->_eol && !isspace(*(str - 1))) || (!isspace(*str) && isspace(*(str + 1))) ||
- (isspace(*str) && !isspace(*(str + 1)))) {
+ if ((str == exp->_bol && !ISSPACE(*str))
+ || ((str == exp->_eol && !ISSPACE(*(str - 1))))
+ || ((!ISSPACE(*str) && ISSPACE(*(str + 1))))
+ || ((ISSPACE(*str) && !ISSPACE(*(str + 1))))) {
return (node->left == 'b') ? str : NULL;
}
return (node->left == 'b') ? NULL : str;
case OP_BOL:
- if (str == exp->_bol)
- return str;
+ if (str == exp->_bol) return str;
return NULL;
case OP_EOL:
- if (str == exp->_eol)
- return str;
+ if (str == exp->_eol) return str;
return NULL;
- case OP_DOT: {
+ case OP_DOT:
str++;
- }
return str;
case OP_NCLASS:
case OP_CLASS:
- if (trex_matchclass(exp, &exp->_nodes[node->left], *str) ? (type == OP_CLASS ? TRex_True : TRex_False)
- : (type == OP_NCLASS ? TRex_True : TRex_False)) {
+ if (trex_matchclass(exp, &exp->_nodes[node->left], *str) ? (type == OP_CLASS ? TRex_True : TRex_False) : (type == OP_NCLASS ? TRex_True : TRex_False)) {
str++;
return str;
}
@@ -4244,32 +3333,31 @@ static const TRexChar* trex_matchnode(TRex* exp, TRexNode* node, const TRexChar*
return NULL;
default: /* char */
if (exp->_flags & TREX_ICASE) {
- if (*str != tolower(node->type) && *str != toupper(node->type))
- return NULL;
+ if (*str != tolower(node->type) && *str != toupper(node->type)) return NULL;
} else {
- if (*str != node->type)
- return NULL;
+ if (*str != node->type) return NULL;
}
str++;
return str;
}
+ return NULL;
}
/* public api */
-TRex* trex_compile(const TRexChar* pattern, const TRexChar** error, int flags) {
- TRex* exp = (TRex*)xmalloc(sizeof(TRex));
+TRex *trex_compile(const TRexChar *pattern, const TRexChar **error, int flags) {
+ TRex *exp = (TRex *)malloc(sizeof(TRex));
exp->_eol = exp->_bol = NULL;
exp->_p = pattern;
exp->_nallocated = (int)scstrlen(pattern) * sizeof(TRexChar);
- exp->_nodes = (TRexNode*)xmalloc(exp->_nallocated * sizeof(TRexNode));
+ exp->_nodes = (TRexNode *)malloc(exp->_nallocated * sizeof(TRexNode));
exp->_nsize = 0;
exp->_matches = 0;
exp->_nsubexpr = 0;
exp->_first = trex_newnode(exp, OP_EXPR);
exp->_error = error;
- exp->_jmpbuf = xmalloc(sizeof(jmp_buf));
+ exp->_jmpbuf = malloc(sizeof(jmp_buf));
exp->_flags = flags;
- if (setjmp(*((jmp_buf*)exp->_jmpbuf)) == 0) {
+ if (setjmp(*((jmp_buf *)exp->_jmpbuf)) == 0) {
int res = trex_list(exp);
exp->_nodes[exp->_first].left = res;
if (*exp->_p != '\0')
@@ -4277,7 +3365,7 @@ TRex* trex_compile(const TRexChar* pattern, const TRexChar** error, int flags) {
#ifdef _DEBUG
{
int nsize, i;
- TRexNode* t;
+ TRexNode *t;
nsize = exp->_nsize;
t = &exp->_nodes[0];
scprintf(_SC("\n"));
@@ -4291,7 +3379,7 @@ TRex* trex_compile(const TRexChar* pattern, const TRexChar** error, int flags) {
scprintf(_SC("\n"));
}
#endif
- exp->_matches = (TRexMatch*)xmalloc(exp->_nsubexpr * sizeof(TRexMatch));
+ exp->_matches = (TRexMatch *) malloc(exp->_nsubexpr * sizeof(TRexMatch));
memset(exp->_matches, 0, exp->_nsubexpr * sizeof(TRexMatch));
} else {
trex_free(exp);
@@ -4300,17 +3388,17 @@ TRex* trex_compile(const TRexChar* pattern, const TRexChar** error, int flags) {
return exp;
}
-void trex_free(TRex* exp) {
+void trex_free(TRex *exp) {
if (exp) {
- xfree(exp->_nodes);
- xfree(exp->_jmpbuf);
- xfree(exp->_matches);
- xfree(exp);
+ if (exp->_nodes) free(exp->_nodes);
+ if (exp->_jmpbuf) free(exp->_jmpbuf);
+ if (exp->_matches) free(exp->_matches);
+ free(exp);
}
}
-TRexBool trex_match(TRex* exp, const TRexChar* text) {
- const TRexChar* res = NULL;
+TRexBool trex_match(TRex *exp, const TRexChar *text) {
+ const TRexChar *res = NULL;
exp->_bol = text;
exp->_eol = text + scstrlen(text);
exp->_currsubexp = 0;
@@ -4320,11 +3408,10 @@ TRexBool trex_match(TRex* exp, const TRexChar* text) {
return TRex_True;
}
-TRexBool trex_searchrange(TRex* exp, const TRexChar* text_begin, const TRexChar* text_end, const TRexChar** out_begin, const TRexChar** out_end) {
- const TRexChar* cur = NULL;
+TRexBool trex_searchrange(TRex *exp, const TRexChar *text_begin, const TRexChar *text_end, const TRexChar **out_begin, const TRexChar **out_end) {
+ const TRexChar *cur = NULL;
int node = exp->_first;
- if (text_begin >= text_end)
- return TRex_False;
+ if (text_begin >= text_end) return TRex_False;
exp->_bol = text_begin;
exp->_eol = text_end;
do {
@@ -4344,30 +3431,25 @@ TRexBool trex_searchrange(TRex* exp, const TRexChar* text_begin, const TRexChar*
--text_begin;
- if (out_begin)
- *out_begin = text_begin;
- if (out_end)
- *out_end = cur;
+ if (out_begin) *out_begin = text_begin;
+ if (out_end) *out_end = cur;
return TRex_True;
}
-TRexBool trex_search(TRex* exp, const TRexChar* text, const TRexChar** out_begin, const TRexChar** out_end) {
+TRexBool trex_search(TRex *exp, const TRexChar *text, const TRexChar **out_begin, const TRexChar **out_end) {
return trex_searchrange(exp, text, text + scstrlen(text), out_begin, out_end);
}
-int trex_getsubexpcount(TRex* exp) {
+int trex_getsubexpcount(TRex *exp) {
return exp->_nsubexpr;
}
-TRexBool trex_getsubexp(TRex* exp, int n, TRexMatch* subexp) {
- if (n < 0 || n >= exp->_nsubexpr)
- return TRex_False;
+TRexBool trex_getsubexp(TRex *exp, int n, TRexMatch *subexp) {
+ if (n < 0 || n >= exp->_nsubexpr) return TRex_False;
*subexp = exp->_matches[n];
return TRex_True;
}
/*******************************************************************************
- * arg_str: Implements the str command-line option
- *
* This file is part of the argtable3 library.
*
* Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
@@ -4397,34 +3479,31 @@ TRexBool trex_getsubexp(TRex* exp, int n, TRexMatch* subexp) {
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
-#include "argtable3.h"
-
-#ifndef ARG_AMALGAMATION
-#include "argtable3_private.h"
-#endif
-
#include
-static void arg_str_resetfn(struct arg_str* parent) {
+#include "argtable3.h"
+
+
+static void arg_str_resetfn(struct arg_str *parent) {
int i;
-
ARG_TRACE(("%s:resetfn(%p)\n", __FILE__, parent));
+ parent->count = 0;
for (i = 0; i < parent->count; i++) {
parent->sval[i] = "";
}
- parent->count = 0;
}
-static int arg_str_scanfn(struct arg_str* parent, const char* argval) {
+
+static int arg_str_scanfn(struct arg_str *parent, const char *argval) {
int errorcode = 0;
if (parent->count == parent->hdr.maxcount) {
/* maximum number of arguments exceeded */
- errorcode = ARG_ERR_MAXCOUNT;
+ errorcode = EMAXCOUNT;
} else if (!argval) {
/* a valid argument with no argument value was given. */
/* This happens when an optional argument value was invoked. */
- /* leave parent argument value unaltered but still count the argument. */
+ /* leave parent arguiment value unaltered but still count the argument. */
parent->count++;
} else {
parent->sval[parent->count++] = argval;
@@ -4434,366 +3513,110 @@ static int arg_str_scanfn(struct arg_str* parent, const char* argval) {
return errorcode;
}
-static int arg_str_checkfn(struct arg_str* parent) {
- int errorcode = (parent->count < parent->hdr.mincount) ? ARG_ERR_MINCOUNT : 0;
+
+static int arg_str_checkfn(struct arg_str *parent) {
+ int errorcode = (parent->count < parent->hdr.mincount) ? EMINCOUNT : 0;
ARG_TRACE(("%s:checkfn(%p) returns %d\n", __FILE__, parent, errorcode));
return errorcode;
}
-static void arg_str_errorfn(struct arg_str* parent, arg_dstr_t ds, int errorcode, const char* argval, const char* progname) {
- const char* shortopts = parent->hdr.shortopts;
- const char* longopts = parent->hdr.longopts;
- const char* datatype = parent->hdr.datatype;
+
+static void arg_str_errorfn(
+ struct arg_str *parent,
+ FILE *fp,
+ int errorcode,
+ const char *argval,
+ const char *progname) {
+ const char *shortopts = parent->hdr.shortopts;
+ const char *longopts = parent->hdr.longopts;
+ const char *datatype = parent->hdr.datatype;
/* make argval NULL safe */
argval = argval ? argval : "";
- arg_dstr_catf(ds, "%s: ", progname);
+ fprintf(fp, "%s: ", progname);
switch (errorcode) {
- case ARG_ERR_MINCOUNT:
- arg_dstr_cat(ds, "missing option ");
- arg_print_option_ds(ds, shortopts, longopts, datatype, "\n");
+ case EMINCOUNT:
+ fputs("missing option ", fp);
+ arg_print_option(fp, shortopts, longopts, datatype, "\n");
break;
- case ARG_ERR_MAXCOUNT:
- arg_dstr_cat(ds, "excess option ");
- arg_print_option_ds(ds, shortopts, longopts, argval, "\n");
+ case EMAXCOUNT:
+ fputs("excess option ", fp);
+ arg_print_option(fp, shortopts, longopts, argval, "\n");
break;
}
}
-struct arg_str* arg_str0(const char* shortopts, const char* longopts, const char* datatype, const char* glossary) {
+
+struct arg_str *arg_str0(
+ const char *shortopts,
+ const char *longopts,
+ const char *datatype,
+ const char *glossary) {
return arg_strn(shortopts, longopts, datatype, 0, 1, glossary);
}
-struct arg_str* arg_str1(const char* shortopts, const char* longopts, const char* datatype, const char* glossary) {
+
+struct arg_str *arg_str1(
+ const char *shortopts,
+ const char *longopts,
+ const char *datatype,
+ const char *glossary) {
return arg_strn(shortopts, longopts, datatype, 1, 1, glossary);
}
-struct arg_str* arg_strn(const char* shortopts, const char* longopts, const char* datatype, int mincount, int maxcount, const char* glossary) {
+
+struct arg_str *arg_strn(
+ const char *shortopts,
+ const char *longopts,
+ const char *datatype,
+ int mincount,
+ int maxcount,
+ const char *glossary) {
size_t nbytes;
- struct arg_str* result;
- int i;
+ struct arg_str *result;
/* should not allow this stupid error */
/* we should return an error code warning this logic error */
/* foolproof things by ensuring maxcount is not less than mincount */
maxcount = (maxcount < mincount) ? mincount : maxcount;
- nbytes = sizeof(struct arg_str) /* storage for struct arg_str */
- + maxcount * sizeof(char*); /* storage for sval[maxcount] array */
+ nbytes = sizeof(struct arg_str) /* storage for struct arg_str */
+ + maxcount * sizeof(char *); /* storage for sval[maxcount] array */
- result = (struct arg_str*)xmalloc(nbytes);
+ result = (struct arg_str *)malloc(nbytes);
+ if (result) {
+ int i;
- /* init the arg_hdr struct */
- result->hdr.flag = ARG_HASVALUE;
- result->hdr.shortopts = shortopts;
- result->hdr.longopts = longopts;
- result->hdr.datatype = datatype ? datatype : "";
- result->hdr.glossary = glossary;
- result->hdr.mincount = mincount;
- result->hdr.maxcount = maxcount;
- result->hdr.parent = result;
- result->hdr.resetfn = (arg_resetfn*)arg_str_resetfn;
- result->hdr.scanfn = (arg_scanfn*)arg_str_scanfn;
- result->hdr.checkfn = (arg_checkfn*)arg_str_checkfn;
- result->hdr.errorfn = (arg_errorfn*)arg_str_errorfn;
+ /* init the arg_hdr struct */
+ result->hdr.flag = ARG_HASVALUE;
+ result->hdr.shortopts = shortopts;
+ result->hdr.longopts = longopts;
+ result->hdr.datatype = datatype ? datatype : "";
+ result->hdr.glossary = glossary;
+ result->hdr.mincount = mincount;
+ result->hdr.maxcount = maxcount;
+ result->hdr.parent = result;
+ result->hdr.resetfn = (arg_resetfn *)arg_str_resetfn;
+ result->hdr.scanfn = (arg_scanfn *)arg_str_scanfn;
+ result->hdr.checkfn = (arg_checkfn *)arg_str_checkfn;
+ result->hdr.errorfn = (arg_errorfn *)arg_str_errorfn;
- /* store the sval[maxcount] array immediately after the arg_str struct */
- result->sval = (const char**)(result + 1);
- result->count = 0;
+ /* store the sval[maxcount] array immediately after the arg_str struct */
+ result->sval = (const char * *)(result + 1);
+ result->count = 0;
- /* foolproof the string pointers by initializing them to reference empty strings */
- for (i = 0; i < maxcount; i++)
- result->sval[i] = "";
+ /* foolproof the string pointers by initialising them to reference empty strings */
+ for (i = 0; i < maxcount; i++)
+ result->sval[i] = "";
+ }
ARG_TRACE(("arg_strn() returns %p\n", result));
return result;
}
/*******************************************************************************
- * arg_cmd: Provides the sub-command mechanism
- *
- * This file is part of the argtable3 library.
- *
- * Copyright (C) 2013-2019 Tom G. Huang
- *
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * Neither the name of STEWART HEITMANN nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT,
- * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- ******************************************************************************/
-
-#include "argtable3.h"
-
-#ifndef ARG_AMALGAMATION
-#include "argtable3_private.h"
-#endif
-
-#include
-#include
-#include
-
-#define MAX_MODULE_VERSION_SIZE 128
-
-static arg_hashtable_t* s_hashtable = NULL;
-static char* s_module_name = NULL;
-static int s_mod_ver_major = 0;
-static int s_mod_ver_minor = 0;
-static int s_mod_ver_patch = 0;
-static char* s_mod_ver_tag = NULL;
-static char* s_mod_ver = NULL;
-
-void arg_set_module_name(const char* name) {
- size_t slen;
-
- xfree(s_module_name);
- slen = strlen(name);
- s_module_name = (char*)xmalloc(slen + 1);
- memset(s_module_name, 0, slen + 1);
-
-#if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || (defined(__STDC_SECURE_LIB__) && defined(__STDC_WANT_SECURE_LIB__))
- strncpy_s(s_module_name, slen + 1, name, slen);
-#else
- memcpy(s_module_name, name, slen);
-#endif
-}
-
-void arg_set_module_version(int major, int minor, int patch, const char* tag) {
- size_t slen_tag, slen_ds;
- arg_dstr_t ds;
-
- s_mod_ver_major = major;
- s_mod_ver_minor = minor;
- s_mod_ver_patch = patch;
-
- xfree(s_mod_ver_tag);
- slen_tag = strlen(tag);
- s_mod_ver_tag = (char*)xmalloc(slen_tag + 1);
- memset(s_mod_ver_tag, 0, slen_tag + 1);
-
-#if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || (defined(__STDC_SECURE_LIB__) && defined(__STDC_WANT_SECURE_LIB__))
- strncpy_s(s_mod_ver_tag, slen_tag + 1, tag, slen_tag);
-#else
- memcpy(s_mod_ver_tag, tag, slen_tag);
-#endif
-
- ds = arg_dstr_create();
- arg_dstr_catf(ds, "%d.", s_mod_ver_major);
- arg_dstr_catf(ds, "%d.", s_mod_ver_minor);
- arg_dstr_catf(ds, "%d.", s_mod_ver_patch);
- arg_dstr_cat(ds, s_mod_ver_tag);
-
- xfree(s_mod_ver);
- slen_ds = strlen(arg_dstr_cstr(ds));
- s_mod_ver = (char*)xmalloc(slen_ds + 1);
- memset(s_mod_ver, 0, slen_ds + 1);
-
-#if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || (defined(__STDC_SECURE_LIB__) && defined(__STDC_WANT_SECURE_LIB__))
- strncpy_s(s_mod_ver, slen_ds + 1, arg_dstr_cstr(ds), slen_ds);
-#else
- memcpy(s_mod_ver, arg_dstr_cstr(ds), slen_ds);
-#endif
-
- arg_dstr_destroy(ds);
-}
-
-static unsigned int hash_key(const void* key) {
- const char* str = (const char*)key;
- int c;
- unsigned int hash = 5381;
-
- while ((c = *str++) != 0)
- hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
-
- return hash;
-}
-
-static int equal_keys(const void* key1, const void* key2) {
- char* k1 = (char*)key1;
- char* k2 = (char*)key2;
- return (0 == strcmp(k1, k2));
-}
-
-void arg_cmd_init(void) {
- s_hashtable = arg_hashtable_create(32, hash_key, equal_keys);
-}
-
-void arg_cmd_uninit(void) {
- arg_hashtable_destroy(s_hashtable, 1);
-}
-
-void arg_cmd_register(const char* name, arg_cmdfn* proc, const char* description) {
- arg_cmd_info_t* cmd_info;
- size_t slen_name;
- void* k;
-
- assert(strlen(name) < ARG_CMD_NAME_LEN);
- assert(strlen(description) < ARG_CMD_DESCRIPTION_LEN);
-
- /* Check if the command already exists. */
- /* If the command exists, replace the existing command. */
- /* If the command doesn't exist, insert the command. */
- cmd_info = (arg_cmd_info_t*)arg_hashtable_search(s_hashtable, name);
- if (cmd_info) {
- arg_hashtable_remove(s_hashtable, name);
- cmd_info = NULL;
- }
-
- cmd_info = (arg_cmd_info_t*)xmalloc(sizeof(arg_cmd_info_t));
- memset(cmd_info, 0, sizeof(arg_cmd_info_t));
-
-#if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || (defined(__STDC_SECURE_LIB__) && defined(__STDC_WANT_SECURE_LIB__))
- strncpy_s(cmd_info->name, ARG_CMD_NAME_LEN, name, strlen(name));
- strncpy_s(cmd_info->description, ARG_CMD_DESCRIPTION_LEN, description, strlen(description));
-#else
- memcpy(cmd_info->name, name, strlen(name));
- memcpy(cmd_info->description, description, strlen(description));
-#endif
-
- cmd_info->proc = proc;
-
- slen_name = strlen(name);
- k = xmalloc(slen_name + 1);
- memset(k, 0, slen_name + 1);
-
-#if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || (defined(__STDC_SECURE_LIB__) && defined(__STDC_WANT_SECURE_LIB__))
- strncpy_s((char*)k, slen_name + 1, name, slen_name);
-#else
- memcpy((char*)k, name, slen_name);
-#endif
-
- arg_hashtable_insert(s_hashtable, k, cmd_info);
-}
-
-void arg_cmd_unregister(const char* name) {
- arg_hashtable_remove(s_hashtable, name);
-}
-
-int arg_cmd_dispatch(const char* name, int argc, char* argv[], arg_dstr_t res) {
- arg_cmd_info_t* cmd_info = arg_cmd_info(name);
-
- assert(cmd_info != NULL);
- assert(cmd_info->proc != NULL);
-
- return cmd_info->proc(argc, argv, res);
-}
-
-arg_cmd_info_t* arg_cmd_info(const char* name) {
- return (arg_cmd_info_t*)arg_hashtable_search(s_hashtable, name);
-}
-
-unsigned int arg_cmd_count(void) {
- return arg_hashtable_count(s_hashtable);
-}
-
-arg_cmd_itr_t arg_cmd_itr_create(void) {
- return (arg_cmd_itr_t)arg_hashtable_itr_create(s_hashtable);
-}
-
-int arg_cmd_itr_advance(arg_cmd_itr_t itr) {
- return arg_hashtable_itr_advance((arg_hashtable_itr_t*)itr);
-}
-
-char* arg_cmd_itr_key(arg_cmd_itr_t itr) {
- return (char*)arg_hashtable_itr_key((arg_hashtable_itr_t*)itr);
-}
-
-arg_cmd_info_t* arg_cmd_itr_value(arg_cmd_itr_t itr) {
- return (arg_cmd_info_t*)arg_hashtable_itr_value((arg_hashtable_itr_t*)itr);
-}
-
-void arg_cmd_itr_destroy(arg_cmd_itr_t itr) {
- arg_hashtable_itr_destroy((arg_hashtable_itr_t*)itr);
-}
-
-int arg_cmd_itr_search(arg_cmd_itr_t itr, void* k) {
- return arg_hashtable_itr_search((arg_hashtable_itr_t*)itr, s_hashtable, k);
-}
-
-static const char* module_name(void) {
- if (s_module_name == NULL || strlen(s_module_name) == 0)
- return "";
-
- return s_module_name;
-}
-
-static const char* module_version(void) {
- if (s_mod_ver == NULL || strlen(s_mod_ver) == 0)
- return "0.0.0.0";
-
- return s_mod_ver;
-}
-
-void arg_make_get_help_msg(arg_dstr_t res) {
- arg_dstr_catf(res, "%s v%s\n", module_name(), module_version());
- arg_dstr_catf(res, "Please type '%s help' to get more information.\n", module_name());
-}
-
-void arg_make_help_msg(arg_dstr_t ds, char* cmd_name, void** argtable) {
- arg_cmd_info_t* cmd_info = (arg_cmd_info_t*)arg_hashtable_search(s_hashtable, cmd_name);
- if (cmd_info) {
- arg_dstr_catf(ds, "%s: %s\n", cmd_name, cmd_info->description);
- }
-
- arg_dstr_cat(ds, "Usage:\n");
- arg_dstr_catf(ds, " %s", module_name());
-
- arg_print_syntaxv_ds(ds, argtable, "\n \nAvailable options:\n");
- arg_print_glossary_ds(ds, argtable, " %-23s %s\n");
-
- arg_dstr_cat(ds, "\n");
-}
-
-void arg_make_syntax_err_msg(arg_dstr_t ds, void** argtable, struct arg_end* end) {
- arg_print_errors_ds(ds, end, module_name());
- arg_dstr_cat(ds, "Usage: \n");
- arg_dstr_catf(ds, " %s", module_name());
- arg_print_syntaxv_ds(ds, argtable, "\n");
- arg_dstr_cat(ds, "\n");
-}
-
-int arg_make_syntax_err_help_msg(arg_dstr_t ds, char* name, int help, int nerrors, void** argtable, struct arg_end* end, int* exitcode) {
- /* help handling
- * note: '-h|--help' takes precedence over error reporting
- */
- if (help > 0) {
- arg_make_help_msg(ds, name, argtable);
- *exitcode = EXIT_SUCCESS;
- return 1;
- }
-
- /* syntax error handling */
- if (nerrors > 0) {
- arg_make_syntax_err_msg(ds, argtable, end);
- *exitcode = EXIT_FAILURE;
- return 1;
- }
-
- return 0;
-}
-/*******************************************************************************
- * argtable3: Implements the main interfaces of the library
- *
* This file is part of the argtable3 library.
*
* Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann
@@ -4823,26 +3646,18 @@ int arg_make_syntax_err_help_msg(arg_dstr_t ds, char* name, int help, int nerror
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
-#include "argtable3.h"
-
-#ifndef ARG_AMALGAMATION
-#include "argtable3_private.h"
-#include "getopt.h"
-#endif
-
-#ifdef _WIN32
-#define WIN32_LEAN_AND_MEAN
-#include
-#undef WIN32_LEAN_AND_MEAN
-#endif
-
-#include
-#include
-#include
#include
#include
+#include
+#include
-static void arg_register_error(struct arg_end* end, void* parent, int error, const char* argval) {
+#include "argtable3.h"
+
+static
+void arg_register_error(struct arg_end *end,
+ void *parent,
+ int error,
+ const char *argval) {
/* printf("arg_register_error(%p,%p,%d,%s)\n",end,parent,error,argval); */
if (end->count < end->hdr.maxcount) {
end->error[end->count] = error;
@@ -4850,20 +3665,22 @@ static void arg_register_error(struct arg_end* end, void* parent, int error, con
end->argval[end->count] = argval;
end->count++;
} else {
- end->error[end->hdr.maxcount - 1] = ARG_ELIMIT;
+ end->error[end->hdr.maxcount - 1] = ARG_ELIMIT;
end->parent[end->hdr.maxcount - 1] = end;
end->argval[end->hdr.maxcount - 1] = NULL;
}
}
+
/*
* Return index of first table entry with a matching short option
* or -1 if no match was found.
*/
-static int find_shortoption(struct arg_hdr** table, char shortopt) {
+static int find_shortoption(struct arg_hdr **table, char shortopt) {
int tabindex;
for (tabindex = 0; !(table[tabindex]->flag & ARG_TERMINATOR); tabindex++) {
- if (table[tabindex]->shortopts && strchr(table[tabindex]->shortopts, shortopt))
+ if (table[tabindex]->shortopts &&
+ strchr(table[tabindex]->shortopts, shortopt))
return tabindex;
}
return -1;
@@ -4872,18 +3689,16 @@ static int find_shortoption(struct arg_hdr** table, char shortopt) {
struct longoptions {
int getoptval;
int noptions;
- struct option* options;
+ struct option *options;
};
#if 0
static
-void dump_longoptions(struct longoptions * longoptions)
-{
+void dump_longoptions(struct longoptions *longoptions) {
int i;
printf("getoptval = %d\n", longoptions->getoptval);
printf("noptions = %d\n", longoptions->noptions);
- for (i = 0; i < longoptions->noptions; i++)
- {
+ for (i = 0; i < longoptions->noptions; i++) {
printf("options[%d].name = \"%s\"\n",
i,
longoptions->options[i].name);
@@ -4894,14 +3709,12 @@ void dump_longoptions(struct longoptions * longoptions)
}
#endif
-static struct longoptions* alloc_longoptions(struct arg_hdr** table) {
- struct longoptions* result;
+static struct longoptions *alloc_longoptions(struct arg_hdr **table) {
+ struct longoptions *result;
size_t nbytes;
int noptions = 1;
size_t longoptlen = 0;
int tabindex;
- int option_index = 0;
- char* store;
/*
* Determine the total number of option structs required
@@ -4915,7 +3728,7 @@ static struct longoptions* alloc_longoptions(struct arg_hdr** table) {
*/
tabindex = 0;
do {
- const char* longopts = table[tabindex]->longopts;
+ const char *longopts = table[tabindex]->longopts;
longoptlen += (longopts ? strlen(longopts) : 0) + 1;
while (longopts) {
noptions++;
@@ -4924,110 +3737,130 @@ static struct longoptions* alloc_longoptions(struct arg_hdr** table) {
} while (!(table[tabindex++]->flag & ARG_TERMINATOR));
/*printf("%d long options consuming %d chars in total\n",noptions,longoptlen);*/
+
/* allocate storage for return data structure as: */
/* (struct longoptions) + (struct options)[noptions] + char[longoptlen] */
- nbytes = sizeof(struct longoptions) + sizeof(struct option) * noptions + longoptlen;
- result = (struct longoptions*)xmalloc(nbytes);
+ nbytes = sizeof(struct longoptions)
+ + sizeof(struct option) * noptions
+ + longoptlen;
+ result = (struct longoptions *)malloc(nbytes);
+ if (result) {
+ int option_index = 0;
+ char *store;
- result->getoptval = 0;
- result->noptions = noptions;
- result->options = (struct option*)(result + 1);
- store = (char*)(result->options + noptions);
+ result->getoptval = 0;
+ result->noptions = noptions;
+ result->options = (struct option *)(result + 1);
+ store = (char *)(result->options + noptions);
- for (tabindex = 0; !(table[tabindex]->flag & ARG_TERMINATOR); tabindex++) {
- const char* longopts = table[tabindex]->longopts;
+ for (tabindex = 0; !(table[tabindex]->flag & ARG_TERMINATOR); tabindex++) {
+ const char *longopts = table[tabindex]->longopts;
- while (longopts && *longopts) {
- char* storestart = store;
+ while (longopts && *longopts) {
+ char *storestart = store;
- /* copy progressive longopt strings into the store */
- while (*longopts != 0 && *longopts != ',')
- *store++ = *longopts++;
- *store++ = 0;
- if (*longopts == ',')
- longopts++;
- /*fprintf(stderr,"storestart=\"%s\"\n",storestart);*/
+ /* copy progressive longopt strings into the store */
+ while (*longopts != 0 && *longopts != ',')
+ *store++ = *longopts++;
+ *store++ = 0;
+ if (*longopts == ',')
+ longopts++;
+ /*fprintf(stderr,"storestart=\"%s\"\n",storestart);*/
- result->options[option_index].name = storestart;
- result->options[option_index].flag = &(result->getoptval);
- result->options[option_index].val = tabindex;
- if (table[tabindex]->flag & ARG_HASOPTVALUE)
- result->options[option_index].has_arg = 2;
- else if (table[tabindex]->flag & ARG_HASVALUE)
- result->options[option_index].has_arg = 1;
- else
- result->options[option_index].has_arg = 0;
+ result->options[option_index].name = storestart;
+ result->options[option_index].flag = &(result->getoptval);
+ result->options[option_index].val = tabindex;
+ if (table[tabindex]->flag & ARG_HASOPTVALUE)
+ result->options[option_index].has_arg = 2;
+ else if (table[tabindex]->flag & ARG_HASVALUE)
+ result->options[option_index].has_arg = 1;
+ else
+ result->options[option_index].has_arg = 0;
- option_index++;
+ option_index++;
+ }
}
+ /* terminate the options array with a zero-filled entry */
+ result->options[option_index].name = 0;
+ result->options[option_index].has_arg = 0;
+ result->options[option_index].flag = 0;
+ result->options[option_index].val = 0;
}
- /* terminate the options array with a zero-filled entry */
- result->options[option_index].name = 0;
- result->options[option_index].has_arg = 0;
- result->options[option_index].flag = 0;
- result->options[option_index].val = 0;
/*dump_longoptions(result);*/
return result;
}
-static char* alloc_shortoptions(struct arg_hdr** table) {
- char* result;
+static char *alloc_shortoptions(struct arg_hdr **table) {
+ char *result;
size_t len = 2;
int tabindex;
- char* res;
/* determine the total number of option chars required */
for (tabindex = 0; !(table[tabindex]->flag & ARG_TERMINATOR); tabindex++) {
- struct arg_hdr* hdr = table[tabindex];
+ struct arg_hdr *hdr = table[tabindex];
len += 3 * (hdr->shortopts ? strlen(hdr->shortopts) : 0);
}
- result = xmalloc(len);
+ result = malloc(len);
+ if (result) {
+ char *res = result;
- res = result;
+ /* add a leading ':' so getopt return codes distinguish */
+ /* unrecognised option and options missing argument values */
+ *res++ = ':';
- /* add a leading ':' so getopt return codes distinguish */
- /* unrecognised option and options missing argument values */
- *res++ = ':';
-
- for (tabindex = 0; !(table[tabindex]->flag & ARG_TERMINATOR); tabindex++) {
- struct arg_hdr* hdr = table[tabindex];
- const char* shortopts = hdr->shortopts;
- while (shortopts && *shortopts) {
- *res++ = *shortopts++;
- if (hdr->flag & ARG_HASVALUE)
- *res++ = ':';
- if (hdr->flag & ARG_HASOPTVALUE)
- *res++ = ':';
+ for (tabindex = 0; !(table[tabindex]->flag & ARG_TERMINATOR); tabindex++) {
+ struct arg_hdr *hdr = table[tabindex];
+ const char *shortopts = hdr->shortopts;
+ while (shortopts && *shortopts) {
+ *res++ = *shortopts++;
+ if (hdr->flag & ARG_HASVALUE)
+ *res++ = ':';
+ if (hdr->flag & ARG_HASOPTVALUE)
+ *res++ = ':';
+ }
}
+ /* null terminate the string */
+ *res = 0;
}
- /* null terminate the string */
- *res = 0;
/*printf("alloc_shortoptions() returns \"%s\"\n",(result?result:"NULL"));*/
return result;
}
+
/* return index of the table terminator entry */
-static int arg_endindex(struct arg_hdr** table) {
+static int arg_endindex(struct arg_hdr **table) {
int tabindex = 0;
while (!(table[tabindex]->flag & ARG_TERMINATOR))
tabindex++;
return tabindex;
}
-static void arg_parse_tagged(int argc, char** argv, struct arg_hdr** table, struct arg_end* endtable) {
- struct longoptions* longoptions;
- char* shortoptions;
+
+static void arg_parse_tagged(int argc,
+ char **argv,
+ struct arg_hdr **table,
+ struct arg_end *endtable) {
+ struct longoptions *longoptions;
+ char *shortoptions;
int copt;
/*printf("arg_parse_tagged(%d,%p,%p,%p)\n",argc,argv,table,endtable);*/
/* allocate short and long option arrays for the given opttable[]. */
/* if the allocs fail then put an error msg in the last table entry. */
- longoptions = alloc_longoptions(table);
+ longoptions = alloc_longoptions(table);
shortoptions = alloc_shortoptions(table);
+ if (!longoptions || !shortoptions) {
+ /* one or both memory allocs failed */
+ arg_register_error(endtable, endtable, ARG_EMALLOC, NULL);
+ /* free anything that was allocated (this is null safe) */
+ free(shortoptions);
+ free(longoptions);
+ return;
+ }
/*dump_longoptions(longoptions);*/
@@ -5036,7 +3869,9 @@ static void arg_parse_tagged(int argc, char** argv, struct arg_hdr** table, stru
opterr = 0;
/* fetch and process args using getopt_long */
- while ((copt = getopt_long(argc, argv, shortoptions, longoptions->options, NULL)) != -1) {
+ while ((copt =
+ getopt_long(argc, argv, shortoptions, longoptions->options,
+ NULL)) != -1) {
/*
printf("optarg='%s'\n",optarg);
printf("optind=%d\n",optind);
@@ -5046,11 +3881,13 @@ static void arg_parse_tagged(int argc, char** argv, struct arg_hdr** table, stru
switch (copt) {
case 0: {
int tabindex = longoptions->getoptval;
- void* parent = table[tabindex]->parent;
+ void *parent = table[tabindex]->parent;
/*printf("long option detected from argtable[%d]\n", tabindex);*/
- if (optarg && optarg[0] == 0 && (table[tabindex]->flag & ARG_HASVALUE)) {
+ if (optarg && optarg[0] == 0 &&
+ (table[tabindex]->flag & ARG_HASVALUE)) {
/* printf(": long option %s requires an argument\n",argv[optind-1]); */
- arg_register_error(endtable, endtable, ARG_EMISSARG, argv[optind - 1]);
+ arg_register_error(endtable, endtable, ARG_EMISSARG,
+ argv[optind - 1]);
/* continue to scan the (empty) argument value to enforce argument count checking */
}
if (table[tabindex]->scanfn) {
@@ -5058,7 +3895,8 @@ static void arg_parse_tagged(int argc, char** argv, struct arg_hdr** table, stru
if (errorcode != 0)
arg_register_error(endtable, parent, errorcode, optarg);
}
- } break;
+ }
+ break;
case '?':
/*
@@ -5069,7 +3907,8 @@ static void arg_parse_tagged(int argc, char** argv, struct arg_hdr** table, stru
switch (optopt) {
case 0:
/*printf("?0 unrecognised long option %s\n",argv[optind-1]);*/
- arg_register_error(endtable, endtable, ARG_ELONGOPT, argv[optind - 1]);
+ arg_register_error(endtable, endtable, ARG_ELONGOPT,
+ argv[optind - 1]);
break;
default:
/*printf("?* unrecognised short option '%c'\n",optopt);*/
@@ -5083,7 +3922,8 @@ static void arg_parse_tagged(int argc, char** argv, struct arg_hdr** table, stru
* getopt_long() found an option with its argument missing.
*/
/*printf(": option %s requires an argument\n",argv[optind-1]); */
- arg_register_error(endtable, endtable, ARG_EMISSARG, argv[optind - 1]);
+ arg_register_error(endtable, endtable, ARG_EMISSARG,
+ argv[optind - 1]);
break;
default: {
@@ -5096,7 +3936,7 @@ static void arg_parse_tagged(int argc, char** argv, struct arg_hdr** table, stru
arg_register_error(endtable, endtable, copt, NULL);
} else {
if (table[tabindex]->scanfn) {
- void* parent = table[tabindex]->parent;
+ void *parent = table[tabindex]->parent;
int errorcode = table[tabindex]->scanfn(parent, optarg);
if (errorcode != 0)
arg_register_error(endtable, parent, errorcode, optarg);
@@ -5107,19 +3947,23 @@ static void arg_parse_tagged(int argc, char** argv, struct arg_hdr** table, stru
}
}
- xfree(shortoptions);
- xfree(longoptions);
+ free(shortoptions);
+ free(longoptions);
}
-static void arg_parse_untagged(int argc, char** argv, struct arg_hdr** table, struct arg_end* endtable) {
+
+static void arg_parse_untagged(int argc,
+ char **argv,
+ struct arg_hdr **table,
+ struct arg_end *endtable) {
int tabindex = 0;
int errorlast = 0;
- const char* optarglast = NULL;
- void* parentlast = NULL;
+ const char *optarglast = NULL;
+ void *parentlast = NULL;
/*printf("arg_parse_untagged(%d,%p,%p,%p)\n",argc,argv,table,endtable);*/
while (!(table[tabindex]->flag & ARG_TERMINATOR)) {
- void* parent;
+ void *parent;
int errorcode;
/* if we have exhausted our argv[optind] entries then we have finished */
@@ -5182,12 +4026,13 @@ static void arg_parse_untagged(int argc, char** argv, struct arg_hdr** table, st
return;
}
-static void arg_parse_check(struct arg_hdr** table, struct arg_end* endtable) {
+
+static void arg_parse_check(struct arg_hdr **table, struct arg_end *endtable) {
int tabindex = 0;
/* printf("arg_parse_check()\n"); */
do {
if (table[tabindex]->checkfn) {
- void* parent = table[tabindex]->parent;
+ void *parent = table[tabindex]->parent;
int errorcode = table[tabindex]->checkfn(parent);
if (errorcode != 0)
arg_register_error(endtable, parent, errorcode, NULL);
@@ -5195,8 +4040,9 @@ static void arg_parse_check(struct arg_hdr** table, struct arg_end* endtable) {
} while (!(table[tabindex++]->flag & ARG_TERMINATOR));
}
-static void arg_reset(void** argtable) {
- struct arg_hdr** table = (struct arg_hdr**)argtable;
+
+static void arg_reset(void **argtable) {
+ struct arg_hdr * *table = (struct arg_hdr * *)argtable;
int tabindex = 0;
/*printf("arg_reset(%p)\n",argtable);*/
do {
@@ -5205,12 +4051,12 @@ static void arg_reset(void** argtable) {
} while (!(table[tabindex++]->flag & ARG_TERMINATOR));
}
-int arg_parse(int argc, char** argv, void** argtable) {
- struct arg_hdr** table = (struct arg_hdr**)argtable;
- struct arg_end* endtable;
+
+int arg_parse(int argc, char * *argv, void * *argtable) {
+ struct arg_hdr * *table = (struct arg_hdr * *)argtable;
+ struct arg_end *endtable;
int endindex;
- char** argvcopy = NULL;
- int i;
+ char * *argvcopy = NULL;
/*printf("arg_parse(%d,%p,%p)\n",argc,argv,argtable);*/
@@ -5219,7 +4065,7 @@ int arg_parse(int argc, char** argv, void** argtable) {
/* locate the first end-of-table marker within the array */
endindex = arg_endindex(table);
- endtable = (struct arg_end*)table[endindex];
+ endtable = (struct arg_end *)table[endindex];
/* Special case of argc==0. This can occur on Texas Instruments DSP. */
/* Failure to trap this case results in an unwanted NULL result from */
@@ -5232,34 +4078,41 @@ int arg_parse(int argc, char** argv, void** argtable) {
return endtable->count;
}
- argvcopy = (char**)xmalloc(sizeof(char*) * (argc + 1));
+ argvcopy = (char **)malloc(sizeof(char *) * (argc + 1));
+ if (argvcopy) {
+ int i;
- /*
- Fill in the local copy of argv[]. We need a local copy
- because getopt rearranges argv[] which adversely affects
- susbsequent parsing attempts.
- */
- for (i = 0; i < argc; i++)
- argvcopy[i] = argv[i];
+ /*
+ Fill in the local copy of argv[]. We need a local copy
+ because getopt rearranges argv[] which adversely affects
+ susbsequent parsing attempts.
+ */
+ for (i = 0; i < argc; i++)
+ argvcopy[i] = argv[i];
- argvcopy[argc] = NULL;
+ argvcopy[argc] = NULL;
- /* parse the command line (local copy) for tagged options */
- arg_parse_tagged(argc, argvcopy, table, endtable);
+ /* parse the command line (local copy) for tagged options */
+ arg_parse_tagged(argc, argvcopy, table, endtable);
- /* parse the command line (local copy) for untagged options */
- arg_parse_untagged(argc, argvcopy, table, endtable);
+ /* parse the command line (local copy) for untagged options */
+ arg_parse_untagged(argc, argvcopy, table, endtable);
- /* if no errors so far then perform post-parse checks otherwise dont bother */
- if (endtable->count == 0)
- arg_parse_check(table, endtable);
+ /* if no errors so far then perform post-parse checks otherwise dont bother */
+ if (endtable->count == 0)
+ arg_parse_check(table, endtable);
- /* release the local copt of argv[] */
- xfree(argvcopy);
+ /* release the local copt of argv[] */
+ free(argvcopy);
+ } else {
+ /* memory alloc failed */
+ arg_register_error(endtable, endtable, ARG_EMALLOC, NULL);
+ }
return endtable->count;
}
+
/*
* Concatenate contents of src[] string onto *pdest[] string.
* The *pdest pointer is altered to point to the end of the
@@ -5280,9 +4133,9 @@ int arg_parse(int argc, char** argv, void** argtable) {
* dest[] == "goodbye cruel world!"
* ndest == 10
*/
-static void arg_cat(char** pdest, const char* src, size_t* pndest) {
- char* dest = *pdest;
- char* end = dest + *pndest;
+static void arg_cat(char **pdest, const char *src, size_t *pndest) {
+ char *dest = *pdest;
+ char *end = dest + *pndest;
/*locate null terminator of dest string */
while (dest < end && *dest != 0)
@@ -5297,10 +4150,16 @@ static void arg_cat(char** pdest, const char* src, size_t* pndest) {
/* update *pdest and *pndest */
*pndest = end - dest;
- *pdest = dest;
+ *pdest = dest;
}
-static void arg_cat_option(char* dest, size_t ndest, const char* shortopts, const char* longopts, const char* datatype, int optvalue) {
+
+static void arg_cat_option(char *dest,
+ size_t ndest,
+ const char *shortopts,
+ const char *longopts,
+ const char *datatype,
+ int optvalue) {
if (shortopts) {
char option[3];
@@ -5328,7 +4187,7 @@ static void arg_cat_option(char* dest, size_t ndest, const char* shortopts, cons
/* add comma separated option tag */
ncspn = strcspn(longopts, ",");
-#if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || (defined(__STDC_SECURE_LIB__) && defined(__STDC_WANT_SECURE_LIB__))
+#ifdef __STDC_WANT_SECURE_LIB__
strncat_s(dest, ndest, longopts, (ncspn < ndest) ? ncspn : ndest);
#else
strncat(dest, longopts, (ncspn < ndest) ? ncspn : ndest);
@@ -5353,12 +4212,17 @@ static void arg_cat_option(char* dest, size_t ndest, const char* shortopts, cons
}
}
-static void
-arg_cat_optionv(char* dest, size_t ndest, const char* shortopts, const char* longopts, const char* datatype, int optvalue, const char* separator) {
+static void arg_cat_optionv(char *dest,
+ size_t ndest,
+ const char *shortopts,
+ const char *longopts,
+ const char *datatype,
+ int optvalue,
+ const char *separator) {
separator = separator ? separator : "";
if (shortopts) {
- const char* c = shortopts;
+ const char *c = shortopts;
while (*c) {
/* "-a|-b|-c" */
char shortopt[3];
@@ -5380,7 +4244,7 @@ arg_cat_optionv(char* dest, size_t ndest, const char* shortopts, const char* lon
arg_cat(&dest, separator, &ndest);
if (longopts) {
- const char* c = longopts;
+ const char *c = longopts;
while (*c) {
size_t ncspn;
@@ -5389,7 +4253,7 @@ arg_cat_optionv(char* dest, size_t ndest, const char* shortopts, const char* lon
/* add comma separated option tag */
ncspn = strcspn(c, ",");
-#if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || (defined(__STDC_SECURE_LIB__) && defined(__STDC_WANT_SECURE_LIB__))
+#ifdef __STDC_WANT_SECURE_LIB__
strncat_s(dest, ndest, c, (ncspn < ndest) ? ncspn : ndest);
#else
strncat(dest, c, (ncspn < ndest) ? ncspn : ndest);
@@ -5419,38 +4283,46 @@ arg_cat_optionv(char* dest, size_t ndest, const char* shortopts, const char* lon
}
}
-void arg_print_option_ds(arg_dstr_t ds, const char* shortopts, const char* longopts, const char* datatype, const char* suffix) {
+
+/* this function should be deprecated because it doesnt consider optional argument values (ARG_HASOPTVALUE) */
+void arg_print_option(FILE *fp,
+ const char *shortopts,
+ const char *longopts,
+ const char *datatype,
+ const char *suffix) {
char syntax[200] = "";
suffix = suffix ? suffix : "";
/* there is no way of passing the proper optvalue for optional argument values here, so we must ignore it */
- arg_cat_optionv(syntax, sizeof(syntax), shortopts, longopts, datatype, 0, "|");
+ arg_cat_optionv(syntax,
+ sizeof(syntax),
+ shortopts,
+ longopts,
+ datatype,
+ 0,
+ "|");
- arg_dstr_cat(ds, syntax);
- arg_dstr_cat(ds, (char*)suffix);
+ fputs(syntax, fp);
+ fputs(suffix, fp);
}
-/* this function should be deprecated because it doesn't consider optional argument values (ARG_HASOPTVALUE) */
-void arg_print_option(FILE* fp, const char* shortopts, const char* longopts, const char* datatype, const char* suffix) {
- arg_dstr_t ds = arg_dstr_create();
- arg_print_option_ds(ds, shortopts, longopts, datatype, suffix);
- fputs(arg_dstr_cstr(ds), fp);
- arg_dstr_destroy(ds);
-}
/*
* Print a GNU style [OPTION] string in which all short options that
* do not take argument values are presented in abbreviated form, as
* in: -xvfsd, or -xvf[sd], or [-xvsfd]
*/
-static void arg_print_gnuswitch_ds(arg_dstr_t ds, struct arg_hdr** table) {
+static
+void arg_print_gnuswitch(FILE *fp, struct arg_hdr * *table) {
int tabindex;
- char* format1 = " -%c";
- char* format2 = " [-%c";
- char* suffix = "";
+ const char *format1 = " -%c";
+ const char *format2 = " [-%c";
+ const char *suffix = "";
/* print all mandatory switches that are without argument values */
- for (tabindex = 0; table[tabindex] && !(table[tabindex]->flag & ARG_TERMINATOR); tabindex++) {
+ for (tabindex = 0;
+ table[tabindex] && !(table[tabindex]->flag & ARG_TERMINATOR);
+ tabindex++) {
/* skip optional options */
if (table[tabindex]->mincount < 1)
continue;
@@ -5464,13 +4336,15 @@ static void arg_print_gnuswitch_ds(arg_dstr_t ds, struct arg_hdr** table) {
continue;
/* print the short option (only the first short option char, ignore multiple choices)*/
- arg_dstr_catf(ds, format1, table[tabindex]->shortopts[0]);
+ fprintf(fp, format1, table[tabindex]->shortopts[0]);
format1 = "%c";
format2 = "[%c";
}
/* print all optional switches that are without argument values */
- for (tabindex = 0; table[tabindex] && !(table[tabindex]->flag & ARG_TERMINATOR); tabindex++) {
+ for (tabindex = 0;
+ table[tabindex] && !(table[tabindex]->flag & ARG_TERMINATOR);
+ tabindex++) {
/* skip mandatory args */
if (table[tabindex]->mincount > 0)
continue;
@@ -5484,161 +4358,142 @@ static void arg_print_gnuswitch_ds(arg_dstr_t ds, struct arg_hdr** table) {
continue;
/* print first short option */
- arg_dstr_catf(ds, format2, table[tabindex]->shortopts[0]);
+ fprintf(fp, format2, table[tabindex]->shortopts[0]);
format2 = "%c";
suffix = "]";
}
- arg_dstr_catf(ds, "%s", suffix);
+ fprintf(fp, "%s", suffix);
}
-void arg_print_syntax_ds(arg_dstr_t ds, void** argtable, const char* suffix) {
- struct arg_hdr** table = (struct arg_hdr**)argtable;
+
+void arg_print_syntax(FILE *fp, void * *argtable, const char *suffix) {
+ struct arg_hdr * *table = (struct arg_hdr * *)argtable;
int i, tabindex;
/* print GNU style [OPTION] string */
- arg_print_gnuswitch_ds(ds, table);
+ arg_print_gnuswitch(fp, table);
/* print remaining options in abbreviated style */
- for (tabindex = 0; table[tabindex] && !(table[tabindex]->flag & ARG_TERMINATOR); tabindex++) {
+ for (tabindex = 0;
+ table[tabindex] && !(table[tabindex]->flag & ARG_TERMINATOR);
+ tabindex++) {
char syntax[200] = "";
const char *shortopts, *longopts, *datatype;
/* skip short options without arg values (they were printed by arg_print_gnu_switch) */
- if (table[tabindex]->shortopts && !(table[tabindex]->flag & ARG_HASVALUE))
+ if (table[tabindex]->shortopts &&
+ !(table[tabindex]->flag & ARG_HASVALUE))
continue;
shortopts = table[tabindex]->shortopts;
- longopts = table[tabindex]->longopts;
- datatype = table[tabindex]->datatype;
- arg_cat_option(syntax, sizeof(syntax), shortopts, longopts, datatype, table[tabindex]->flag & ARG_HASOPTVALUE);
+ longopts = table[tabindex]->longopts;
+ datatype = table[tabindex]->datatype;
+ arg_cat_option(syntax,
+ sizeof(syntax),
+ shortopts,
+ longopts,
+ datatype,
+ table[tabindex]->flag & ARG_HASOPTVALUE);
if (strlen(syntax) > 0) {
/* print mandatory instances of this option */
- for (i = 0; i < table[tabindex]->mincount; i++) {
- arg_dstr_cat(ds, " ");
- arg_dstr_cat(ds, syntax);
- }
+ for (i = 0; i < table[tabindex]->mincount; i++)
+ fprintf(fp, " %s", syntax);
/* print optional instances enclosed in "[..]" */
switch (table[tabindex]->maxcount - table[tabindex]->mincount) {
case 0:
break;
case 1:
- arg_dstr_cat(ds, " [");
- arg_dstr_cat(ds, syntax);
- arg_dstr_cat(ds, "]");
+ fprintf(fp, " [%s]", syntax);
break;
case 2:
- arg_dstr_cat(ds, " [");
- arg_dstr_cat(ds, syntax);
- arg_dstr_cat(ds, "]");
- arg_dstr_cat(ds, " [");
- arg_dstr_cat(ds, syntax);
- arg_dstr_cat(ds, "]");
+ fprintf(fp, " [%s] [%s]", syntax, syntax);
break;
default:
- arg_dstr_cat(ds, " [");
- arg_dstr_cat(ds, syntax);
- arg_dstr_cat(ds, "]...");
+ fprintf(fp, " [%s]...", syntax);
break;
}
}
}
- if (suffix) {
- arg_dstr_cat(ds, (char*)suffix);
- }
+ if (suffix)
+ fprintf(fp, "%s", suffix);
}
-void arg_print_syntax(FILE* fp, void** argtable, const char* suffix) {
- arg_dstr_t ds = arg_dstr_create();
- arg_print_syntax_ds(ds, argtable, suffix);
- fputs(arg_dstr_cstr(ds), fp);
- arg_dstr_destroy(ds);
-}
-void arg_print_syntaxv_ds(arg_dstr_t ds, void** argtable, const char* suffix) {
- struct arg_hdr** table = (struct arg_hdr**)argtable;
+void arg_print_syntaxv(FILE *fp, void * *argtable, const char *suffix) {
+ struct arg_hdr * *table = (struct arg_hdr * *)argtable;
int i, tabindex;
/* print remaining options in abbreviated style */
- for (tabindex = 0; table[tabindex] && !(table[tabindex]->flag & ARG_TERMINATOR); tabindex++) {
+ for (tabindex = 0;
+ table[tabindex] && !(table[tabindex]->flag & ARG_TERMINATOR);
+ tabindex++) {
char syntax[200] = "";
const char *shortopts, *longopts, *datatype;
shortopts = table[tabindex]->shortopts;
- longopts = table[tabindex]->longopts;
- datatype = table[tabindex]->datatype;
- arg_cat_optionv(syntax, sizeof(syntax), shortopts, longopts, datatype, table[tabindex]->flag & ARG_HASOPTVALUE, "|");
+ longopts = table[tabindex]->longopts;
+ datatype = table[tabindex]->datatype;
+ arg_cat_optionv(syntax,
+ sizeof(syntax),
+ shortopts,
+ longopts,
+ datatype,
+ table[tabindex]->flag & ARG_HASOPTVALUE,
+ "|");
/* print mandatory options */
- for (i = 0; i < table[tabindex]->mincount; i++) {
- arg_dstr_cat(ds, " ");
- arg_dstr_cat(ds, syntax);
- }
+ for (i = 0; i < table[tabindex]->mincount; i++)
+ fprintf(fp, " %s", syntax);
/* print optional args enclosed in "[..]" */
switch (table[tabindex]->maxcount - table[tabindex]->mincount) {
case 0:
break;
case 1:
- arg_dstr_cat(ds, " [");
- arg_dstr_cat(ds, syntax);
- arg_dstr_cat(ds, "]");
+ fprintf(fp, " [%s]", syntax);
break;
case 2:
- arg_dstr_cat(ds, " [");
- arg_dstr_cat(ds, syntax);
- arg_dstr_cat(ds, "]");
- arg_dstr_cat(ds, " [");
- arg_dstr_cat(ds, syntax);
- arg_dstr_cat(ds, "]");
+ fprintf(fp, " [%s] [%s]", syntax, syntax);
break;
default:
- arg_dstr_cat(ds, " [");
- arg_dstr_cat(ds, syntax);
- arg_dstr_cat(ds, "]...");
+ fprintf(fp, " [%s]...", syntax);
break;
}
}
- if (suffix) {
- arg_dstr_cat(ds, (char*)suffix);
- }
+ if (suffix)
+ fprintf(fp, "%s", suffix);
}
-void arg_print_syntaxv(FILE* fp, void** argtable, const char* suffix) {
- arg_dstr_t ds = arg_dstr_create();
- arg_print_syntaxv_ds(ds, argtable, suffix);
- fputs(arg_dstr_cstr(ds), fp);
- arg_dstr_destroy(ds);
-}
-void arg_print_glossary_ds(arg_dstr_t ds, void** argtable, const char* format) {
- struct arg_hdr** table = (struct arg_hdr**)argtable;
+void arg_print_glossary(FILE *fp, void * *argtable, const char *format) {
+ struct arg_hdr * *table = (struct arg_hdr * *)argtable;
int tabindex;
format = format ? format : " %-20s %s\n";
for (tabindex = 0; !(table[tabindex]->flag & ARG_TERMINATOR); tabindex++) {
if (table[tabindex]->glossary) {
char syntax[200] = "";
- const char* shortopts = table[tabindex]->shortopts;
- const char* longopts = table[tabindex]->longopts;
- const char* datatype = table[tabindex]->datatype;
- const char* glossary = table[tabindex]->glossary;
- arg_cat_optionv(syntax, sizeof(syntax), shortopts, longopts, datatype, table[tabindex]->flag & ARG_HASOPTVALUE, ", ");
- arg_dstr_catf(ds, format, syntax, glossary);
+ const char *shortopts = table[tabindex]->shortopts;
+ const char *longopts = table[tabindex]->longopts;
+ const char *datatype = table[tabindex]->datatype;
+ const char *glossary = table[tabindex]->glossary;
+ arg_cat_optionv(syntax,
+ sizeof(syntax),
+ shortopts,
+ longopts,
+ datatype,
+ table[tabindex]->flag & ARG_HASOPTVALUE,
+ ", ");
+ fprintf(fp, format, syntax, glossary);
}
}
}
-void arg_print_glossary(FILE* fp, void** argtable, const char* format) {
- arg_dstr_t ds = arg_dstr_create();
- arg_print_glossary_ds(ds, argtable, format);
- fputs(arg_dstr_cstr(ds), fp);
- arg_dstr_destroy(ds);
-}
/**
* Print a piece of text formatted, which means in a column with a
@@ -5672,62 +4527,62 @@ void arg_print_glossary(FILE* fp, void** argtable, const char* format) {
*
* Author: Uli Fouquet
*/
-static void arg_print_formatted_ds(arg_dstr_t ds, const unsigned lmargin, const unsigned rmargin, const char* text) {
- const unsigned int textlen = (unsigned int)strlen(text);
- unsigned int line_start = 0;
- unsigned int line_end = textlen;
- const unsigned int colwidth = (rmargin - lmargin) + 1;
-
- assert(strlen(text) < UINT_MAX);
+static
+void arg_print_formatted(FILE *fp,
+ const unsigned lmargin,
+ const unsigned rmargin,
+ const char *text) {
+ const unsigned textlen = (unsigned)strlen(text);
+ unsigned line_start = 0;
+ unsigned line_end = textlen + 1;
+ const unsigned colwidth = (rmargin - lmargin) + 1;
/* Someone doesn't like us... */
- if (line_end < line_start) {
- arg_dstr_catf(ds, "%s\n", text);
+ if (line_end == line_start) {
+ fprintf(fp, "%s\n", text);
}
- while (line_end > line_start) {
- /* Eat leading white spaces. This is essential because while
+ while (line_end - 1 > line_start) {
+ /* Eat leading whitespaces. This is essential because while
wrapping lines, there will often be a whitespace at beginning
of line */
- while (isspace(*(text + line_start))) {
- line_start++;
- }
+ while (ISSPACE(*(text + line_start)))
+ { line_start++; }
+
+ if ((line_end - line_start) > colwidth)
+ { line_end = line_start + colwidth; }
/* Find last whitespace, that fits into line */
- if (line_end - line_start > colwidth) {
- line_end = line_start + colwidth;
+ while ((line_end > line_start)
+ && (line_end - line_start > colwidth)
+ && !ISSPACE(*(text + line_end)))
+ { line_end--; }
- while ((line_end > line_start) && !isspace(*(text + line_end))) {
- line_end--;
- }
-
- /* Consume trailing spaces */
- while ((line_end > line_start) && isspace(*(text + line_end))) {
- line_end--;
- }
-
- /* Restore the last non-space character */
- line_end++;
- }
+ /* Do not print trailing whitespace. If this text
+ has got only one line, line_end now points to the
+ last char due to initialization. */
+ line_end--;
/* Output line of text */
while (line_start < line_end) {
- char c = *(text + line_start);
- arg_dstr_catc(ds, c);
+ fputc(*(text + line_start), fp);
line_start++;
}
- arg_dstr_cat(ds, "\n");
+ fputc('\n', fp);
/* Initialize another line */
- if (line_end < textlen) {
+ if (line_end + 1 < textlen) {
unsigned i;
- for (i = 0; i < lmargin; i++) {
- arg_dstr_cat(ds, " ");
- }
+ for (i = 0; i < lmargin; i++)
+ { fputc(' ', fp); }
line_end = textlen;
}
+
+ /* If we have to print another line, get also the last char. */
+ line_end++;
+
} /* lines of text */
}
@@ -5740,17 +4595,17 @@ static void arg_print_formatted_ds(arg_dstr_t ds, const unsigned lmargin, const
*
* Contributed by Uli Fouquet
*/
-void arg_print_glossary_gnu_ds(arg_dstr_t ds, void** argtable) {
- struct arg_hdr** table = (struct arg_hdr**)argtable;
+void arg_print_glossary_gnu(FILE *fp, void * *argtable) {
+ struct arg_hdr * *table = (struct arg_hdr * *)argtable;
int tabindex;
for (tabindex = 0; !(table[tabindex]->flag & ARG_TERMINATOR); tabindex++) {
if (table[tabindex]->glossary) {
char syntax[200] = "";
- const char* shortopts = table[tabindex]->shortopts;
- const char* longopts = table[tabindex]->longopts;
- const char* datatype = table[tabindex]->datatype;
- const char* glossary = table[tabindex]->glossary;
+ const char *shortopts = table[tabindex]->shortopts;
+ const char *longopts = table[tabindex]->longopts;
+ const char *datatype = table[tabindex]->datatype;
+ const char *glossary = table[tabindex]->glossary;
if (!shortopts && longopts) {
/* Indent trailing line by 4 spaces... */
@@ -5758,35 +4613,35 @@ void arg_print_glossary_gnu_ds(arg_dstr_t ds, void** argtable) {
*(syntax + 4) = '\0';
}
- arg_cat_optionv(syntax, sizeof(syntax), shortopts, longopts, datatype, table[tabindex]->flag & ARG_HASOPTVALUE, ", ");
+ arg_cat_optionv(syntax,
+ sizeof(syntax),
+ shortopts,
+ longopts,
+ datatype,
+ table[tabindex]->flag & ARG_HASOPTVALUE,
+ ", ");
/* If syntax fits not into column, print glossary in new line... */
if (strlen(syntax) > 25) {
- arg_dstr_catf(ds, " %-25s %s\n", syntax, "");
+ fprintf(fp, " %-25s %s\n", syntax, "");
*syntax = '\0';
}
- arg_dstr_catf(ds, " %-25s ", syntax);
- arg_print_formatted_ds(ds, 28, 79, glossary);
+ fprintf(fp, " %-25s ", syntax);
+ arg_print_formatted(fp, 28, 79, glossary);
}
} /* for each table entry */
- arg_dstr_cat(ds, "\n");
+ fputc('\n', fp);
}
-void arg_print_glossary_gnu(FILE* fp, void** argtable) {
- arg_dstr_t ds = arg_dstr_create();
- arg_print_glossary_gnu_ds(ds, argtable);
- fputs(arg_dstr_cstr(ds), fp);
- arg_dstr_destroy(ds);
-}
/**
* Checks the argtable[] array for NULL entries and returns 1
* if any are found, zero otherwise.
*/
-int arg_nullcheck(void** argtable) {
- struct arg_hdr** table = (struct arg_hdr**)argtable;
+int arg_nullcheck(void * *argtable) {
+ struct arg_hdr * *table = (struct arg_hdr * *)argtable;
int tabindex;
/*printf("arg_nullcheck(%p)\n",argtable);*/
@@ -5814,8 +4669,8 @@ int arg_nullcheck(void** argtable) {
* with the newer arg_freetable() function.
* We still keep arg_free() for backwards compatibility.
*/
-void arg_free(void** argtable) {
- struct arg_hdr** table = (struct arg_hdr**)argtable;
+void arg_free(void * *argtable) {
+ struct arg_hdr * *table = (struct arg_hdr * *)argtable;
int tabindex = 0;
int flag;
/*printf("arg_free(%p)\n",argtable);*/
@@ -5830,31 +4685,23 @@ void arg_free(void** argtable) {
break;
flag = table[tabindex]->flag;
- xfree(table[tabindex]);
+ free(table[tabindex]);
table[tabindex++] = NULL;
} while (!(flag & ARG_TERMINATOR));
}
/* frees each non-NULL element of argtable[], where n is the size of the number of entries in the array */
-void arg_freetable(void** argtable, size_t n) {
- struct arg_hdr** table = (struct arg_hdr**)argtable;
+void arg_freetable(void * *argtable, size_t n) {
+ struct arg_hdr * *table = (struct arg_hdr * *)argtable;
size_t tabindex = 0;
/*printf("arg_freetable(%p)\n",argtable);*/
for (tabindex = 0; tabindex < n; tabindex++) {
if (table[tabindex] == NULL)
continue;
- xfree(table[tabindex]);
+ free(table[tabindex]);
table[tabindex] = NULL;
};
}
-#ifdef _WIN32
-BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) {
- return TRUE;
- UNREFERENCED_PARAMETER(hinstDLL);
- UNREFERENCED_PARAMETER(fdwReason);
- UNREFERENCED_PARAMETER(lpvReserved);
-}
-#endif
diff --git a/client/deps/cliparser/argtable3.h b/client/deps/cliparser/argtable3.h
index 204253876..d8e3c53cc 100644
--- a/client/deps/cliparser/argtable3.h
+++ b/client/deps/cliparser/argtable3.h
@@ -33,8 +33,8 @@
#ifndef ARGTABLE3
#define ARGTABLE3
-#include /* FILE */
-#include /* struct tm */
+#include /* FILE */
+#include /* struct tm */
#ifdef __cplusplus
extern "C" {
@@ -50,226 +50,259 @@ extern "C" {
#endif /* ARG_REPLACE_GETOPT */
/* bit masks for arg_hdr.flag */
-enum { ARG_TERMINATOR = 0x1, ARG_HASVALUE = 0x2, ARG_HASOPTVALUE = 0x4 };
+enum {
+ ARG_TERMINATOR = 0x1,
+ ARG_HASVALUE = 0x2,
+ ARG_HASOPTVALUE = 0x4
+};
-#if defined(_WIN32)
- #if defined(argtable3_EXPORTS)
- #define ARG_EXTERN __declspec(dllexport)
- #elif defined(argtable3_IMPORTS)
- #define ARG_EXTERN __declspec(dllimport)
- #else
- #define ARG_EXTERN
- #endif
-#else
- #define ARG_EXTERN
-#endif
+typedef void (arg_resetfn)(void *parent);
+typedef int (arg_scanfn)(void *parent, const char *argval);
+typedef int (arg_checkfn)(void *parent);
+typedef void (arg_errorfn)(void *parent, FILE *fp, int error, const char *argval, const char *progname);
-typedef struct _internal_arg_dstr* arg_dstr_t;
-typedef void* arg_cmd_itr_t;
-
-typedef void(arg_resetfn)(void* parent);
-typedef int(arg_scanfn)(void* parent, const char* argval);
-typedef int(arg_checkfn)(void* parent);
-typedef void(arg_errorfn)(void* parent, arg_dstr_t ds, int error, const char* argval, const char* progname);
-typedef void(arg_dstr_freefn)(char* buf);
-typedef int(arg_cmdfn)(int argc, char* argv[], arg_dstr_t res);
-typedef int(arg_comparefn)(const void* k1, const void* k2);
/*
- * The arg_hdr struct defines properties that are common to all arg_xxx structs.
- * The argtable library requires each arg_xxx struct to have an arg_hdr
- * struct as its first data member.
- * The argtable library functions then use this data to identify the
- * properties of the command line option, such as its option tags,
- * datatype string, and glossary strings, and so on.
- * Moreover, the arg_hdr struct contains pointers to custom functions that
- * are provided by each arg_xxx struct which perform the tasks of parsing
- * that particular arg_xxx arguments, performing post-parse checks, and
- * reporting errors.
- * These functions are private to the individual arg_xxx source code
- * and are the pointer to them are initiliased by that arg_xxx struct's
- * constructor function. The user could alter them after construction
- * if desired, but the original intention is for them to be set by the
- * constructor and left unaltered.
- */
+* The arg_hdr struct defines properties that are common to all arg_xxx structs.
+* The argtable library requires each arg_xxx struct to have an arg_hdr
+* struct as its first data member.
+* The argtable library functions then use this data to identify the
+* properties of the command line option, such as its option tags,
+* datatype string, and glossary strings, and so on.
+* Moreover, the arg_hdr struct contains pointers to custom functions that
+* are provided by each arg_xxx struct which perform the tasks of parsing
+* that particular arg_xxx arguments, performing post-parse checks, and
+* reporting errors.
+* These functions are private to the individual arg_xxx source code
+* and are the pointer to them are initiliased by that arg_xxx struct's
+* constructor function. The user could alter them after construction
+* if desired, but the original intention is for them to be set by the
+* constructor and left unaltered.
+*/
struct arg_hdr {
- char flag; /* Modifier flags: ARG_TERMINATOR, ARG_HASVALUE. */
- const char* shortopts; /* String defining the short options */
- const char* longopts; /* String defiing the long options */
- const char* datatype; /* Description of the argument data type */
- const char* glossary; /* Description of the option as shown by arg_print_glossary function */
- int mincount; /* Minimum number of occurences of this option accepted */
- int maxcount; /* Maximum number of occurences if this option accepted */
- void* parent; /* Pointer to parent arg_xxx struct */
- arg_resetfn* resetfn; /* Pointer to parent arg_xxx reset function */
- arg_scanfn* scanfn; /* Pointer to parent arg_xxx scan function */
- arg_checkfn* checkfn; /* Pointer to parent arg_xxx check function */
- arg_errorfn* errorfn; /* Pointer to parent arg_xxx error function */
- void* priv; /* Pointer to private header data for use by arg_xxx functions */
+ char flag; /* Modifier flags: ARG_TERMINATOR, ARG_HASVALUE. */
+ const char *shortopts; /* String defining the short options */
+ const char *longopts; /* String defiing the long options */
+ const char *datatype; /* Description of the argument data type */
+ const char *glossary; /* Description of the option as shown by arg_print_glossary function */
+ int mincount; /* Minimum number of occurences of this option accepted */
+ int maxcount; /* Maximum number of occurences if this option accepted */
+ void *parent; /* Pointer to parent arg_xxx struct */
+ arg_resetfn *resetfn; /* Pointer to parent arg_xxx reset function */
+ arg_scanfn *scanfn; /* Pointer to parent arg_xxx scan function */
+ arg_checkfn *checkfn; /* Pointer to parent arg_xxx check function */
+ arg_errorfn *errorfn; /* Pointer to parent arg_xxx error function */
+ void *priv; /* Pointer to private header data for use by arg_xxx functions */
};
struct arg_rem {
- struct arg_hdr hdr; /* The mandatory argtable header struct */
+ struct arg_hdr hdr; /* The mandatory argtable header struct */
};
struct arg_lit {
- struct arg_hdr hdr; /* The mandatory argtable header struct */
- int count; /* Number of matching command line args */
+ struct arg_hdr hdr; /* The mandatory argtable header struct */
+ int count; /* Number of matching command line args */
};
struct arg_int {
- struct arg_hdr hdr; /* The mandatory argtable header struct */
- int count; /* Number of matching command line args */
- int* ival; /* Array of parsed argument values */
+ struct arg_hdr hdr; /* The mandatory argtable header struct */
+ int count; /* Number of matching command line args */
+ int *ival; /* Array of parsed argument values */
};
struct arg_dbl {
- struct arg_hdr hdr; /* The mandatory argtable header struct */
- int count; /* Number of matching command line args */
- double* dval; /* Array of parsed argument values */
+ struct arg_hdr hdr; /* The mandatory argtable header struct */
+ int count; /* Number of matching command line args */
+ double *dval; /* Array of parsed argument values */
};
struct arg_str {
- struct arg_hdr hdr; /* The mandatory argtable header struct */
- int count; /* Number of matching command line args */
- const char** sval; /* Array of parsed argument values */
+ struct arg_hdr hdr; /* The mandatory argtable header struct */
+ int count; /* Number of matching command line args */
+ const char **sval; /* Array of parsed argument values */
};
struct arg_rex {
- struct arg_hdr hdr; /* The mandatory argtable header struct */
- int count; /* Number of matching command line args */
- const char** sval; /* Array of parsed argument values */
+ struct arg_hdr hdr; /* The mandatory argtable header struct */
+ int count; /* Number of matching command line args */
+ const char **sval; /* Array of parsed argument values */
};
struct arg_file {
- struct arg_hdr hdr; /* The mandatory argtable header struct */
- int count; /* Number of matching command line args*/
- const char** filename; /* Array of parsed filenames (eg: /home/foo.bar) */
- const char** basename; /* Array of parsed basenames (eg: foo.bar) */
- const char** extension; /* Array of parsed extensions (eg: .bar) */
+ struct arg_hdr hdr; /* The mandatory argtable header struct */
+ int count; /* Number of matching command line args*/
+ const char **filename; /* Array of parsed filenames (eg: /home/foo.bar) */
+ const char **basename; /* Array of parsed basenames (eg: foo.bar) */
+ const char **extension; /* Array of parsed extensions (eg: .bar) */
};
struct arg_date {
- struct arg_hdr hdr; /* The mandatory argtable header struct */
- const char* format; /* strptime format string used to parse the date */
- int count; /* Number of matching command line args */
- struct tm* tmval; /* Array of parsed time values */
+ struct arg_hdr hdr; /* The mandatory argtable header struct */
+ const char *format; /* strptime format string used to parse the date */
+ int count; /* Number of matching command line args */
+ struct tm *tmval; /* Array of parsed time values */
};
-enum { ARG_ELIMIT = 1, ARG_EMALLOC, ARG_ENOMATCH, ARG_ELONGOPT, ARG_EMISSARG };
+enum {ARG_ELIMIT = 1, ARG_EMALLOC, ARG_ENOMATCH, ARG_ELONGOPT, ARG_EMISSARG};
struct arg_end {
- struct arg_hdr hdr; /* The mandatory argtable header struct */
- int count; /* Number of errors encountered */
- int* error; /* Array of error codes */
- void** parent; /* Array of pointers to offending arg_xxx struct */
- const char** argval; /* Array of pointers to offending argv[] string */
+ struct arg_hdr hdr; /* The mandatory argtable header struct */
+ int count; /* Number of errors encountered */
+ int *error; /* Array of error codes */
+ void **parent; /* Array of pointers to offending arg_xxx struct */
+ const char **argval; /* Array of pointers to offending argv[] string */
};
+/*
typedef struct arg_cmd_info {
char name[ARG_CMD_NAME_LEN];
char description[ARG_CMD_DESCRIPTION_LEN];
arg_cmdfn* proc;
} arg_cmd_info_t;
+*/
/**** arg_xxx constructor functions *********************************/
-ARG_EXTERN struct arg_rem* arg_rem(const char* datatype, const char* glossary);
+struct arg_rem *arg_rem(const char *datatype, const char *glossary);
-ARG_EXTERN struct arg_lit* arg_lit0(const char* shortopts, const char* longopts, const char* glossary);
-ARG_EXTERN struct arg_lit* arg_lit1(const char* shortopts, const char* longopts, const char* glossary);
-ARG_EXTERN struct arg_lit* arg_litn(const char* shortopts, const char* longopts, int mincount, int maxcount, const char* glossary);
+struct arg_lit *arg_lit0(const char *shortopts,
+ const char *longopts,
+ const char *glossary);
+struct arg_lit *arg_lit1(const char *shortopts,
+ const char *longopts,
+ const char *glossary);
+struct arg_lit *arg_litn(const char *shortopts,
+ const char *longopts,
+ int mincount,
+ int maxcount,
+ const char *glossary);
-ARG_EXTERN struct arg_key* arg_key0(const char* keyword, int flags, const char* glossary);
-ARG_EXTERN struct arg_key* arg_key1(const char* keyword, int flags, const char* glossary);
-ARG_EXTERN struct arg_key* arg_keyn(const char* keyword, int flags, int mincount, int maxcount, const char* glossary);
+struct arg_key *arg_key0(const char *keyword,
+ int flags,
+ const char *glossary);
+struct arg_key *arg_key1(const char *keyword,
+ int flags,
+ const char *glossary);
+struct arg_key *arg_keyn(const char *keyword,
+ int flags,
+ int mincount,
+ int maxcount,
+ const char *glossary);
-ARG_EXTERN struct arg_int* arg_int0(const char* shortopts, const char* longopts, const char* datatype, const char* glossary);
-ARG_EXTERN struct arg_int* arg_int1(const char* shortopts, const char* longopts, const char* datatype, const char* glossary);
-ARG_EXTERN struct arg_int* arg_intn(const char* shortopts, const char* longopts, const char* datatype, int mincount, int maxcount, const char* glossary);
+struct arg_int *arg_int0(const char *shortopts,
+ const char *longopts,
+ const char *datatype,
+ const char *glossary);
+struct arg_int *arg_int1(const char *shortopts,
+ const char *longopts,
+ const char *datatype,
+ const char *glossary);
+struct arg_int *arg_intn(const char *shortopts,
+ const char *longopts,
+ const char *datatype,
+ int mincount,
+ int maxcount,
+ const char *glossary);
-ARG_EXTERN struct arg_dbl* arg_dbl0(const char* shortopts, const char* longopts, const char* datatype, const char* glossary);
-ARG_EXTERN struct arg_dbl* arg_dbl1(const char* shortopts, const char* longopts, const char* datatype, const char* glossary);
-ARG_EXTERN struct arg_dbl* arg_dbln(const char* shortopts, const char* longopts, const char* datatype, int mincount, int maxcount, const char* glossary);
+struct arg_dbl *arg_dbl0(const char *shortopts,
+ const char *longopts,
+ const char *datatype,
+ const char *glossary);
+struct arg_dbl *arg_dbl1(const char *shortopts,
+ const char *longopts,
+ const char *datatype,
+ const char *glossary);
+struct arg_dbl *arg_dbln(const char *shortopts,
+ const char *longopts,
+ const char *datatype,
+ int mincount,
+ int maxcount,
+ const char *glossary);
-ARG_EXTERN struct arg_str* arg_str0(const char* shortopts, const char* longopts, const char* datatype, const char* glossary);
-ARG_EXTERN struct arg_str* arg_str1(const char* shortopts, const char* longopts, const char* datatype, const char* glossary);
-ARG_EXTERN struct arg_str* arg_strn(const char* shortopts, const char* longopts, const char* datatype, int mincount, int maxcount, const char* glossary);
+struct arg_str *arg_str0(const char *shortopts,
+ const char *longopts,
+ const char *datatype,
+ const char *glossary);
+struct arg_str *arg_str1(const char *shortopts,
+ const char *longopts,
+ const char *datatype,
+ const char *glossary);
+struct arg_str *arg_strn(const char *shortopts,
+ const char *longopts,
+ const char *datatype,
+ int mincount,
+ int maxcount,
+ const char *glossary);
-ARG_EXTERN struct arg_rex* arg_rex0(const char* shortopts, const char* longopts, const char* pattern, const char* datatype, int flags, const char* glossary);
-ARG_EXTERN struct arg_rex* arg_rex1(const char* shortopts, const char* longopts, const char* pattern, const char* datatype, int flags, const char* glossary);
-ARG_EXTERN struct arg_rex* arg_rexn(const char* shortopts,
- const char* longopts,
- const char* pattern,
- const char* datatype,
+struct arg_rex *arg_rex0(const char *shortopts,
+ const char *longopts,
+ const char *pattern,
+ const char *datatype,
+ int flags,
+ const char *glossary);
+struct arg_rex *arg_rex1(const char *shortopts,
+ const char *longopts,
+ const char *pattern,
+ const char *datatype,
+ int flags,
+ const char *glossary);
+struct arg_rex *arg_rexn(const char *shortopts,
+ const char *longopts,
+ const char *pattern,
+ const char *datatype,
int mincount,
int maxcount,
int flags,
- const char* glossary);
+ const char *glossary);
-ARG_EXTERN struct arg_file* arg_file0(const char* shortopts, const char* longopts, const char* datatype, const char* glossary);
-ARG_EXTERN struct arg_file* arg_file1(const char* shortopts, const char* longopts, const char* datatype, const char* glossary);
-ARG_EXTERN struct arg_file* arg_filen(const char* shortopts, const char* longopts, const char* datatype, int mincount, int maxcount, const char* glossary);
+struct arg_file *arg_file0(const char *shortopts,
+ const char *longopts,
+ const char *datatype,
+ const char *glossary);
+struct arg_file *arg_file1(const char *shortopts,
+ const char *longopts,
+ const char *datatype,
+ const char *glossary);
+struct arg_file *arg_filen(const char *shortopts,
+ const char *longopts,
+ const char *datatype,
+ int mincount,
+ int maxcount,
+ const char *glossary);
-ARG_EXTERN struct arg_date* arg_date0(const char* shortopts, const char* longopts, const char* format, const char* datatype, const char* glossary);
-ARG_EXTERN struct arg_date* arg_date1(const char* shortopts, const char* longopts, const char* format, const char* datatype, const char* glossary);
-ARG_EXTERN struct arg_date* arg_daten(const char* shortopts, const char* longopts, const char* format, const char* datatype, int mincount, int maxcount, const char* glossary);
+struct arg_date *arg_date0(const char *shortopts,
+ const char *longopts,
+ const char *format,
+ const char *datatype,
+ const char *glossary);
+struct arg_date *arg_date1(const char *shortopts,
+ const char *longopts,
+ const char *format,
+ const char *datatype,
+ const char *glossary);
+struct arg_date *arg_daten(const char *shortopts,
+ const char *longopts,
+ const char *format,
+ const char *datatype,
+ int mincount,
+ int maxcount,
+ const char *glossary);
-ARG_EXTERN struct arg_end* arg_end(int maxerrors);
+struct arg_end *arg_end(int maxcount);
-#define ARG_DSTR_STATIC ((arg_dstr_freefn*)0)
-#define ARG_DSTR_VOLATILE ((arg_dstr_freefn*)1)
-#define ARG_DSTR_DYNAMIC ((arg_dstr_freefn*)3)
/**** other functions *******************************************/
-ARG_EXTERN int arg_nullcheck(void** argtable);
-ARG_EXTERN int arg_parse(int argc, char** argv, void** argtable);
-ARG_EXTERN void arg_print_option(FILE* fp, const char* shortopts, const char* longopts, const char* datatype, const char* suffix);
-ARG_EXTERN void arg_print_syntax(FILE* fp, void** argtable, const char* suffix);
-ARG_EXTERN void arg_print_syntaxv(FILE* fp, void** argtable, const char* suffix);
-ARG_EXTERN void arg_print_glossary(FILE* fp, void** argtable, const char* format);
-ARG_EXTERN void arg_print_glossary_gnu(FILE* fp, void** argtable);
-ARG_EXTERN void arg_print_errors(FILE* fp, struct arg_end* end, const char* progname);
-ARG_EXTERN void arg_print_option_ds(arg_dstr_t ds, const char* shortopts, const char* longopts, const char* datatype, const char* suffix);
-ARG_EXTERN void arg_print_syntax_ds(arg_dstr_t ds, void** argtable, const char* suffix);
-ARG_EXTERN void arg_print_syntaxv_ds(arg_dstr_t ds, void** argtable, const char* suffix);
-ARG_EXTERN void arg_print_glossary_ds(arg_dstr_t ds, void** argtable, const char* format);
-ARG_EXTERN void arg_print_glossary_gnu_ds(arg_dstr_t ds, void** argtable);
-ARG_EXTERN void arg_print_errors_ds(arg_dstr_t ds, struct arg_end* end, const char* progname);
-ARG_EXTERN void arg_freetable(void** argtable, size_t n);
-
-ARG_EXTERN arg_dstr_t arg_dstr_create(void);
-ARG_EXTERN void arg_dstr_destroy(arg_dstr_t ds);
-ARG_EXTERN void arg_dstr_reset(arg_dstr_t ds);
-ARG_EXTERN void arg_dstr_free(arg_dstr_t ds);
-ARG_EXTERN void arg_dstr_set(arg_dstr_t ds, char* str, arg_dstr_freefn* free_proc);
-ARG_EXTERN void arg_dstr_cat(arg_dstr_t ds, const char* str);
-ARG_EXTERN void arg_dstr_catc(arg_dstr_t ds, char c);
-ARG_EXTERN void arg_dstr_catf(arg_dstr_t ds, const char* fmt, ...);
-ARG_EXTERN char* arg_dstr_cstr(arg_dstr_t ds);
-
-ARG_EXTERN void arg_cmd_init(void);
-ARG_EXTERN void arg_cmd_uninit(void);
-ARG_EXTERN void arg_cmd_register(const char* name, arg_cmdfn* proc, const char* description);
-ARG_EXTERN void arg_cmd_unregister(const char* name);
-ARG_EXTERN int arg_cmd_dispatch(const char* name, int argc, char* argv[], arg_dstr_t res);
-ARG_EXTERN unsigned int arg_cmd_count(void);
-ARG_EXTERN arg_cmd_info_t* arg_cmd_info(const char* name);
-ARG_EXTERN arg_cmd_itr_t arg_cmd_itr_create(void);
-ARG_EXTERN void arg_cmd_itr_destroy(arg_cmd_itr_t itr);
-ARG_EXTERN int arg_cmd_itr_advance(arg_cmd_itr_t itr);
-ARG_EXTERN char* arg_cmd_itr_key(arg_cmd_itr_t itr);
-ARG_EXTERN arg_cmd_info_t* arg_cmd_itr_value(arg_cmd_itr_t itr);
-ARG_EXTERN int arg_cmd_itr_search(arg_cmd_itr_t itr, void* k);
-ARG_EXTERN void arg_mgsort(void* data, int size, int esize, int i, int k, arg_comparefn* comparefn);
-ARG_EXTERN void arg_make_get_help_msg(arg_dstr_t res);
-ARG_EXTERN void arg_make_help_msg(arg_dstr_t ds, char* cmd_name, void** argtable);
-ARG_EXTERN void arg_make_syntax_err_msg(arg_dstr_t ds, void** argtable, struct arg_end* end);
-ARG_EXTERN int arg_make_syntax_err_help_msg(arg_dstr_t ds, char* name, int help, int nerrors, void** argtable, struct arg_end* end, int* exitcode);
-ARG_EXTERN void arg_set_module_name(const char* name);
-ARG_EXTERN void arg_set_module_version(int major, int minor, int patch, const char* tag);
+int arg_nullcheck(void **argtable);
+int arg_parse(int argc, char **argv, void **argtable);
+void arg_print_option(FILE *fp, const char *shortopts, const char *longopts, const char *datatype, const char *suffix);
+void arg_print_syntax(FILE *fp, void **argtable, const char *suffix);
+void arg_print_syntaxv(FILE *fp, void **argtable, const char *suffix);
+void arg_print_glossary(FILE *fp, void **argtable, const char *format);
+void arg_print_glossary_gnu(FILE *fp, void **argtable);
+void arg_print_errors(FILE *fp, struct arg_end *end, const char *progname);
+void arg_freetable(void **argtable, size_t n);
/**** deprecated functions, for back-compatibility only ********/
-ARG_EXTERN void arg_free(void** argtable);
+void arg_free(void **argtable);
#ifdef __cplusplus
}
From e8999f3318ee8c8234d0dae73d0f15fd7a4b8e62 Mon Sep 17 00:00:00 2001
From: dxl <64101226@qq.com>
Date: Thu, 7 May 2020 16:57:15 +0800
Subject: [PATCH 090/632] Translation some comments from Chinese to English.
---
client/android/CMakeLists.txt | 19 ++++++++-------
client/android/jni_tools.c | 41 +++++++++-----------------------
client/android/jni_tools.h | 14 +++++------
client/android/pm3_main.c | 44 ++++++++++++++++-------------------
4 files changed, 48 insertions(+), 70 deletions(-)
diff --git a/client/android/CMakeLists.txt b/client/android/CMakeLists.txt
index d320db6a1..1e03d1658 100644
--- a/client/android/CMakeLists.txt
+++ b/client/android/CMakeLists.txt
@@ -1,17 +1,20 @@
-#需要的最cmake版本
+# version
cmake_minimum_required(VERSION 3.4.1)
-#添加预编译宏定义参数,此次的作用是开启配置文件的引入!
+# We are build on android platform, so we need add def "ANDROID"
+# NDK version for SDK 19 doesn't implement the whole C++11 standard in the STL.
+# see: https://stackoverflow.com/questions/44736135/ndk-clang-error-undefined-reference-to-localeconv
+# so we need add def getlocaledecpoint()='.'
add_definitions(-DANDROID -D"getlocaledecpoint()='.'" -DZ_SOLO)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99 -O3 -fvisibility=hidden -w")
-#缩短路径定义
+# Root path into client
set(PM3_ROOT ../../)
add_subdirectory(../deps deps)
-#添加动态库定义
+# client resources
add_library(pm3rrg_rdv4 SHARED
${PM3_ROOT}/common/util_posix.c
${PM3_ROOT}/common/crapto1/crapto1.c
@@ -143,13 +146,12 @@ add_library(pm3rrg_rdv4 SHARED
${PM3_ROOT}/client/src/cmdlfpcf7931.c
${PM3_ROOT}/client/src/cmdhfmfhard.c
${PM3_ROOT}/client/src/cmdusart.c
-
- # android source
+ # android resources
jni_tools.c
pm3_main.c
)
-#添加头文件配置
+# includes
target_include_directories(pm3rrg_rdv4 PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}
${PM3_ROOT}/include/
@@ -166,5 +168,4 @@ find_library(pm3rrg_rdv4_reveng REQUIRED)
find_library(pm3rrg_rdv4_z REQUIRED)
find_library(pm3rrg_rdv4_hardnested REQUIRED)
-target_link_libraries(pm3rrg_rdv4 pm3rrg_rdv4_hardnested pm3rrg_rdv4_mbedtls pm3rrg_rdv4_cliparser pm3rrg_rdv4_jansson pm3rrg_rdv4_lua pm3rrg_rdv4_tinycbor pm3rrg_rdv4_amiibo pm3rrg_rdv4_reveng pm3rrg_rdv4_z android log)
-#添加动态库链接!
+target_link_libraries(pm3rrg_rdv4 pm3rrg_rdv4_hardnested pm3rrg_rdv4_mbedtls pm3rrg_rdv4_cliparser pm3rrg_rdv4_jansson pm3rrg_rdv4_lua pm3rrg_rdv4_tinycbor pm3rrg_rdv4_amiibo pm3rrg_rdv4_reveng pm3rrg_rdv4_z android log)
\ No newline at end of file
diff --git a/client/android/jni_tools.c b/client/android/jni_tools.c
index 1a5fc9592..6e12da2be 100644
--- a/client/android/jni_tools.c
+++ b/client/android/jni_tools.c
@@ -7,10 +7,10 @@
#include
#include "stdbool.h"
-//当前线程是否添加的标志位
+// native thread attach label
static bool g_IsAttach;
-//TODO 环境变量获取函数
+// get current env for jvm
JNIEnv *getJniEnv() {
JNIEnv *currentThreadEnv;
g_IsAttach = false;
@@ -32,66 +32,47 @@ JNIEnv *getJniEnv() {
}
}
-//解绑线程env
-void deatchThread() {
+// detach native thread from jvm
+void detachThread() {
if (g_IsAttach) {
- LOGD("线程解绑成功!");
(*g_JavaVM)->DetachCurrentThread(g_JavaVM);
}
}
-//TODO 命令行解析
+// cmd arg parse
CMD *parse_command_line(const char *commandStr) {
- //一个指针,指向传进来的命令字符串(const修饰的,我们需要复刻一份!)
CMD *cmd = (CMD *) malloc(sizeof(CMD));
if (!cmd) {
- LOGD("申请空间失败!");
return NULL;
}
- //拷贝字符串到堆空间!
+ // copy the source to the heap
char *pTmp = strdup(commandStr);
- LOGD("拷贝参数字符串到临时堆!");
- //返回的结果!先初始化为20个空间
+ // new memory size is default 20 for char **
int size = 20;
cmd->cmd = (char **) malloc(size * sizeof(char **));
- if (cmd->cmd) {
- LOGD("申请参数空间成功!");
- } else {
- LOGD("申请空间失败!");
- }
- //进行截取
+ if (!cmd->cmd) return NULL;
+ // parse
char *pStr = strtok(pTmp, " ");
- LOGD("第0次截取完成: %s", pStr);
- //给结果数组进行下标为0的第一次初始化
cmd->cmd[0] = pStr;
- //局部变量用于储存解析到的命令个数,下标移动为一
int count = 1;
- //需要截取命令参数,以空格为限定符
for (; pStr != NULL; ++count) {
- //如果容量不够,则扩容!
+ // Capacity expansion
if (count == (size - 1)) {
size += 20;
cmd->cmd = (char **) realloc(cmd->cmd, size * sizeof(char **));
- LOGD("超过初始容量,自动扩容!");
}
pStr = strtok(NULL, " ");
if (pStr) {
cmd->cmd[count] = pStr;
- LOGD("第%d次截取完成: %s", count, pStr);
}
}
cmd->len = (count - 1);
- LOGD("解析函数执行完成!");
return cmd;
}
-//内存释放
+// cmd arg struct free
void free_command_line(CMD *cmd) {
- //二级指针需要逐层释放!
- LOGD("释放命令行字符串二级引用!");
free(cmd->cmd[0]);
- LOGD("释放命令行一级引用!");
free(cmd->cmd);
- LOGD("释放结构体内存");
free(cmd);
}
diff --git a/client/android/jni_tools.h b/client/android/jni_tools.h
index 3d76184b9..8e900374f 100644
--- a/client/android/jni_tools.h
+++ b/client/android/jni_tools.h
@@ -10,31 +10,31 @@
#include
//JNI LOG
-#define TAG "DXL BlUESPP_PN532"
+#define TAG "PM3"
#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE,TAG,__VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,TAG,__VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,TAG,__VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN,TAG,__VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,TAG,__VA_ARGS__)
-//全局的环境变量定义
+// a global jvm instance
JavaVM *g_JavaVM;
-//线程环境指针获取函数
+// get current env for jvm
JNIEnv *getJniEnv();
-//子线程释放函数,必须是native层创建的线程才可以调用
-void deatchThread();
+// detach native thread from jvm, must native thread can detach!
+void detachThread();
typedef struct {
char **cmd;
int len;
} CMD;
-//命令行解析函数
+// cmd arg parse
CMD *parse_command_line(const char *commandStr);
-//解析结果释放函数!
+// cmd arg struct free
void free_command_line(CMD *);
#endif //DXL_TOOLS_H
diff --git a/client/android/pm3_main.c b/client/android/pm3_main.c
index 87c6bbd44..3039bbf8e 100644
--- a/client/android/pm3_main.c
+++ b/client/android/pm3_main.c
@@ -79,7 +79,7 @@ static bool open() {
}
/*
- * 发送一条命令等待执行!
+ * Transfers to the command buffer and waits for a new command to be executed
* */
jint sendCMD(JNIEnv *env, jobject instance, jstring cmd_) {
//may be pm3 not running.
@@ -93,19 +93,9 @@ jint sendCMD(JNIEnv *env, jobject instance, jstring cmd_) {
CloseProxmark();
}
}
- //无论如何,新的命令的输入了,就要换个行!
+ // display on new line
PrintAndLogEx(NORMAL, "\n");
- char *cmd = (char *)((*env)->GetStringUTFChars(env, cmd_, 0));
- // Many parts of the PM3 client will assume that they can read any write from pwd. So we set
- // pwd to whatever the PM3 "executable directory" is, to get consistent behaviour.
- /*int ret = chdir(get_my_executable_directory());
- if (ret == -1) {
- LOGW("Couldn't chdir(get_my_executable_directory()), errno=%s", strerror(errno));
- }
- char pwd[1024];
- memset((void *) &pwd, 0, sizeof(pwd));
- getcwd((char *) &pwd, sizeof(pwd));
- LOGI("pwd = %s", pwd);*/
+ char *cmd = (char *) ((*env)->GetStringUTFChars(env, cmd_, 0));
int ret = CommandReceived(cmd);
if (ret == 99) {
// exit / quit
@@ -117,14 +107,14 @@ jint sendCMD(JNIEnv *env, jobject instance, jstring cmd_) {
}
/*
- * 是否在执行命令
+ * Is client running!
* */
jboolean isExecuting(JNIEnv *env, jobject instance) {
- return (jboolean)((jboolean) conn.run);
+ return (jboolean) ((jboolean) conn.run);
}
/*
- * 进行设备链接验证!
+ * test hw and hw and client.
* */
jboolean testPm3(JNIEnv *env, jobject instance) {
bool ret1 = open();
@@ -133,13 +123,19 @@ jboolean testPm3(JNIEnv *env, jobject instance) {
return false;
}
bool ret2 = TestProxmark() == PM3_SUCCESS;
- return (jboolean)(ret1 && ret2);
+ return (jboolean) (ret1 && ret2);
}
+/*
+ * stop pm3 client
+ * */
void stopPm3(JNIEnv *env, jobject instance) {
CloseProxmark();
}
+/*
+ * native function map to jvm
+ * */
JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *reserved) {
JNIEnv *jniEnv = NULL;
if ((*vm)->GetEnv(vm, (void **) &jniEnv, JNI_VERSION_1_4) != JNI_OK) {
@@ -152,21 +148,21 @@ JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *reserved) {
}
jclass clz_test = (*jniEnv)->FindClass(jniEnv, "cn/rrg/devices/Proxmark3RRGRdv4");
JNINativeMethod methods[] = {
- {"startExecute", "(Ljava/lang/String;)I", (void *) sendCMD},
- {"stopExecute", "()V", (void *) stopPm3},
- {"isExecuting", "()Z", (void *) isExecuting}
+ {"startExecute", "(Ljava/lang/String;)I", (void *) sendCMD},
+ {"stopExecute", "()V", (void *) stopPm3},
+ {"isExecuting", "()Z", (void *) isExecuting}
};
JNINativeMethod methods1[] = {
- {"testPm3", "()Z", (void *) testPm3},
- {"closePm3", "()V", stopPm3}
+ {"testPm3", "()Z", (void *) testPm3},
+ {"closePm3", "()V", stopPm3}
};
if ((*jniEnv)->RegisterNatives(jniEnv, clazz, methods, sizeof(methods) / sizeof(methods[0])) !=
- JNI_OK) {
+ JNI_OK) {
return -1;
}
if ((*jniEnv)->RegisterNatives(jniEnv, clz_test, methods1,
sizeof(methods1) / sizeof(methods1[0])) !=
- JNI_OK) {
+ JNI_OK) {
return -1;
}
(*jniEnv)->DeleteLocalRef(jniEnv, clazz);
From 00b5841597742ec3bb902d9d927e962d4b2ba124 Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Thu, 7 May 2020 12:13:52 +0200
Subject: [PATCH 091/632] cmake android: add backslashes for host compatibility
---
client/android/CMakeLists.txt | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/client/android/CMakeLists.txt b/client/android/CMakeLists.txt
index 1e03d1658..fc7c759bb 100644
--- a/client/android/CMakeLists.txt
+++ b/client/android/CMakeLists.txt
@@ -5,7 +5,7 @@ cmake_minimum_required(VERSION 3.4.1)
# NDK version for SDK 19 doesn't implement the whole C++11 standard in the STL.
# see: https://stackoverflow.com/questions/44736135/ndk-clang-error-undefined-reference-to-localeconv
# so we need add def getlocaledecpoint()='.'
-add_definitions(-DANDROID -D"getlocaledecpoint()='.'" -DZ_SOLO)
+add_definitions(-DANDROID -D"getlocaledecpoint\(\)='.'" -DZ_SOLO)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99 -O3 -fvisibility=hidden -w")
From b34851d2812fd5712273ae6ca5e2a25ebb6d8cd8 Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Thu, 7 May 2020 12:19:46 +0200
Subject: [PATCH 092/632] make style
---
client/android/pm3_main.c | 20 ++++++++++----------
1 file changed, 10 insertions(+), 10 deletions(-)
diff --git a/client/android/pm3_main.c b/client/android/pm3_main.c
index 3039bbf8e..6855856ab 100644
--- a/client/android/pm3_main.c
+++ b/client/android/pm3_main.c
@@ -95,7 +95,7 @@ jint sendCMD(JNIEnv *env, jobject instance, jstring cmd_) {
}
// display on new line
PrintAndLogEx(NORMAL, "\n");
- char *cmd = (char *) ((*env)->GetStringUTFChars(env, cmd_, 0));
+ char *cmd = (char *)((*env)->GetStringUTFChars(env, cmd_, 0));
int ret = CommandReceived(cmd);
if (ret == 99) {
// exit / quit
@@ -110,7 +110,7 @@ jint sendCMD(JNIEnv *env, jobject instance, jstring cmd_) {
* Is client running!
* */
jboolean isExecuting(JNIEnv *env, jobject instance) {
- return (jboolean) ((jboolean) conn.run);
+ return (jboolean)((jboolean) conn.run);
}
/*
@@ -123,7 +123,7 @@ jboolean testPm3(JNIEnv *env, jobject instance) {
return false;
}
bool ret2 = TestProxmark() == PM3_SUCCESS;
- return (jboolean) (ret1 && ret2);
+ return (jboolean)(ret1 && ret2);
}
/*
@@ -148,21 +148,21 @@ JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *reserved) {
}
jclass clz_test = (*jniEnv)->FindClass(jniEnv, "cn/rrg/devices/Proxmark3RRGRdv4");
JNINativeMethod methods[] = {
- {"startExecute", "(Ljava/lang/String;)I", (void *) sendCMD},
- {"stopExecute", "()V", (void *) stopPm3},
- {"isExecuting", "()Z", (void *) isExecuting}
+ {"startExecute", "(Ljava/lang/String;)I", (void *) sendCMD},
+ {"stopExecute", "()V", (void *) stopPm3},
+ {"isExecuting", "()Z", (void *) isExecuting}
};
JNINativeMethod methods1[] = {
- {"testPm3", "()Z", (void *) testPm3},
- {"closePm3", "()V", stopPm3}
+ {"testPm3", "()Z", (void *) testPm3},
+ {"closePm3", "()V", stopPm3}
};
if ((*jniEnv)->RegisterNatives(jniEnv, clazz, methods, sizeof(methods) / sizeof(methods[0])) !=
- JNI_OK) {
+ JNI_OK) {
return -1;
}
if ((*jniEnv)->RegisterNatives(jniEnv, clz_test, methods1,
sizeof(methods1) / sizeof(methods1[0])) !=
- JNI_OK) {
+ JNI_OK) {
return -1;
}
(*jniEnv)->DeleteLocalRef(jniEnv, clazz);
From b9f6f096aa9d565af3a59998fd65c744da318f96 Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Thu, 7 May 2020 14:20:49 +0200
Subject: [PATCH 093/632] hook reveng outputs to pm3 machinery, add regression
test
---
client/deps/reveng/Makefile | 2 +-
client/deps/reveng/bmpbit.c | 6 ++++++
client/deps/reveng/config.h | 6 ++++++
pm3test.sh | 2 +-
4 files changed, 14 insertions(+), 2 deletions(-)
diff --git a/client/deps/reveng/Makefile b/client/deps/reveng/Makefile
index 0dbfa6007..d0382771d 100644
--- a/client/deps/reveng/Makefile
+++ b/client/deps/reveng/Makefile
@@ -4,7 +4,7 @@
# Add -DPRESETS to compile with preset models (edit config.h)
MYSRCPATHS =
-MYINCLUDES = -I../cliparser
+MYINCLUDES = -I../cliparser -I../../src -I../../../include
MYCFLAGS =
MYDEFS = -DPRESETS
MYSRCS = \
diff --git a/client/deps/reveng/bmpbit.c b/client/deps/reveng/bmpbit.c
index e44ddb250..522d71ecc 100644
--- a/client/deps/reveng/bmpbit.c
+++ b/client/deps/reveng/bmpbit.c
@@ -30,6 +30,12 @@
#endif
#include "reveng.h"
+#ifdef BMPTST
+# undef fprintf
+# undef puts
+# undef fputs
+#endif
+
#if (defined BMPTST) || (BMP_BIT < 32)
/* Size in bits of a bmp_t. Not necessarily a power of two. */
int bmpbit;
diff --git a/client/deps/reveng/config.h b/client/deps/reveng/config.h
index 94d3c4da5..177df030e 100644
--- a/client/deps/reveng/config.h
+++ b/client/deps/reveng/config.h
@@ -101,4 +101,10 @@
* *
*****************************************/
+// Proxmark3 stdout/stderr hooking
+#include "ui.h"
+#define fprintf(stream, ...) PrintAndLogEx(INFO, __VA_ARGS__)
+#define fputs(s, stream) PrintAndLogEx(INFO, "%s", s)
+#define puts(s) PrintAndLogEx(SUCCESS, "%s", s)
+
#endif /* CONFIG_H */
diff --git a/pm3test.sh b/pm3test.sh
index 99fe168dc..825398fae 100755
--- a/pm3test.sh
+++ b/pm3test.sh
@@ -108,7 +108,7 @@ while true; do
if ! CheckExecute "proxmark help text hardnested" "$PM3BIN -t 2>&1" "hardnested"; then break; fi
printf "\n${C_BLUE}Testing data manipulation:${C_NC}\n"
- if ! CheckExecute "reveng test" "$PM3BIN -c 'reveng -w 8 -s 01020304e3 010204039d'" "CRC-8/SMBUS"; then break; fi
+ if ! CheckExecute "reveng test" "$PM3BIN -c 'reveng -h;reveng -w 8 -s 01020304e3 010204039d'" "CRC-8/SMBUS"; then break; fi
if ! CheckExecute "mfu pwdgen test" "$PM3BIN -c 'hf mfu pwdgen t'" "Selftest OK"; then break; fi
printf "\n${C_BLUE}Testing LF:${C_NC}\n"
From 94d4f2b75efbad9a68a47261c911065fb2356aaf Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Thu, 7 May 2020 14:45:53 +0200
Subject: [PATCH 094/632] fix cmake for reveng
---
client/deps/reveng.cmake | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)
diff --git a/client/deps/reveng.cmake b/client/deps/reveng.cmake
index d5f3259ed..d7e3cfd8a 100644
--- a/client/deps/reveng.cmake
+++ b/client/deps/reveng.cmake
@@ -8,7 +8,10 @@ add_library(pm3rrg_rdv4_reveng STATIC
)
target_compile_definitions(pm3rrg_rdv4_reveng PRIVATE PRESETS)
-target_include_directories(pm3rrg_rdv4_reveng PRIVATE ../cliparser)
+target_include_directories(pm3rrg_rdv4_reveng PRIVATE
+ cliparser
+ ../src
+ ../../include)
target_include_directories(pm3rrg_rdv4_reveng INTERFACE reveng)
target_compile_options(pm3rrg_rdv4_reveng PRIVATE -Wall -Werror -O3)
set_property(TARGET pm3rrg_rdv4_reveng PROPERTY POSITION_INDEPENDENT_CODE ON)
From cdf7f776534d93ee678970e9aa444a838db527e8 Mon Sep 17 00:00:00 2001
From: iceman1001
Date: Thu, 7 May 2020 16:25:26 +0200
Subject: [PATCH 095/632] chg: added test for revengs readline/cliparsing
---
pm3test.sh | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/pm3test.sh b/pm3test.sh
index 825398fae..9a90ddcc5 100755
--- a/pm3test.sh
+++ b/pm3test.sh
@@ -108,7 +108,8 @@ while true; do
if ! CheckExecute "proxmark help text hardnested" "$PM3BIN -t 2>&1" "hardnested"; then break; fi
printf "\n${C_BLUE}Testing data manipulation:${C_NC}\n"
- if ! CheckExecute "reveng test" "$PM3BIN -c 'reveng -h;reveng -w 8 -s 01020304e3 010204039d'" "CRC-8/SMBUS"; then break; fi
+ if ! CheckExecute "reveng readline test" "$PM3BIN -c 'reveng -h;reveng -D'" "CRC-64/GO-ISO"; then break; fi
+ if ! CheckExecute "reveng test" "$PM3BIN -c 'reveng -w 8 -s 01020304e3 010204039d'" "CRC-8/SMBUS"; then break; fi
if ! CheckExecute "mfu pwdgen test" "$PM3BIN -c 'hf mfu pwdgen t'" "Selftest OK"; then break; fi
printf "\n${C_BLUE}Testing LF:${C_NC}\n"
From d6fd7f14d6a61879802adf67e1b8c3f6033d484d Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Thu, 7 May 2020 19:14:53 +0200
Subject: [PATCH 096/632] simpler ul_print_type
---
client/src/cmdhfmfu.c | 58 +++++++++++++++++++------------------------
1 file changed, 26 insertions(+), 32 deletions(-)
diff --git a/client/src/cmdhfmfu.c b/client/src/cmdhfmfu.c
index c71cff645..9dc739417 100644
--- a/client/src/cmdhfmfu.c
+++ b/client/src/cmdhfmfu.c
@@ -653,66 +653,60 @@ static int ndef_print_CC(uint8_t *data) {
int ul_print_type(uint32_t tagtype, uint8_t spaces) {
- char spc[11] = " ";
- spc[10] = 0x00;
-
if (spaces > 10)
spaces = 10;
-
- char *spacer = spc + (10 - spaces);
-
if (tagtype & UL)
- PrintAndLogEx(SUCCESS, "%sTYPE: " _YELLOW_("MIFARE Ultralight (MF0ICU1) %s"), spacer, (tagtype & MAGIC) ? "" : "");
+ PrintAndLogEx(SUCCESS, "%*sTYPE: " _YELLOW_("MIFARE Ultralight (MF0ICU1) %s"), spaces, "", (tagtype & MAGIC) ? "" : "");
else if (tagtype & UL_C)
- PrintAndLogEx(SUCCESS, "%sTYPE: " _YELLOW_("MIFARE Ultralight C (MF0ULC) %s"), spacer, (tagtype & MAGIC) ? "" : "");
+ PrintAndLogEx(SUCCESS, "%*sTYPE: " _YELLOW_("MIFARE Ultralight C (MF0ULC) %s"), spaces, "", (tagtype & MAGIC) ? "" : "");
else if (tagtype & UL_NANO_40)
- PrintAndLogEx(SUCCESS, "%sTYPE: " _YELLOW_("MIFARE Ultralight Nano 40bytes (MF0UNH00)"), spacer);
+ PrintAndLogEx(SUCCESS, "%*sTYPE: " _YELLOW_("MIFARE Ultralight Nano 40bytes (MF0UNH00)"), spaces, "");
else if (tagtype & UL_EV1_48)
- PrintAndLogEx(SUCCESS, "%sTYPE: " _YELLOW_("MIFARE Ultralight EV1 48bytes (MF0UL1101)"), spacer);
+ PrintAndLogEx(SUCCESS, "%*sTYPE: " _YELLOW_("MIFARE Ultralight EV1 48bytes (MF0UL1101)"), spaces, "");
else if (tagtype & UL_EV1_128)
- PrintAndLogEx(SUCCESS, "%sTYPE: " _YELLOW_("MIFARE Ultralight EV1 128bytes (MF0UL2101)"), spacer);
+ PrintAndLogEx(SUCCESS, "%*sTYPE: " _YELLOW_("MIFARE Ultralight EV1 128bytes (MF0UL2101)"), spaces, "");
else if (tagtype & UL_EV1)
- PrintAndLogEx(NORMAL, "%sTYPE: " _YELLOW_("MIFARE Ultralight EV1 UNKNOWN"), spacer);
+ PrintAndLogEx(NORMAL, "%*sTYPE: " _YELLOW_("MIFARE Ultralight EV1 UNKNOWN"), spaces, "");
else if (tagtype & NTAG)
- PrintAndLogEx(NORMAL, "%sTYPE: " _YELLOW_("NTAG UNKNOWN"), spacer);
+ PrintAndLogEx(NORMAL, "%*sTYPE: " _YELLOW_("NTAG UNKNOWN"), spaces, "");
else if (tagtype & NTAG_203)
- PrintAndLogEx(SUCCESS, "%sTYPE: " _YELLOW_("NTAG 203 144bytes (NT2H0301F0DT)"), spacer);
+ PrintAndLogEx(SUCCESS, "%*sTYPE: " _YELLOW_("NTAG 203 144bytes (NT2H0301F0DT)"), spaces, "");
else if (tagtype & NTAG_210)
- PrintAndLogEx(SUCCESS, "%sTYPE: " _YELLOW_("NTAG 210 48bytes (NT2L1011G0DU)"), spacer);
+ PrintAndLogEx(SUCCESS, "%*sTYPE: " _YELLOW_("NTAG 210 48bytes (NT2L1011G0DU)"), spaces, "");
else if (tagtype & NTAG_212)
- PrintAndLogEx(SUCCESS, "%sTYPE: " _YELLOW_("NTAG 212 128bytes (NT2L1211G0DU)"), spacer);
+ PrintAndLogEx(SUCCESS, "%*sTYPE: " _YELLOW_("NTAG 212 128bytes (NT2L1211G0DU)"), spaces, "");
else if (tagtype & NTAG_213)
- PrintAndLogEx(SUCCESS, "%sTYPE: " _YELLOW_("NTAG 213 144bytes (NT2H1311G0DU)"), spacer);
+ PrintAndLogEx(SUCCESS, "%*sTYPE: " _YELLOW_("NTAG 213 144bytes (NT2H1311G0DU)"), spaces, "");
else if (tagtype & NTAG_213_F)
- PrintAndLogEx(SUCCESS, "%sTYPE: " _YELLOW_("NTAG 213F 144bytes (NT2H1311F0DTL)"), spacer);
+ PrintAndLogEx(SUCCESS, "%*sTYPE: " _YELLOW_("NTAG 213F 144bytes (NT2H1311F0DTL)"), spaces, "");
else if (tagtype & NTAG_215)
- PrintAndLogEx(SUCCESS, "%sTYPE: " _YELLOW_("NTAG 215 504bytes (NT2H1511G0DU)"), spacer);
+ PrintAndLogEx(SUCCESS, "%*sTYPE: " _YELLOW_("NTAG 215 504bytes (NT2H1511G0DU)"), spaces, "");
else if (tagtype & NTAG_216)
- PrintAndLogEx(SUCCESS, "%sTYPE: " _YELLOW_("NTAG 216 888bytes (NT2H1611G0DU)"), spacer);
+ PrintAndLogEx(SUCCESS, "%*sTYPE: " _YELLOW_("NTAG 216 888bytes (NT2H1611G0DU)"), spaces, "");
else if (tagtype & NTAG_216_F)
- PrintAndLogEx(SUCCESS, "%sTYPE: " _YELLOW_("NTAG 216F 888bytes (NT2H1611F0DTL)"), spacer);
+ PrintAndLogEx(SUCCESS, "%*sTYPE: " _YELLOW_("NTAG 216F 888bytes (NT2H1611F0DTL)"), spaces, "");
else if (tagtype & NTAG_I2C_1K)
- PrintAndLogEx(SUCCESS, "%sTYPE: " _YELLOW_("NTAG I2C 888bytes (NT3H1101FHK)"), spacer);
+ PrintAndLogEx(SUCCESS, "%*sTYPE: " _YELLOW_("NTAG I2C 888bytes (NT3H1101FHK)"), spaces, "");
else if (tagtype & NTAG_I2C_2K)
- PrintAndLogEx(SUCCESS, "%sTYPE: " _YELLOW_("NTAG I2C 1904bytes (NT3H1201FHK)"), spacer);
+ PrintAndLogEx(SUCCESS, "%*sTYPE: " _YELLOW_("NTAG I2C 1904bytes (NT3H1201FHK)"), spaces, "");
else if (tagtype & NTAG_I2C_1K_PLUS)
- PrintAndLogEx(SUCCESS, "%sTYPE: " _YELLOW_("NTAG I2C plus 888bytes (NT3H2111FHK)"), spacer);
+ PrintAndLogEx(SUCCESS, "%*sTYPE: " _YELLOW_("NTAG I2C plus 888bytes (NT3H2111FHK)"), spaces, "");
else if (tagtype & NTAG_I2C_2K_PLUS)
- PrintAndLogEx(SUCCESS, "%sTYPE: " _YELLOW_("NTAG I2C plus 1912bytes (NT3H2211FHK)"), spacer);
+ PrintAndLogEx(SUCCESS, "%*sTYPE: " _YELLOW_("NTAG I2C plus 1912bytes (NT3H2211FHK)"), spaces, "");
else if (tagtype & MY_D)
- PrintAndLogEx(SUCCESS, "%sTYPE: " _YELLOW_("INFINEON my-d\x99 (SLE 66RxxS)"), spacer);
+ PrintAndLogEx(SUCCESS, "%*sTYPE: " _YELLOW_("INFINEON my-d\x99 (SLE 66RxxS)"), spaces, "");
else if (tagtype & MY_D_NFC)
- PrintAndLogEx(SUCCESS, "%sTYPE: " _YELLOW_("INFINEON my-d\x99 NFC (SLE 66RxxP)"), spacer);
+ PrintAndLogEx(SUCCESS, "%*sTYPE: " _YELLOW_("INFINEON my-d\x99 NFC (SLE 66RxxP)"), spaces, "");
else if (tagtype & MY_D_MOVE)
- PrintAndLogEx(SUCCESS, "%sTYPE: " _YELLOW_("INFINEON my-d\x99 move (SLE 66R01P)"), spacer);
+ PrintAndLogEx(SUCCESS, "%*sTYPE: " _YELLOW_("INFINEON my-d\x99 move (SLE 66R01P)"), spaces, "");
else if (tagtype & MY_D_MOVE_NFC)
- PrintAndLogEx(SUCCESS, "%sTYPE: " _YELLOW_("INFINEON my-d\x99 move NFC (SLE 66R01P)"), spacer);
+ PrintAndLogEx(SUCCESS, "%*sTYPE: " _YELLOW_("INFINEON my-d\x99 move NFC (SLE 66R01P)"), spaces, "");
else if (tagtype & MY_D_MOVE_LEAN)
- PrintAndLogEx(SUCCESS, "%sTYPE: " _YELLOW_("INFINEON my-d\x99 move lean (SLE 66R01L)"), spacer);
+ PrintAndLogEx(SUCCESS, "%*sTYPE: " _YELLOW_("INFINEON my-d\x99 move lean (SLE 66R01L)"), spaces, "");
else if (tagtype & FUDAN_UL)
- PrintAndLogEx(SUCCESS, "%sTYPE: " _YELLOW_("FUDAN Ultralight Compatible (or other compatible) %s"), spacer, (tagtype & MAGIC) ? "" : "");
+ PrintAndLogEx(SUCCESS, "%*sTYPE: " _YELLOW_("FUDAN Ultralight Compatible (or other compatible) %s"), spaces, "", (tagtype & MAGIC) ? "" : "");
else
- PrintAndLogEx(NORMAL, "%sTYPE: " _YELLOW_("Unknown %06x"), spacer, tagtype);
+ PrintAndLogEx(NORMAL, "%*sTYPE: " _YELLOW_("Unknown %06x"), spaces, "", tagtype);
return PM3_SUCCESS;
}
From 4066287b9842e56868938fceab4bb1948d757c93 Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Thu, 7 May 2020 19:17:09 +0200
Subject: [PATCH 097/632] Let's see if the prompt suffixed spaces are still
needed. Please shout if it breaks.
---
client/src/ui.c | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/client/src/ui.c b/client/src/ui.c
index 0b0ffdb56..488cce8d9 100644
--- a/client/src/ui.c
+++ b/client/src/ui.c
@@ -314,7 +314,7 @@ static void fPrintAndLog(FILE *stream, const char *fmt, ...) {
if (g_printAndLog & PRINTANDLOG_PRINT) {
memcpy_filter_emoji(buffer3, buffer2, sizeof(buffer2), session.emoji_mode);
fprintf(stream, "%s", buffer3);
- fprintf(stream, " "); // cleaning prompt
+// fprintf(stream, " "); // cleaning prompt
fprintf(stream, "\n");
}
From a8a9e98ca22d97be0eb0bdbb59e3efa693bd3caa Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Thu, 7 May 2020 19:44:03 +0200
Subject: [PATCH 098/632] Revert "Let's see if the prompt suffixed spaces are
still needed. Please shout if it breaks."
ok now I see where it breaks :) will debug locally...
This reverts commit 4066287b9842e56868938fceab4bb1948d757c93.
---
client/src/ui.c | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/client/src/ui.c b/client/src/ui.c
index 488cce8d9..0b0ffdb56 100644
--- a/client/src/ui.c
+++ b/client/src/ui.c
@@ -314,7 +314,7 @@ static void fPrintAndLog(FILE *stream, const char *fmt, ...) {
if (g_printAndLog & PRINTANDLOG_PRINT) {
memcpy_filter_emoji(buffer3, buffer2, sizeof(buffer2), session.emoji_mode);
fprintf(stream, "%s", buffer3);
-// fprintf(stream, " "); // cleaning prompt
+ fprintf(stream, " "); // cleaning prompt
fprintf(stream, "\n");
}
From edb1c85cd3bfbdd3900d71d59f1fcb3079d873f5 Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Thu, 7 May 2020 21:56:09 +0200
Subject: [PATCH 099/632] fix colored readline prompt bug
---
client/src/proxmark3.h | 13 ++++++-------
client/src/ui.c | 4 ++++
include/ansi.h | 14 ++++++++++++--
3 files changed, 22 insertions(+), 9 deletions(-)
diff --git a/client/src/proxmark3.h b/client/src/proxmark3.h
index 9f4c767e2..6402baea9 100644
--- a/client/src/proxmark3.h
+++ b/client/src/proxmark3.h
@@ -18,15 +18,14 @@
#define PROXPROMPT_COMPOSE "[" "%s%s" "] pm3 --> "
-#define PROXPROMPT_CTX_SCRIPTFILE "|" _GREEN_("script")
-#define PROXPROMPT_CTX_SCRIPTCMD "|" _GREEN_("script")
-#define PROXPROMPT_CTX_STDIN "|" _GREEN_("script")
+#define PROXPROMPT_CTX_SCRIPTFILE "|" _RL_GREEN_("script")
+#define PROXPROMPT_CTX_SCRIPTCMD "|" _RL_GREEN_("script")
+#define PROXPROMPT_CTX_STDIN "|" _RL_GREEN_("script")
#define PROXPROMPT_CTX_INTERACTIVE ""
-#define PROXPROMPT_DEV_USB _BOLD_GREEN_("usb")
-#define PROXPROMPT_DEV_FPC _BOLD_GREEN_("fpc")
-#define PROXPROMPT_DEV_OFFLINE _BOLD_RED_("offline")
-
+#define PROXPROMPT_DEV_USB _RL_BOLD_GREEN_("usb")
+#define PROXPROMPT_DEV_FPC _RL_BOLD_GREEN_("fpc")
+#define PROXPROMPT_DEV_OFFLINE _RL_BOLD_RED_("offline")
#define PROXHISTORY "history.txt"
#define PROXLOG "log_%Y%m%d.txt"
diff --git a/client/src/ui.c b/client/src/ui.c
index 0b0ffdb56..58cd1606a 100644
--- a/client/src/ui.c
+++ b/client/src/ui.c
@@ -358,6 +358,10 @@ void memcpy_filter_ansi(void *dest, const void *src, size_t n, bool filter) {
uint8_t *rsrc = (uint8_t *)src;
uint16_t si = 0;
for (uint16_t i = 0; i < n; i++) {
+ if ((i < n)
+ && ((rsrc[i] == '\001') || (rsrc[i] == '\002')))
+ // skip readline special markers
+ continue;
if ((i < n - 1)
&& (rsrc[i] == '\x1b')
&& (rsrc[i + 1] >= 0x40)
diff --git a/include/ansi.h b/include/ansi.h
index e86a36ee4..28784ba8c 100644
--- a/include/ansi.h
+++ b/include/ansi.h
@@ -5,12 +5,22 @@
#define _BLUE_(s) "\x1b[34m" s AEND
#define _RED_(s) "\x1b[31m" s AEND
-#define _BOLD_RED_(s) "\x1b[1;31m" s AEND
#define _GREEN_(s) "\x1b[32m" s AEND
-#define _BOLD_GREEN_(s) "\x1b[1;32m" s AEND
#define _YELLOW_(s) "\x1b[33m" s AEND
#define _MAGENTA_(s) "\x1b[35m" s AEND
#define _CYAN_(s) "\x1b[36m" s AEND
#define _WHITE_(s) "\x1b[37m" s AEND
+// https://wiki.hackzine.org/development/misc/readline-color-prompt.html
+// Applications may indicate that the prompt contains
+// characters that take up no physical screen space when displayed by
+// bracketing a sequence of such characters with the special markers
+// RL_PROMPT_START_IGNORE = '\001' and RL_PROMPT_END_IGNORE = '\002'
+#define RL_ESC(a) "\001" a "\002"
+
+#define _RL_RED_(s) RL_ESC("\x1b[31m") s RL_ESC(AEND)
+#define _RL_GREEN_(s) RL_ESC("\x1b[32m") s RL_ESC(AEND)
+#define _RL_BOLD_RED_(s) RL_ESC("\x1b[1;31m") s RL_ESC(AEND)
+#define _RL_BOLD_GREEN_(s) RL_ESC("\x1b[1;32m") s RL_ESC(AEND)
+
#endif
From 1c136c3e932d94551cdc86c83521cbf076d12df2 Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Thu, 7 May 2020 19:17:09 +0200
Subject: [PATCH 100/632] Let's see if the prompt suffixed spaces are still
needed. Please shout if it breaks.
---
client/src/ui.c | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/client/src/ui.c b/client/src/ui.c
index 58cd1606a..f4e9ec9a6 100644
--- a/client/src/ui.c
+++ b/client/src/ui.c
@@ -314,7 +314,7 @@ static void fPrintAndLog(FILE *stream, const char *fmt, ...) {
if (g_printAndLog & PRINTANDLOG_PRINT) {
memcpy_filter_emoji(buffer3, buffer2, sizeof(buffer2), session.emoji_mode);
fprintf(stream, "%s", buffer3);
- fprintf(stream, " "); // cleaning prompt
+// fprintf(stream, " "); // cleaning prompt
fprintf(stream, "\n");
}
From 1ad5cc473fdbf0fc2c6a0dfd59609b44a1bf067c Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Thu, 7 May 2020 23:00:45 +0200
Subject: [PATCH 101/632] rework banners
---
client/src/proxmark3.c | 79 +++++++++++++++++++-----------------------
1 file changed, 35 insertions(+), 44 deletions(-)
diff --git a/client/src/proxmark3.c b/client/src/proxmark3.c
index 1ed8bb65a..f57ca4018 100644
--- a/client/src/proxmark3.c
+++ b/client/src/proxmark3.c
@@ -40,10 +40,11 @@
// Used to enable/disable use of preferences json file
#define USE_PREFERENCE_FILE
-#ifdef _WIN32
-
-static void utf8_showBanner(void) {
+#define BANNERMSG1 " :snowflake: iceman@icesql.net :coffee:"
+#define BANNERMSG2 " https://github.com/rfidresearchgroup/proxmark3/"
+#define BANNERMSG3 "pre-release v4.0"
+static inline void utf8_showBanner(void) {
char sq[] = { 0xE2, 0x96, 0x88, 0x00 }; // square block
char tr[] = { 0xE2, 0x95, 0x97, 0x00 }; // top rigth corner
char tl[] = { 0xE2, 0x95, 0x94, 0x00 }; // top left corner
@@ -51,59 +52,49 @@ static void utf8_showBanner(void) {
char bl[] = { 0xE2, 0x95, 0x9A, 0x00 }; // bottom left corner
char hl[] = { 0xE2, 0x95, 0x90, 0x00 }; // horiz line
char vl[] = { 0xE2, 0x95, 0x91, 0x00 }; // vert line
- char msg1 [60];
- char msg2 [60];
- char msg3 [60];
-
- strcpy(msg1, " :snowflake: iceman@icesql.net :coffee:");
- strcpy(msg2, " https://github.com/rfidresearchgroup/proxmark3/");
- strcpy(msg3, "pre-release v4.0");
-
- g_printAndLog = PRINTANDLOG_PRINT;
-
- PrintAndLogEx(NORMAL, "\n");
PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s%s%s%s%s %s%s%s%s %s%s%s%s %s%s%s%s%s "), sq, sq, sq, sq, sq, sq, tr, sq, sq, sq, tr, sq, sq, sq, tr, sq, sq, sq, sq, tr);
PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s%s%s%s%s%s%s%s%s%s%s %s%s%s%s%s %s%s%s%s"), sq, sq, tl, hl, hl, sq, sq, tr, sq, sq, sq, sq, tr, sq, sq, sq, sq, vl, hl, hl, sq, vl);
PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s %s%s%s%s%s%s"), sq, sq, sq, sq, sq, sq, tl, br, sq, sq, tl, sq, sq, sq, sq, tl, sq, sq, vl, sq, sq, sq, sq, tl, br);
- PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s%s%s%s%s %s%s%s%s%s%s%s%s%s%s%s %s%s%s%s")" %s", sq, sq, tr, hl, hl, hl, br, sq, sq, vl, bl, sq, sq, tl, br, sq, sq, vl, hl, hl, sq, vl, msg1);
- PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s %s%s%s %s%s%s %s%s%s %s%s%s%s%s%s")" %s", sq, sq, vl, sq, sq, vl, bl, hl, br, sq, sq, vl, sq, sq, sq, sq, tl, br, msg2);
- PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s %s%s%s %s%s%s %s%s%s%s%s ")" %s", bl, hl, br, bl, hl, br, bl, hl, br, bl, hl, hl, hl, br, msg3);
-
- PrintAndLogEx(NORMAL, "");
- fflush(stdout);
- g_printAndLog = PRINTANDLOG_PRINT | PRINTANDLOG_LOG;
+ PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s%s%s%s%s %s%s%s%s%s%s%s%s%s%s%s %s%s%s%s")" %s", sq, sq, tr, hl, hl, hl, br, sq, sq, vl, bl, sq, sq, tl, br, sq, sq, vl, hl, hl, sq, vl, BANNERMSG1);
+ PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s %s%s%s %s%s%s %s%s%s %s%s%s%s%s%s")" %s", sq, sq, vl, sq, sq, vl, bl, hl, br, sq, sq, vl, sq, sq, sq, sq, tl, br, BANNERMSG2);
+ PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s %s%s%s %s%s%s %s%s%s%s%s ")" %s", bl, hl, br, bl, hl, br, bl, hl, br, bl, hl, hl, hl, br, BANNERMSG3);
}
-#endif
-
-static void showBanner(void) {
-
-#ifdef _WIN32
- // If on windows and using UTF-8 then we need utf-8 ascii art for banner.
- if (GetConsoleCP() == 65001) {
- utf8_showBanner();
- return;
- }
-#endif
-
- g_printAndLog = PRINTANDLOG_PRINT;
-
- PrintAndLogEx(NORMAL, "\n");
-#if defined(__linux__) || defined(__APPLE__) || defined(_WIN32)
+static inline void ansi_showBanner(void) {
PrintAndLogEx(NORMAL, " " _BLUE_("██████╗ ███╗ ███╗ ████╗ "));
PrintAndLogEx(NORMAL, " " _BLUE_("██╔══██╗████╗ ████║ ══█║"));
PrintAndLogEx(NORMAL, " " _BLUE_("██████╔╝██╔████╔██║ ████╔╝"));
- PrintAndLogEx(NORMAL, " " _BLUE_("██╔═══╝ ██║╚██╔╝██║ ══█║") " :snowflake: iceman@icesql.net :coffee:");
- PrintAndLogEx(NORMAL, " " _BLUE_("██║ ██║ ╚═╝ ██║ ████╔╝") " https://github.com/rfidresearchgroup/proxmark3/");
- PrintAndLogEx(NORMAL, " " _BLUE_("╚═╝ ╚═╝ ╚═╝ ╚═══╝ ") " pre-release v4.0");
-#else
+ PrintAndLogEx(NORMAL, " " _BLUE_("██╔═══╝ ██║╚██╔╝██║ ══█║") " " BANNERMSG1);
+ PrintAndLogEx(NORMAL, " " _BLUE_("██║ ██║ ╚═╝ ██║ ████╔╝") " " BANNERMSG2);
+ PrintAndLogEx(NORMAL, " " _BLUE_("╚═╝ ╚═╝ ╚═╝ ╚═══╝ ") " " BANNERMSG3);
+}
+
+static inline void ascii_showBanner(void) {
PrintAndLogEx(NORMAL, " ======. ===. ===. ====.");
PrintAndLogEx(NORMAL, " ==...==.====. ====. ..=.");
PrintAndLogEx(NORMAL, " ======..==.====.==. ====..");
- PrintAndLogEx(NORMAL, " ==..... ==..==..==. ..=. iceman@icesql.net :coffee:");
- PrintAndLogEx(NORMAL, " ==. ==. ... ==. ====.. https://github.com/rfidresearchgroup/proxmark3/");
- PrintAndLogEx(NORMAL, " ... ... ... ..... pre-release v4.0");
+ PrintAndLogEx(NORMAL, " ==..... ==..==..==. ..=." " " BANNERMSG1);
+ PrintAndLogEx(NORMAL, " ==. ==. ... ==. ====.." " " BANNERMSG2);
+ PrintAndLogEx(NORMAL, " ... ... ... ..... " " " BANNERMSG3);
+}
+
+static void showBanner(void) {
+
+ g_printAndLog = PRINTANDLOG_PRINT;
+ PrintAndLogEx(NORMAL, "\n");
+
+#if defined(_WIN32)
+ if (GetConsoleCP() == 65001) {
+ // If on Windows and using UTF-8 then we need utf-8 ascii art for banner.
+ utf8_showBanner();
+ } else {
+ ansi_showBanner();
+ }
+#elif defined(__linux__) || defined(__APPLE__)
+ ansi_showBanner();
+#else
+ ascii_showBanner();
#endif
// PrintAndLogEx(NORMAL, "\nSupport iceman on patreon - https://www.patreon.com/iceman1001/");
// PrintAndLogEx(NORMAL, " on paypal - https://www.paypal.me/iceman1001");
From 3a75de121599baf25a96bb52d4e832ba078b391f Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Thu, 7 May 2020 23:33:35 +0200
Subject: [PATCH 102/632] rework banners
---
client/src/proxmark3.c | 55 ++++++++++++++++++++++++------------------
1 file changed, 31 insertions(+), 24 deletions(-)
diff --git a/client/src/proxmark3.c b/client/src/proxmark3.c
index f57ca4018..c854241cb 100644
--- a/client/src/proxmark3.c
+++ b/client/src/proxmark3.c
@@ -45,38 +45,45 @@
#define BANNERMSG3 "pre-release v4.0"
static inline void utf8_showBanner(void) {
- char sq[] = { 0xE2, 0x96, 0x88, 0x00 }; // square block
- char tr[] = { 0xE2, 0x95, 0x97, 0x00 }; // top rigth corner
- char tl[] = { 0xE2, 0x95, 0x94, 0x00 }; // top left corner
- char br[] = { 0xE2, 0x95, 0x9D, 0x00 }; // bottom right corner
- char bl[] = { 0xE2, 0x95, 0x9A, 0x00 }; // bottom left corner
- char hl[] = { 0xE2, 0x95, 0x90, 0x00 }; // horiz line
- char vl[] = { 0xE2, 0x95, 0x91, 0x00 }; // vert line
+ const char* sq = "\xE2\x96\x88"; // square block
+ const char* tr = "\xE2\x95\x97"; // top right corner
+ const char* tl = "\xE2\x95\x94"; // top left corner
+ const char* br = "\xE2\x95\x9D"; // bottom right corner
+ const char* bl = "\xE2\x95\x9A"; // bottom left corner
+ const char* hl = "\xE2\x95\x90"; // horiz line
+ const char* vl = "\xE2\x95\x91"; // vert line
+ const char* __ = " ";
- PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s%s%s%s%s %s%s%s%s %s%s%s%s %s%s%s%s%s "), sq, sq, sq, sq, sq, sq, tr, sq, sq, sq, tr, sq, sq, sq, tr, sq, sq, sq, sq, tr);
- PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s%s%s%s%s%s%s%s%s%s%s %s%s%s%s%s %s%s%s%s"), sq, sq, tl, hl, hl, sq, sq, tr, sq, sq, sq, sq, tr, sq, sq, sq, sq, vl, hl, hl, sq, vl);
- PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s %s%s%s%s%s%s"), sq, sq, sq, sq, sq, sq, tl, br, sq, sq, tl, sq, sq, sq, sq, tl, sq, sq, vl, sq, sq, sq, sq, tl, br);
- PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s%s%s%s%s %s%s%s%s%s%s%s%s%s%s%s %s%s%s%s")" %s", sq, sq, tr, hl, hl, hl, br, sq, sq, vl, bl, sq, sq, tl, br, sq, sq, vl, hl, hl, sq, vl, BANNERMSG1);
- PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s %s%s%s %s%s%s %s%s%s %s%s%s%s%s%s")" %s", sq, sq, vl, sq, sq, vl, bl, hl, br, sq, sq, vl, sq, sq, sq, sq, tl, br, BANNERMSG2);
- PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s %s%s%s %s%s%s %s%s%s%s%s ")" %s", bl, hl, br, bl, hl, br, bl, hl, br, bl, hl, hl, hl, br, BANNERMSG3);
+ PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s"),
+ sq, sq, sq, sq, sq, sq, tr, __, sq, sq, sq, tr, __, __, __, sq, sq, sq, tr, sq, sq, sq, sq, sq, tr, __);
+ PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s"),
+ sq, sq, tl, hl, hl, sq, sq, tr, sq, sq, sq, sq, tr, __, sq, sq, sq, sq, vl, bl, hl, hl, hl, sq, sq, tr);
+ PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s"),
+ sq, sq, sq, sq, sq, sq, tl, br, sq, sq, tl, sq, sq, sq, sq, tl, sq, sq, vl, __, sq, sq, sq, sq, tl, br);
+ PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s")" " BANNERMSG1,
+ sq, sq, tl, hl, hl, hl, br, __, sq, sq, vl, bl, sq, sq, tl, br, sq, sq, vl, __, bl, hl, hl, sq, sq, tr);
+ PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s")" " BANNERMSG2,
+ sq, sq, vl, __, __, __, __, __, sq, sq, vl, __, bl, hl, br, __, sq, sq, vl, sq, sq, sq, sq, sq, tl, br);
+ PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s")" " BANNERMSG3,
+ bl, hl, br, __, __, __, __, __, bl, hl, br, __, __, __, __, __, bl, hl, br, bl, hl, hl, hl, hl, br, __);
}
static inline void ansi_showBanner(void) {
- PrintAndLogEx(NORMAL, " " _BLUE_("██████╗ ███╗ ███╗ ████╗ "));
- PrintAndLogEx(NORMAL, " " _BLUE_("██╔══██╗████╗ ████║ ══█║"));
+ PrintAndLogEx(NORMAL, " " _BLUE_("██████╗ ███╗ ███╗█████╗ "));
+ PrintAndLogEx(NORMAL, " " _BLUE_("██╔══██╗████╗ ████║╚═══██╗"));
PrintAndLogEx(NORMAL, " " _BLUE_("██████╔╝██╔████╔██║ ████╔╝"));
- PrintAndLogEx(NORMAL, " " _BLUE_("██╔═══╝ ██║╚██╔╝██║ ══█║") " " BANNERMSG1);
- PrintAndLogEx(NORMAL, " " _BLUE_("██║ ██║ ╚═╝ ██║ ████╔╝") " " BANNERMSG2);
- PrintAndLogEx(NORMAL, " " _BLUE_("╚═╝ ╚═╝ ╚═╝ ╚═══╝ ") " " BANNERMSG3);
+ PrintAndLogEx(NORMAL, " " _BLUE_("██╔═══╝ ██║╚██╔╝██║ ╚══██╗") " " BANNERMSG1);
+ PrintAndLogEx(NORMAL, " " _BLUE_("██║ ██║ ╚═╝ ██║█████╔╝") " " BANNERMSG2);
+ PrintAndLogEx(NORMAL, " " _BLUE_("╚═╝ ╚═╝ ╚═╝╚════╝ ") " " BANNERMSG3);
}
static inline void ascii_showBanner(void) {
- PrintAndLogEx(NORMAL, " ======. ===. ===. ====.");
- PrintAndLogEx(NORMAL, " ==...==.====. ====. ..=.");
- PrintAndLogEx(NORMAL, " ======..==.====.==. ====..");
- PrintAndLogEx(NORMAL, " ==..... ==..==..==. ..=." " " BANNERMSG1);
- PrintAndLogEx(NORMAL, " ==. ==. ... ==. ====.." " " BANNERMSG2);
- PrintAndLogEx(NORMAL, " ... ... ... ..... " " " BANNERMSG3);
+ PrintAndLogEx(NORMAL, " ######. ###. ###.#####. ");
+ PrintAndLogEx(NORMAL, " ##...##.####. ####. ...##.");
+ PrintAndLogEx(NORMAL, " ######..##.####.##. ####..");
+ PrintAndLogEx(NORMAL, " ##..... ##..##..##. ..##." " " BANNERMSG1);
+ PrintAndLogEx(NORMAL, " ##. ##. .. ##.#####.." " " BANNERMSG2);
+ PrintAndLogEx(NORMAL, " .. .. .. ..... " " " BANNERMSG3);
}
static void showBanner(void) {
From 59057b6a35a98cdd4d9ff22053f22001ad0c9f69 Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Fri, 8 May 2020 00:48:20 +0200
Subject: [PATCH 103/632] banners: clang still warns on unused static inlines
fcts, change strategy
---
client/src/proxmark3.c | 91 +++++++++++++++++++++++-------------------
1 file changed, 49 insertions(+), 42 deletions(-)
diff --git a/client/src/proxmark3.c b/client/src/proxmark3.c
index c854241cb..0a0e99024 100644
--- a/client/src/proxmark3.c
+++ b/client/src/proxmark3.c
@@ -44,46 +44,53 @@
#define BANNERMSG2 " https://github.com/rfidresearchgroup/proxmark3/"
#define BANNERMSG3 "pre-release v4.0"
-static inline void utf8_showBanner(void) {
- const char* sq = "\xE2\x96\x88"; // square block
- const char* tr = "\xE2\x95\x97"; // top right corner
- const char* tl = "\xE2\x95\x94"; // top left corner
- const char* br = "\xE2\x95\x9D"; // bottom right corner
- const char* bl = "\xE2\x95\x9A"; // bottom left corner
- const char* hl = "\xE2\x95\x90"; // horiz line
- const char* vl = "\xE2\x95\x91"; // vert line
- const char* __ = " ";
+typedef enum LogoMode { UTF8, ANSI, ASCII } LogoMode;
- PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s"),
- sq, sq, sq, sq, sq, sq, tr, __, sq, sq, sq, tr, __, __, __, sq, sq, sq, tr, sq, sq, sq, sq, sq, tr, __);
- PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s"),
- sq, sq, tl, hl, hl, sq, sq, tr, sq, sq, sq, sq, tr, __, sq, sq, sq, sq, vl, bl, hl, hl, hl, sq, sq, tr);
- PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s"),
- sq, sq, sq, sq, sq, sq, tl, br, sq, sq, tl, sq, sq, sq, sq, tl, sq, sq, vl, __, sq, sq, sq, sq, tl, br);
- PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s")" " BANNERMSG1,
- sq, sq, tl, hl, hl, hl, br, __, sq, sq, vl, bl, sq, sq, tl, br, sq, sq, vl, __, bl, hl, hl, sq, sq, tr);
- PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s")" " BANNERMSG2,
- sq, sq, vl, __, __, __, __, __, sq, sq, vl, __, bl, hl, br, __, sq, sq, vl, sq, sq, sq, sq, sq, tl, br);
- PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s")" " BANNERMSG3,
- bl, hl, br, __, __, __, __, __, bl, hl, br, __, __, __, __, __, bl, hl, br, bl, hl, hl, hl, hl, br, __);
-}
+static void showBanner_logo(LogoMode mode) {
+ switch (mode) {
+ case UTF8: {
+ const char* sq = "\xE2\x96\x88"; // square block
+ const char* tr = "\xE2\x95\x97"; // top right corner
+ const char* tl = "\xE2\x95\x94"; // top left corner
+ const char* br = "\xE2\x95\x9D"; // bottom right corner
+ const char* bl = "\xE2\x95\x9A"; // bottom left corner
+ const char* hl = "\xE2\x95\x90"; // horiz line
+ const char* vl = "\xE2\x95\x91"; // vert line
+ const char* __ = " ";
-static inline void ansi_showBanner(void) {
- PrintAndLogEx(NORMAL, " " _BLUE_("██████╗ ███╗ ███╗█████╗ "));
- PrintAndLogEx(NORMAL, " " _BLUE_("██╔══██╗████╗ ████║╚═══██╗"));
- PrintAndLogEx(NORMAL, " " _BLUE_("██████╔╝██╔████╔██║ ████╔╝"));
- PrintAndLogEx(NORMAL, " " _BLUE_("██╔═══╝ ██║╚██╔╝██║ ╚══██╗") " " BANNERMSG1);
- PrintAndLogEx(NORMAL, " " _BLUE_("██║ ██║ ╚═╝ ██║█████╔╝") " " BANNERMSG2);
- PrintAndLogEx(NORMAL, " " _BLUE_("╚═╝ ╚═╝ ╚═╝╚════╝ ") " " BANNERMSG3);
-}
-
-static inline void ascii_showBanner(void) {
- PrintAndLogEx(NORMAL, " ######. ###. ###.#####. ");
- PrintAndLogEx(NORMAL, " ##...##.####. ####. ...##.");
- PrintAndLogEx(NORMAL, " ######..##.####.##. ####..");
- PrintAndLogEx(NORMAL, " ##..... ##..##..##. ..##." " " BANNERMSG1);
- PrintAndLogEx(NORMAL, " ##. ##. .. ##.#####.." " " BANNERMSG2);
- PrintAndLogEx(NORMAL, " .. .. .. ..... " " " BANNERMSG3);
+ PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s"),
+ sq, sq, sq, sq, sq, sq, tr, __, sq, sq, sq, tr, __, __, __, sq, sq, sq, tr, sq, sq, sq, sq, sq, tr, __);
+ PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s"),
+ sq, sq, tl, hl, hl, sq, sq, tr, sq, sq, sq, sq, tr, __, sq, sq, sq, sq, vl, bl, hl, hl, hl, sq, sq, tr);
+ PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s"),
+ sq, sq, sq, sq, sq, sq, tl, br, sq, sq, tl, sq, sq, sq, sq, tl, sq, sq, vl, __, sq, sq, sq, sq, tl, br);
+ PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s")" " BANNERMSG1,
+ sq, sq, tl, hl, hl, hl, br, __, sq, sq, vl, bl, sq, sq, tl, br, sq, sq, vl, __, bl, hl, hl, sq, sq, tr);
+ PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s")" " BANNERMSG2,
+ sq, sq, vl, __, __, __, __, __, sq, sq, vl, __, bl, hl, br, __, sq, sq, vl, sq, sq, sq, sq, sq, tl, br);
+ PrintAndLogEx(NORMAL, " " _BLUE_("%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s")" " BANNERMSG3,
+ bl, hl, br, __, __, __, __, __, bl, hl, br, __, __, __, __, __, bl, hl, br, bl, hl, hl, hl, hl, br, __);
+ break;
+ }
+ case ANSI: {
+ PrintAndLogEx(NORMAL, " " _BLUE_("██████╗ ███╗ ███╗█████╗ "));
+ PrintAndLogEx(NORMAL, " " _BLUE_("██╔══██╗████╗ ████║╚═══██╗"));
+ PrintAndLogEx(NORMAL, " " _BLUE_("██████╔╝██╔████╔██║ ████╔╝"));
+ PrintAndLogEx(NORMAL, " " _BLUE_("██╔═══╝ ██║╚██╔╝██║ ╚══██╗") " " BANNERMSG1);
+ PrintAndLogEx(NORMAL, " " _BLUE_("██║ ██║ ╚═╝ ██║█████╔╝") " " BANNERMSG2);
+ PrintAndLogEx(NORMAL, " " _BLUE_("╚═╝ ╚═╝ ╚═╝╚════╝ ") " " BANNERMSG3);
+ break;
+ }
+ case ASCII: {
+ PrintAndLogEx(NORMAL, " ######. ###. ###.#####. ");
+ PrintAndLogEx(NORMAL, " ##...##.####. ####. ...##.");
+ PrintAndLogEx(NORMAL, " ######..##.####.##. ####..");
+ PrintAndLogEx(NORMAL, " ##..... ##..##..##. ..##." " " BANNERMSG1);
+ PrintAndLogEx(NORMAL, " ##. ##. .. ##.#####.." " " BANNERMSG2);
+ PrintAndLogEx(NORMAL, " .. .. .. ..... " " " BANNERMSG3);
+ break;
+ }
+ }
}
static void showBanner(void) {
@@ -94,14 +101,14 @@ static void showBanner(void) {
#if defined(_WIN32)
if (GetConsoleCP() == 65001) {
// If on Windows and using UTF-8 then we need utf-8 ascii art for banner.
- utf8_showBanner();
+ showBanner_logo(UTF8);
} else {
- ansi_showBanner();
+ showBanner_logo(ANSI);
}
#elif defined(__linux__) || defined(__APPLE__)
- ansi_showBanner();
+ showBanner_logo(ANSI);
#else
- ascii_showBanner();
+ showBanner_logo(ASCII);
#endif
// PrintAndLogEx(NORMAL, "\nSupport iceman on patreon - https://www.patreon.com/iceman1001/");
// PrintAndLogEx(NORMAL, " on paypal - https://www.paypal.me/iceman1001");
From 293b638f717c580a4d447ff6e25ff59152c4d52b Mon Sep 17 00:00:00 2001
From: Philippe Teuwen
Date: Fri, 8 May 2020 11:55:43 +0200
Subject: [PATCH 104/632] fix mem corruption in trace load/list
---
client/src/cmdtrace.c | 12 +++++++-----
1 file changed, 7 insertions(+), 5 deletions(-)
diff --git a/client/src/cmdtrace.c b/client/src/cmdtrace.c
index 2da9ce675..53acb1b92 100644
--- a/client/src/cmdtrace.c
+++ b/client/src/cmdtrace.c
@@ -494,6 +494,7 @@ static int CmdTraceLoad(const char *Cmd) {
if (g_trace)
free(g_trace);
+ g_traceLen = 0;
g_trace = calloc(fsize, sizeof(uint8_t));
if (!g_trace) {
PrintAndLogEx(FAILED, "Cannot allocate memory for trace");
@@ -628,16 +629,17 @@ int CmdTraceList(const char *Cmd) {
uint16_t tracepos = 0;
- // reserve some space.
- if (!g_trace) {
+
+ if (isOnline) {
+ // reserve some space.
+ if (g_trace)
+ free(g_trace);
+ g_traceLen = 0;
g_trace = calloc(PM3_CMD_DATA_SIZE, sizeof(uint8_t));
if (g_trace == NULL) {
PrintAndLogEx(FAILED, "Cannot allocate memory for trace");
return PM3_EMALLOC;
}
- }
-
- if (isOnline) {
// Query for the size of the trace, downloading PM3_CMD_DATA_SIZE
PacketResponseNG response;
if (!GetFromDevice(BIG_BUF, g_trace, PM3_CMD_DATA_SIZE, 0, NULL, 0, &response, 4000, true)) {
From f6c2516779075e45ff72d3579abcfd17b1a53fa0 Mon Sep 17 00:00:00 2001
From: iceman1001
Date: Fri, 8 May 2020 12:30:18 +0200
Subject: [PATCH 105/632] chg: "trace list" - adjust messages
---
client/src/cmdtrace.c | 16 +++++++++++-----
1 file changed, 11 insertions(+), 5 deletions(-)
diff --git a/client/src/cmdtrace.c b/client/src/cmdtrace.c
index 53acb1b92..3e00e10e0 100644
--- a/client/src/cmdtrace.c
+++ b/client/src/cmdtrace.c
@@ -496,7 +496,7 @@ static int CmdTraceLoad(const char *Cmd) {
g_traceLen = 0;
g_trace = calloc(fsize, sizeof(uint8_t));
- if (!g_trace) {
+ if (g_trace == NULL) {
PrintAndLogEx(FAILED, "Cannot allocate memory for trace");
fclose(f);
return PM3_EMALLOC;
@@ -505,7 +505,7 @@ static int CmdTraceLoad(const char *Cmd) {
size_t bytes_read = fread(g_trace, 1, fsize, f);
g_traceLen = bytes_read;
fclose(f);
- PrintAndLogEx(SUCCESS, "Recorded Activity (TraceLen = %lu bytes) loaded from file %s", g_traceLen, filename);
+ PrintAndLogEx(SUCCESS, "Recorded Activity (TraceLen = " _YELLOW_("%lu") " bytes) loaded from " _YELLOW_("%s"), g_traceLen, filename);
return PM3_SUCCESS;
}
@@ -627,10 +627,8 @@ int CmdTraceList(const char *Cmd) {
//Validations
if (errors) return usage_trace_list();
- uint16_t tracepos = 0;
-
-
if (isOnline) {
+
// reserve some space.
if (g_trace)
free(g_trace);
@@ -640,6 +638,9 @@ int CmdTraceList(const char *Cmd) {
PrintAndLogEx(FAILED, "Cannot allocate memory for trace");
return PM3_EMALLOC;
}
+
+ PrintAndLogEx(INFO, "downloading tracelog from device");
+
// Query for the size of the trace, downloading PM3_CMD_DATA_SIZE
PacketResponseNG response;
if (!GetFromDevice(BIG_BUF, g_trace, PM3_CMD_DATA_SIZE, 0, NULL, 0, &response, 4000, true)) {
@@ -665,6 +666,11 @@ int CmdTraceList(const char *Cmd) {
}
PrintAndLogEx(SUCCESS, "Recorded activity (trace len = " _YELLOW_("%lu") " bytes)", g_traceLen);
+ if (g_traceLen == 0) {
+ return PM3_SUCCESS;
+ }
+
+ uint16_t tracepos = 0;
/*
if (protocol == FELICA) {
From 3716d4d82327477d9a724cdee4ab563f2876b31d Mon Sep 17 00:00:00 2001
From: iceman1001
Date: Fri, 8 May 2020 12:42:10 +0200
Subject: [PATCH 106/632] convert OLD->MIX
---
armsrc/appmain.c | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/armsrc/appmain.c b/armsrc/appmain.c
index abfe6a86e..bd8bb8d22 100644
--- a/armsrc/appmain.c
+++ b/armsrc/appmain.c
@@ -1428,7 +1428,7 @@ static void PacketReceived(PacketCommandNG *packet) {
// upload file from client
uint8_t *mem = BigBuf_get_addr();
memcpy(mem + packet->oldarg[0], packet->data.asBytes, PM3_CMD_DATA_SIZE);
- reply_old(CMD_ACK, 1, 0, 0, 0, 0);
+ reply_mix(CMD_ACK, 1, 0, 0, 0, 0);
break;
}
case CMD_SMART_UPGRADE: {
@@ -1628,7 +1628,7 @@ static void PacketReceived(PacketCommandNG *packet) {
// arg1 = RFU
// arg2 = tracelen?
// asbytes = samplingconfig array
- reply_old(CMD_ACK, 1, 0, BigBuf_get_traceLen(), getSamplingConfig(), sizeof(sample_config));
+ reply_mix(CMD_ACK, 1, 0, BigBuf_get_traceLen(), getSamplingConfig(), sizeof(sample_config));
LED_B_OFF();
break;
}
@@ -1759,7 +1759,7 @@ static void PacketReceived(PacketCommandNG *packet) {
int changed = rdv40_spiffs_lazy_mount();
uint32_t size = size_in_spiffs((char *)filename);
if (changed) rdv40_spiffs_lazy_unmount();
- reply_old(CMD_ACK, size, 0, 0, 0, 0);
+ reply_mix(CMD_ACK, size, 0, 0, 0, 0);
LED_B_OFF();
break;
}
@@ -1935,7 +1935,7 @@ static void PacketReceived(PacketCommandNG *packet) {
Flash_UniqueID(info->flashid);
FlashStop();
}
- reply_old(CMD_ACK, isok, 0, 0, info, sizeof(rdv40_validation_t));
+ reply_mix(CMD_ACK, isok, 0, 0, info, sizeof(rdv40_validation_t));
BigBuf_free();
LED_B_OFF();
From 1621b0e7c88d5a1c777bc6a684f5e8633bc3b41d Mon Sep 17 00:00:00 2001
From: iceman1001
Date: Fri, 8 May 2020 13:23:06 +0200
Subject: [PATCH 107/632] trace list - different alloc
---
client/src/cmdtrace.c | 14 ++++++++++----
1 file changed, 10 insertions(+), 4 deletions(-)
diff --git a/client/src/cmdtrace.c b/client/src/cmdtrace.c
index 3e00e10e0..6cbfc2e7a 100644
--- a/client/src/cmdtrace.c
+++ b/client/src/cmdtrace.c
@@ -632,7 +632,9 @@ int CmdTraceList(const char *Cmd) {
// reserve some space.
if (g_trace)
free(g_trace);
+
g_traceLen = 0;
+
g_trace = calloc(PM3_CMD_DATA_SIZE, sizeof(uint8_t));
if (g_trace == NULL) {
PrintAndLogEx(FAILED, "Cannot allocate memory for trace");
@@ -645,18 +647,22 @@ int CmdTraceList(const char *Cmd) {
PacketResponseNG response;
if (!GetFromDevice(BIG_BUF, g_trace, PM3_CMD_DATA_SIZE, 0, NULL, 0, &response, 4000, true)) {
PrintAndLogEx(WARNING, "timeout while waiting for reply.");
+ free(g_trace);
return PM3_ETIMEOUT;
}
g_traceLen = response.oldarg[2];
+
+ // if tracelog buffer was larger and we need to download more.
if (g_traceLen > PM3_CMD_DATA_SIZE) {
- uint8_t *p = realloc(g_trace, g_traceLen);
- if (p == NULL) {
+
+ free(g_trace);
+ g_trace = calloc(g_traceLen, sizeof(uint8_t));
+ if (g_trace == NULL) {
PrintAndLogEx(FAILED, "Cannot allocate memory for trace");
- free(g_trace);
return PM3_EMALLOC;
}
- g_trace = p;
+
if (!GetFromDevice(BIG_BUF, g_trace, g_traceLen, 0, NULL, 0, NULL, 2500, false)) {
PrintAndLogEx(WARNING, "command execution time out");
free(g_trace);
From f70210ebef5eba908ffd862ac614c5a147ed99cf Mon Sep 17 00:00:00 2001
From: iceman1001
Date: Fri, 8 May 2020 13:27:45 +0200
Subject: [PATCH 108/632] textual
---
client/src/comms.c | 9 +++++----
1 file changed, 5 insertions(+), 4 deletions(-)
diff --git a/client/src/comms.c b/client/src/comms.c
index de5eafb24..4c0a8d990 100644
--- a/client/src/comms.c
+++ b/client/src/comms.c
@@ -830,6 +830,9 @@ static bool dl_it(uint8_t *dest, uint32_t bytes, PacketResponseNG *response, siz
if (getReply(response)) {
+ if (response->cmd == CMD_ACK)
+ return true;
+
// sample_buf is a array pointer, located in data.c
// arg0 = offset in transfer. Startindex of this chunk
// arg1 = length bytes to transfer
@@ -852,8 +855,6 @@ static bool dl_it(uint8_t *dest, uint32_t bytes, PacketResponseNG *response, siz
memcpy(dest + offset, response->data.asBytes, copy_bytes);
bytes_completed += copy_bytes;
- } else if (response->cmd == CMD_ACK) {
- return true;
} else if (response->cmd == CMD_WTX && response->length == sizeof(uint16_t)) {
uint16_t wtx = response->data.asDwords[0] & 0xFFFF;
PrintAndLogEx(DEBUG, "Got Waiting Time eXtension request %i ms", wtx);
@@ -870,8 +871,8 @@ static bool dl_it(uint8_t *dest, uint32_t bytes, PacketResponseNG *response, siz
if (msclock() - tmp_clk > 3000 && show_warning) {
// 3 seconds elapsed (but this doesn't mean the timeout was exceeded)
- PrintAndLogEx(NORMAL, "Waiting for a response from the Proxmark3...");
- PrintAndLogEx(NORMAL, "You can cancel this operation by pressing the pm3 button");
+ PrintAndLogEx(INFO, "Waiting for a response from the Proxmark3...");
+ PrintAndLogEx(INFO, "You can cancel this operation by pressing the pm3 button");
show_warning = false;
}
}
From 1efda3aa849f1885f3934a1f5d316438076e92f8 Mon Sep 17 00:00:00 2001
From: iceman1001