diff --git a/CHANGELOG.md b/CHANGELOG.md index b98f3f5d0..dcc4dd5be 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,9 +3,12 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] - - Removed `save_restoreDB` - replaced by `buffer_savestate_t` implementation (@HACKhalo2) - Removed `save_restoreGB` - replaced by `buffer_savestate_t` implementation (@HACKhalo2) +- Changed `lf hitag dump --nrar` - now supports attack 1 from "gone in 360 seconds" paper. Thanks @kevsecurity! (@iceman1001) +- Added `lf hitag selftest` - converted from RFIDLers selftest (@iceman1001) +- Added `lf hitag chk` - dictionary attack against card (@iceman1001) +- Added `lf hitag lookup` - verify collected challenges aginst dictionary (@iceman1001) - Updated windows workflow to use latest setup-wsl script (@iceman1001) - Added a micro second clock in the client (@iceman1001) - Fix `hf mfdes read` - buffer overflow when reading large files (@iceman1001) diff --git a/armsrc/Makefile b/armsrc/Makefile index b42061267..2f27534ef 100644 --- a/armsrc/Makefile +++ b/armsrc/Makefile @@ -71,7 +71,7 @@ else endif ifneq (,$(findstring WITH_HITAG,$(APP_CFLAGS))) - SRC_HITAG = hitag2_crypto.c hitag2.c hitagS.c + SRC_HITAG = hitag2_crypto.c hitag2.c hitagS.c hitag2_crack.c APP_CFLAGS += -I../common/hitag2 else SRC_HITAG = diff --git a/armsrc/appmain.c b/armsrc/appmain.c index 22bdc0ca1..8883f8ab4 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -40,6 +40,7 @@ #include "thinfilm.h" #include "felica.h" #include "hitag2.h" +#include "hitag2_crack.h" #include "hitagS.h" #include "em4x50.h" #include "em4x70.h" @@ -1131,7 +1132,7 @@ static void PacketReceived(PacketCommandNG *packet) { #ifdef WITH_HITAG case CMD_LF_HITAG_SNIFF: { // Eavesdrop Hitag tag, args = type SniffHitag2(true); -// SniffHitag2(packet->oldarg[0]); + //hitag_sniff(); reply_ng(CMD_LF_HITAG_SNIFF, PM3_SUCCESS, NULL, 0); break; } @@ -1139,8 +1140,24 @@ static void PacketReceived(PacketCommandNG *packet) { SimulateHitag2(true); break; } + case CMD_LF_HITAG2_CRACK: { + lf_hitag_data_t *payload = (lf_hitag_data_t *) packet->data.asBytes; + ht2_crack(payload->NrAr); + break; + } case CMD_LF_HITAG_READER: { // Reader for Hitag tags, args = type and function - ReaderHitag((hitag_function)packet->oldarg[0], (hitag_data *)packet->data.asBytes, true); + lf_hitag_data_t *payload = (lf_hitag_data_t *) packet->data.asBytes; + + switch (payload->cmd) { + case RHT2F_UID_ONLY: { + ht2_read_uid(NULL, true, true, false); + break; + } + default: { + ReaderHitag(payload, true); + break; + } + } break; } case CMD_LF_HITAGS_SIMULATE: { // Simulate Hitag s tag, args = memory content @@ -1148,25 +1165,28 @@ static void PacketReceived(PacketCommandNG *packet) { break; } case CMD_LF_HITAGS_TEST_TRACES: { // Tests every challenge within the given file - Hitag_check_challenges(packet->data.asBytes, packet->oldarg[0], true); + Hitag_check_challenges(packet->data.asBytes, packet->length, true); break; } - case CMD_LF_HITAGS_READ: { //Reader for only Hitag S tags, args = key or challenge - ReadHitagS((hitag_function)packet->oldarg[0], (hitag_data *)packet->data.asBytes, true); + case CMD_LF_HITAGS_READ: { // Reader for only Hitag S tags, args = key or challenge + lf_hitag_data_t *payload = (lf_hitag_data_t *) packet->data.asBytes; + ReadHitagS(payload, true); break; } - case CMD_LF_HITAGS_WRITE: { //writer for Hitag tags args=data to write,page and key or challenge - if ((hitag_function)packet->oldarg[0] < 10) { - WritePageHitagS((hitag_function)packet->oldarg[0], (hitag_data *)packet->data.asBytes, packet->oldarg[2], true); - } else { - WriterHitag((hitag_function)packet->oldarg[0], (hitag_data *)packet->data.asBytes, packet->oldarg[2], true); - } + case CMD_LF_HITAGS_WRITE: { + lf_hitag_data_t *payload = (lf_hitag_data_t *) packet->data.asBytes; + WritePageHitagS(payload, true); + break; + } + case CMD_LF_HITAG2_WRITE: { + lf_hitag_data_t *payload = (lf_hitag_data_t *) packet->data.asBytes; + WriterHitag(payload, true); break; } case CMD_LF_HITAG_ELOAD: { lf_hitag_t *payload = (lf_hitag_t *) packet->data.asBytes; uint8_t *mem = BigBuf_get_EM_addr(); - memcpy((uint8_t *)mem, payload->data, payload->len); + memcpy(mem, payload->data, payload->len); break; } #endif @@ -1371,7 +1391,7 @@ static void PacketReceived(PacketCommandNG *packet) { struct p *payload = (struct p *) packet->data.asBytes; SetTag15693Uid_v2(payload->uid); break; - } + } case CMD_HF_ISO15693_SLIX_DISABLE_EAS: { struct p { uint8_t pwd[4]; diff --git a/armsrc/hitag2.c b/armsrc/hitag2.c index ff345afb7..adc567d59 100644 --- a/armsrc/hitag2.c +++ b/armsrc/hitag2.c @@ -146,6 +146,8 @@ static void hitag2_init(void) { #define HITAG_T_TAG_CAPTURE_THREE_HALF 41 #define HITAG_T_TAG_CAPTURE_FOUR_HALF 57 +#define HT2_MAX_NRSZ ((8 * HITAG_FRAME_LEN + 5) * 2) + /* // sim static void hitag_send_bit(int bit, bool ledcontrol) { @@ -319,9 +321,9 @@ static void hitag2_handle_reader_command(uint8_t *rx, const size_t rxlen, uint8_ // reader/writer // returns how long it took -static uint32_t hitag_reader_send_bit(int bit, bool ledcontrol) { +static uint32_t hitag_reader_send_bit(int bit) { uint32_t wait = 0; - if (ledcontrol) LED_A_ON(); + // Binary pulse length modulation (BPLM) is used to encode the data stream // This means that a transmission of a one takes longer than that of a zero @@ -345,17 +347,43 @@ static uint32_t hitag_reader_send_bit(int bit, bool ledcontrol) { wait += HITAG_T_1 - HITAG_T_LOW; } - if (ledcontrol) LED_A_OFF(); return wait; } // reader / writer commands -static uint32_t hitag_reader_send_frame(const uint8_t *frame, size_t frame_len, bool ledcontrol) { +// frame_len is in number of bits? +static uint32_t hitag_reader_send_frame(const uint8_t *frame, size_t frame_len) { uint32_t wait = 0; // Send the content of the frame for (size_t i = 0; i < frame_len; i++) { - wait += hitag_reader_send_bit((frame[i / 8] >> (7 - (i % 8))) & 1, ledcontrol); + wait += hitag_reader_send_bit((frame[i / 8] >> (7 - (i % 8))) & 1); + } + + // Enable modulation, which means, drop the field + lf_modulation(true); + + // Wait for 4-10 times the carrier period + lf_wait_periods(HITAG_T_LOW); + wait += HITAG_T_LOW; + + // Disable modulation, just activates the field again + lf_modulation(false); + + // t_stop, high field for stop condition (> 36) + lf_wait_periods(HITAG_T_STOP); + wait += HITAG_T_STOP; + return wait; +} + +// reader / writer commands +// frame_len is in number of bits? +static uint32_t hitag_reader_send_framebits(const uint8_t *frame, size_t frame_len) { + + uint32_t wait = 0; + // Send the content of the frame + for (size_t i = 0; i < frame_len; i++) { + wait += hitag_reader_send_bit(frame[i]); } // Enable modulation, which means, drop the field @@ -739,7 +767,7 @@ static bool hitag2_crypto(uint8_t *rx, const size_t rxlen, uint8_t *tx, size_t * ht2_hitag2_cipher_transcrypt(&cipher_state, rx, rxlen / 8, rxlen % 8); } - if (bCrypto && !bAuthenticating && write) { + if (bCrypto && (bAuthenticating == false) && write) { if (hitag2_write_page(rx, rxlen, tx, txlen) == false) { return false; } @@ -808,22 +836,26 @@ static bool hitag2_crypto(uint8_t *rx, const size_t rxlen, uint8_t *tx, size_t * bCrypto = true; bAuthenticating = true; } else { + // stage 2, got config byte+password TAG, discard as will read later if (bAuthenticating) { + bAuthenticating = false; + if (write) { if (hitag2_write_page(rx, rxlen, tx, txlen) == false) { return false; } break; } - } - // stage 2+, got data block - else { + + } else { // stage 2+, got data block + // Store the received block memcpy(tag.sectors[blocknr], rx, 4); blocknr++; } + if (blocknr > 7) { DBG DbpString("Read successful!"); bSuccessful = true; @@ -834,67 +866,99 @@ static bool hitag2_crypto(uint8_t *rx, const size_t rxlen, uint8_t *tx, size_t * tx[1] = ((blocknr ^ 7) << 6); } } + break; } - break; - - // Unexpected response default: { DBG Dbprintf("Unknown frame length: " _RED_("%d"), rxlen); return false; } - break; } } - if (bCrypto) { - // We have to return now to avoid double encryption - if (bAuthenticating == false) { - ht2_hitag2_cipher_transcrypt(&cipher_state, tx, *txlen / 8, *txlen % 8); - } + // try to avoid double encryption calls + if (bCrypto && bAuthenticating == false) { + ht2_hitag2_cipher_transcrypt(&cipher_state, tx, *txlen / 8, *txlen % 8); } return true; } -static bool hitag2_authenticate(uint8_t *rx, const size_t rxlen, uint8_t *tx, size_t *txlen) { +static bool hitag2_authenticate(uint8_t *rx, const size_t rxlen, uint8_t *tx, size_t *txlen, bool write) { // Reset the transmission frame length *txlen = 0; // Try to find out which command was send by selecting on length (in bits) switch (rxlen) { - // No answer, try to resurrect case 0: { + // No answer, try to resurrect // Stop if there is no answer while we are in crypto mode (after sending NrAr) if (bCrypto) { - DBG DbpString("Authentication failed!"); + DBG DbpString("No answer after sending NrAr!"); return false; - } - *txlen = 5; - memcpy(tx, "\xC0", nbytes(*txlen)); - } - break; + } else { - // Received UID, crypto tag answer + // Failed during authentication + if (bAuthenticating) { + DBG DbpString("Authentication - failed!"); + return false; + } + + DBG DbpString("Authenticating - send 0xC0"); + *txlen = 5; + memcpy(tx, "\xC0", nbytes(*txlen)); + } + break; + } case 32: { - if (!bCrypto) { + // Received UID or crypto tag answer + if (bCrypto == false) { *txlen = 64; - memcpy(tx, NrAr, 8); + memcpy(tx, NrAr, sizeof(NrAr)); bCrypto = true; + bAuthenticating = true; + DBG DbpString("Authenticating sending NrAr"); } else { DBG DbpString("Authentication successful!"); - return true; - } - } - break; - // Unexpected response + // stage 2, got config byte+password TAG, discard as will read later + if (bAuthenticating) { + + bAuthenticating = false; + + if (write) { + if (hitag2_write_page(rx, rxlen, tx, txlen) == false) { + return false; + } + break; + } + + } else { // stage 2+, got data block + + // Store the received block + memcpy(tag.sectors[blocknr], rx, 4); + blocknr++; + } + + if (blocknr > 7) { + DBG DbpString("Read successful!"); + bSuccessful = true; + return false; + } else { + + DBG Dbprintf("Sending read block %u", blocknr); + + *txlen = 10; + tx[0] = 0xc0 | (blocknr << 3) | ((blocknr ^ 7) >> 2); + tx[1] = ((blocknr ^ 7) << 6); + } + } + break; + } default: { - DBG Dbprintf("Unknown frame length: %d", rxlen); + DBG Dbprintf("Unknown frame length: " _RED_("%d"), rxlen); return false; } - break; } - return true; } @@ -936,7 +1000,7 @@ static bool hitag2_test_auth_attempts(uint8_t *rx, const size_t rxlen, uint8_t * memcpy(tx, NrAr, 8); bCrypto = true; } else { - Dbprintf("auth: %02x%02x%02x%02x%02x%02x%02x%02x OK", NrAr[0], NrAr[1], NrAr[2], NrAr[3], NrAr[4], NrAr[5], NrAr[6], NrAr[7]); + Dbprintf("auth: %02x%02x%02x%02x%02x%02x%02x%02x ( " _GREEN_("ok") " )", NrAr[0], NrAr[1], NrAr[2], NrAr[3], NrAr[4], NrAr[5], NrAr[6], NrAr[7]); bCrypto = false; if ((auth_table_pos + 8) == auth_table_len) { return false; @@ -948,7 +1012,7 @@ static bool hitag2_test_auth_attempts(uint8_t *rx, const size_t rxlen, uint8_t * break; default: { - Dbprintf("Unknown frame length: %d", rxlen); + Dbprintf("Unknown frame length: " _RED_("%d"), rxlen); return false; } break; @@ -957,53 +1021,25 @@ static bool hitag2_test_auth_attempts(uint8_t *rx, const size_t rxlen, uint8_t * return true; } -static bool hitag2_read_uid(uint8_t *rx, const size_t rxlen, uint8_t *tx, size_t *txlen) { - // Reset the transmission frame length - *txlen = 0; - - // Try to find out which command was send by selecting on length (in bits) - switch (rxlen) { - // No answer, try to resurrect - case 0: { - // Just starting or if there is no answer - *txlen = 5; - memcpy(tx, "\xC0", nbytes(*txlen)); - } - break; - // Received UID - case 32: { - // Check if we received answer tag (at) - if (bAuthenticating) { - bAuthenticating = false; - } else { - // Store the received block - memcpy(tag.sectors[blocknr], rx, 4); - blocknr++; - - DBG Dbhexdump(4, rx, false); - } - if (blocknr > 0) { - DBG DbpString("Read successful!"); - bSuccessful = true; - return true; - } - } - break; - // Unexpected response - default: { - DBG Dbprintf("Unknown frame length: " _RED_("%d"), rxlen); - return false; - } - break; - } - return true; -} - -void EloadHitag(const uint8_t *data, uint16_t len) { - memcpy(tag.sectors, data, sizeof(tag.sectors)); -} - // Hitag2 Sniffing +void hitag_sniff(void) { + + FpgaDownloadAndGo(FPGA_BITSTREAM_LF); + + BigBuf_free(); + BigBuf_Clear_ext(false); + clear_trace(); + set_tracing(true); + + // Set up eavesdropping mode, frequency divisor which will drive the FPGA + // and analog mux selection. + FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT | FPGA_LF_EDGE_DETECT_TOGGLE_MODE); + FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); // 125Khz + SetAdcMuxFor(GPIO_MUXSEL_LOPKD); + RELAY_OFF(); + +} + // T0 18-22 fc (total time ZERO) // T1 26-32 fc (total time ONE) @@ -1024,8 +1060,7 @@ void SniffHitag2(bool ledcontrol) { lf_init(false, false, ledcontrol); // no logging of the raw signal - // g_logging = lf_get_reader_modulation(); - g_logging = false; + g_logging = true; uint32_t total_count = 0; uint8_t rx[HITAG_FRAME_BIT_COUNT * 2]; @@ -1050,9 +1085,12 @@ void SniffHitag2(bool ledcontrol) { // Detected two sequential equal bits and a modulation switch // NRZ modulation: (11 => --|) or (11 __|) rx[rxlen++] = mod_state; + if (rxlen < sizeof(rx)) { rx[rxlen++] = mod_state; + } // toggle tag modulation state mod_state ^= 1; + } else if (periods > 0 && periods < 24) { // Detected one bit and a modulation switch // NRZ modulation: (1 => -|) or (0 _|) @@ -1060,49 +1098,55 @@ void SniffHitag2(bool ledcontrol) { mod_state ^= 1; } else { mod_state ^= 1; + // The function lf_count_edge_periods() returns > 64 periods, this is not a valid number periods + Dbprintf("Detected unexpected period count... " _YELLOW_("%zu"), periods); break; } + } - if (rxlen == 0) + if (rxlen < 10) { continue; + } // tag sends 11111 + uid, - bool got_tag = ((memcmp(rx, "\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00", 10) == 0)); + bool got_tag = (memcmp(rx, "\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00", 10) == 0); + + Dbprintf("periods... %zu rxlen... %u", periods, rxlen); + Dbhexdump(rxlen, rx, false); if (got_tag) { - // mqnchester decode + bool bad_man = false; uint16_t bitnum = 0; + // mqnchester decode for (uint16_t i = 0; i < rxlen; i += 2) { + if (rx[i] == 1 && (rx[i + 1] == 0)) { rx[bitnum++] = 0; } else if ((rx[i] == 0) && rx[i + 1] == 1) { rx[bitnum++] = 1; } else { bad_man = true; + break; } } - + // Dbprintf(_YELLOW_("TAG") " rxlen... %u bitnum... %u", rxlen, bitnum); if (bad_man) { - DBG DbpString("bad manchester"); - continue; + Dbprintf("bad manchester ( bitnum %u )", bitnum); + continue;; } if (bitnum < 5) { - DBG DbpString("too few bits"); + DbpString("too few bits"); continue; } - // skip header 11111 - uint16_t i = 0; - if (got_tag) { - i = 5; - } - - // Pack the response into a byte array + // Pack the response into a byte array, + // and skip header 11111 (start at idx 5) rxlen = 0; - for (; i < bitnum; i++) { + + for (uint16_t i = 5; i < bitnum; i++) { uint8_t b = rx[i]; rx[rxlen >> 3] |= b << (7 - (rxlen % 8)); rxlen++; @@ -1114,27 +1158,41 @@ void SniffHitag2(bool ledcontrol) { } // nothing to log - if (rxlen == 0) + if (rxlen == 0) { + if (ledcontrol) LED_A_INV(); continue; + } - LogTraceBits(rx, rxlen, 0, 0, false); + LogTraceBits(rx, rxlen, 0, periods, false); total_count += nbytes(rxlen); - } else { - // decode reader comms - LogTrace(rx, rxlen, 0, 0, NULL, true); - total_count += rxlen; - // Pack the response into a byte array - // LogTraceBits(rx, rdr, 0, 0, true); - // total_count += nbytes(rdr); + } else { + + // nothing to log + if (rxlen < 3) { + if (ledcontrol) LED_A_INV(); + continue; + } + + uint16_t n = 0; + for (uint16_t i = 0; i < rxlen; i++) { + uint8_t b = rx[i]; + rx[n >> 3] |= b << (7 - (n % 8)); + n++; + } + + // decode reader comms + LogTraceBits(rx, n, 0, periods, true); + total_count += nbytes(n); } if (ledcontrol) LED_A_INV(); } lf_finalize(ledcontrol); - Dbprintf("Collected %u bytes", total_count); - + switch_off(); + BigBuf_free(); + } */ // Set up eavesdropping mode, frequency divisor which will drive the FPGA @@ -1145,11 +1203,11 @@ void SniffHitag2(bool ledcontrol) { RELAY_OFF(); // Configure output pin that is connected to the FPGA (for modulating) - AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT; - AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT; +// AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT; +// AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT; // Disable modulation, we are going to eavesdrop, not modulate ;) - LOW(GPIO_SSC_DOUT); +// LOW(GPIO_SSC_DOUT); // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the reader frames AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC1); @@ -1168,31 +1226,35 @@ void SniffHitag2(bool ledcontrol) { // Assert a sync signal. This sets all timers to 0 on next active clock edge AT91C_BASE_TCB->TCB_BCR = 1; - int frame_count = 0, response = 0, overflow = 0, lastbit = 1, tag_sof = 4; + int frame_count = 0, response = 0, lastbit = 1, tag_sof = 4; + int overflow = 0; bool rising_edge, reader_frame = false, bSkip = true; - uint8_t rx[HITAG_FRAME_LEN]; + +// bool exit_due_to_overflow; + // HACK -- add one byte to avoid rewriting manchester decoder for edge case + uint8_t rx[HITAG_FRAME_LEN + 1]; size_t rxlen = 0; auth_table_len = 0; auth_table_pos = 0; - // Reset the received frame, frame count and timing info - memset(rx, 0x00, sizeof(rx)); - - auth_table = (uint8_t *)BigBuf_malloc(AUTH_TABLE_LENGTH); - memset(auth_table, 0x00, AUTH_TABLE_LENGTH); + auth_table = (uint8_t *)BigBuf_calloc(AUTH_TABLE_LENGTH); while (BUTTON_PRESS() == false) { WDT_HIT(); - memset(rx, 0x00, sizeof(rx)); + +// bool exit_due_to_overflow = false; // Receive frame, watch for at most T0 * EOF periods while (AT91C_BASE_TC1->TC_CV < (HITAG_T0 * HITAG_T_EOF)) { + // Check if rising edge in modulation is detected if (AT91C_BASE_TC1->TC_SR & AT91C_TC_LDRAS) { + // Retrieve the new timing values - int ra = (AT91C_BASE_TC1->TC_RA / HITAG_T0); + int ra = (AT91C_BASE_TC1->TC_RA / HITAG_T0) + overflow; + overflow = 0; // Find out if we are dealing with a rising or falling edge rising_edge = (AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_FRAME) > 0; @@ -1206,7 +1268,7 @@ void SniffHitag2(bool ledcontrol) { } // Only handle if reader frame and rising edge, or tag frame and falling edge - if (reader_frame == rising_edge) { + if (reader_frame != rising_edge) { overflow += ra; continue; } @@ -1216,6 +1278,7 @@ void SniffHitag2(bool ledcontrol) { overflow = 0; if (reader_frame) { + if (ledcontrol) LED_B_ON(); // Capture reader frame if (ra >= HITAG_T_STOP) { @@ -1224,6 +1287,7 @@ void SniffHitag2(bool ledcontrol) { // } // Capture the T0 periods that have passed since last communication or field drop (reset) response = (ra - HITAG_T_LOW); + if (rxlen != 0) { Dbprintf("ra - HITAG_T_LOW... %i", response); } } else if (ra >= HITAG_T_1_MIN) { // '1' bit @@ -1279,15 +1343,16 @@ void SniffHitag2(bool ledcontrol) { } } } - } + } // end while // Check if frame was captured if (rxlen) { + frame_count++; LogTraceBits(rx, rxlen, response, 0, reader_frame); // Check if we recognize a valid authentication attempt - if (nbytes(rxlen) == 8) { + if (rxlen == 64) { // Store the authentication attempt if (auth_table_len < (AUTH_TABLE_LENGTH - 8)) { memcpy(auth_table + auth_table_len, rx, 8); @@ -1295,6 +1360,11 @@ void SniffHitag2(bool ledcontrol) { } } + if (ledcontrol) { + LED_B_OFF(); + LED_C_OFF(); + } + response = 0; reader_frame = false; lastbit = 1; @@ -1317,13 +1387,13 @@ void SniffHitag2(bool ledcontrol) { // Reset the timer to restart while-loop that receives frames AT91C_BASE_TC1->TC_CCR = AT91C_TC_SWTRG; - AT91C_BASE_TC1->TC_CCR = AT91C_TC_SWTRG; // Assert a sync signal. This sets all timers to 0 on next active clock edge AT91C_BASE_TCB->TCB_BCR = 1; } if (ledcontrol) LEDsoff(); + AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS; AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKDIS; @@ -1334,6 +1404,7 @@ void SniffHitag2(bool ledcontrol) { BigBuf_free(); } + // Hitag2 simulation void SimulateHitag2(bool ledcontrol) { @@ -1468,7 +1539,7 @@ void SimulateHitag2(bool ledcontrol) { } else { reader_modulation ^= 1; // The function lf_count_edge_periods() returns > 64 periods, this is not a valid number periods - Dbprintf("Detected unexpected period count: %d", periods); + Dbprintf("Detected unexpected period count: %zu", periods); break; } } @@ -1488,6 +1559,10 @@ void SimulateHitag2(bool ledcontrol) { // The last modulation change of a zero is not detected, but we should take // the half period in account, otherwise the demodulator will fail. if ((nrzs % 2) != 0) { + if (nrzs >= max_nrzs) { + Dbprintf("max_nrzs (%d) is odd? Must be even!", max_nrzs); // should be a static assert above + continue; + } nrz_samples[nrzs++] = reader_modulation; } @@ -1558,7 +1633,7 @@ void SimulateHitag2(bool ledcontrol) { // reply_ng(CMD_LF_HITAG_SIMULATE, (checked == -1) ? PM3_EOPABORTED : PM3_SUCCESS, (uint8_t *)tag.sectors, tag_size); } -void ReaderHitag(hitag_function htf, const hitag_data *htd, bool ledcontrol) { +void ReaderHitag(const lf_hitag_data_t *payload, bool ledcontrol) { uint32_t command_start = 0, command_duration = 0; uint32_t response_start = 0, response_duration = 0; @@ -1587,7 +1662,7 @@ void ReaderHitag(hitag_function htf, const hitag_data *htd, bool ledcontrol) { clear_trace(); // Check configuration - switch (htf) { + switch (payload->cmd) { case RHT1F_PLAIN: { DBG Dbprintf("Read public blocks in plain mode"); // this part will be unreadable @@ -1597,15 +1672,19 @@ void ReaderHitag(hitag_function htf, const hitag_data *htd, bool ledcontrol) { } case RHT1F_AUTHENTICATE: { DBG Dbprintf("Read all blocks in authed mode"); - memcpy(nonce, htd->ht1auth.nonce, 4); - memcpy(key, htd->ht1auth.key, 4); - memcpy(logdata_0, htd->ht1auth.logdata_0, 4); - memcpy(logdata_1, htd->ht1auth.logdata_1, 4); + + memcpy(nonce, payload->nonce, 4); + memcpy(key, payload->key, 4); + memcpy(logdata_0, payload->logdata_0, 4); + memcpy(logdata_1, payload->logdata_1, 4); + // TEST memset(nonce, 0x0, 4); memset(logdata_1, 0x00, 4); + byte_value = 0; - key_no = htd->ht1auth.key_no; + key_no = payload->key_no; + DBG Dbprintf("Authenticating using key #%u :", key_no); DBG Dbhexdump(4, key, false); DBG DbpString("Nonce:"); @@ -1619,31 +1698,34 @@ void ReaderHitag(hitag_function htf, const hitag_data *htd, bool ledcontrol) { } case RHT2F_PASSWORD: { DBG Dbprintf("List identifier in password mode"); - if (memcmp(htd->pwd.password, "\x00\x00\x00\x00", 4) == 0) + if (memcmp(payload->pwd, "\x00\x00\x00\x00", 4) == 0) { memcpy(password, tag.sectors[1], sizeof(password)); - else - memcpy(password, htd->pwd.password, sizeof(password)); - + } else { + memcpy(password, payload->pwd, sizeof(password)); + } blocknr = 0; bPwd = false; bAuthenticating = false; break; } case RHT2F_AUTHENTICATE: { - DBG DbpString("Authenticating using nr,ar pair:"); - memcpy(NrAr, htd->auth.NrAr, 8); + DBG DbpString("Authenticating using NrAr pair:"); + memcpy(NrAr, payload->NrAr, 8); DBG Dbhexdump(8, NrAr, false); + // We can't read block 0, 1, 2.. + blocknr = 3; bCrypto = false; + bPwd = false; bAuthenticating = false; break; } case RHT2F_CRYPTO: { DBG DbpString("Authenticating using key:"); - memcpy(key, htd->crypto.key, 6); //HACK; 4 or 6?? I read both in the code. + memcpy(key, payload->key, 6); //HACK; 4 or 6?? I read both in the code. DBG Dbhexdump(6, key, false); DBG DbpString("Nonce:"); DBG Dbhexdump(4, nonce, false); - memcpy(nonce, htd->crypto.data, 4); + memcpy(nonce, payload->data, 4); blocknr = 0; bCrypto = false; bAuthenticating = false; @@ -1656,15 +1738,10 @@ void ReaderHitag(hitag_function htf, const hitag_data *htd, bool ledcontrol) { bCrypto = false; break; } - case RHT2F_UID_ONLY: { - blocknr = 0; - bCrypto = false; - bAuthenticating = false; - break; - } default: { - DBG Dbprintf("Error, unknown function: %d", htf); + DBG Dbprintf("Error, unknown function: " _RED_("%d"), payload->cmd); set_tracing(false); + reply_ng(CMD_LF_HITAG_READER, PM3_ESOFT, NULL, 0); return; } } @@ -1674,11 +1751,9 @@ void ReaderHitag(hitag_function htf, const hitag_data *htd, bool ledcontrol) { // hitag2 state machine? hitag2_init(); - uint8_t attempt_count = 0; - // Tag specific configuration settings (sof, timings, etc.) // TODO HTS - /* if (htf <= HTS_LAST_CMD) { + /* if (payload->cmd <= HTS_LAST_CMD) { // hitagS settings t_wait_1 = 204; t_wait_2 = 128; @@ -1686,14 +1761,14 @@ void ReaderHitag(hitag_function htf, const hitag_data *htd, bool ledcontrol) { tag_size = 8; DBG DbpString("Configured for " _YELLOW_("HitagS") " reader"); } else */ - if (htf <= HT1_LAST_CMD) { + if (payload->cmd <= HT1_LAST_CMD) { // hitag1 settings t_wait_1 = 204; t_wait_2 = 128; tag_size = 256; flipped_bit = 0; - DBG DbpString("Configured for hitag1 reader"); - } else if (htf <= HT2_LAST_CMD) { + DBG DbpString("Configured for " _YELLOW_("Hitag 1") " reader"); + } else if (payload->cmd <= HT2_LAST_CMD) { // hitag2 settings t_wait_1 = HITAG_T_WAIT_1_MIN; t_wait_2 = HITAG_T_WAIT_2_MIN; @@ -1733,7 +1808,7 @@ void ReaderHitag(hitag_function htf, const hitag_data *htd, bool ledcontrol) { // By default reset the transmission buffer tx = txbuf; - switch (htf) { + switch (payload->cmd) { case RHT1F_PLAIN: { bStop = !hitag_plain(rx, rxlen, tx, &txlen, false); break; @@ -1747,7 +1822,7 @@ void ReaderHitag(hitag_function htf, const hitag_data *htd, bool ledcontrol) { break; } case RHT2F_AUTHENTICATE: { - bStop = !hitag2_authenticate(rx, rxlen, tx, &txlen); + bStop = !hitag2_authenticate(rx, rxlen, tx, &txlen, false); break; } case RHT2F_CRYPTO: { @@ -1758,20 +1833,12 @@ void ReaderHitag(hitag_function htf, const hitag_data *htd, bool ledcontrol) { bStop = !hitag2_test_auth_attempts(rx, rxlen, tx, &txlen); break; } - case RHT2F_UID_ONLY: { - bStop = !hitag2_read_uid(rx, rxlen, tx, &txlen); - - attempt_count++; //attempt 3 times to get uid then quit - if ((bStop == false) && (attempt_count == 3)) { - bStop = true; - } - break; - } default: { - DBG Dbprintf("Error, unknown function: %d", htf); + DBG Dbprintf("Error, unknown function: " _RED_("%d"), payload->cmd); goto out; } } + if (bStop) { break; } @@ -1791,7 +1858,7 @@ void ReaderHitag(hitag_function htf, const hitag_data *htd, bool ledcontrol) { } // Transmit the reader frame - command_duration = hitag_reader_send_frame(tx, txlen, ledcontrol); + command_duration = hitag_reader_send_frame(tx, txlen); response_start = command_start + command_duration; // Let the antenna and ADC values settle @@ -1855,7 +1922,9 @@ void ReaderHitag(hitag_function htf, const hitag_data *htd, bool ledcontrol) { // Detected two sequential equal bits and a modulation switch // NRZ modulation: (11 => --|) or (11 __|) nrz_samples[nrzs++] = tag_modulation; - nrz_samples[nrzs++] = tag_modulation; + if (nrzs < max_nrzs) { + nrz_samples[nrzs++] = tag_modulation; + } response_duration += periods; // Invert tag modulation state tag_modulation ^= 1; @@ -1894,6 +1963,11 @@ void ReaderHitag(hitag_function htf, const hitag_data *htd, bool ledcontrol) { // The last modulation change of a zero is not detected, but we should take // the half period in account, otherwise the demodulator will fail. if ((nrzs % 2) != 0) { + + if (nrzs >= max_nrzs) { + DBG Dbprintf("max_nrzs ( " _YELLOW_("%zu") " ) is odd? Must be even!", max_nrzs); + continue; + } nrz_samples[nrzs++] = tag_modulation; } @@ -1955,19 +2029,19 @@ out: // release allocated memory from BigBuff. BigBuf_free(); - // + if (checked == -1) { - // user interupted - reply_mix(CMD_ACK, false, 0, 0, 0, 0); + reply_ng(CMD_LF_HITAG_READER, PM3_ESOFT, NULL, 0); } - if (bSuccessful) - reply_mix(CMD_ACK, bSuccessful, 0, 0, (uint8_t *)tag.sectors, tag_size); - else - reply_mix(CMD_ACK, bSuccessful, 0, 0, 0, 0); + reply_ng(CMD_LF_HITAG_READER + , (bSuccessful) ? PM3_SUCCESS : PM3_EFAILED + , (uint8_t *)tag.sectors + , tag_size + ); } -void WriterHitag(hitag_function htf, const hitag_data *htd, int page, bool ledcontrol) { +void WriterHitag(const lf_hitag_data_t *payload, bool ledcontrol) { uint32_t command_start = 0; uint32_t command_duration = 0; @@ -1991,6 +2065,8 @@ void WriterHitag(hitag_function htf, const hitag_data *htd, int page, bool ledco // Raw demodulation/decoding by sampling edge periods size_t periods = 0; + // iceman: Hitag2 is filled with static global vars. + // these following are globals status indicator :-| // Reset the return status bSuccessful = false; @@ -2001,33 +2077,35 @@ void WriterHitag(hitag_function htf, const hitag_data *htd, int page, bool ledco set_tracing(true); clear_trace(); - // Check configuration - switch (htf) { + switch (payload->cmd) { case WHT2F_CRYPTO: { DbpString("Authenticating using key:"); - memcpy(key, htd->crypto.key, 6); //HACK; 4 or 6?? I read both in the code. - memcpy(writedata, htd->crypto.data, 4); + memcpy(key, payload->key, 6); //HACK; 4 or 6?? I read both in the code. + memcpy(writedata, payload->data, 4); Dbhexdump(6, key, false); - blocknr = page; + blocknr = payload->page; bCrypto = false; bAuthenticating = false; - writestate = WRITE_STATE_START; } break; case WHT2F_PASSWORD: { - DbpString("Authenticating using password:"); - memcpy(password, htd->pwd.password, 4); - memcpy(writedata, htd->crypto.data, 4); - Dbhexdump(4, password, false); - blocknr = page; + DBG DbpString("Authenticating using password:"); + if (memcmp(payload->pwd, "\x00\x00\x00\x00", 4) == 0) { + memcpy(password, tag.sectors[1], sizeof(password)); + } else { + memcpy(password, payload->pwd, sizeof(password)); + } + memcpy(writedata, payload->data, 4); + DBG Dbhexdump(4, password, false); + blocknr = payload->page; bPwd = false; bAuthenticating = false; - writestate = WRITE_STATE_START; } break; default: { - Dbprintf("Error, unknown function: %d", htf); + Dbprintf("Error, unknown function: " _RED_("%d"), payload->cmd); + reply_ng(CMD_LF_HITAG2_WRITE, PM3_ESOFT, NULL, 0); return; } break; @@ -2043,31 +2121,30 @@ void WriterHitag(hitag_function htf, const hitag_data *htd, int page, bool ledco // Tag specific configuration settings (sof, timings, etc.) // TODO HTS - /* if (htf <= HTS_LAST_CMD) { + /* if (payload->cmd <= HTS_LAST_CMD) { // hitagS settings t_wait_1 = 204; t_wait_2 = 128; //tag_size = 256; flipped_bit = 0; tag_size = 8; - DbpString("Configured for hitagS writer"); - } else */ -// TODO HT1 - /* if (htf <= HT1_LAST_CMD) { - // hitag1 settings - t_wait_1 = 204; - t_wait_2 = 128; - tag_size = 256; - flipped_bit = 0; - DbpString("Configured for hitag1 writer"); - } else */ -// if (htf <= HT2_LAST_CMD) { - // hitag2 settings - t_wait_1 = HITAG_T_WAIT_1_MIN; - t_wait_2 = HITAG_T_WAIT_2_MIN; - tag_size = 48; - DbpString("Configured for hitag2 writer"); -// } + DBG DbpString("Configured for " _YELLOW_("HitagS") " writer"); + } else + */ + if (payload->cmd <= HT1_LAST_CMD) { + // hitag1 settings + t_wait_1 = 204; + t_wait_2 = 128; + tag_size = 256; + flipped_bit = 0; + DBG DbpString("Configured for " _YELLOW_("Hitag 1") " writer"); + } else if (payload->cmd <= HT2_LAST_CMD) { + // hitag2 settings + t_wait_1 = HITAG_T_WAIT_1_MIN; + t_wait_2 = HITAG_T_WAIT_2_MIN; + tag_size = 48; + DBG DbpString("Configured for " _YELLOW_("Hitag 2") " writer"); + } uint8_t tag_modulation; size_t max_nrzs = (8 * HITAG_FRAME_LEN + 5) * 2; // up to 2 nrzs per bit @@ -2097,7 +2174,8 @@ void WriterHitag(hitag_function htf, const hitag_data *htd, int page, bool ledco // By default reset the transmission buffer tx = txbuf; - switch (htf) { + + switch (payload->cmd) { case WHT2F_CRYPTO: { bStop = !hitag2_crypto(rx, rxlen, tx, &txlen, true); break; @@ -2107,7 +2185,6 @@ void WriterHitag(hitag_function htf, const hitag_data *htd, int page, bool ledco break; } default: { - Dbprintf("Error, unknown function: %d", htf); goto out; } } @@ -2131,7 +2208,16 @@ void WriterHitag(hitag_function htf, const hitag_data *htd, int page, bool ledco } // Transmit the reader frame - command_duration = hitag_reader_send_frame(tx, txlen, ledcontrol); + command_duration = hitag_reader_send_frame(tx, txlen); + + // global write state variable used + // tearoff occurred + if ((writestate == WRITE_STATE_PROG) && (tearoff_hook() == PM3_ETEAROFF)) { + reply_ng(CMD_LF_HITAG2_WRITE, PM3_ETEAROFF, NULL, 0); + lf_finalize(ledcontrol); + BigBuf_free(); + return; + } response_start = command_start + command_duration; @@ -2195,7 +2281,9 @@ void WriterHitag(hitag_function htf, const hitag_data *htd, int page, bool ledco // Detected two sequential equal bits and a modulation switch // NRZ modulation: (11 => --|) or (11 __|) nrz_samples[nrzs++] = tag_modulation; - nrz_samples[nrzs++] = tag_modulation; + if (nrzs < max_nrzs) { + nrz_samples[nrzs++] = tag_modulation; + } response_duration += periods; // Invert tag modulation state tag_modulation ^= 1; @@ -2236,7 +2324,13 @@ void WriterHitag(hitag_function htf, const hitag_data *htd, int page, bool ledco // The last modulation change of a zero is not detected, but we should take // the half period in account, otherwise the demodulator will fail. if ((nrzs % 2) != 0) { - nrz_samples[nrzs++] = tag_modulation; + + if (nrzs >= max_nrzs) { + Dbprintf("max_nrzs ( " _YELLOW_("%zu") " ) is odd? Must be even!", max_nrzs); + continue; + } else { + nrz_samples[nrzs++] = tag_modulation; + } } if (ledcontrol) LED_B_ON(); @@ -2299,8 +2393,335 @@ out: BigBuf_free(); if (checked == -1) { - reply_mix(CMD_ACK, false, 0, 0, 0, 0); - } else { - reply_mix(CMD_ACK, bSuccessful, 0, 0, (uint8_t *)tag.sectors, tag_size); + reply_ng(CMD_LF_HITAG2_WRITE, PM3_ESOFT, NULL, 0); } + + reply_ng(CMD_LF_HITAG2_WRITE + , (bSuccessful) ? PM3_SUCCESS : PM3_EFAILED + , (uint8_t *)tag.sectors + , tag_size + ); +} + + +static void ht2_send(bool turn_on, uint32_t *cmd_start + , uint32_t *cmd_duration, uint32_t *resp_start + , uint8_t *tx, size_t txlen, bool send_bits) { + + // Tag specific configuration settings (sof, timings, etc.) HITAG2 Settings +#define T_WAIT_1_GUARD 8 + + if (turn_on) { + // Wait 50ms with field off to be sure the transponder gets reset + SpinDelay(50); + FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_ADC | FPGA_LF_ADC_READER_FIELD); + + // Wait with field on to be in "Wait for START_AUTH" timeframe + lf_wait_periods(HITAG_T_WAIT_POWERUP + HITAG_T_WAIT_START_AUTH_MAX / 4); + *cmd_start += HITAG_T_WAIT_POWERUP + HITAG_T_WAIT_START_AUTH_MAX / 4; + + } else { + // Wait for t_wait_2 carrier periods after the last tag bit before transmitting, + lf_wait_periods(HITAG_T_WAIT_2_MIN + HITAG_T_WAIT_2_MIN); + *cmd_start += (HITAG_T_WAIT_2_MIN + HITAG_T_WAIT_2_MIN); + } + + // Transmit the reader frame + if (send_bits) { + *cmd_duration = hitag_reader_send_framebits(tx, txlen); + } else { + *cmd_duration = hitag_reader_send_frame(tx, txlen); + } + + *resp_start = (*cmd_start + *cmd_duration); + + *resp_start += (HITAG_T_WAIT_1_MIN - T_WAIT_1_GUARD); + // Let the antenna and ADC values settle + // And find the position where edge sampling should start + lf_wait_periods(HITAG_T_WAIT_1_MIN - T_WAIT_1_GUARD); +} + +static bool ht2_receive(uint32_t *resp_start, uint32_t *resp_duration, uint8_t *nrz_samples, size_t *samples) { + + // Keep administration of the first edge detection + bool waiting_for_first_edge = true; + + // Did we detected any modulaiton at all + bool detected_tag_modulation = false; + + // Reset the number of NRZ samples and use edge detection to detect them + size_t nrzs = 0; + + // Use the current modulation state as starting point + uint8_t tag_modulation = lf_get_tag_modulation(); + + // Raw demodulation/decoding by sampling edge periods + + while (nrzs < HT2_MAX_NRSZ) { + + // Get the timing of the next edge in number of wave periods + size_t periods = lf_count_edge_periods(128); + + // Are we dealing with the first incoming edge + if (waiting_for_first_edge) { + + // Just break out of loop after an initial time-out (tag is probably not available) + if (periods == 0) { + break; + } + + if (tag_modulation == 0) { + // hitag replies always start with 11111 == 1010101010, if we see 0 + // it means we missed the first period, e.g. if the signal never crossed 0 since reader signal + // so let's add it: + nrz_samples[nrzs++] = tag_modulation ^ 1; + // Register the number of periods that have passed + // we missed the begin of response but we know it happened one period of 16 earlier + resp_start += (periods - 16); + resp_duration = resp_start; + + } else { + // Register the number of periods that have passed + resp_start += periods; + resp_duration = resp_start; + } + + // Indicate that we have dealt with the first edge + waiting_for_first_edge = false; + // The first edge is always a single NRZ bit, force periods on 16 + periods = 16; + // We have received more than 0 periods, so we have detected a tag response + detected_tag_modulation = true; + + } else { + // The function lf_count_edge_periods() returns 0 when a time-out occurs + if (periods == 0) { + break; + } + } + // Evaluate the number of periods before the next edge + if (periods > 24 && periods <= 64) { + // Detected two sequential equal bits and a modulation switch + // NRZ modulation: (11 => --|) or (11 __|) + nrz_samples[nrzs++] = tag_modulation; + + if (nrzs < HT2_MAX_NRSZ) { + nrz_samples[nrzs++] = tag_modulation; + } + + resp_duration += periods; + // Invert tag modulation state + tag_modulation ^= 1; + + } else if (periods > 0 && periods <= 24) { + // Detected one bit and a modulation switch + // NRZ modulation: (1 => -|) or (0 _|) + nrz_samples[nrzs++] = tag_modulation; + + resp_duration += periods; + + tag_modulation ^= 1; + + } else { + // The function lf_count_edge_periods() returns > 64 periods, this is not a valid number periods + break; + } + } + + // Make sure we always have an even number of samples. This fixes the problem + // of ending the manchester decoding with a zero. See the example below where + // the '|' character is end of modulation + // One at the end: ..._-|_____... + // Zero at the end: ...-_|_____... + // The last modulation change of a zero is not detected, but we should take + // the half period in account, otherwise the demodulator will fail. + if ((nrzs % 2) != 0) { + + if (nrzs >= HT2_MAX_NRSZ) { + return false; + } + + nrz_samples[nrzs++] = tag_modulation; + } + + *samples = nrzs; + + return detected_tag_modulation; +} + +bool ht2_packbits(uint8_t *nrz_samples, size_t nrzs, uint8_t *rx, size_t *rxlen) { + // Verify if the header consists of five consecutive ones + if (nrzs < 5) { + return false; + } + + // detect hitag2 header + if (memcmp(nrz_samples, "\x01\x01\x01\x01\x01", 5)) { + return false; + } + + // Pack the response into a byte array + for (size_t i = 5; i < nrzs && *rxlen < (HITAG_FRAME_LEN << 3); i++) { + + uint8_t bit = nrz_samples[i]; + + // When Manchester detects impossible symbol it writes "7" + if (bit > 1) { + break; + } + + rx[*rxlen >> 3] |= bit << (7 - (*rxlen % 8)); + *rxlen = *rxlen + 1; + } + + // skip spurious bit + if (*rxlen % 8 == 1) { + *rxlen = *rxlen - 1; + } + return true; +} + +int ht2_read_uid(uint8_t *uid, bool ledcontrol, bool send_answer, bool keep_field_up) { + + // Clean up trace and prepare it for storing frames + set_tracing(true); + + // keep field up indicates there are more traffic to be done. + if (keep_field_up == false) { + clear_trace(); + } + + // hitag2 state machine? + hitag2_init(); + + // init as reader + lf_init(true, false, true); + + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + + uint8_t rx[HITAG_FRAME_LEN] = {0}; + size_t rxlen = 0; // In number of bits + + uint8_t nrz_samples[HT2_MAX_NRSZ]; + + uint8_t attempt_count = 3; + + int res = PM3_EFAILED; + bool turn_on = true; + + while (attempt_count && BUTTON_PRESS() == false) { + + attempt_count--; + + WDT_HIT(); + + uint32_t command_start = 0, command_duration = 0; + uint32_t response_start = 0, response_duration = 0; + + // start AUTH command + size_t txlen = 5; + uint8_t tx[1] = {0xC0}; + + // Transmit as reader + ht2_send(turn_on, &command_start, &command_duration, &response_start, tx, txlen, false); + + turn_on = false; + + // Reset the number of NRZ samples and use edge detection to detect them + size_t nrzs = 0; + + // receive raw samples + if (ht2_receive(&response_start, &response_duration, nrz_samples, &nrzs) == false) { + continue;; + } + + // Store the transmit frame ( TX ), we do this now at this point, to avoid delay in processing + // and to be able to overwrite the first samples with the trace (since they currently + // still use the same memory space) + LogTraceBits(tx, txlen, command_start, command_start + command_duration, true); + + // decode raw samples from Manchester Encoded to bits + manrawdecode(nrz_samples, &nrzs, true, 0); + + // pack bits to bytes + if (ht2_packbits(nrz_samples, nrzs, rx, &rxlen) == false) { + continue; + } + + // log Receive data + LogTraceBits(rx, rxlen, response_start, response_start + response_duration, false); + + if (rxlen != 32) { + continue; + } + + // Store received UID + memcpy(tag.sectors[0], rx, 4); + if (uid) { + memcpy(uid, rx, 4); + } + res = PM3_SUCCESS; + break; + } + + if (keep_field_up == false) { + lf_finalize(false); + BigBuf_free_keep_EM(); + } + + if (send_answer) { + reply_ng(CMD_LF_HITAG_READER, res, (uint8_t *)tag.sectors, 4); + } + + return res; +} + +// This function assumes you have called hitag2_read_uid before to turn on the field :) +// tx = expects bin arrays 0,1 i +// txlen = number of bits to send +// rx = return bin arrys +// rxlen = number of bits returned +int ht2_tx_rx(uint8_t *tx, size_t txlen, uint8_t *rx, size_t *rxlen, bool ledcontrol, bool keep_field_up) { + + int res = PM3_EFAILED; + size_t nrzs = 0; + uint8_t samples[HT2_MAX_NRSZ]; + + // waith between sending commands + lf_wait_periods(HITAG_T_WAIT_2_MIN); + + WDT_HIT(); + + uint32_t command_start = 0, command_duration = 0; + uint32_t response_start = 0, response_duration = 0; + + // Transmit as reader + ht2_send(false, &command_start, &command_duration, &response_start, tx, txlen, true); + + // receive raw samples + if (ht2_receive(&response_start, &response_duration, samples, &nrzs) == false) { + goto out; + } + + // decode raw samples from Manchester Encoded to bits + if (manrawdecode(samples, &nrzs, true, 0)) { + goto out; + } + + // pack bits to bytes + if (ht2_packbits(samples, nrzs, rx, rxlen) == false) { + goto out; + } + + // log Receive data + LogTraceBits(rx, *rxlen, response_start, response_start + response_duration, false); + + res = PM3_SUCCESS; + +out: + if (keep_field_up == false) { + lf_finalize(false); + BigBuf_free_keep_EM(); + } + return res; } diff --git a/armsrc/hitag2.h b/armsrc/hitag2.h index 90aa8132b..f2f7fff06 100644 --- a/armsrc/hitag2.h +++ b/armsrc/hitag2.h @@ -23,8 +23,12 @@ #include "hitag.h" void SniffHitag2(bool ledcontrol); +void hitag_sniff(void); void SimulateHitag2(bool ledcontrol); -void ReaderHitag(hitag_function htf, const hitag_data *htd, bool ledcontrol); -void WriterHitag(hitag_function htf, const hitag_data *htd, int page, bool ledcontrol); -void EloadHitag(const uint8_t *data, uint16_t len); +void ReaderHitag(const lf_hitag_data_t *payload, bool ledcontrol); +void WriterHitag(const lf_hitag_data_t *payload, bool ledcontrol); + +bool ht2_packbits(uint8_t *nrz_samples, size_t nrzs, uint8_t *rx, size_t *rxlen); +int ht2_read_uid(uint8_t *uid, bool ledcontrol, bool send_answer, bool keep_field_up); +int ht2_tx_rx(uint8_t *tx, size_t txlen, uint8_t *rx, size_t *rxlen, bool ledcontrol, bool keep_field_up); #endif diff --git a/armsrc/hitag2_crack.c b/armsrc/hitag2_crack.c index bc3b197cb..b9a247957 100644 --- a/armsrc/hitag2_crack.c +++ b/armsrc/hitag2_crack.c @@ -14,7 +14,7 @@ // See LICENSE.txt for the text of the license. //----------------------------------------------------------------------------- -// This coode has been converted from RFIDler source code to work with Proxmark3. +// This coode has been converted from RFIDler source code to work with Proxmark3. // https://github.com/AdamLaurie/RFIDler/blob/master/firmware/Pic32/RFIDler.X/src/hitag2crack.c @@ -32,7 +32,7 @@ const static uint8_t ERROR_RESPONSE[] = { 0xF4, 0x02, 0x88, 0x9C }; // #define READP0CMD "1100000111" -const static uint8_t read_p0_cmd[] = {1,1,0,0,0,0,0,1,1,1}; +const static uint8_t read_p0_cmd[] = {1, 1, 0, 0, 0, 0, 0, 1, 1, 1}; // hitag2crack_xor XORs the source with the pad to produce the target. // source, target and pad are binarrays of length len. @@ -121,7 +121,7 @@ static bool hitag2crack_read_page(uint8_t *resp, uint8_t pagenum, uint8_t *nrar, uint8_t response[32]; // convert to binarray - hex2binarray((char*)e_response, (char*)e_resp); + hex2binarray((char *)e_response, (char *)e_resp); // decrypt response hitag2crack_xor(response, e_response, keybits + 10, 32); @@ -129,7 +129,7 @@ static bool hitag2crack_read_page(uint8_t *resp, uint8_t pagenum, uint8_t *nrar, binarray2hex(response, 32, resp); return true; - } + } } return false; @@ -200,7 +200,7 @@ static bool hitag2crack_find_e_page0_cmd(uint8_t *keybits, uint8_t *e_firstcmd, // representing the inverted bit and the 3 page bits // in both the non-inverted and inverted parts of the // encrypted command. - uint8_t guess[10]; + uint8_t guess[10]; memcpy(guess, e_firstcmd, 10); if (a) { guess[5] = !guess[5]; @@ -231,7 +231,7 @@ static bool hitag2crack_find_e_page0_cmd(uint8_t *keybits, uint8_t *e_firstcmd, // convert response to binarray uint8_t e_uid[32]; - hex2binarray((char*)e_uid, (char*)resp); + hex2binarray((char *)e_uid, (char *)resp); // test if the guess was 'read page 0' command if (hitag2crack_test_e_p0cmd(keybits, nrar, guess, uid, e_uid)) { @@ -299,13 +299,13 @@ static bool hitag2crack_find_valid_e_cmd(uint8_t *e_cmd, uint8_t *nrar) { // hitag2_crack implements the first crack algorithm described in the paper, // Gone In 360 Seconds by Verdult, Garcia and Balasch. // response is a multi-line text response containing the 8 pages of the cracked tag -// nrarhex is a string containing hex representations of the 32 bit nR and aR values +// nrarhex is a string containing hex representations of the 32 bit nR and aR values void ht2_crack(uint8_t *nrar_hex) { clear_trace(); lf_hitag_crack_response_t packet; - memset((uint8_t*)&packet, 0x00, sizeof(lf_hitag_crack_response_t)); + memset((uint8_t *)&packet, 0x00, sizeof(lf_hitag_crack_response_t)); int res = PM3_SUCCESS; @@ -319,7 +319,7 @@ void ht2_crack(uint8_t *nrar_hex) { // convert to binarray uint8_t nrar[64] = {0}; - hex2binarray_n((char*)nrar, (char*)nrar_hex, 8); + hex2binarray_n((char *)nrar, (char *)nrar_hex, 8); // find a valid encrypted command uint8_t e_firstcmd[10]; @@ -331,7 +331,7 @@ void ht2_crack(uint8_t *nrar_hex) { // now we got a first encrypted command inside e_firstcmd uint8_t uid[32]; - hex2binarray_n((char*)uid, (char*)uid_hex, 4); + hex2binarray_n((char *)uid, (char *)uid_hex, 4); // find the 'read page 0' command and recover key stream uint8_t keybits[42]; @@ -352,5 +352,5 @@ void ht2_crack(uint8_t *nrar_hex) { packet.status = 1; out: - reply_ng(CMD_LF_HITAG2_CRACK, res, (uint8_t*)&packet, sizeof(lf_hitag_crack_response_t)); + reply_ng(CMD_LF_HITAG2_CRACK, res, (uint8_t *)&packet, sizeof(lf_hitag_crack_response_t)); } diff --git a/armsrc/hitagS.c b/armsrc/hitagS.c index 0c24daeac..16ba8ef11 100644 --- a/armsrc/hitagS.c +++ b/armsrc/hitagS.c @@ -52,7 +52,7 @@ static uint32_t temp_uid; static int temp2 = 0; static int sof_bits; // number of start-of-frame bits static uint8_t pwdh0, pwdl0, pwdl1; // password bytes -static uint32_t rnd = 0x74124485; // randomnumber +static uint32_t rnd = 0x74124485; // random number //#define SENDBIT_TEST /* array index 3 2 1 0 // bytes in sim.bin file are 0 1 2 3 @@ -125,12 +125,13 @@ static void calc_crc(unsigned char *crc, unsigned char data, unsigned char Bitco } static void hitag_send_bit(int bit, bool ledcontrol) { + if (ledcontrol) LED_A_ON(); // Reset clock for the next bit AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG; switch (m) { - case AC2K: + case AC2K: { if (bit == 0) { // AC Coding --__ HIGH(GPIO_SSC_DOUT); @@ -156,7 +157,8 @@ static void hitag_send_bit(int bit, bool ledcontrol) { } if (ledcontrol) LED_A_OFF(); break; - case AC4K: + } + case AC4K: { if (bit == 0) { // AC Coding --__ HIGH(GPIO_SSC_DOUT); @@ -181,7 +183,8 @@ static void hitag_send_bit(int bit, bool ledcontrol) { } if (ledcontrol) LED_A_OFF(); break; - case MC4K: + } + case MC4K: { if (bit == 0) { // Manchester: Unloaded, then loaded |__--| LOW(GPIO_SSC_DOUT); @@ -201,7 +204,8 @@ static void hitag_send_bit(int bit, bool ledcontrol) { } if (ledcontrol) LED_A_OFF(); break; - case MC8K: + } + case MC8K: { if (bit == 0) { // Manchester: Unloaded, then loaded |__--| LOW(GPIO_SSC_DOUT); @@ -221,26 +225,33 @@ static void hitag_send_bit(int bit, bool ledcontrol) { } if (ledcontrol) LED_A_OFF(); break; - default: + } + default: { break; + } } } static void hitag_send_frame(const uint8_t *frame, size_t frame_len, bool ledcontrol) { - if (g_dbglevel >= DBG_EXTENDED) + + if (g_dbglevel >= DBG_EXTENDED) { Dbprintf("hitag_send_frame: (%i) %02X %02X %02X %02X", frame_len, frame[0], frame[1], frame[2], frame[3]); + } + // The beginning of the frame is hidden in some high level; pause until our bits will have an effect AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG; HIGH(GPIO_SSC_DOUT); switch (m) { case AC4K: - case MC8K: + case MC8K: { while (AT91C_BASE_TC0->TC_CV < T0 * 40) {}; //FADV break; + } case AC2K: - case MC4K: + case MC4K: { while (AT91C_BASE_TC0->TC_CV < T0 * 20) {}; //STD + ADV break; + } } // SOF - send start of frame @@ -317,43 +328,101 @@ static void hitag_reader_send_frame(const uint8_t *frame, size_t frame_len, bool LOW(GPIO_SSC_DOUT); } +static void hitagS_init_clock(void) { + + // Enable Peripheral Clock for + // TIMER_CLOCK0, used to measure exact timing before answering + // TIMER_CLOCK1, used to capture edges of the tag frames + AT91C_BASE_PMC->PMC_PCER |= (1 << AT91C_ID_TC0) | (1 << AT91C_ID_TC1); + + AT91C_BASE_PIOA->PIO_BSR = GPIO_SSC_FRAME; + + // Disable timer during configuration + AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKDIS; + AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS; + + // TC0: Capture mode, default timer source = MCK/2 (TIMER_CLOCK1), no triggers + AT91C_BASE_TC0->TC_CMR = AT91C_TC_CLKS_TIMER_DIV1_CLOCK; + + // TC1: Capture mode, default timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger, + // external trigger rising edge, load RA on falling edge of TIOA. + AT91C_BASE_TC1->TC_CMR = + AT91C_TC_CLKS_TIMER_DIV1_CLOCK | + AT91C_TC_ETRGEDG_FALLING | + AT91C_TC_ABETRG | + AT91C_TC_LDRA_FALLING | + AT91C_TC_ACPA_CLEAR | // RA comperator clears TIOA (carry bit) + AT91C_TC_ASWTRG_SET; // SWTriger sets TIOA (carry bit) + + AT91C_BASE_TC0->TC_RC = 0; // set TIOA (carry bit) on overflow, return to zero + AT91C_BASE_TC0->TC_RA = 1; // clear carry bit on next clock cycle + + // Enable and reset counters + AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG; + AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG; + + // synchronized startup procedure + while (AT91C_BASE_TC0->TC_CV > 0); // wait until TC0 returned to zero +// while (AT91C_BASE_TC0->TC_CV < 2); // and has started (TC_CV > TC_RA, now TC1 is cleared) + + // return to zero + AT91C_BASE_TC1->TC_CCR = AT91C_TC_SWTRG; + AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG; + while (AT91C_BASE_TC0->TC_CV > 0); + +} + +static void hitagS_stop_clock(void) { + AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKDIS; + AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS; +} + /* * to check if the right uid was selected */ static int check_select(const uint8_t *rx, uint32_t uid) { + unsigned char resp[48]; uint32_t ans = 0x0; - for (int i = 0; i < 48; i++) - resp[i] = (rx[i / 8] >> (7 - (i % 8))) & 0x1; - for (int i = 0; i < 32; i++) + for (int i = 0; i < 48; i++) { + resp[i] = (rx[i / 8] >> (7 - (i % 8))) & 0x1; + } + + for (int i = 0; i < 32; i++) { ans += resp[5 + i] << (31 - i); + } // global var? temp_uid = ans; - if (ans == tag.uid) + if (ans == tag.uid) { return 1; + } return 0; } static void hitagS_set_frame_modulation(void) { switch (tag.mode) { - case HT_STANDARD: + case HT_STANDARD: { sof_bits = 1; m = MC4K; break; - case HT_ADVANCED: + } + case HT_ADVANCED: { sof_bits = 6; m = MC4K; break; - case HT_FAST_ADVANCED: + } + case HT_FAST_ADVANCED: { sof_bits = 6; m = MC8K; break; - default: + } + default: { break; + } } } @@ -411,16 +480,18 @@ static void hitagS_handle_reader_command(uint8_t *rx, const size_t rxlen, for (int i = 0; i < 4; i++) { tx[i] = (tag.uid >> (24 - (i * 8))) & 0xFF; } + break; } - break; case 45: { //select command from reader received - if (g_dbglevel >= DBG_EXTENDED) + if (g_dbglevel >= DBG_EXTENDED) { DbpString("SELECT"); + } if (check_select(rx, tag.uid) == 1) { - if (g_dbglevel >= DBG_EXTENDED) + if (g_dbglevel >= DBG_EXTENDED) { DbpString("SELECT match"); + } //if the right tag was selected *txlen = 32; @@ -434,8 +505,10 @@ static void hitagS_handle_reader_command(uint8_t *rx, const size_t rxlen, tx[3] = 0xff; if (tag.mode != HT_STANDARD) { + *txlen = 40; crc = CRC_PRESET; + for (int i = 0; i < 4; i++) { calc_crc(&crc, tx[i], 8); } @@ -443,8 +516,8 @@ static void hitagS_handle_reader_command(uint8_t *rx, const size_t rxlen, tx[4] = crc; } } + break; } - break; case 64: { //challenge message received Dbprintf("Challenge for UID: %X", temp_uid); @@ -499,9 +572,9 @@ static void hitagS_handle_reader_command(uint8_t *rx, const size_t rxlen, tag.pages[0][3] = 0x88; } */ + break; } - break; - case 40: + case 40: { if (g_dbglevel >= DBG_EXTENDED) Dbprintf("WRITE"); //data received to be written @@ -535,6 +608,7 @@ static void hitagS_handle_reader_command(uint8_t *rx, const size_t rxlen, } } break; + } case 20: { //write page, write block, read page or read block command received if ((rx[0] & 0xf0) == 0xc0) { //read page @@ -567,9 +641,12 @@ static void hitagS_handle_reader_command(uint8_t *rx, const size_t rxlen, sof_bits = 0; *txlen = 0; } + } else if ((rx[0] & 0xf0) == 0xd0) { //read block + uint8_t page = ((rx[0] & 0x0f) * 16) + ((rx[1] & 0xf0) / 16); *txlen = 32 * 4; + //send page,...,page+3 data for (int i = 0; i < 4; i++) { tx[0 + i * 4] = tag.pages[page + 0 + i * 4][0]; @@ -594,8 +671,11 @@ static void hitagS_handle_reader_command(uint8_t *rx, const size_t rxlen, sof_bits = 0; *txlen = 0; } + } else if ((rx[0] & 0xf0) == 0x80) { //write page + uint8_t page = ((rx[0] & 0x0f) * 16) + ((rx[1] & 0xf0) / 16); + if ((tag.LCON && page == 1) || (tag.LKP && (page == 2 || page == 3))) { //deny @@ -609,8 +689,10 @@ static void hitagS_handle_reader_command(uint8_t *rx, const size_t rxlen, } } else if ((rx[0] & 0xf0) == 0x90) { //write block + uint8_t page = ((rx[0] & 0x0f) * 6) + ((rx[1] & 0xf0) / 16); hitagS_set_frame_modulation(); + if (page % 4 != 0 || page == 0) { //deny *txlen = 0; @@ -623,12 +705,14 @@ static void hitagS_handle_reader_command(uint8_t *rx, const size_t rxlen, tag.tstate = HT_WRITING_BLOCK_DATA; } } - } - break; - default: - if (g_dbglevel >= DBG_EXTENDED) - Dbprintf("unknown rxlen: (%i) %02X %02X %02X %02X ...", rxlen, rx[0], rx[1], rx[2], rx[3]); break; + } + default: { + if (g_dbglevel >= DBG_EXTENDED) { + Dbprintf("unknown rxlen: (%i) %02X %02X %02X %02X ...", rxlen, rx[0], rx[1], rx[2], rx[3]); + } + break; + } } } @@ -639,7 +723,6 @@ void SimulateHitagSTag(bool tag_mem_supplied, const uint8_t *data, bool ledcontr StopTicks(); -// int frame_count = 0; int response = 0, overflow = 0; uint8_t rx[HITAG_FRAME_LEN]; size_t rxlen = 0; @@ -666,6 +749,7 @@ void SimulateHitagSTag(bool tag_mem_supplied, const uint8_t *data, bool ledcontr // read tag data into memory if (tag_mem_supplied) { + for (int i = 0; i < 16; i++) { for (int j = 0; j < 4; j++) { tag.pages[i][j] = 0x0; @@ -700,7 +784,8 @@ void SimulateHitagSTag(bool tag_mem_supplied, const uint8_t *data, bool ledcontr tag.max_page = 0; } - if (g_dbglevel >= DBG_EXTENDED) + if (g_dbglevel >= DBG_EXTENDED) { + for (int i = 0; i < tag.max_page; i++) { Dbprintf("Page[%2d]: %02X %02X %02X %02X", i, (tag.pages[i][3]) & 0xFF, @@ -709,6 +794,8 @@ void SimulateHitagSTag(bool tag_mem_supplied, const uint8_t *data, bool ledcontr tag.pages[i][0] & 0xFF ); } + } + //con1 tag.auth = 0; if ((tag.pages[1][1] & 0x80) == 0x80) { @@ -814,8 +901,10 @@ void SimulateHitagSTag(bool tag_mem_supplied, const uint8_t *data, bool ledcontr // Receive frame, watch for at most T0*EOF periods while (AT91C_BASE_TC1->TC_CV < T0 * HITAG_T_EOF) { + // Check if rising edge in modulation is detected if (AT91C_BASE_TC1->TC_SR & AT91C_TC_LDRAS) { + // Retrieve the new timing values int ra = (AT91C_BASE_TC1->TC_RA / T0) + overflow; overflow = 0; @@ -901,6 +990,7 @@ static void hitagS_receive_frame(uint8_t *rx, size_t sizeofrx, size_t *rxlen, ui // Reset values for receiving frames memset(rx, 0x00, sizeofrx); *rxlen = 0; + int lastbit = 1; bool bSkip = true; *resptime = 0; @@ -914,8 +1004,8 @@ static void hitagS_receive_frame(uint8_t *rx, size_t sizeofrx, size_t *rxlen, ui // Receive frame, watch for at most T0*EOF periods while (AT91C_BASE_TC0->TC_CV + (overcount << 16) < (T0 * HITAG_T_PROG_MAX)) { - // detect and track counter overflows + // detect and track counter overflows uint32_t tmpcv = AT91C_BASE_TC0->TC_CV; if (tmpcv < prevcv) { overcount++; @@ -924,10 +1014,13 @@ static void hitagS_receive_frame(uint8_t *rx, size_t sizeofrx, size_t *rxlen, ui // Check if falling edge in tag modulation is detected if (AT91C_BASE_TC1->TC_SR & AT91C_TC_LDRAS) { + // Retrieve the new timing values uint32_t ra = (AT91C_BASE_TC1->TC_RA + (overcount << 16)) / T0; + // Reset timer every frame, we have to capture the last edge for timing AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG; + prevcv = 0; overcount = 0; @@ -935,7 +1028,8 @@ static void hitagS_receive_frame(uint8_t *rx, size_t sizeofrx, size_t *rxlen, ui // Capture tag frame (manchester decoding using only falling edges) - if (!bStarted) { + if (bStarted == false) { + if (ra >= HITAG_T_EOF) { bStarted = true; // Capture the T0 periods that have passed since last communication or field drop (reset) @@ -944,28 +1038,37 @@ static void hitagS_receive_frame(uint8_t *rx, size_t sizeofrx, size_t *rxlen, ui } else { errorCount++; } + } else if (ra >= HITAG_T_TAG_CAPTURE_FOUR_HALF) { + // Manchester coding example |-_|_-|-_| (101) rx[(*rxlen) / 8] |= 0 << (7 - ((*rxlen) % 8)); (*rxlen)++; + rx[(*rxlen) / 8] |= 1 << (7 - ((*rxlen) % 8)); (*rxlen)++; + } else if (ra >= HITAG_T_TAG_CAPTURE_THREE_HALF) { + // Manchester coding example |_-|...|_-|-_| (0...01) rx[(*rxlen) / 8] |= 0 << (7 - ((*rxlen) % 8)); (*rxlen)++; + // We have to skip this half period at start and add the 'one' the second time - if (!bSkip) { + if (bSkip == false) { rx[(*rxlen) / 8] |= 1 << (7 - ((*rxlen) % 8)); (*rxlen)++; } + lastbit = !lastbit; bSkip = !bSkip; + } else if (ra >= HITAG_T_TAG_CAPTURE_TWO_HALF) { // Manchester coding example |_-|_-| (00) or |-_|-_| (11) // bit is same as last bit rx[(*rxlen) / 8] |= lastbit << (7 - ((*rxlen) % 8)); (*rxlen)++; + } else { // Ignore weird value, is to small to mean anything errorCount++; @@ -973,11 +1076,13 @@ static void hitagS_receive_frame(uint8_t *rx, size_t sizeofrx, size_t *rxlen, ui } // if we saw over 100 weird values break it probably isn't hitag... - if (errorCount > 100) break; + if (errorCount > 100) { + break; + } // We can break this loop if we received the last bit from a frame - if (AT91C_BASE_TC1->TC_CV > T0 * HITAG_T_EOF) { - if ((*rxlen) > 0) { + if (AT91C_BASE_TC1->TC_CV > (T0 * HITAG_T_EOF)) { + if ((*rxlen)) { break; } } @@ -998,7 +1103,6 @@ static void sendReceiveHitagS(uint8_t *tx, size_t txlen, uint8_t *rx, size_t siz // falling edge occurred halfway the period. with respect to this falling edge, // we need to wait (T_Wait2 + half_tag_period) when the last was a 'one'. // All timer values are in terms of T0 units - while (AT91C_BASE_TC0->TC_CV < T0 * t_wait) {}; // Transmit the reader frame @@ -1011,48 +1115,82 @@ static void sendReceiveHitagS(uint8_t *tx, size_t txlen, uint8_t *rx, size_t siz size_t rxlen = 0; hitagS_receive_frame(rx, sizeofrx, &rxlen, &resptime, ledcontrol); int k = 0; + // Check if frame was captured and store it if (rxlen > 0) { + uint8_t response_bit[sizeofrx * 8]; - for (int i = 0; i < rxlen; i++) { + + for (size_t i = 0; i < rxlen; i++) { response_bit[i] = (rx[i / 8] >> (7 - (i % 8))) & 1; } + + Dbprintf("htS: rxlen...... %zu", rxlen); + Dbprintf("htS: sizeofrx... %zu", sizeofrx); + memset(rx, 0x00, sizeofrx); + if (ac_seq) { + + DbpString("htS: AntiCollision Sequence ( ac seq )"); + Dbhexdump(rxlen, response_bit, false); + // Tag Response is AC encoded + // We used UID Request Advanced, meaning AC SEQ header is 111. for (int i = 6; i < rxlen; i += 2) { + rx[k / 8] |= response_bit[i] << (7 - (k % 8)); + k++; - if (k >= 8 * sizeofrx) + + if (k > 8 * sizeofrx) { break; + } } + + DbpString("htS: ac sequence compress"); + Dbhexdump(k / 8, rx, false); + } else { - for (int i = 5; i < rxlen; i++) { // ignore first 5 bits: SOF (actually 1 or 6 depending on response protocol) + + DbpString("htS: skipping 5 bit header"); + + // ignore first 5 bits: SOF (actually 1 or 6 depending on response protocol) + // or rather a header. + for (size_t i = 5; i < rxlen; i++) { + rx[k / 8] |= response_bit[i] << (7 - (k % 8)); k++; - if (k >= 8 * sizeofrx) + + if (k > 8 * sizeofrx) { break; + } } + + } LogTraceBits(rx, k, resptime, resptime, false); } *prxbits = k; } -static size_t concatbits(uint8_t *dstbuf, size_t dstbufskip, const uint8_t *srcbuf, size_t srcbufstart, size_t srcbuflen) { +static size_t concatbits(uint8_t *dst, size_t dstskip, const uint8_t *src, size_t srcstart, size_t srclen) { // erase dstbuf bits that will be overriden - dstbuf[dstbufskip / 8] &= 0xFF - ((1 << (7 - (dstbufskip % 8) + 1)) - 1); - for (size_t i = (dstbufskip / 8) + 1; i <= (dstbufskip + srcbuflen) / 8; i++) { - dstbuf[i] = 0; + dst[dstskip / 8] &= 0xFF - ((1 << (7 - (dstskip % 8) + 1)) - 1); + for (size_t i = (dstskip / 8) + 1; i <= (dstskip + srclen) / 8; i++) { + dst[i] = 0; } - for (size_t i = 0; i < srcbuflen; i++) { + + for (size_t i = 0; i < srclen; i++) { // equiv of dstbufbits[dstbufskip + i] = srcbufbits[srcbufstart + i] - dstbuf[(dstbufskip + i) / 8] |= ((srcbuf[(srcbufstart + i) / 8] >> (7 - ((srcbufstart + i) % 8))) & 1) << (7 - ((dstbufskip + i) % 8)); + dst[(dstskip + i) / 8] |= ((src[(srcstart + i) / 8] >> (7 - ((srcstart + i) % 8))) & 1) << (7 - ((dstskip + i) % 8)); } - return dstbufskip + srcbuflen; + + return dstskip + srclen; } -static int selectHitagS(hitag_function htf, const hitag_data *htd, uint8_t *tx, size_t sizeoftx, uint8_t *rx, size_t sizeofrx, int t_wait, bool ledcontrol) { +static int selectHitagS(const lf_hitag_data_t *packet, uint8_t *tx, size_t sizeoftx, uint8_t *rx, size_t sizeofrx, int t_wait, bool ledcontrol) { + StopTicks(); FpgaDownloadAndGo(FPGA_BITSTREAM_LF); @@ -1075,50 +1213,28 @@ static int selectHitagS(hitag_function htf, const hitag_data *htd, uint8_t *tx, // Disable modulation at default, which means enable the field LOW(GPIO_SSC_DOUT); - // Enable Peripheral Clock for - // TIMER_CLOCK0, used to measure exact timing before answering - // TIMER_CLOCK1, used to capture edges of the tag frames - AT91C_BASE_PMC->PMC_PCER |= (1 << AT91C_ID_TC0) | (1 << AT91C_ID_TC1); + hitagS_init_clock(); - AT91C_BASE_PIOA->PIO_BSR = GPIO_SSC_FRAME; - - // Disable timer during configuration - AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKDIS; - AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS; - - // TC0: Capture mode, default timer source = MCK/2 (TIMER_CLOCK1), no triggers - AT91C_BASE_TC0->TC_CMR = AT91C_TC_CLKS_TIMER_DIV1_CLOCK; - - // TC1: Capture mode, default timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger, - // external trigger rising edge, load RA on falling edge of TIOA. - AT91C_BASE_TC1->TC_CMR = - AT91C_TC_CLKS_TIMER_DIV1_CLOCK | - AT91C_TC_ETRGEDG_FALLING | - AT91C_TC_ABETRG | - AT91C_TC_LDRA_FALLING; - - // Enable and reset counters - AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG; - AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG; - - // synchronized startup procedure - while (AT91C_BASE_TC0->TC_CV > 0); // wait until TC0 returned to zero - - //start authentication + // UID request standard 00110 + // UID request Advanced 1100x + // UID request FAdvanced 11010 size_t txlen = 0; size_t rxlen = 0; - uint8_t cmd = 0x18; + uint8_t cmd = 0x18; // 11000 UID Request Advanced txlen = concatbits(tx, txlen, &cmd, 8 - 5, 5); sendReceiveHitagS(tx, txlen, rx, sizeofrx, &rxlen, t_wait, ledcontrol, true); if (rxlen != 32) { - Dbprintf("UID Request failed!"); + DbpString("UID Request failed!"); return -1; } tag.uid = (rx[3] << 24 | rx[2] << 16 | rx[1] << 8 | rx[0]); - if (g_dbglevel >= DBG_EXTENDED) + + if (g_dbglevel >= DBG_EXTENDED) { Dbprintf("UID: %02X %02X %02X %02X", rx[0], rx[1], rx[2], rx[3]); + } + //select uid txlen = 0; cmd = 0x00; @@ -1165,25 +1281,29 @@ static int selectHitagS(hitag_function htf, const hitag_data *htd, uint8_t *tx, tag.LCK1 = (conf_pages[2] >> 1) & 0x1; tag.LCK0 = (conf_pages[2] >> 0) & 0x1; - if (g_dbglevel >= DBG_EXTENDED) - Dbprintf("conf0: %02X conf1: %02X conf2: %02X", conf_pages[0], conf_pages[1], conf_pages[2]); + if (g_dbglevel >= DBG_EXTENDED) { + Dbprintf("conf 0: %02X conf 1: %02X conf 2: %02X", conf_pages[0], conf_pages[1], conf_pages[2]); + } if (tag.auth == 1) { uint64_t key = 0; //if the tag is in authentication mode try the key or challenge - if (htf == RHTSF_KEY || htf == WHTSF_KEY) { + if (packet->cmd == RHTSF_KEY || packet->cmd == WHTSF_KEY) { + if (g_dbglevel >= DBG_EXTENDED) { DbpString("Authenticating using key:"); - Dbhexdump(6, htd->crypto.key, false); + Dbhexdump(6, packet->key, false); } - key = ((uint64_t)htd->crypto.key[0]) << 0 | - ((uint64_t)htd->crypto.key[1]) << 8 | - ((uint64_t)htd->crypto.key[2]) << 16 | - ((uint64_t)htd->crypto.key[3]) << 24 | - ((uint64_t)htd->crypto.key[4]) << 32 | - ((uint64_t)htd->crypto.key[5]) << 40 + key = ((uint64_t)packet->key[0]) << 0 | + ((uint64_t)packet->key[1]) << 8 | + ((uint64_t)packet->key[2]) << 16 | + ((uint64_t)packet->key[3]) << 24 | + ((uint64_t)packet->key[4]) << 32 | + ((uint64_t)packet->key[5]) << 40 ; + uint64_t state = ht2_hitag2_init(REV64(key), REV32(tag.uid), REV32(rnd)); + uint8_t auth_ks[4]; for (int i = 0; i < 4; i++) { auth_ks[i] = ht2_hitag2_byte(&state) ^ 0xff; @@ -1194,37 +1314,44 @@ static int selectHitagS(hitag_function htf, const hitag_data *htd, uint8_t *tx, txlen = concatbits(tx, txlen, revrnd, 0, 32); txlen = concatbits(tx, txlen, auth_ks, 0, 32); - if (g_dbglevel >= DBG_EXTENDED) - Dbprintf("%02X %02X %02X %02X %02X %02X %02X %02X", tx[0], - tx[1], tx[2], tx[3], tx[4], tx[5], tx[6], tx[7]); + if (g_dbglevel >= DBG_EXTENDED) { + Dbprintf("%02X %02X %02X %02X %02X %02X %02X %02X" + , tx[0], tx[1], tx[2], tx[3] + , tx[4], tx[5], tx[6], tx[7] + ); + } + + } else if (packet->cmd == RHTSF_CHALLENGE || packet->cmd == WHTSF_CHALLENGE) { - } else if (htf == RHTSF_CHALLENGE || htf == WHTSF_CHALLENGE) { if (g_dbglevel >= DBG_EXTENDED) { DbpString("Authenticating using nr,ar pair:"); - Dbhexdump(8, htd->auth.NrAr, false); + Dbhexdump(8, packet->NrAr, false); } + uint64_t NrAr = 0; - NrAr = ((uint64_t)htd->auth.NrAr[7]) << 0 | - ((uint64_t)htd->auth.NrAr[6]) << 8 | - ((uint64_t)htd->auth.NrAr[5]) << 16 | - ((uint64_t)htd->auth.NrAr[4]) << 24 | - ((uint64_t)htd->auth.NrAr[3]) << 32 | - ((uint64_t)htd->auth.NrAr[2]) << 40 | - ((uint64_t)htd->auth.NrAr[1]) << 48 | - ((uint64_t)htd->auth.NrAr[0]) << 56; + NrAr = ((uint64_t)packet->NrAr[7]) << 0 | + ((uint64_t)packet->NrAr[6]) << 8 | + ((uint64_t)packet->NrAr[5]) << 16 | + ((uint64_t)packet->NrAr[4]) << 24 | + ((uint64_t)packet->NrAr[3]) << 32 | + ((uint64_t)packet->NrAr[2]) << 40 | + ((uint64_t)packet->NrAr[1]) << 48 | + ((uint64_t)packet->NrAr[0]) << 56; + txlen = 64; for (int i = 0; i < 8; i++) { tx[i] = ((NrAr >> (56 - (i * 8))) & 0xFF); } + } else { - Dbprintf("Error , unknown function: %d", htf); + Dbprintf("Error , unknown function: " _RED_("%d"), packet->cmd); return -1; } sendReceiveHitagS(tx, txlen, rx, sizeofrx, &rxlen, t_wait, ledcontrol, false); if (rxlen != 40) { - Dbprintf("Authenticate failed! %i", rxlen); + Dbprintf("Authenticate failed! " _RED_("%i"), rxlen); return -1; } @@ -1238,19 +1365,21 @@ static int selectHitagS(hitag_function htf, const hitag_data *htd, uint8_t *tx, pwdh0 = 0; pwdl0 = 0; pwdl1 = 0; - if (htf == RHTSF_KEY || htf == WHTSF_KEY) { + if (packet->cmd == RHTSF_KEY || packet->cmd == WHTSF_KEY) { + uint64_t state = ht2_hitag2_init(REV64(key), REV32(tag.uid), REV32(rnd)); for (int i = 0; i < 4; i++) { ht2_hitag2_byte(&state); } + uint8_t con2 = rx[0] ^ ht2_hitag2_byte(&state); pwdh0 = rx[1] ^ ht2_hitag2_byte(&state); pwdl0 = rx[2] ^ ht2_hitag2_byte(&state); pwdl1 = rx[3] ^ ht2_hitag2_byte(&state); - if (g_dbglevel >= DBG_EXTENDED) + if (g_dbglevel >= DBG_EXTENDED) { Dbprintf("con2 %02X pwdh0 %02X pwdl0 %02X pwdl1 %02X", con2, pwdh0, pwdl0, pwdl1); - + } //Dbprintf("%X %02X", rnd, ((rx[4] & 0x0f) * 16) + ((rx[5] & 0xf0) / 16)); //rnd += 1; } @@ -1263,21 +1392,26 @@ static int selectHitagS(hitag_function htf, const hitag_data *htd, uint8_t *tx, * If the key was given the password will be decrypted. * Reads every page of a hitag S transpoder. */ -void ReadHitagS(hitag_function htf, const hitag_data *htd, bool ledcontrol) { +void ReadHitagS(const lf_hitag_data_t *payload, bool ledcontrol) { uint8_t rx[HITAG_FRAME_LEN]; size_t rxlen = 0; + uint8_t tx[HITAG_FRAME_LEN]; + int t_wait = HITAG_T_WAIT_MAX; + if (selectHitagS(payload, tx, ARRAYLEN(tx), rx, ARRAYLEN(rx), t_wait, ledcontrol) == -1) { - if (selectHitagS(htf, htd, tx, ARRAYLEN(tx), rx, ARRAYLEN(rx), t_wait, ledcontrol) == -1) { + hitagS_stop_clock(); set_tracing(false); lf_finalize(ledcontrol); - reply_mix(CMD_ACK, 0, 0, 0, 0, 0); + reply_ng(CMD_LF_HITAGS_READ, PM3_ERFTRANS, NULL, 0); return; } + int pageNum = 0; + while ((BUTTON_PRESS() == false) && (data_available() == false)) { WDT_HIT(); @@ -1319,18 +1453,18 @@ void ReadHitagS(hitag_function htf, const hitag_data *htd, bool ledcontrol) { pageNum++; //display key and password if possible if (pageNum == 2 && tag.auth == 1 && tag.LKP) { - if (htf == RHTSF_KEY) { + if (payload->cmd == RHTSF_KEY) { Dbprintf("Page[ 2]: %02X %02X %02X %02X", - htd->crypto.key[1], - htd->crypto.key[0], + payload->key[1], + payload->key[0], pwdl1, pwdl0 ); Dbprintf("Page[ 3]: %02X %02X %02X %02X", - htd->crypto.key[5], - htd->crypto.key[4], - htd->crypto.key[3], - htd->crypto.key[2] + payload->key[5], + payload->key[4], + payload->key[3], + payload->key[2] ); } else { //if the authentication is done with a challenge the key and password are unknown @@ -1344,78 +1478,89 @@ void ReadHitagS(hitag_function htf, const hitag_data *htd, bool ledcontrol) { break; } } + + hitagS_stop_clock(); set_tracing(false); - lf_finalize(ledcontrol); - - // TODO reply_mix(CMD_ACK, 1, 0, 0, 0, 0); and send dump as well, to be decoded in the client - reply_mix(CMD_ACK, 0, 0, 0, 0, 0); + reply_ng(CMD_LF_HITAGS_READ, PM3_SUCCESS, (uint8_t *)tag.pages, sizeof(tag.pages)); } /* * Authenticates to the Tag with the given Key or Challenge. * Writes the given 32Bit data into page_ */ -void WritePageHitagS(hitag_function htf, const hitag_data *htd, int page, bool ledcontrol) { +void WritePageHitagS(const lf_hitag_data_t *payload, bool ledcontrol) { - bool bSuccessful = false; //check for valid input - if (page == 0) { + if (payload->page == 0) { Dbprintf("Error, invalid page"); - reply_mix(CMD_ACK, bSuccessful, 0, 0, 0, 0); + reply_ng(CMD_LF_HITAGS_WRITE, PM3_EINVARG, NULL, 0); return; } uint8_t rx[HITAG_FRAME_LEN]; size_t rxlen = 0; + uint8_t tx[HITAG_FRAME_LEN]; size_t txlen = 0; + int t_wait = HITAG_T_WAIT_MAX; - if (selectHitagS(htf, htd, tx, ARRAYLEN(tx), rx, ARRAYLEN(rx), t_wait, ledcontrol) == -1) { + int res = PM3_ESOFT; + + if (selectHitagS(payload, tx, ARRAYLEN(tx), rx, ARRAYLEN(rx), t_wait, ledcontrol) == -1) { + res = PM3_ERFTRANS; goto write_end; } //check if the given page exists - if (page > tag.max_page) { - Dbprintf("page number too big for this tag"); + if (payload->page > tag.max_page) { + Dbprintf("Error, page number too large"); + res = PM3_EINVARG; goto write_end; } //send write page request txlen = 0; + uint8_t cmd = 0x08; txlen = concatbits(tx, txlen, &cmd, 8 - 4, 4); - uint8_t addr = page; + + uint8_t addr = payload->page; txlen = concatbits(tx, txlen, &addr, 0, 8); + uint8_t crc = CRC8Hitag1Bits(tx, txlen); txlen = concatbits(tx, txlen, &crc, 0, 8); sendReceiveHitagS(tx, txlen, rx, ARRAYLEN(rx), &rxlen, t_wait, ledcontrol, false); if ((rxlen != 2) || (rx[0] >> (8 - 2) != 0x1)) { - Dbprintf("no write access on page %d", page); + Dbprintf("no write access on page " _YELLOW_("%d"), payload->page); + res = PM3_ESOFT; goto write_end; } //ACK received to write the page. send data uint8_t data[4] = {0, 0, 0, 0}; - switch (htf) { + switch (payload->cmd) { case WHTSF_CHALLENGE: - data[0] = htd->auth.data[3]; - data[1] = htd->auth.data[2]; - data[2] = htd->auth.data[1]; - data[3] = htd->auth.data[0]; + data[0] = payload->data[3]; + data[1] = payload->data[2]; + data[2] = payload->data[1]; + data[3] = payload->data[0]; break; case WHTSF_KEY: - data[0] = htd->crypto.data[3]; - data[1] = htd->crypto.data[2]; - data[2] = htd->crypto.data[1]; - data[3] = htd->crypto.data[0]; + data[0] = payload->data[3]; + data[1] = payload->data[2]; + data[2] = payload->data[1]; + data[3] = payload->data[0]; break; - default: + default: { + res = PM3_EINVARG; return; + } } + txlen = 0; txlen = concatbits(tx, txlen, data, 0, 32); crc = CRC8Hitag1Bits(tx, txlen); @@ -1424,16 +1569,16 @@ void WritePageHitagS(hitag_function htf, const hitag_data *htd, int page, bool l sendReceiveHitagS(tx, txlen, rx, ARRAYLEN(rx), &rxlen, t_wait, ledcontrol, false); if ((rxlen != 2) || (rx[0] >> (8 - 2) != 0x1)) { - Dbprintf("write on page %d failed", page); + res = PM3_ESOFT; // write failed } else { - Dbprintf("write on page %d successful", page); - bSuccessful = true; + res = PM3_SUCCESS; } write_end: + hitagS_stop_clock(); set_tracing(false); lf_finalize(ledcontrol); - reply_mix(CMD_ACK, bSuccessful, 0, 0, 0, 0); + reply_ng(CMD_LF_HITAGS_WRITE, res, NULL, 0); } /* @@ -1444,10 +1589,11 @@ write_end: * detects these challenges. */ void Hitag_check_challenges(const uint8_t *data, uint32_t datalen, bool ledcontrol) { + //check for valid input if (datalen < 8) { - Dbprintf("Error, need chals"); - reply_mix(CMD_ACK, 0, 0, 0, 0, 0); + Dbprintf("Error, missing challenges"); + reply_ng(CMD_LF_HITAGS_TEST_TRACES, PM3_EINVARG, NULL, 0); return; } uint32_t dataoffset = 0; @@ -1460,38 +1606,42 @@ void Hitag_check_challenges(const uint8_t *data, uint32_t datalen, bool ledcontr // Watchdog hit WDT_HIT(); - hitag_data htd; - memset(&htd, 0, sizeof(htd)); + lf_hitag_data_t payload; + memset(&payload, 0, sizeof(payload)); + payload.cmd = RHTSF_CHALLENGE; - memcpy(htd.auth.NrAr, data + dataoffset, 8); + memcpy(payload.NrAr, data + dataoffset, 8); - int res = selectHitagS(RHTSF_CHALLENGE, &htd, tx, ARRAYLEN(tx), rx, ARRAYLEN(rx), t_wait, ledcontrol); + int res = selectHitagS(&payload, tx, ARRAYLEN(tx), rx, ARRAYLEN(rx), t_wait, ledcontrol); Dbprintf("Challenge %s: %02X %02X %02X %02X %02X %02X %02X %02X", res == -1 ? "failed " : "success", - htd.auth.NrAr[0], htd.auth.NrAr[1], - htd.auth.NrAr[2], htd.auth.NrAr[3], - htd.auth.NrAr[4], htd.auth.NrAr[5], - htd.auth.NrAr[6], htd.auth.NrAr[7] + payload.NrAr[0], payload.NrAr[1], + payload.NrAr[2], payload.NrAr[3], + payload.NrAr[4], payload.NrAr[5], + payload.NrAr[6], payload.NrAr[7] ); if (res == -1) { // Need to do a dummy UID select that will fail FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); SpinDelay(2); - selectHitagS(RHTSF_CHALLENGE, &htd, tx, ARRAYLEN(tx), rx, ARRAYLEN(rx), t_wait, ledcontrol); + selectHitagS(&payload, tx, ARRAYLEN(tx), rx, ARRAYLEN(rx), t_wait, ledcontrol); } dataoffset += 8; - if (dataoffset >= datalen - 8) + if (dataoffset >= datalen - 8) { break; + } // reset field FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + // min t_reset = 2ms SpinDelay(2); } + hitagS_stop_clock(); set_tracing(false); lf_finalize(ledcontrol); - reply_mix(CMD_ACK, 1, 0, 0, 0, 0); + reply_ng(CMD_ACK, PM3_SUCCESS, NULL, 0); return; } diff --git a/armsrc/hitagS.h b/armsrc/hitagS.h index cbb87722f..6278b1b18 100644 --- a/armsrc/hitagS.h +++ b/armsrc/hitagS.h @@ -22,11 +22,10 @@ #define _HITAGS_H_ #include "common.h" - #include "hitag.h" void SimulateHitagSTag(bool tag_mem_supplied, const uint8_t *data, bool ledcontrol); -void ReadHitagS(hitag_function htf, const hitag_data *htd, bool ledcontrol); -void WritePageHitagS(hitag_function htf, const hitag_data *htd, int page, bool ledcontrol); +void ReadHitagS(const lf_hitag_data_t *payload, bool ledcontrol); +void WritePageHitagS(const lf_hitag_data_t *payload, bool ledcontrol); void Hitag_check_challenges(const uint8_t *data, uint32_t datalen, bool ledcontrol); #endif diff --git a/armsrc/iso15693.c b/armsrc/iso15693.c index 31b2fdf97..0c7d1335a 100644 --- a/armsrc/iso15693.c +++ b/armsrc/iso15693.c @@ -2941,14 +2941,11 @@ void SetTag15693Uid_v2(const uint8_t *uid) { { ISO15_REQ_DATARATE_HIGH, ISO15693_MAGIC_WRITE, 0x09, 0x47, 0x3f, 0x03, 0x8b, 0x00, 0x00, 0x00 }, { ISO15_REQ_DATARATE_HIGH, ISO15693_MAGIC_WRITE, 0x09, 0x52, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, // hf 15 raw -wac -d 02 e0 09 41 + uid first four bytes - {ISO15_REQ_DATARATE_HIGH, ISO15693_MAGIC_WRITE, 0x09, 0x41, uid[7], uid[6], uid[5], uid[4], 0x00, 0x00}, + {ISO15_REQ_DATARATE_HIGH, ISO15693_MAGIC_WRITE, 0x09, 0x40, uid[7], uid[6], uid[5], uid[4], 0x00, 0x00}, // hf 15 raw -wac -d 02 e0 09 40 + uid last four bytes - {ISO15_REQ_DATARATE_HIGH, ISO15693_MAGIC_WRITE, 0x09, 0x40, uid[3], uid[2], uid[1], uid[0], 0x00, 0x00} + {ISO15_REQ_DATARATE_HIGH, ISO15693_MAGIC_WRITE, 0x09, 0x41, uid[3], uid[2], uid[1], uid[0], 0x00, 0x00} }; - AddCrc15(cmd[0], 8); - AddCrc15(cmd[1], 8); - uint8_t buf[ISO15693_MAX_RESPONSE_LENGTH] = {0x00}; uint32_t start_time = 0; @@ -2958,6 +2955,8 @@ void SetTag15693Uid_v2(const uint8_t *uid) { int res = PM3_SUCCESS; for (int i = 0; i < 4; i++) { + + AddCrc15(cmd[i], 8); res = SendDataTag( cmd[i], sizeof(cmd[i]), diff --git a/armsrc/util.c b/armsrc/util.c index 84a5aee69..252b09d0d 100644 --- a/armsrc/util.c +++ b/armsrc/util.c @@ -91,7 +91,7 @@ int hex2binarray_n(char *target, char *source, int sourcelen) { // process 4 bits (1 hex digit) at a time while (sourcelen--) { - + char x = *(source++); *(target++) = (x >> 7) & 1; @@ -102,7 +102,7 @@ int hex2binarray_n(char *target, char *source, int sourcelen) { *(target++) = (x >> 2) & 1; *(target++) = (x >> 1) & 1; *(target++) = (x & 1); - + count += 8; } return count; @@ -122,9 +122,9 @@ int binarray2hex(const uint8_t *bs, int bs_len, uint8_t *hex) { if (bs[i] == 1) { hex[byte_index] |= (1 << (7 - (count % 8))); } - + count++; - + // Move to the next byte if 8 bits have been filled if (count % 8 == 0) { byte_index++; diff --git a/client/CMakeLists.txt b/client/CMakeLists.txt index 65784c008..4169b8b57 100644 --- a/client/CMakeLists.txt +++ b/client/CMakeLists.txt @@ -263,6 +263,7 @@ set (TARGET_SOURCES ${PM3_ROOT}/common/cardhelper.c ${PM3_ROOT}/common/generator.c ${PM3_ROOT}/common/bruteforce.c + ${PM3_ROOT}/common/hitag2/hitag2_crypto.c ${PM3_ROOT}/client/src/crypto/asn1dump.c ${PM3_ROOT}/client/src/crypto/asn1utils.c ${PM3_ROOT}/client/src/crypto/libpcrypto.c diff --git a/client/dictionaries/ht2_default.dic b/client/dictionaries/ht2_default.dic index f503fa543..43120be3b 100644 --- a/client/dictionaries/ht2_default.dic +++ b/client/dictionaries/ht2_default.dic @@ -1,13 +1,25 @@ # +# Mifare Default Keys +# -- Iceman version -- +# -- contribute to this list, sharing is caring -- +# +# Lets see how long it takes before other project takes this file +# and claim they created it. +# # factory HT2 pwd 4D494B52 +# factory HT2 crypto key +4F4E4D494B52 # -# GE HT2 reader -# -# TSPL -5453504C -05040202 -25293C2F +# Gone in 360 seconds +FFFF814632FF # # Paxton HT2 BDF5E846 +# +# +# GE HT2 reader +# TSPL +5453504C +05040202 +25293C2F \ No newline at end of file diff --git a/client/luascripts/lf_awid_bulkclone.lua b/client/luascripts/lf_awid_bulkclone.lua index 0c5974360..0085a09c9 100644 --- a/client/luascripts/lf_awid_bulkclone.lua +++ b/client/luascripts/lf_awid_bulkclone.lua @@ -125,4 +125,4 @@ local function main(args) end end -main(args) \ No newline at end of file +main(args) diff --git a/client/src/cmddata.c b/client/src/cmddata.c index 662cccf55..7ce60933a 100644 --- a/client/src/cmddata.c +++ b/client/src/cmddata.c @@ -1719,12 +1719,12 @@ static int CmdSetGraphMarkers(const char *Cmd) { g_MarkerC.pos = arg_get_u32_def(ctx, 4, (keep ? g_MarkerC.pos : 0)); g_MarkerD.pos = arg_get_u32_def(ctx, 5, (keep ? g_MarkerD.pos : 0)); CLIParserFree(ctx); - PrintAndLogEx(INFO, "Setting markers " _BRIGHT_YELLOW_("A") "=%u, "_BRIGHT_MAGENTA_("B") "=%u, "_RED_("C") "=%u, "_BLUE_("D") "=%u", - g_MarkerA.pos, - g_MarkerB.pos, - g_MarkerC.pos, - g_MarkerD.pos - ); + PrintAndLogEx(INFO, "Setting markers " _BRIGHT_YELLOW_("A") "=%u, "_BRIGHT_MAGENTA_("B") "=%u, "_RED_("C") "=%u, "_BLUE_("D") "=%u", + g_MarkerA.pos, + g_MarkerB.pos, + g_MarkerC.pos, + g_MarkerD.pos + ); RepaintGraphWindow(); return PM3_SUCCESS; } @@ -3847,7 +3847,7 @@ static command_t CommandTable[] = { {"save", CmdSave, AlwaysAvailable, "Save signal trace data"}, {"setdebugmode", CmdSetDebugMode, AlwaysAvailable, "Set Debugging Level on client side"}, {"xor", CmdXor, AlwaysAvailable, "Xor a input string"}, - + {"-----------", CmdHelp, AlwaysAvailable, "------------------------- " _CYAN_("Modulation") "-------------------------"}, {"biphaserawdecode", CmdBiphaseDecodeRaw, AlwaysAvailable, "Biphase decode bin stream in DemodBuffer"}, {"detectclock", CmdDetectClockRate, AlwaysAvailable, "Detect ASK, FSK, NRZ, PSK clock rate of wave in GraphBuffer"}, diff --git a/client/src/cmdhf15.c b/client/src/cmdhf15.c index 0144f7fcf..55e9970d1 100644 --- a/client/src/cmdhf15.c +++ b/client/src/cmdhf15.c @@ -2737,7 +2737,7 @@ static int CmdHF15CSetUID(const char *Cmd) { "Set UID for magic Chinese card (only works with such cards)\n", "hf 15 csetuid -u E011223344556677 -> use gen1 command\n" "hf 15 csetuid -u E011223344556677 --v2 -> use gen2 command" - ); + ); void *argtable[] = { arg_param_begin, diff --git a/client/src/cmdhfmfp.c b/client/src/cmdhfmfp.c index df8bddd0c..11f1ce899 100644 --- a/client/src/cmdhfmfp.c +++ b/client/src/cmdhfmfp.c @@ -355,7 +355,7 @@ static int CmdHFMFPInfo(const char *Cmd) { if (supportVersion) { int cardtype = getCardType(version[1], version[3], version[4]); - switch(cardtype) { + switch (cardtype) { case PLUS_EV1: { if (supportSignature) { PrintAndLogEx(INFO, "Tech..... " _GREEN_("MIFARE Plus EV1")); diff --git a/client/src/cmdlfhitag.c b/client/src/cmdlfhitag.c index 4edc50724..81ab2707b 100644 --- a/client/src/cmdlfhitag.c +++ b/client/src/cmdlfhitag.c @@ -30,6 +30,8 @@ #include "lfdemod.h" #include "cmddata.h" // setDemodBuff #include "pm3_cmd.h" // return codes +#include "hitag2/hitag2_crypto.h" +#include "util_posix.h" // msclock static int CmdHelp(const char *Cmd); @@ -205,33 +207,66 @@ static int CmdLFHitagList(const char *Cmd) { static void print_hitag2_paxton(const uint8_t *data) { - uint64_t bytes = 0; + // if the pwd isn't.. + if (memcmp(data + 4, "\xBD\xF5\xE8\x46", 4)) { + return; + } + uint64_t num = 0; uint64_t paxton_id = 0; uint16_t skip = 48; - uint16_t digit = 0; uint64_t mask = 0xF80000000000; - for (int i = 16; i < 22; i++) { - bytes = (bytes * 0x100) + data[i]; - } + uint64_t bytes = bytes_to_num(data + 16, 6); for (int j = 0; j < 8; j++) { + num = bytes & mask; skip -= 5; - mask = mask >> 5; - digit = (num >> skip & 15); + mask >>= 5; + + uint8_t digit = (num >> skip & 0xF); paxton_id = (paxton_id * 10) + digit; if (j == 5) { skip -= 2; - mask = mask >> 2; + mask >>= 2; + } + } + + /* + const uint8_t isocard = 0x06; + const uint8_t fob = 0x03; + const uint8_t iso_magstripe = 0x02; + */ + +// [=] 4/0x04 | 39 04 21 1C | 9.!. | RW | User +// [=] 5/0x05 | AC 3F 00 06 | .?.. | RW | User + + char formfactor[16]; + switch (data[23]) { + case 0x06: { + strcat(formfactor, "isocard"); + break; + } + case 0x03: { + strcat(formfactor, "fob"); + break; + } + case 0x02: { + strcat(formfactor, "iso magstripe"); + break; + } + default: { + snprintf(formfactor, sizeof(formfactor), "unk: %02x", data[23]); + break; } } PrintAndLogEx(INFO, ""); PrintAndLogEx(INFO, "--- " _CYAN_("Possible de-scramble patterns") " -------------"); - PrintAndLogEx(SUCCESS, "Paxton id... %" PRIu64 " | 0x%" PRIx64, paxton_id, paxton_id); + PrintAndLogEx(SUCCESS, "Paxton id... %" PRIu64 " | 0x%" PRIx64 " ( %s )", paxton_id, paxton_id, formfactor); + PrintAndLogEx(INFO, ""); } static void print_hitag2_configuration(uint32_t uid, uint8_t config) { @@ -283,6 +318,7 @@ static void print_hitag2_configuration(uint32_t uid, uint8_t config) { } else { PrintAndLogEx(SUCCESS, " %s", sprint_breakdown_bin(C_NONE, bs, 8, 7, 1, "Manchester")); } + PrintAndLogEx(NORMAL, ""); } const char *annotation[] = { @@ -381,15 +417,140 @@ static struct { STATE_HALT, STATE_START_AUTH, STATE_AUTH, + STATE_START_ENCRYPTED, STATE_ENCRYPTED, } state; + uint32_t uid; + uint64_t cipher_state; + uint8_t plainlen; + uint8_t plain[30]; + bool found_key; + uint64_t key; } _ht2state; void annotateHitag2_init(void) { _ht2state.state = STATE_HALT; + _ht2state.uid = 0; + _ht2state.cipher_state = 0; + _ht2state.plainlen = 0; + memset(_ht2state.plain, 0, sizeof(_ht2state.plain)); } -void annotateHitag2(char *exp, size_t size, const uint8_t *cmd, uint8_t cmdsize, uint8_t bits, bool is_response) { +static void rev_msb_array(uint8_t *d, uint8_t n) { + for (uint8_t i = 0 ; i < n ; i++) { + d[i] = reflect8(d[i]); + } +} + +// param nrar must be 8 bytes +static bool ht2_check_cryptokeys(const uint64_t *keys, const uint32_t keycount, const uint8_t *nrar) { + + if (keys == NULL || keycount == 0 || nrar == NULL) { + return false; + } + + uint32_t iv = REV32((nrar[3] << 24) + (nrar[2] << 16) + (nrar[1] << 8) + nrar[0]); + uint32_t ar = (nrar[4] << 24) + (nrar[5] << 16) + (nrar[6] << 8) + nrar[7]; + + bool found = false; + for (uint32_t i = 0; i < keycount; i++) { + + uint64_t key = keys[i]; + key = BSWAP_48(key); + key = REV64(key); + + hitag_state_t hs2; + ht2_hitag2_init_ex(&hs2, key, _ht2state.uid, iv); + + uint32_t tbits = ht2_hitag2_nstep(&hs2, 32); + if ((ar ^ tbits) == 0xFFFFFFFF) { + _ht2state.found_key = true; + _ht2state.key = key; + found = true; + break; + } + } + return found; +} + +static int ht2_check_dictionary(uint32_t key_count, uint8_t *keys, uint8_t keylen, uint32_t *found_idx) { + + lf_hitag_data_t packet; + memset(&packet, 0, sizeof(packet)); + + uint8_t *pkeys = keys; + + while (key_count--) { + + if (keylen == 4) { + packet.cmd = RHT2F_PASSWORD; + memcpy(packet.pwd, pkeys, keylen); + } else { + packet.cmd = RHT2F_CRYPTO; + memcpy(packet.key, pkeys, keylen); + } + + pkeys += keylen; + + clearCommandBuffer(); + SendCommandNG(CMD_LF_HITAG_READER, (uint8_t *)&packet, sizeof(packet)); + PacketResponseNG resp; + if (WaitForResponseTimeout(CMD_LF_HITAG_READER, &resp, 2000) == false) { + PrintAndLogEx(WARNING, "timeout while waiting for reply."); + SendCommandNG(CMD_BREAK_LOOP, NULL, 0); + return PM3_ETIMEOUT; + } + + if (resp.status != PM3_SUCCESS) { + *found_idx = *found_idx + 1; + continue; + } + return PM3_SUCCESS; + } + return PM3_ESOFT; +} + + +bool hitag2_get_plain(uint8_t *plain, uint8_t *plen) { + if (_ht2state.state == STATE_ENCRYPTED || _ht2state.state == STATE_START_ENCRYPTED) { + if (_ht2state.found_key) { + *plen = _ht2state.plainlen; + memcpy(plain, _ht2state.plain, _ht2state.plainlen); + return true; + } + } + return false; +} + +static uint8_t hitag2_get_page(const char *bs) { + if ((memcmp(bs + 2, "000", 3) == 0) && (memcmp(bs + 2 + 3 + 2, "111", 3) == 0)) { + return 0; + } + if ((memcmp(bs + 2, "001", 3) == 0) && (memcmp(bs + 2 + 3 + 2, "110", 3) == 0)) { + return 1; + } + if ((memcmp(bs + 2, "010", 3) == 0) && (memcmp(bs + 2 + 3 + 2, "101", 3) == 0)) { + return 2; + } + if ((memcmp(bs + 2, "011", 3) == 0) && (memcmp(bs + 2 + 3 + 2, "100", 3) == 0)) { + return 3; + } + if ((memcmp(bs + 2, "100", 3) == 0) && (memcmp(bs + 2 + 3 + 2, "011", 3) == 0)) { + return 4; + } + if ((memcmp(bs + 2, "101", 3) == 0) && (memcmp(bs + 2 + 3 + 2, "010", 3) == 0)) { + return 5; + } + if ((memcmp(bs + 2, "110", 3) == 0) && (memcmp(bs + 2 + 3 + 2, "001", 3) == 0)) { + return 6; + } + if ((memcmp(bs + 2, "111", 3) == 0) && (memcmp(bs + 2 + 3 + 2, "000", 3) == 0)) { + return 7; + } + return 255; +} + +void hitag2_annotate_plain(char *exp, size_t size, const uint8_t *cmd, uint8_t cmdsize, uint8_t bits) { if (cmdsize == 0) { return; @@ -411,10 +572,88 @@ void annotateHitag2(char *exp, size_t size, const uint8_t *cmd, uint8_t cmdsize, } } + switch (bn) { + case 5: { + snprintf(exp, size, " "); + break; + } + case 10: { + if (memcmp(binstr, HITAG2_HALT, 2) == 0) { + snprintf(exp, size, " "); + break; + } + + uint8_t page = hitag2_get_page(binstr); + + if (memcmp(binstr, HITAG2_READ_PAGE, 2) == 0) { + snprintf(exp, size, "READ PAGE (" _MAGENTA_("%u") ")", page); + break; + } + + if (memcmp(binstr, HITAG2_READ_PAGE_INVERTED, 2) == 0) { + snprintf(exp, size, "READ PAGE INV (" _MAGENTA_("%u") ")", page); + break; + } + + if (memcmp(binstr, HITAG2_WRITE_PAGE, 2) == 0) { + snprintf(exp, size, "WRITE PAGE (" _MAGENTA_("%u") ")", page); + break; + } + break; + } + case 32: { // password or data + snprintf(exp, size, " "); + break; + } + case 64: { // crypto handshake + snprintf(exp, size, " "); + break; + } + default: { + snprintf(exp, size, " "); + break; + } + } + free(binstr); +} + +void annotateHitag2(char *exp, size_t size, const uint8_t *cmd, uint8_t cmdsize, uint8_t bits, bool is_response, const uint64_t *keys, uint32_t keycount, bool isdecrypted) { + + if (cmdsize == 0) { + return; + } + + char *binstr = (char *)calloc((cmdsize * 8) + 1, sizeof(uint8_t)); + if (binstr == NULL) { + return; + } + + bytes_2_binstr(binstr, cmd, cmdsize); + + size_t bn = strlen(binstr); + if (bits) { + if (cmdsize == 1) { + bn = bits; + } else if (cmdsize > 1) { + bn = ((cmdsize - 1) * 8) + bits; + } + } + + memcpy(_ht2state.plain, cmd, cmdsize); + _ht2state.plainlen = cmdsize; + + if (_ht2state.state == STATE_ENCRYPTED || _ht2state.state == STATE_START_ENCRYPTED) { + + if (_ht2state.found_key && isdecrypted == false) { + ht2_hitag2_cipher_transcrypt(&_ht2state.cipher_state, _ht2state.plain, bn / 8, bn % 8); + } + } + // 11000 AUTH only one with 5 bits. cmdsize 1 switch (bn) { case 5: { - _ht2state.state = STATE_HALT; + annotateHitag2_init(); + if (memcmp(binstr, HITAG2_START_AUTH, 5) == 0) { snprintf(exp, size, "START AUTH"); _ht2state.state = STATE_START_AUTH; @@ -425,7 +664,7 @@ void annotateHitag2(char *exp, size_t size, const uint8_t *cmd, uint8_t cmdsize, } case 10: { - if (_ht2state.state == STATE_ENCRYPTED) { + if (isdecrypted == false && _ht2state.state == STATE_ENCRYPTED) { snprintf(exp, size, "ENC CMD"); break; } @@ -435,18 +674,21 @@ void annotateHitag2(char *exp, size_t size, const uint8_t *cmd, uint8_t cmdsize, _ht2state.state = STATE_HALT; break; } + + uint8_t page = hitag2_get_page(binstr); + if (memcmp(binstr, HITAG2_READ_PAGE, 2) == 0) { - snprintf(exp, size, "READ_PAGE (%u)", 0); + snprintf(exp, size, "READ PAGE (" _MAGENTA_("%u") ")", page); break; } if (memcmp(binstr, HITAG2_READ_PAGE_INVERTED, 2) == 0) { - snprintf(exp, size, "READ_PAGE_INVERTED (%u)", 0); + snprintf(exp, size, "READ PAGE INV (" _MAGENTA_("%u") ")", page); break; } if (memcmp(binstr, HITAG2_WRITE_PAGE, 2) == 0) { - snprintf(exp, size, "WRITE_PAGE ()"); + snprintf(exp, size, "WRITE PAGE (" _MAGENTA_("%u") ")", page); break; } break; @@ -456,6 +698,10 @@ void annotateHitag2(char *exp, size_t size, const uint8_t *cmd, uint8_t cmdsize, if (_ht2state.state == STATE_START_AUTH) { if (is_response) { snprintf(exp, size, "UID"); + uint8_t uid[4]; + memcpy(uid, cmd, 4); + rev_msb_array(uid, 4); + _ht2state.uid = MemLeToUint4byte(uid); } else { snprintf(exp, size, "PWD: " _GREEN_("0x%02X%02X%02X%02X"), cmd[0], cmd[1], cmd[2], cmd[3]); _ht2state.state = STATE_AUTH; @@ -465,19 +711,51 @@ void annotateHitag2(char *exp, size_t size, const uint8_t *cmd, uint8_t cmdsize, if (_ht2state.state == STATE_AUTH) { snprintf(exp, size, "DATA"); - } else { - snprintf(exp, size, "?"); + break; + } + + if (_ht2state.state == STATE_START_ENCRYPTED) { + snprintf(exp, size, "At"); + _ht2state.state = STATE_ENCRYPTED; + break; + } + + if (isdecrypted == false && _ht2state.state == STATE_ENCRYPTED) { + snprintf(exp, size, "ENC DATA"); } break; } case 64: { // crypto handshake - snprintf(exp, size, "AUTH: Nr Ar"); - _ht2state.state = STATE_ENCRYPTED; + + if (_ht2state.state == STATE_START_AUTH) { + _ht2state.state = STATE_START_ENCRYPTED; + + // need to be called with filename... + if (ht2_check_cryptokeys(keys, keycount, cmd)) { + + _ht2state.cipher_state = ht2_hitag2_init( + _ht2state.key, + _ht2state.uid, + REV32((cmd[3] << 24) + (cmd[2] << 16) + (cmd[1] << 8) + cmd[0]) + ); + ht2_hitag2_cipher_transcrypt(&_ht2state.cipher_state, _ht2state.plain + 4, 4, 0); + + uint64_t key = REV64(_ht2state.key); + key = BSWAP_48(key); + snprintf(exp, size, "Nr Ar " _WHITE_("( ") _GREEN_("%012" PRIx64) " )", key); + + } else { + snprintf(exp, size, "AUTH: Nr Ar"); + } + } else { + snprintf(exp, size, "AUTH: Nr Ar"); + } break; } default: { snprintf(exp, size, "?"); + _ht2state.state = STATE_HALT; break; } } @@ -488,18 +766,22 @@ void annotateHitag2(char *exp, size_t size, const uint8_t *cmd, uint8_t cmdsize, void annotateHitagS(char *exp, size_t size, const uint8_t *cmd, uint8_t cmdsize, bool is_response) { } + static bool getHitag2Uid(uint32_t *uid) { - hitag_data htd; - memset(&htd, 0, sizeof(htd)); + + lf_hitag_data_t packet; + memset(&packet, 0, sizeof(packet)); + packet.cmd = RHT2F_UID_ONLY; + clearCommandBuffer(); - SendCommandMIX(CMD_LF_HITAG_READER, RHT2F_UID_ONLY, 0, 0, &htd, sizeof(htd)); + SendCommandNG(CMD_LF_HITAG_READER, (uint8_t *) &packet, sizeof(packet)); PacketResponseNG resp; - if (WaitForResponseTimeout(CMD_ACK, &resp, 2500) == false) { + if (WaitForResponseTimeout(CMD_LF_HITAG_READER, &resp, 1500) == false) { PrintAndLogEx(WARNING, "timeout while waiting for reply."); return false; } - if (resp.oldarg[0] == false) { + if (resp.status != PM3_SUCCESS) { PrintAndLogEx(DEBUG, "DEBUG: Error - failed getting UID"); return false; } @@ -530,14 +812,16 @@ static int CmdLFHitagInfo(const char *Cmd) { return PM3_ESOFT; } // how to determine Hitag types? + // need auth / pwd to get it. + // we could try the default key/pwd and print if successful // read block3, get configuration byte. // common configurations. - print_hitag2_configuration(uid, 0x06); - // print_hitag2_configuration( uid, 0x0E ); - // print_hitag2_configuration( uid, 0x02 ); - // print_hitag2_configuration( uid, 0x00 ); - // print_hitag2_configuration( uid, 0x04 ); + print_hitag2_configuration(uid, 0x06); // pwd mode enabled / AM + // print_hitag2_configuration(uid, 0x0E); // crypto mode enabled / AM + // print_hitag2_configuration(uid, 0x02); + // print_hitag2_configuration(uid, 0x00); + // print_hitag2_configuration(uid, 0x04); return PM3_SUCCESS; } @@ -545,27 +829,22 @@ static int CmdLFHitagReader(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "lf hitag read", - "Read Hitag memory\n" - "Crypto mode key format: ISK high + ISK low", - "Hitag S, plain mode\n" - " lf hitag read --hts\n" - "Hitag S, challenge mode\n" - " lf hitag read --hts --nrar 0102030411223344\n" - "Hitag S, crypto mode => use default key 4F4E4D494B52 (ONMIKR)\n" - " lf hitag read --hts --crypto\n" - "Hitag S, long key = crypto mode\n" - " lf hitag read --hts -k 4F4E4D494B52\n\n" - - "Hitag 2, password mode => use default key 4D494B52 (MIKR)\n" - " lf hitag read --ht2 --pwd\n" - "Hitag 2, providing a short key = password mode\n" - " lf hitag read --ht2 -k 4D494B52\n" - "Hitag 2, challenge mode\n" - " lf hitag read --ht2 --nrar 0102030411223344\n" - "Hitag 2, crypto mode => use default key 4F4E4D494B52 (ONMIKR)\n" - " lf hitag read --ht2 --crypto\n" - "Hitag 2, providing a long key = crypto mode\n" - " lf hitag read --ht2 -k 4F4E4D494B52\n" + "Read Hitag memory. It support HitagS and Hitag 2\n\n" + " Password mode:\n" + " - default key 4D494B52 (MIKR)\n\n" + " Crypto mode: \n" + " - key format ISK high + ISK low\n" + " - default key 4F4E4D494B52 (ONMIKR)\n" + , + " lf hitag read --hts -> HitagS, plain mode\n" + " lf hitag read --hts --nrar 0102030411223344 -> HitagS, challenge mode\n" + " lf hitag read --hts --crypto -> HitagS, crypto mode, def key\n" + " lf hitag read --hts -k 4F4E4D494B52 -> HitagS, crypto mode\n\n" + " lf hitag read --ht2 --pwd -> Hitag 2, pwd mode, def key\n" + " lf hitag read --ht2 -k 4D494B52 -> Hitag 2, pwd mode\n" + " lf hitag read --ht2 --nrar 0102030411223344 -> Hitag 2, challenge mode\n" + " lf hitag read --ht2 --crypto -> Hitag 2, crypto mode, def key\n" + " lf hitag read --ht2 -k 4F4E4D494B52 -> Hitag 2, crypto mode\n" ); void *argtable[] = { @@ -670,48 +949,61 @@ static int CmdLFHitagReader(const char *Cmd) { return PM3_EINVARG; } - hitag_function htf; - hitag_data htd; - memset(&htd, 0, sizeof(htd)); - uint16_t cmd; - if (use_hts && use_nrar) { - cmd = CMD_LF_HITAGS_READ; - htf = RHTSF_CHALLENGE; - memcpy(htd.auth.NrAr, nrar, sizeof(htd.auth.NrAr)); + lf_hitag_data_t packet; + memset(&packet, 0, sizeof(packet)); + + int pm3cmd; + if (use_hts) { + // plain mode? + pm3cmd = CMD_LF_HITAGS_READ; + } else if (use_hts && use_nrar) { + pm3cmd = CMD_LF_HITAGS_READ; + packet.cmd = RHTSF_CHALLENGE; + memcpy(packet.NrAr, nrar, sizeof(packet.NrAr)); + } else if (use_hts && use_crypto) { - cmd = CMD_LF_HITAGS_READ; - htf = RHTSF_KEY; - memcpy(htd.crypto.key, key, sizeof(htd.crypto.key)); + pm3cmd = CMD_LF_HITAGS_READ; + packet.cmd = RHTSF_KEY; + memcpy(packet.key, key, sizeof(packet.key)); + } else if (use_ht2 && use_pwd) { - cmd = CMD_LF_HITAG_READER; - htf = RHT2F_PASSWORD; - memcpy(htd.pwd.password, key, sizeof(htd.pwd.password)); + pm3cmd = CMD_LF_HITAG_READER; + packet.cmd = RHT2F_PASSWORD; + memcpy(packet.pwd, key, sizeof(packet.pwd)); + } else if (use_ht2 && use_nrar) { - cmd = CMD_LF_HITAG_READER; - htf = RHT2F_AUTHENTICATE; - memcpy(htd.auth.NrAr, nrar, sizeof(htd.auth.NrAr)); + pm3cmd = CMD_LF_HITAG_READER; + packet.cmd = RHT2F_AUTHENTICATE; + memcpy(packet.NrAr, nrar, sizeof(packet.NrAr)); } else if (use_ht2 && use_crypto) { - htf = RHT2F_CRYPTO; - cmd = CMD_LF_HITAG_READER; - memcpy(htd.crypto.key, key, sizeof(htd.crypto.key)); + + pm3cmd = CMD_LF_HITAG_READER; + packet.cmd = RHT2F_CRYPTO; + memcpy(packet.key, key, sizeof(packet.key)); } else { PrintAndLogEx(WARNING, "Sorry, not yet implemented"); return PM3_ENOTIMPL; } clearCommandBuffer(); - SendCommandMIX(cmd, htf, 0, 0, &htd, sizeof(htd)); + SendCommandNG(pm3cmd, (uint8_t *)&packet, sizeof(packet)); + PacketResponseNG resp; - if (WaitForResponseTimeout(CMD_ACK, &resp, 2000) == false) { + if (WaitForResponseTimeout(pm3cmd, &resp, 2000) == false) { PrintAndLogEx(WARNING, "timeout while waiting for reply."); SendCommandNG(CMD_BREAK_LOOP, NULL, 0); return PM3_ETIMEOUT; } - if (resp.oldarg[0] == false) { + + if (resp.status != PM3_SUCCESS) { PrintAndLogEx(DEBUG, "DEBUG: Error - hitag failed"); return PM3_ESOFT; } + if (use_nrar) { + return PM3_SUCCESS; + } + uint8_t *data = resp.data.asBytes; uint32_t uid = bytes_to_num(data, HITAG_UID_SIZE); print_hitag2_configuration(uid, data[HITAG_BLOCK_SIZE * 3]); @@ -720,7 +1012,7 @@ static int CmdLFHitagReader(const char *Cmd) { print_hitag2_blocks(data, HITAG2_MAX_BYTE_SIZE); print_hitag2_paxton(data); } else { - print_hex_break(data, HITAG2_MAX_BYTE_SIZE, HITAG_BLOCK_SIZE); + print_hex_break(data, HITAG_MAX_BYTE_SIZE, HITAG_BLOCK_SIZE); } return PM3_SUCCESS; } @@ -746,22 +1038,28 @@ static int CmdLFHitagSCheckChallenges(const char *Cmd) { CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen); CLIParserFree(ctx); - clearCommandBuffer(); - uint8_t *data = NULL; size_t datalen = 0; int res = loadFile_safe(filename, ".cc", (void **)&data, &datalen); if (res == PM3_SUCCESS) { - if (datalen % 8 == 0) { - SendCommandMIX(CMD_LF_HITAGS_TEST_TRACES, datalen, 0, 0, data, datalen); - } else { - PrintAndLogEx(ERR, "Error, file length mismatch. Expected multiple of 8, got %zu", datalen); + + if (datalen % 8) { + PrintAndLogEx(ERR, "Error, file length mismatch. Expected multiple of 8, got " _RED_("%zu"), datalen); + free(data); + return PM3_EINVARG; } + if (datalen != (8 * 60)) { + PrintAndLogEx(ERR, "Error, file length mismatch. Expected 480, got " _RED_("%zu"), datalen); + free(data); + return PM3_EINVARG; + } + + clearCommandBuffer(); + SendCommandNG(CMD_LF_HITAGS_TEST_TRACES, data, datalen); } if (data) { free(data); } - return PM3_SUCCESS; } @@ -773,14 +1071,18 @@ static int CmdLFHitag2CheckChallenges(const char *Cmd) { ); CLIParserFree(ctx); + lf_hitag_data_t packet; + memset(&packet, 0, sizeof(lf_hitag_data_t)); + packet.cmd = RHT2F_TEST_AUTH_ATTEMPTS; + clearCommandBuffer(); - SendCommandMIX(CMD_LF_HITAG_READER, RHT2F_TEST_AUTH_ATTEMPTS, 0, 0, NULL, 0); + SendCommandNG(CMD_LF_HITAG_READER, (uint8_t *)&packet, sizeof(packet)); PacketResponseNG resp; - if (WaitForResponseTimeout(CMD_ACK, &resp, 2000) == false) { + if (WaitForResponseTimeout(CMD_LF_HITAG_READER, &resp, 2000) == false) { PrintAndLogEx(WARNING, "timeout while waiting for reply."); return PM3_ETIMEOUT; } - if (resp.oldarg[0] == false) { + if (resp.status != PM3_SUCCESS) { PrintAndLogEx(DEBUG, "DEBUG: Error - hitag failed"); return PM3_ESOFT; } @@ -792,27 +1094,22 @@ static int CmdLFHitag2CheckChallenges(const char *Cmd) { static int CmdLFHitagWriter(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "lf hitag wrbl", - "Write a page in Hitag memory\n" - "Crypto mode key format: ISK high + ISK low", - "Hitag S, plain mode\n" - " lf hitag wrbl --hts -p 6 -d 01020304\n" - "Hitag S, challenge mode\n" - " lf hitag wrbl --hts --nrar 0102030411223344 -p 6 -d 01020304\n" - "Hitag S, crypto mode => use default key 4F4E4D494B52 (ONMIKR)\n" - " lf hitag wrbl --hts --crypto -p 6 -d 01020304\n" - "Hitag S, long key = crypto mode\n" - " lf hitag wrbl --hts -k 4F4E4D494B52 -p 6 -d 01020304\n\n" - - "Hitag 2, password mode => use default key 4D494B52 (MIKR)\n" - " lf hitag wrbl --ht2 --pwd -p 6 -d 01020304\n" - "Hitag 2, providing a short key = password mode\n" - " lf hitag wrbl --ht2 -k 4D494B52 -p 6 -d 01020304\n" - "Hitag 2, challenge mode\n" - " lf hitag wrbl --ht2 --nrar 0102030411223344 -p 6 -d 01020304\n" - "Hitag 2, crypto mode => use default key 4F4E4D494B52 (ONMIKR)\n" - " lf hitag wrbl --ht2 --crypto -p 6 -d 01020304\n" - "Hitag 2, providing a long key = crypto mode\n" - " lf hitag wrbl --ht2 -k 4F4E4D494B52 -p 6 -d 01020304\n" + "Write a page in Hitag memory. It support HitagS and Hitag 2\n" + " Password mode:\n" + " - default key 4D494B52 (MIKR)\n\n" + " Crypto mode: \n" + " - key format ISK high + ISK low\n" + " - default key 4F4E4D494B52 (ONMIKR)\n" + , + " lf hitag wrbl --hts -p 6 -d 01020304 -> HitagS, plain mode\n" + " lf hitag wrbl --hts -p 6 -d 01020304 --nrar 0102030411223344 -> HitagS, challenge mode\n" + " lf hitag wrbl --hts -p 6 -d 01020304 --crypto -> HitagS, crypto mode, def key\n" + " lf hitag wrbl --hts -p 6 -d 01020304 -k 4F4E4D494B52 -> HitagS, crypto mode\n\n" + " lf hitag wrbl --ht2 -p 6 -d 01020304 --pwd -> Hitag 2, pwd mode, def key\n" + " lf hitag wrbl --ht2 -p 6 -d 01020304 -k 4D494B52 -> Hitag 2, pwd mode\n" + " lf hitag wrbl --ht2 -p 6 -d 01020304 --nrar 0102030411223344 -> Hitag 2, challenge mode\n" + " lf hitag wrbl --ht2 -p 6 -d 01020304 --crypto -> Hitag 2, crypto mode, def key\n" + " lf hitag wrbl --ht2 -p 6 -d 01020304 -k 4F4E4D494B52 -> Hitag 2, crypto mode\n" ); void *argtable[] = { @@ -854,7 +1151,7 @@ static int CmdLFHitagWriter(const char *Cmd) { return PM3_EINVARG; } - uint32_t page = arg_get_u32_def(ctx, 7, 0); + int page = arg_get_int_def(ctx, 7, 0); uint8_t data[4]; int dlen = 0; @@ -931,47 +1228,83 @@ static int CmdLFHitagWriter(const char *Cmd) { return PM3_EINVARG; } - hitag_function htf; - hitag_data htd; - memset(&htd, 0, sizeof(htd)); + lf_hitag_data_t packet; + memset(&packet, 0, sizeof(packet)); if (use_hts && use_nrar) { - htf = WHTSF_CHALLENGE; - memcpy(htd.auth.NrAr, nrar, sizeof(htd.auth.NrAr)); - memcpy(htd.auth.data, data, sizeof(data)); - PrintAndLogEx(INFO, "Authenticating to Hitag S in Challenge mode"); + packet.cmd = WHTSF_CHALLENGE; + memcpy(packet.NrAr, nrar, sizeof(packet.NrAr)); + memcpy(packet.data, data, sizeof(data)); + // iceman: No page in Hitag S ? + PrintAndLogEx(INFO, "Authenticating to " _YELLOW_("Hitag S") " in Challenge mode"); + } else if (use_hts && use_crypto) { - htf = WHTSF_KEY; - memcpy(htd.crypto.key, key, sizeof(htd.crypto.key)); - memcpy(htd.crypto.data, data, sizeof(data)); - PrintAndLogEx(INFO, "Authenticating to Hitag S in Crypto mode"); + packet.cmd = WHTSF_KEY; + memcpy(packet.key, key, sizeof(packet.key)); + memcpy(packet.data, data, sizeof(data)); + // iceman: No page in Hitag S ? + PrintAndLogEx(INFO, "Authenticating to " _YELLOW_("Hitag S") " in Crypto mode"); + } else if (use_ht2 && use_pwd) { - htf = WHT2F_PASSWORD; - memcpy(htd.pwd.password, key, sizeof(htd.pwd.password)); - memcpy(htd.crypto.data, data, sizeof(data)); - PrintAndLogEx(INFO, "Authenticating to Hitag 2 in Password mode"); + packet.cmd = WHT2F_PASSWORD; + packet.page = page; + memcpy(packet.pwd, key, sizeof(packet.pwd)); + memcpy(packet.data, data, sizeof(data)); + PrintAndLogEx(INFO, "Authenticating to " _YELLOW_("Hitag 2") " in Password mode"); + } else if (use_ht2 && use_crypto) { - htf = WHT2F_CRYPTO; - memcpy(htd.crypto.key, key, sizeof(htd.crypto.key)); - memcpy(htd.crypto.data, data, sizeof(data)); - PrintAndLogEx(INFO, "Authenticating to Hitag 2 in Crypto mode"); + packet.cmd = WHT2F_CRYPTO; + packet.page = page; + memcpy(packet.key, key, sizeof(packet.key)); + memcpy(packet.data, data, sizeof(data)); + PrintAndLogEx(INFO, "Authenticating to " _YELLOW_("Hitag 2") " in Crypto mode"); + } else { PrintAndLogEx(WARNING, "Sorry, not yet implemented"); return PM3_ENOTIMPL; } - uint16_t cmd = CMD_LF_HITAGS_WRITE; + clearCommandBuffer(); - SendCommandMIX(cmd, htf, 0, page, &htd, sizeof(htd)); - PacketResponseNG resp; - if (WaitForResponseTimeout(CMD_ACK, &resp, 4000) == false) { - PrintAndLogEx(WARNING, "timeout while waiting for reply."); - return PM3_ETIMEOUT; + + if (use_ht2) { + SendCommandNG(CMD_LF_HITAG2_WRITE, (uint8_t *)&packet, sizeof(packet)); + PacketResponseNG resp; + if (WaitForResponseTimeout(CMD_LF_HITAG2_WRITE, &resp, 4000) == false) { + PrintAndLogEx(WARNING, "timeout while waiting for reply."); + return PM3_ETIMEOUT; + } + + if (resp.status == PM3_ETEAROFF) { + PrintAndLogEx(INFO, "Writing tear off triggered"); + return PM3_SUCCESS; + } + + if (resp.status != PM3_SUCCESS) { + PrintAndLogEx(FAILED, "Write ( " _RED_("fail") " )"); + return resp.status; + } + + } else { + + SendCommandNG(CMD_LF_HITAGS_WRITE, (uint8_t *)&packet, sizeof(packet)); + PacketResponseNG resp; + if (WaitForResponseTimeout(CMD_LF_HITAGS_WRITE, &resp, 4000) == false) { + PrintAndLogEx(WARNING, "timeout while waiting for reply."); + return PM3_ETIMEOUT; + } + + if (resp.status == PM3_ETEAROFF) { + PrintAndLogEx(INFO, "Writing tear off triggered"); + return PM3_SUCCESS; + } + + if (resp.status != PM3_SUCCESS) { + PrintAndLogEx(FAILED, "Write ( " _RED_("fail") " )"); + return resp.status; + } } - if (resp.oldarg[0] == false) { - PrintAndLogEx(DEBUG, "DEBUG: Error - hitag write failed"); - return PM3_ESOFT; - } + PrintAndLogEx(SUCCESS, "Write ( " _GREEN_("ok") " )"); return PM3_SUCCESS; } @@ -980,17 +1313,13 @@ static int CmdLFHitag2Dump(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "lf hitag dump", "Read all Hitag 2 card memory and save to file\n" - "Crypto mode key format: ISK high + ISK low", - "Password mode => use default key 4D494B52 (MIKR)\n" - " lf hitag dump --pwd\n" - "Short key = password mode\n" - " lf hitag dump -k 4D494B52\n" - "Challenge mode\n" - " lf hitag dump --nrar 0102030411223344\n" - "Crypto mode => use default key 4F4E4D494B52 (ONMIKR)\n" - " lf hitag dump --crypto\n" - "Long key = crypto mode\n" - " lf hitag dump -k 4F4E4D494B52\n" + "Crypto mode key format: ISK high + ISK low, 4F4E4D494B52 (ONMIKR)\n" + "Password mode, default key 4D494B52 (MIKR)\n", + "lf hitag dump --pwd -> use def pwd\n" + "lf hitag dump -k 4D494B52 -> pwd mode\n" + "lf hitag dump --crypto -> use def crypto\n" + "lf hitag dump -k 4F4E4D494B52 -> crypto mode\n" + "lf hitag dump --nrar 0102030411223344\n" ); void *argtable[] = { @@ -1022,7 +1351,7 @@ static int CmdLFHitag2Dump(const char *Cmd) { bool use_nrar = nalen > 0; bool use_crypto = arg_get_lit(ctx, 3); - uint8_t key[HITAG_CRYPTOKEY_SIZE]; + uint8_t key[HITAG_NRAR_SIZE]; int keylen = 0; res = CLIParamHexToBuf(arg_get_str(ctx, 4), key, sizeof(key), &keylen); if (res != 0) { @@ -1047,8 +1376,11 @@ static int CmdLFHitag2Dump(const char *Cmd) { return PM3_EINVARG; } - if (keylen != 0 && keylen != 4 && keylen != 6) { - PrintAndLogEx(WARNING, "Wrong KEY len expected 0, 4 or 6, got %d", keylen); + if (keylen != 0 && + keylen != HITAG_PASSWORD_SIZE && + keylen != HITAG_CRYPTOKEY_SIZE && + keylen != HITAG_NRAR_SIZE) { + PrintAndLogEx(WARNING, "Wrong KEY len expected (0,4,6,8) got %d", keylen); return PM3_EINVARG; } @@ -1059,6 +1391,10 @@ static int CmdLFHitag2Dump(const char *Cmd) { if (keylen == HITAG_CRYPTOKEY_SIZE) { use_crypto = true; } + if (keylen == HITAG_NRAR_SIZE) { + use_nrar = true; + memcpy(nrar, key, sizeof(nrar)); + } // Set default key / pwd if ((keylen == 0) && use_pwd) { @@ -1094,39 +1430,121 @@ static int CmdLFHitag2Dump(const char *Cmd) { return PM3_EINVARG; } - hitag_function htf; - hitag_data htd; - memset(&htd, 0, sizeof(htd)); + uint32_t uid = 0; + + PacketResponseNG resp; + uint8_t *data = NULL; + + lf_hitag_data_t packet; + memset(&packet, 0, sizeof(packet)); + if (use_ht2 && use_pwd) { - htf = RHT2F_PASSWORD; - memcpy(htd.pwd.password, key, sizeof(htd.pwd.password)); - PrintAndLogEx(INFO, "Authenticating to Hitag2 in Password mode"); + packet.cmd = RHT2F_PASSWORD; + memcpy(packet.pwd, key, sizeof(packet.pwd)); + PrintAndLogEx(INFO, "Authenticating to " _YELLOW_("Hitag 2") " in Password mode"); + } else if (use_ht2 && use_crypto) { - htf = RHT2F_CRYPTO; - memcpy(htd.crypto.key, key, sizeof(htd.crypto.key)); - PrintAndLogEx(INFO, "Authenticating to Hitag2 in Crypto mode"); + packet.cmd = RHT2F_CRYPTO; + memcpy(packet.key, key, sizeof(packet.key)); + PrintAndLogEx(INFO, "Authenticating to " _YELLOW_("Hitag 2") " in Crypto mode"); + + } else if (use_ht2 && use_nrar) { + + + memcpy(packet.NrAr, nrar, sizeof(packet.NrAr)); + + PrintAndLogEx(INFO, _YELLOW_("Hitag 2") " - Challenge mode (NrAR)"); + + uint64_t t1 = msclock(); + + clearCommandBuffer(); + SendCommandNG(CMD_LF_HITAG2_CRACK, (uint8_t *) &packet, sizeof(packet)); + + // loop + uint8_t attempt = 30; + do { + + PrintAndLogEx(INPLACE, "Attack 1 running..."); + fflush(stdout); + + if (WaitForResponseTimeout(CMD_LF_HITAG2_CRACK, &resp, 1000) == false) { + attempt--; + continue; + } + + lf_hitag_crack_response_t *payload = (lf_hitag_crack_response_t *)resp.data.asBytes; + + if (resp.status == PM3_SUCCESS) { + PrintAndLogEx(NORMAL, " ( %s )", _GREEN_("ok")); + data = payload->data; + + t1 = msclock() - t1; + PrintAndLogEx(SUCCESS, "\ntime " _YELLOW_("%.0f") " seconds\n", (float)t1 / 1000.0); + goto out; + } + + // error codes + switch (payload->status) { + case -1: { + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(FAILED, "Couldn't select tag!"); + return PM3_ESOFT; + } + case -2: { + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(FAILED, "Cannot find a valid encrypted command!"); + return PM3_ESOFT; + } + case -3: { + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(FAILED, "Cannot find encrypted 'read page0' command!"); + return PM3_ESOFT; + } + case -4: { + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(FAILED, "Partial data extraction!"); + continue; + } + } + + } while (attempt); + + if (attempt == 0) { + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(WARNING, "timeout while waiting for reply."); + return PM3_ESOFT; + } + + t1 = msclock() - t1; + PrintAndLogEx(SUCCESS, "\ntime " _YELLOW_("%.0f") " seconds\n", (float)t1 / 1000.0); + + goto out; + } else { PrintAndLogEx(WARNING, "Sorry, not yet implemented"); return PM3_ENOTIMPL; } - uint16_t cmd = CMD_LF_HITAG_READER; - clearCommandBuffer(); - SendCommandMIX(cmd, htf, 0, 0, &htd, sizeof(htd)); - PacketResponseNG resp; - if (WaitForResponseTimeout(CMD_ACK, &resp, 2000) == false) { + clearCommandBuffer(); + SendCommandNG(CMD_LF_HITAG_READER, (uint8_t *) &packet, sizeof(packet)); + + if (WaitForResponseTimeout(CMD_LF_HITAG_READER, &resp, 5000) == false) { PrintAndLogEx(WARNING, "timeout while waiting for reply."); return PM3_ETIMEOUT; } - if (resp.oldarg[0] == false) { + if (resp.status != PM3_SUCCESS) { PrintAndLogEx(DEBUG, "DEBUG: Error - hitag failed"); - return PM3_ESOFT; + return resp.status; } - uint8_t *data = resp.data.asBytes; + data = resp.data.asBytes; + +out: + // block3, 1 byte - uint32_t uid = bytes_to_num(data, HITAG_UID_SIZE); + uid = bytes_to_num(data, HITAG_UID_SIZE); + if (use_ht2) { print_hitag2_configuration(uid, data[HITAG_BLOCK_SIZE * 3]); print_hitag2_blocks(data, HITAG2_MAX_BYTE_SIZE); @@ -1384,25 +1802,546 @@ static int CmdLFHitagSniff(const char *Cmd) { return PM3_SUCCESS; } +/* +static int CmdLFHitag2PWMDemod(const char *Cmd) { + + CLIParserContext *ctx; + CLIParserInit(&ctx, "lf hitag pwmdemod", + "Demodulate the data in the GraphBuffer and output binary\n", + "lf hitag pwmdemod" + "lf hitag pwmdemod -t 65 --> specify first wave index\n" + ); + + void *argtable[] = { + arg_param_begin, + arg_int0("t", "start", "", "first wave index"), + arg_int0(NULL, "zero", "", "Zero pulse length"), + arg_int0(NULL, "one", "", "One pulse length"), + arg_param_end + }; + + CLIExecWithReturn(ctx, Cmd, argtable, true); + uint32_t start_idx = (uint32_t)arg_get_int_def(ctx, 1, 0); + uint8_t fclow = (uint8_t)arg_get_int_def(ctx, 2, 20); + uint8_t fchigh = (uint8_t)arg_get_int_def(ctx, 3, 29); + CLIParserFree(ctx); + + uint8_t *bits = calloc(MAX_GRAPH_TRACE_LEN, sizeof(uint8_t)); + if (bits == NULL) { + PrintAndLogEx(INFO, "failed to allocate memory"); + return PM3_EMALLOC; + } + + size_t size = getFromGraphBuffer(bits); + + PrintAndLogEx(DEBUG, "DEBUG: (Hitag2PWM) #samples from graphbuff... %zu", size); + + if (size < 255) { + PrintAndLogEx(INFO, "too few samples in buffer"); + free(bits); + return PM3_ESOFT; + } + + // TODO autodetect + size = HitagPWMDemod(bits, size, &fchigh, &fclow, &start_idx, g_DemodBitRangeBuffer); + if (size == 0) { + PrintAndLogEx(FAILED, "No wave detected"); + free(bits); + return PM3_ESOFT; + } + + PrintAndLogEx(DEBUG, "DEBUG: start_idx... %u size... %zu", start_idx, size); + + setDemodBuffBitRange(bits, size, 0, g_DemodBitRangeBuffer); + setClockGrid(32, start_idx); + + uint32_t total = 0; + for (size_t i = 0; i < size; i++) { + total += g_DemodBitRangeBuffer[i]; + PrintAndLogEx(DEBUG, "%d", g_DemodBitRangeBuffer[i]); + } + PrintAndLogEx(DEBUG, "Total... %d", total); + + PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(INFO, "--- " _CYAN_("HITAG/PWM") " ---------------------------"); + printDemodBuff(0, false, false, false); + printDemodBuff(0, false, false, true); + free(bits); + return PM3_SUCCESS; +} +*/ + +static int CmdLFHitag2Chk(const char *Cmd) { + + CLIParserContext *ctx; + CLIParserInit(&ctx, "lf hitag chk", + "Run dictionary key or password recovery against Hitag card.", + "lf hitag chk\n -> checks for both pwd / crypto keys" + "lf hitag chk --crypto -> use def dictionary\n" + "lf hitag chk --pwd -f my.dic -> pwd mode, custom dictionary" + ); + + void *argtable[] = { + arg_param_begin, + arg_str0("f", "file", "", "specify dictionary filename"), + arg_lit0(NULL, "pwd", "password mode"), + arg_lit0(NULL, "crypto", "crypto mode"), + arg_param_end + }; + + CLIExecWithReturn(ctx, Cmd, argtable, true); + int fnlen = 0; + char filename[FILE_PATH_SIZE] = {0}; + CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen); + + bool use_pwd = arg_get_lit(ctx, 2); + bool use_crypto = arg_get_lit(ctx, 3); + CLIParserFree(ctx); + + if (use_pwd + use_crypto > 1) { + PrintAndLogEx(WARNING, "Only specify one mode"); + return PM3_EINVARG; + } + + // no filename -> use default = ht2_default.dic + if (fnlen == 0) { + snprintf(filename, sizeof(filename), HITAG_DICTIONARY); + } + + uint8_t keylen = 4; + if (use_crypto) { + keylen = 6; + } + + uint64_t t1 = msclock(); + + // just loop twice at max. Starting with 4 or 6. + for (; keylen < 7; keylen += 2) { + // load keys + uint8_t *keys = NULL; + uint32_t key_count = 0; + int res = loadFileDICTIONARY_safe(filename, (void **)&keys, keylen, &key_count); + if (res != PM3_SUCCESS || key_count == 0 || keys == NULL) { + PrintAndLogEx(WARNING, "no keys found in file"); + if (keys != NULL) { + free(keys); + } + return res; + } + + // Main loop + uint32_t found_idx = 0; + int status = ht2_check_dictionary(key_count, keys, keylen, &found_idx); + + if (status == PM3_SUCCESS) { + + PrintAndLogEx(NORMAL, ""); + if (keylen == 6) { + PrintAndLogEx(SUCCESS, "found valid key [ " _GREEN_("%s") " ]", sprint_hex_inrow(keys + (found_idx * keylen), keylen)); + } else { + PrintAndLogEx(SUCCESS, "found valid password [ " _GREEN_("%s") " ]", sprint_hex_inrow(keys + (found_idx * keylen), keylen)); + } + free(keys); + break; + } + free(keys); + } + + t1 = msclock() - t1; + PrintAndLogEx(SUCCESS, "\ntime in check " _YELLOW_("%.0f") " seconds\n", (float)t1 / 1000.0); + return PM3_SUCCESS; +} + +static int CmdLFHitag2Lookup(const char *Cmd) { + + CLIParserContext *ctx; + CLIParserInit(&ctx, "lf hitag lookup", + "This command take sniffed trace data and try to recovery a Hitag2 crypto key.\n" + " You can either\n" + " - verify that NR/AR matches a known crypto key\n" + " - verify if NR/AR matches a known 6 byte crypto key in a dictionary", + "lf hitag lookup --uid 11223344 --nr 73AA5A62 --ar EAB8529C -k 010203040506 -> check key\n" + "lf hitag lookup --uid 11223344 --nr 73AA5A62 --ar EAB8529C -> use def dictionary\n" + "lf hitag lookup --uid 11223344 --nr 73AA5A62 --ar EAB8529C -f my.dic -> use custom dictionary\n" + "lf hitag lookup --uid 11223344 --nrar 73AA5A62EAB8529C" + ); + + void *argtable[] = { + arg_param_begin, + arg_str0("f", "file", "", "specify dictionary filename"), + arg_str0("k", "key", "", "specify known cryptokey as 6 bytes"), + arg_str1("u", "uid", "", "specify UID as 4 hex bytes"), + arg_str0(NULL, "nr", "", "specify nonce as 4 hex bytes"), + arg_str0(NULL, "ar", "", "specify answer as 4 hex bytes"), + arg_str0(NULL, "nrar", "", "specify nonce / answer as 8 hex bytes"), + arg_param_end + }; + + CLIExecWithReturn(ctx, Cmd, argtable, false); + int fnlen = 0; + char filename[FILE_PATH_SIZE] = {0}; + CLIParamStrToBuf(arg_get_str(ctx, 1), (uint8_t *)filename, FILE_PATH_SIZE, &fnlen); + + int inkeylen = 0; + uint8_t inkey[6] = {0}; + CLIGetHexWithReturn(ctx, 2, inkey, &inkeylen); + + int ulen = 0; + uint8_t uidarr[4] = {0}; + CLIGetHexWithReturn(ctx, 3, uidarr, &ulen); + + int nlen = 0; + uint8_t narr[4] = {0}; + CLIGetHexWithReturn(ctx, 4, narr, &nlen); + + int alen = 0; + uint8_t aarr[4] = {0}; + CLIGetHexWithReturn(ctx, 5, aarr, &alen); + + int nalen = 0; + uint8_t nrar[8] = {0}; + CLIGetHexWithReturn(ctx, 6, nrar, &nalen); + + CLIParserFree(ctx); + + // sanity checks + if (inkeylen && inkeylen != 6) { + PrintAndLogEx(INFO, "Key wrong length. expected 6, got %i", inkeylen); + return PM3_EINVARG; + } + + if (ulen && ulen != 4) { + PrintAndLogEx(INFO, "UID wrong length. expected 4, got %i", ulen); + return PM3_EINVARG; + } + + if (nlen && nlen != 4) { + PrintAndLogEx(INFO, "Nr wrong length. expected 4, got %i", nlen); + return PM3_EINVARG; + } + + if (alen && alen != 4) { + PrintAndLogEx(INFO, "Ar wrong length. expected 4, got %i", alen); + return PM3_EINVARG; + } + + if (nalen && nalen != 8) { + PrintAndLogEx(INFO, "NrAr wrong length. expected 8, got %i", nalen); + return PM3_EINVARG; + } + + // Iceman note: + // - key, uid and Nr1 is alway dentoed as LSB/LE order + // - Ar1 is NOT. It is in BE/MSB everywhere. + // - At1 is NOT. It is in BE/MSB everywhere. + // - crypto stream generated is in BE/MSB order in Pm3 code. + // - crypto state is in ? + // - lfsr state is in ? + // + // Different implementations handles internally the state either in MSB or LSB. + // Something to keep an eye for when looking at code. + // + // Termology: + // cs / hstate.shiftregister / crypto state = same + // lsfr = some implementations mixes cs and lsfr into one and only use the state. Some differentiate between them. + // usually the key recovery functions under /tools/hitag2crack + // IV / Nonce Reader 1 / Nr1 = same (clear text), always 00 00 00 00 in PM3 code when acting as reader. + // Answer Reader 1 / Ar1 = encrypted and BE/MSB, +32, the clear text is always FF FF FF FF. + // Answer Tag 1 / At1 = encrypted and BE/MSB, +32, + + /* + When initializer the crypto engine + + 1. UID: 11223344 + 2. KEY: FFFF143624FF + 3. NONCE / IV: 00 00 00 00 + 3. NONCE / IV: 3B 6F 08 4D + + now you have a CS / Shiftregister / state = crypto stream? + + Ar1 - first encrypted crypto stream ^ 0xFFFFFFFF + 4. Ar1: 96 7A 6F 2A ^ FF FF FF FF == 69 85 90 D5 + + */ + rev_msb_array(inkey, sizeof(inkey)); + rev_msb_array(uidarr, sizeof(uidarr)); + rev_msb_array(narr, sizeof(narr)); + rev_msb_array(nrar, 4); + + + // Little Endian + uint64_t knownkey = MemLeToUint6byte(inkey); + uint32_t uid = MemLeToUint4byte(uidarr); + + uint32_t nr; + // Big Endian + uint32_t ar; + + if (nlen && alen) { + nr = MemLeToUint4byte(narr); + ar = MemBeToUint4byte(aarr); + } else if (nalen) { + nr = MemLeToUint4byte(nrar); + ar = MemBeToUint4byte(nrar + 4); + } else { + PrintAndLogEx(INFO, "No nr or ar was supplied"); + return PM3_EINVARG; + } + + uint32_t iv = nr; + + + if (inkeylen) { + + PrintAndLogEx(DEBUG, "UID... %08" PRIx32, uid); + PrintAndLogEx(DEBUG, "IV.... %08" PRIx32, iv); + PrintAndLogEx(DEBUG, "Key... %012" PRIx64, knownkey); + + // initialize state + hitag_state_t hstate; + ht2_hitag2_init_ex(&hstate, knownkey, uid, iv); + + // get 32 bits of crypto stream. + uint32_t cbits = ht2_hitag2_nstep(&hstate, 32); + bool isok = (ar == (cbits ^ 0xFFFFFFFF)); + + PrintAndLogEx(DEBUG, "state.shiftreg...... %012" PRIx64, hstate.shiftreg); + PrintAndLogEx(DEBUG, "state.lfsr.......... %012" PRIx64, hstate.lfsr); + PrintAndLogEx(DEBUG, "c bits.............. %08x", cbits); + PrintAndLogEx(DEBUG, "c-bits ^ FFFFFFFF... %08x", cbits ^ 0xFFFFFFFF); + PrintAndLogEx(DEBUG, "Ar.................. %08" PRIx32 " ( %s )", ar, (isok) ? _GREEN_("ok") : _RED_("fail")); + + PrintAndLogEx(INFO, "Nr/Ar match key ( %s )", (isok) ? _GREEN_("ok") : _RED_("fail")); + PrintAndLogEx(NORMAL, ""); + return PM3_SUCCESS; + } + + if (fnlen == 0) { + snprintf(filename, sizeof(filename), HITAG_DICTIONARY); + } + + // load keys + uint8_t *keys = NULL; + uint32_t key_count = 0; + int res = loadFileDICTIONARY_safe(filename, (void **)&keys, HITAG_CRYPTOKEY_SIZE, &key_count); + if (res != PM3_SUCCESS || key_count == 0 || keys == NULL) { + PrintAndLogEx(WARNING, "no keys found in file"); + if (keys != NULL) { + free(keys); + } + return res; + } + + bool found = false; + for (uint32_t i = 0; i < key_count; i++) { + + uint8_t *pkey = keys + (i * HITAG_CRYPTOKEY_SIZE); + uint64_t mykey = MemLeToUint6byte(pkey); + mykey = REV64(mykey); + + hitag_state_t hs2; + ht2_hitag2_init_ex(&hs2, mykey, uid, iv); + + uint32_t tbits = ht2_hitag2_nstep(&hs2, 32); + if ((ar ^ tbits) == 0xFFFFFFFF) { + PrintAndLogEx(SUCCESS, "Found valid key [ " _GREEN_("%s")" ]", sprint_hex_inrow(pkey, HITAG_CRYPTOKEY_SIZE)); + found = true; + break; + } + + if (g_debugMode) { + PrintAndLogEx(DEBUG, " tbits... %08" PRIx32 " Known ar... %08" PRIx32, tbits, ar); + PrintAndLogEx(DEBUG, " 0xFFFFFFFF ^ tbits... %08" PRIx32, tbits ^ 0xFFFFFFFF); + PrintAndLogEx(DEBUG, " 0xFFFFFFFF ^ ar...... %08" PRIx32, ar ^ 0xFFFFFFFF); + PrintAndLogEx(DEBUG, " tbits ^ ar........... %08" PRIx32 " ( 0xFFFFFFFF )", ar ^ tbits); + } + } + + free(keys); + + if (found == false) { + PrintAndLogEx(WARNING, "check failed"); + } + + PrintAndLogEx(NORMAL, ""); + return PM3_SUCCESS; +} + +/* Test code + + Test data and below information about it comes from + http://www.mikrocontroller.net/attachment/102194/hitag2.c + Written by "I.C. Wiener 2006-2007" + + "MIKRON" = O N M I K R + Key = 4F 4E 4D 49 4B 52 - Secret 48-bit key + Serial = 49 43 57 69 - Serial number of the tag, transmitted in clear + Random = 65 6E 45 72 - Random IV, transmitted in clear + ~28~DC~80~31 = D7 23 7F CE - Authenticator value = inverted first 4 bytes of the keystream + + The code below must print out "D7 23 7F CE 8C D0 37 A9 57 49 C1 E6 48 00 8A B6". + The inverse of the first 4 bytes is sent to the tag to authenticate. + The rest is encrypted by XORing it with the subsequent keystream. +*/ +static uint64_t hitag2_benchtest_gen32(void) { + const uint64_t key = 0x4ad292b272f2; + const uint32_t serial = 0x96eac292; + const uint32_t initvec = 0x4ea276a6; + hitag_state_t state; + + // init crypto + ht2_hitag2_init_ex(&state, key, serial, initvec); + + // benchmark: generation of 32 bit stream (excludes initialisation) + uint64_t t1 = usclock(); + + (void) ht2_hitag2_nstep(&state, 32); + + t1 = usclock() - t1; + return t1; +} + +static uint64_t hitag2_benchtest(uint32_t count) { + + const uint64_t key = 0x4ad292b272f2; + const uint32_t serial = 0x96eac292; + const uint32_t initvec = 0x4ea276a6; + + hitag_state_t state; + + // start timer + uint64_t t1 = usclock(); + + // benchmark: initialise crypto & generate 32 bit authentication + // adding i stops gcc optimizer moving init function call out of loop + for (uint32_t i = 0; i < count; i++) { + ht2_hitag2_init_ex(&state, key, serial, initvec + i); + (void) ht2_hitag2_nstep(&state, 32); + } + + t1 = usclock() - t1; + return t1; +} + +static uint64_t hitag2_verify_crypto_test(void) { + + uint8_t expected[16] = { 0xD7, 0x23, 0x7F, 0xCE, 0x8C, 0xD0, 0x37, 0xA9, 0x57, 0x49, 0xC1, 0xE6, 0x48, 0x00, 0x8A, 0xB6 }; + // key = 0x4ad292b272f2 after each byte has its bit order reversed + // uid = 0x96eac292 ditto + // initvec = 0x4ea276a6 ditto + const uint64_t key = REV64(0x524B494D4E4FUL); + const uint32_t uid = REV32(0x69574349); + const uint32_t iv = REV32(0x72456E65); + + PrintAndLogEx(DEBUG, "UID... %08" PRIx32, uid); + PrintAndLogEx(DEBUG, "IV.... %08" PRIx32, iv); + PrintAndLogEx(DEBUG, "Key... %012" PRIx64, key); + + // initialise + hitag_state_t state; + ht2_hitag2_init_ex(&state, key, uid, iv); + PrintAndLogEx(DEBUG, "hs shiftreg... %012" PRIx64, state.shiftreg); + + for (uint32_t i = 0; i < 16; i++) { + // get 8 bits of keystream + uint8_t x = (uint8_t) ht2_hitag2_nstep(&state, 8); + uint8_t y = expected[i]; + + PrintAndLogEx(DEBUG, "%02X (%02X)", x, y); + if (x != y) { + return 0; + } + } + return 1; +} + +static uint64_t hitag2_verify_crypto_test_round(void) { + + uint8_t expected[16] = { 0xD7, 0x23, 0x7F, 0xCE, 0x8C, 0xD0, 0x37, 0xA9, 0x57, 0x49, 0xC1, 0xE6, 0x48, 0x00, 0x8A, 0xB6 }; + const uint64_t key = REV64(0x524B494D4E4FUL); + const uint32_t uid = REV32(0x69574349); + const uint32_t iv = REV32(0x72456E65); + + PrintAndLogEx(DEBUG, "UID... %08" PRIx32, uid); + PrintAndLogEx(DEBUG, "IV.... %08" PRIx32, iv); + PrintAndLogEx(DEBUG, "Key... %012" PRIx64, key); + + // initialise + uint64_t cs = ht2_hitag2_init(key, uid, iv); + PrintAndLogEx(DEBUG, "hs shiftreg... %012" PRIx64, cs); + + for (uint32_t i = 0; i < 16; i++) { + // get 8 bits of keystream + uint8_t x = (uint8_t) ht2_hitag2_byte(&cs); + uint8_t y = expected[i]; + + PrintAndLogEx(DEBUG, "%02X (%02X)", x, y); + if (x != y) { + return 0; + } + } + return 1; +} + +static int CmdLFHitag2Selftest(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "lf hitag selftest", + "Perform selftest of Hitag crypto engine", + "lf hitag selftest\n" + ); + + void *argtable[] = { + arg_param_begin, + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + CLIParserFree(ctx); + + PrintAndLogEx(INFO, "======== " _CYAN_("Hitag2 crypto test") " ============================"); + uint64_t test = hitag2_verify_crypto_test(); + PrintAndLogEx(INFO, "Crypto self test ( %s )", test ? _GREEN_("ok") : _RED_("fail")); + + test |= hitag2_verify_crypto_test_round(); + PrintAndLogEx(INFO, "Crypto self test ROUND ( %s )", test ? _GREEN_("ok") : _RED_("fail")); + + test |= hitag2_benchtest(1); + PrintAndLogEx(INFO, "Hitag2 crypto, init + gen 32 bits ( us %" PRIu64 " )", test); + + test |= hitag2_benchtest_gen32(); + PrintAndLogEx(INFO, "Hitag2 crypto, gen new 32 bits only ( us: %" PRIu64 " )", test); + + test |= hitag2_benchtest(1000); + PrintAndLogEx(INFO, "Hitag2 crypto, init + gen 32 bits, x1000 ( us: %" PRIu64 " )", test); + + PrintAndLogEx(INFO, "--------------------------------------------------------"); + PrintAndLogEx(SUCCESS, "Tests ( %s )", (test) ? _GREEN_("ok") : _RED_("fail")); + PrintAndLogEx(NORMAL, ""); + return PM3_SUCCESS; +} static command_t CommandTable[] = { - {"-----------", CmdHelp, IfPm3Hitag, "------------------------ " _CYAN_("General") " ------------------------"}, {"help", CmdHelp, AlwaysAvailable, "This help"}, {"list", CmdLFHitagList, AlwaysAvailable, "List Hitag trace history"}, - {"-----------", CmdHelp, IfPm3Hitag, "----------------------- " _CYAN_("Operations") " -----------------------"}, + {"-----------", CmdHelp, IfPm3Hitag, "------------------------ " _CYAN_("General") " ------------------------"}, {"info", CmdLFHitagInfo, IfPm3Hitag, "Hitag 2 tag information"}, + {"selftest", CmdLFHitag2Selftest, AlwaysAvailable, "Perform self test"}, + {"-----------", CmdHelp, IfPm3Hitag, "----------------------- " _CYAN_("Operations") " -----------------------"}, +// {"demod", CmdLFHitag2PWMDemod, IfPm3Hitag, "PWM Hitag 2 reader message demodulation"}, {"dump", CmdLFHitag2Dump, IfPm3Hitag, "Dump Hitag 2 tag"}, {"read", CmdLFHitagReader, IfPm3Hitag, "Read Hitag memory"}, + {"sniff", CmdLFHitagSniff, IfPm3Hitag, "Eavesdrop Hitag communication"}, {"view", CmdLFHitagView, AlwaysAvailable, "Display content from tag dump file"}, {"wrbl", CmdLFHitagWriter, IfPm3Hitag, "Write a block (page) in Hitag memory"}, - {"sniff", CmdLFHitagSniff, IfPm3Hitag, "Eavesdrop Hitag communication"}, - {"cc", CmdLFHitagSCheckChallenges, IfPm3Hitag, "Hitag S: test all provided challenges"}, - {"ta", CmdLFHitag2CheckChallenges, IfPm3Hitag, "Hitag 2: test all recorded authentications"}, {"-----------", CmdHelp, IfPm3Hitag, "----------------------- " _CYAN_("Simulation") " -----------------------"}, {"eload", CmdLFHitagEload, IfPm3Hitag, "Upload file into emulator memory"}, // {"esave", CmdLFHitagESave, IfPm3Hitag, "Save emulator memory to file"}, {"eview", CmdLFHitagEview, IfPm3Hitag, "View emulator memory"}, {"sim", CmdLFHitagSim, IfPm3Hitag, "Simulate Hitag transponder"}, + {"-----------", CmdHelp, IfPm3Hitag, "----------------------- " _CYAN_("Recovery") " -----------------------"}, + {"cc", CmdLFHitagSCheckChallenges, IfPm3Hitag, "Hitag S: test all provided challenges"}, + {"chk", CmdLFHitag2Chk, IfPm3Hitag, "Check keys"}, + {"lookup", CmdLFHitag2Lookup, AlwaysAvailable, "Uses authentication trace to check for key in dictionary file"}, + {"ta", CmdLFHitag2CheckChallenges, IfPm3Hitag, "Hitag 2: test all recorded authentications"}, { NULL, NULL, 0, NULL } }; diff --git a/client/src/cmdlfhitag.h b/client/src/cmdlfhitag.h index c3cefc10d..049df8aa9 100644 --- a/client/src/cmdlfhitag.h +++ b/client/src/cmdlfhitag.h @@ -22,6 +22,7 @@ #include "common.h" +#define HITAG_NRAR_SIZE 8 #define HITAG_CRYPTOKEY_SIZE 6 #define HITAG_PASSWORD_SIZE 4 #define HITAG_UID_SIZE 4 @@ -37,16 +38,18 @@ #define HITAG2_CONFIG_BLOCK 3 #define HITAG2_CONFIG_OFFSET (HITAG_BLOCK_SIZE * HITAG2_CONFIG_BLOCK) +#define HITAG_DICTIONARY "ht2_default" int CmdLFHitag(const char *Cmd); int readHitagUid(void); void annotateHitag1(char *exp, size_t size, const uint8_t *cmd, uint8_t cmdsize, bool is_response); -void annotateHitag2(char *exp, size_t size, const uint8_t *cmd, uint8_t cmdsize, uint8_t bits, bool is_response); +void annotateHitag2(char *exp, size_t size, const uint8_t *cmd, uint8_t cmdsize, uint8_t bits, bool is_response, const uint64_t *keys, uint32_t keycount, bool isdecrypted); void annotateHitagS(char *exp, size_t size, const uint8_t *cmd, uint8_t cmdsize, bool is_response); void annotateHitag2_init(void); - +bool hitag2_get_plain(uint8_t *plain, uint8_t *plen); +void hitag2_annotate_plain(char *exp, size_t size, const uint8_t *cmd, uint8_t cmdsize, uint8_t bits); uint8_t hitag1_CRC_check(uint8_t *d, uint32_t nbit); #endif diff --git a/client/src/cmdtrace.c b/client/src/cmdtrace.c index 8e421a7c7..66e26e27f 100644 --- a/client/src/cmdtrace.c +++ b/client/src/cmdtrace.c @@ -501,7 +501,7 @@ static uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *tr uint32_t end_of_transmission_timestamp = 0; uint8_t topaz_reader_command[9]; - char explanation[40] = {0}; + char explanation[60] = {0}; tracelog_hdr_t *first_hdr = (tracelog_hdr_t *)(trace); tracelog_hdr_t *hdr = (tracelog_hdr_t *)(trace + tracepos); @@ -774,10 +774,9 @@ static uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *tr end_of_transmission_timestamp = hdr->timestamp + duration; - if (prev_eot) + if (prev_eot) { *prev_eot = end_of_transmission_timestamp; - - + } // Always annotate these protocols both reader/tag messages switch (protocol) { @@ -793,7 +792,7 @@ static uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *tr annotateHitag1(explanation, sizeof(explanation), frame, data_len, hdr->isResponse); break; case PROTO_HITAG2: - annotateHitag2(explanation, sizeof(explanation), frame, data_len, parityBytes[0], hdr->isResponse); + annotateHitag2(explanation, sizeof(explanation), frame, data_len, parityBytes[0], hdr->isResponse, mfDicKeys, mfDicKeysCount, false); break; case PROTO_HITAGS: annotateHitagS(explanation, sizeof(explanation), frame, data_len, hdr->isResponse); @@ -979,6 +978,71 @@ static uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *tr } } + if (protocol == PROTO_HITAG2) { + + uint8_t ht2plain[9] = {0}; + uint8_t n = 0; + if (hitag2_get_plain(ht2plain, &n)) { + + memset(explanation, 0x00, sizeof(explanation)); + + // handle partial bytes. The parity array[0] is used to store number of left over bits from NBYTES + // This part prints the number of bits in the trace entry for hitag. + uint8_t nbits = parityBytes[0]; + + annotateHitag2(explanation, sizeof(explanation), ht2plain, n, nbits, hdr->isResponse, NULL, 0, true); + + // iceman: colorise crc bytes here will need a refactor of code from above. + for (int j = 0; j < n && (j / TRACE_MAX_HEX_BYTES) < TRACE_MAX_HEX_BYTES; j++) { + + + if (j == 0) { + + // only apply this to lesser than one byte + if (n == 1) { + + if (nbits == 5) { + snprintf(line[0], 120, "%2u: %02X ", nbits, ht2plain[0] >> (8 - nbits)); + } else { + snprintf(line[0], 120, "%2u: %02X ", nbits, ht2plain[0] >> (8 - nbits)); + } + + } else { + + if (nbits == 0) { + snprintf(line[0], 120, "%2u: %02X ", (n * 8), ht2plain[0]); + } else { + snprintf(line[0], 120, "%2u: %02X ", ((n - 1) * 8) + nbits, ht2plain[0]); + } + } + offset = 4; + + } else { + snprintf(line[j / 18] + ((j % 18) * 4) + offset, 120, "%02X ", ht2plain[j]); + } + } + + num_lines = MIN((n - 1) / TRACE_MAX_HEX_BYTES + 1, TRACE_MAX_HEX_BYTES); + + for (int j = 0; j < num_lines ; j++) { + if (hdr->isResponse) { + PrintAndLogEx(NORMAL, " | | * |%-*s | %-4s| %s", + str_padder, + line[j], + " ", + explanation); + } else { + PrintAndLogEx(NORMAL, " | | * |" _YELLOW_("%-*s")" | " _YELLOW_("%s") "| " _YELLOW_("%s"), + str_padder, + line[j], + " ", + explanation); + } + + } + } + } + if (is_last_record(tracepos, traceLen)) { return traceLen; } @@ -1436,6 +1500,30 @@ int CmdTraceList(const char *Cmd) { } } + if (protocol == PROTO_HITAG2) { + + if (strlen(dictionary) == 0) { + snprintf(dictionary, sizeof(dictionary), HITAG_DICTIONARY); + } + + // load keys + uint8_t *keyBlock = NULL; + int res = loadFileDICTIONARY_safe(dictionary, (void **) &keyBlock, HITAG_CRYPTOKEY_SIZE, &dicKeysCount); + if (res != PM3_SUCCESS || dicKeysCount == 0 || keyBlock == NULL) { + PrintAndLogEx(FAILED, "An error occurred while loading the dictionary!"); + } else { + dicKeys = calloc(dicKeysCount, sizeof(uint64_t)); + for (int i = 0; i < dicKeysCount; i++) { + uint64_t key = bytes_to_num(keyBlock + i * HITAG_CRYPTOKEY_SIZE, HITAG_CRYPTOKEY_SIZE); + memcpy((uint8_t *) &dicKeys[i], &key, sizeof(uint64_t)); + } + dictionaryLoad = true; + } + if (keyBlock != NULL) { + free(keyBlock); + } + } + PrintAndLogEx(NORMAL, ""); if (use_relative) { PrintAndLogEx(NORMAL, " Gap | Duration | Src | Data (! denotes parity error, ' denotes short bytes) | CRC | Annotation"); @@ -1463,16 +1551,19 @@ int CmdTraceList(const char *Cmd) { while (tracepos < gs_traceLen) { tracepos = printTraceLine(tracepos, gs_traceLen, gs_trace, protocol, show_wait_cycles, mark_crc, prev_EOT, use_us, dicKeys, dicKeysCount); - if (kbd_enter_pressed()) + if (kbd_enter_pressed()) { break; + } } - if (dictionaryLoad) + if (dictionaryLoad) { free((void *) dicKeys); + } } - if (show_hex) + if (show_hex) { PrintAndLogEx(HINT, "syntax to use: " _YELLOW_("`text2pcap -t \"%%S.\" -l 264 -n `")); + } return PM3_SUCCESS; } diff --git a/client/src/crypto/libpcrypto.c b/client/src/crypto/libpcrypto.c index 3634e9e4d..02627a872 100644 --- a/client/src/crypto/libpcrypto.c +++ b/client/src/crypto/libpcrypto.c @@ -127,34 +127,38 @@ void des3_decrypt(void *out, const void *in, const void *key, uint8_t keycount) // NIST Special Publication 800-38A — Recommendation for block cipher modes of operation: methods and techniques, 2001. int aes_encode(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *output, int length) { uint8_t iiv[16] = {0}; - if (iv) + if (iv) { memcpy(iiv, iv, 16); + } mbedtls_aes_context aes; mbedtls_aes_init(&aes); - if (mbedtls_aes_setkey_enc(&aes, key, 128)) + if (mbedtls_aes_setkey_enc(&aes, key, 128)) { return 1; - if (mbedtls_aes_crypt_cbc(&aes, MBEDTLS_AES_ENCRYPT, length, iiv, input, output)) + } + if (mbedtls_aes_crypt_cbc(&aes, MBEDTLS_AES_ENCRYPT, length, iiv, input, output)) { return 2; + } mbedtls_aes_free(&aes); - - return 0; + return PM3_SUCCESS; } int aes_decode(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *output, int length) { uint8_t iiv[16] = {0}; - if (iv) + if (iv) { memcpy(iiv, iv, 16); + } mbedtls_aes_context aes; mbedtls_aes_init(&aes); - if (mbedtls_aes_setkey_dec(&aes, key, 128)) + if (mbedtls_aes_setkey_dec(&aes, key, 128)) { return 1; - if (mbedtls_aes_crypt_cbc(&aes, MBEDTLS_AES_DECRYPT, length, iiv, input, output)) + } + if (mbedtls_aes_crypt_cbc(&aes, MBEDTLS_AES_DECRYPT, length, iiv, input, output)) { return 2; + } mbedtls_aes_free(&aes); - - return 0; + return PM3_SUCCESS; } // NIST Special Publication 800-38B — Recommendation for block cipher modes of operation: The CMAC mode for authentication. @@ -171,13 +175,14 @@ int aes_cmac8(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *mac, int lengt memset(mac, 0x00, 8); int res = aes_cmac(iv, key, input, cmac_tmp, length); - if (res) + if (res) { return res; + } - for (int i = 0; i < 8; i++) + for (int i = 0; i < 8; i++) { mac[i] = cmac_tmp[i * 2 + 1]; - - return 0; + } + return PM3_SUCCESS; } static uint8_t fixed_rand_value[250] = {0}; @@ -188,21 +193,23 @@ static int fixed_rand(void *rng_state, unsigned char *output, size_t len) { memset(output, 0x00, len); } - return 0; + return PM3_SUCCESS; } int sha1hash(uint8_t *input, int length, uint8_t *hash) { - if (!hash || !input) + if (!hash || !input) { return 1; + } mbedtls_sha1(input, length, hash); - return 0; + return PM3_SUCCESS; } int sha256hash(uint8_t *input, int length, uint8_t *hash) { - if (!hash || !input) + if (!hash || !input) { return 1; + } mbedtls_sha256_context sctx; mbedtls_sha256_init(&sctx); @@ -211,12 +218,13 @@ int sha256hash(uint8_t *input, int length, uint8_t *hash) { mbedtls_sha256_finish(&sctx, hash); mbedtls_sha256_free(&sctx); - return 0; + return PM3_SUCCESS; } int sha512hash(uint8_t *input, int length, uint8_t *hash) { - if (!hash || !input) + if (!hash || !input) { return 1; + } mbedtls_sha512_context sctx; mbedtls_sha512_init(&sctx); @@ -225,33 +233,35 @@ int sha512hash(uint8_t *input, int length, uint8_t *hash) { mbedtls_sha512_finish(&sctx, hash); mbedtls_sha512_free(&sctx); - return 0; + return PM3_SUCCESS; } static int ecdsa_init_str(mbedtls_ecdsa_context *ctx, mbedtls_ecp_group_id curveid, const char *key_d, const char *key_x, const char *key_y) { - if (!ctx) + if (!ctx) { return 1; - - int res; + } mbedtls_ecdsa_init(ctx); - res = mbedtls_ecp_group_load(&ctx->grp, curveid); - if (res) + int res = mbedtls_ecp_group_load(&ctx->grp, curveid); + if (res) { return res; + } if (key_d) { res = mbedtls_mpi_read_string(&ctx->d, 16, key_d); - if (res) + if (res) { return res; + } } if (key_x && key_y) { res = mbedtls_ecp_point_read_string(&ctx->Q, 16, key_x, key_y); - if (res) + if (res) { return res; + } } - return 0; + return PM3_SUCCESS; } static int ecdsa_init(mbedtls_ecdsa_context *ctx, mbedtls_ecp_group_id curveid, uint8_t *key_d, uint8_t *key_xy) { @@ -278,7 +288,7 @@ static int ecdsa_init(mbedtls_ecdsa_context *ctx, mbedtls_ecp_group_id curveid, return res; } - return 0; + return PM3_SUCCESS; } int ecdsa_key_create(mbedtls_ecp_group_id curveid, uint8_t *key_d, uint8_t *key_xy) { @@ -519,8 +529,9 @@ int ecdsa_nist_test(bool verbose) { size_t siglen = 0; // NIST ecdsa test - if (verbose) - PrintAndLogEx(INFO, " ECDSA NIST test: " NOLF); + if (verbose) { + PrintAndLogEx(INFO, "ECDSA NIST test " NOLF); + } // make signature res = ecdsa_signature_create_test(curveid, T_PRIVATE_KEY, T_Q_X, T_Q_Y, T_K, input, length, signature, &siglen); // PrintAndLogEx(INFO, "res: %x signature[%x]: %s", (res < 0)? -res : res, siglen, sprint_hex(signature, siglen)); @@ -540,15 +551,16 @@ int ecdsa_nist_test(bool verbose) { uint8_t sval_s[33] = {0}; param_gethex_to_eol(T_S, 0, sval_s, sizeof(sval_s), &slen); if (strncmp((char *)rval, (char *)rval_s, 32) || strncmp((char *)sval, (char *)sval_s, 32)) { - PrintAndLogEx(INFO, "R or S check error"); + PrintAndLogEx(NORMAL, "( " _RED_("R or S check error") " )"); res = 100; goto exit; } // verify signature res = ecdsa_signature_verify_keystr(curveid, T_Q_X, T_Q_Y, input, length, signature, siglen, true); - if (res) + if (res) { goto exit; + } // verify wrong signature input[0] ^= 0xFF; @@ -559,8 +571,8 @@ int ecdsa_nist_test(bool verbose) { } if (verbose) { - PrintAndLogEx(NORMAL, _GREEN_("passed")); - PrintAndLogEx(INFO, " ECDSA binary signature create/check test: " NOLF); + PrintAndLogEx(NORMAL, "( " _GREEN_("ok") " )"); + PrintAndLogEx(INFO, "ECDSA binary signature create/check test " NOLF); } // random ecdsa test @@ -587,12 +599,12 @@ int ecdsa_nist_test(bool verbose) { goto exit; if (verbose) - PrintAndLogEx(NORMAL, _GREEN_("passed\n")); + PrintAndLogEx(NORMAL, "( " _GREEN_("ok") " )"); return PM3_SUCCESS; exit: if (verbose) - PrintAndLogEx(NORMAL, _RED_("failed\n")); + PrintAndLogEx(NORMAL, "( " _RED_("fail") " )"); return res; } diff --git a/client/src/graph.c b/client/src/graph.c index 72640c730..e40118387 100644 --- a/client/src/graph.c +++ b/client/src/graph.c @@ -136,7 +136,7 @@ size_t getFromGraphBufferEx(uint8_t *dest, size_t maxLen) { } //TODO: In progress function to get chunks of data from the GB w/o modifying the GB -//Currently seems like it doesn't work correctly? +//Currently seems like it doesn't work correctly? size_t getGraphBufferChunk(uint8_t *dest, size_t start, size_t end) { if (dest == NULL) return 0; if (g_GraphTraceLen == 0) return 0; diff --git a/client/src/mifare/desfirecore.c b/client/src/mifare/desfirecore.c index 66511dc25..1376fce57 100644 --- a/client/src/mifare/desfirecore.c +++ b/client/src/mifare/desfirecore.c @@ -742,7 +742,7 @@ static int DesfireExchangeISONative(bool activate_field, DesfireContext_t *ctx, pos += buflen; if (enable_chaining == false) { if (sw == DESFIRE_GET_ISO_STATUS(MFDES_S_OPERATION_OK) || - sw == DESFIRE_GET_ISO_STATUS(MFDES_ADDITIONAL_FRAME)) { + sw == DESFIRE_GET_ISO_STATUS(MFDES_ADDITIONAL_FRAME)) { if (resplen) { *resplen = pos; diff --git a/client/src/mifare/desfiresecurechan.c b/client/src/mifare/desfiresecurechan.c index 9b8e3fecf..d35833b4d 100644 --- a/client/src/mifare/desfiresecurechan.c +++ b/client/src/mifare/desfiresecurechan.c @@ -626,13 +626,13 @@ static void DesfireSecureChannelDecodeEV1(DesfireContext_t *ctx, uint8_t *srcdat PrintAndLogEx(INFO, " calculated MAC: %s", sprint_hex(cmac, DesfireGetMACLength(ctx))); } else { - + if (GetAPDULogging()) { PrintAndLogEx(INFO, "Received MAC OK"); } } - } else if (ctx->commMode == DCMEncrypted || ctx->commMode == DCMEncryptedWithPadding) { + } else if (ctx->commMode == DCMEncrypted || ctx->commMode == DCMEncryptedWithPadding) { if (srcdatalen < desfire_get_key_block_length(ctx->keyType)) { memcpy(dstdata, srcdata, srcdatalen); diff --git a/client/src/pm3_luawrap.c b/client/src/pm3_luawrap.c index 66cdb71e5..b744305b6 100644 --- a/client/src/pm3_luawrap.c +++ b/client/src/pm3_luawrap.c @@ -140,7 +140,7 @@ # define SWIG_NULLPTR nullptr #else # define SWIG_NULLPTR NULL -#endif +#endif /* ----------------------------------------------------------------------------- * swigcompat.swg @@ -339,10 +339,10 @@ # define SWIG_CASTRANKMASK ((SWIG_CASTRANKLIMIT) -1) # define SWIG_CastRank(r) (r & SWIG_CASTRANKMASK) SWIGINTERNINLINE int SWIG_AddCast(int r) { - return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r; + return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r; } SWIGINTERNINLINE int SWIG_CheckState(int r) { - return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; + return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; } #else /* no cast-rank mode */ # define SWIG_AddCast(r) (r) @@ -361,32 +361,32 @@ typedef struct swig_type_info *(*swig_dycast_func)(void **); /* Structure to store information on one type */ typedef struct swig_type_info { - const char *name; /* mangled name of this type */ - const char *str; /* human readable name of this type */ - swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ - struct swig_cast_info *cast; /* linked list of types that can cast into this type */ - void *clientdata; /* language specific type data */ - int owndata; /* flag if the structure owns the clientdata */ + const char *name; /* mangled name of this type */ + const char *str; /* human readable name of this type */ + swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ + struct swig_cast_info *cast; /* linked list of types that can cast into this type */ + void *clientdata; /* language specific type data */ + int owndata; /* flag if the structure owns the clientdata */ } swig_type_info; /* Structure to store a type and conversion function used for casting */ typedef struct swig_cast_info { - swig_type_info *type; /* pointer to type that is equivalent to this type */ - swig_converter_func converter; /* function to cast the void pointers */ - struct swig_cast_info *next; /* pointer to next cast in linked list */ - struct swig_cast_info *prev; /* pointer to the previous cast */ + swig_type_info *type; /* pointer to type that is equivalent to this type */ + swig_converter_func converter; /* function to cast the void pointers */ + struct swig_cast_info *next; /* pointer to next cast in linked list */ + struct swig_cast_info *prev; /* pointer to the previous cast */ } swig_cast_info; /* Structure used to store module information * Each module generates one structure like this, and the runtime collects * all of these structures and stores them in a circularly linked list.*/ typedef struct swig_module_info { - swig_type_info **types; /* Array of pointers to swig_type_info structures that are in this module */ - size_t size; /* Number of types in this module */ - struct swig_module_info *next; /* Pointer to next element in circularly linked list */ - swig_type_info **type_initial; /* Array of initially generated type structures */ - swig_cast_info **cast_initial; /* Array of initially generated casting structures */ - void *clientdata; /* Language specific module data */ + swig_type_info **types; /* Array of pointers to swig_type_info structures that are in this module */ + size_t size; /* Number of types in this module */ + struct swig_module_info *next; /* Pointer to next element in circularly linked list */ + swig_type_info **type_initial; /* Array of initially generated type structures */ + swig_cast_info **cast_initial; /* Array of initially generated casting structures */ + void *clientdata; /* Language specific module data */ } swig_module_info; /* @@ -398,13 +398,13 @@ typedef struct swig_module_info { */ SWIGRUNTIME int SWIG_TypeNameComp(const char *f1, const char *l1, - const char *f2, const char *l2) { - for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) { - while ((*f1 == ' ') && (f1 != l1)) ++f1; - while ((*f2 == ' ') && (f2 != l2)) ++f2; - if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1; - } - return (int)((l1 - f1) - (l2 - f2)); + const char *f2, const char *l2) { + for (; (f1 != l1) && (f2 != l2); ++f1, ++f2) { + while ((*f1 == ' ') && (f1 != l1)) ++f1; + while ((*f2 == ' ') && (f2 != l2)) ++f2; + if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1; + } + return (int)((l1 - f1) - (l2 - f2)); } /* @@ -413,17 +413,17 @@ SWIG_TypeNameComp(const char *f1, const char *l1, */ SWIGRUNTIME int SWIG_TypeCmp(const char *nb, const char *tb) { - int equiv = 1; - const char* te = tb + strlen(tb); - const char* ne = nb; - while (equiv != 0 && *ne) { - for (nb = ne; *ne; ++ne) { - if (*ne == '|') break; + int equiv = 1; + const char *te = tb + strlen(tb); + const char *ne = nb; + while (equiv != 0 && *ne) { + for (nb = ne; *ne; ++ne) { + if (*ne == '|') break; + } + equiv = SWIG_TypeNameComp(nb, ne, tb, te); + if (*ne) ++ne; } - equiv = SWIG_TypeNameComp(nb, ne, tb, te); - if (*ne) ++ne; - } - return equiv; + return equiv; } /* @@ -432,7 +432,7 @@ SWIG_TypeCmp(const char *nb, const char *tb) { */ SWIGRUNTIME int SWIG_TypeEquiv(const char *nb, const char *tb) { - return SWIG_TypeCmp(nb, tb) == 0 ? 1 : 0; + return SWIG_TypeCmp(nb, tb) == 0 ? 1 : 0; } /* @@ -440,26 +440,26 @@ SWIG_TypeEquiv(const char *nb, const char *tb) { */ SWIGRUNTIME swig_cast_info * SWIG_TypeCheck(const char *c, swig_type_info *ty) { - if (ty) { - swig_cast_info *iter = ty->cast; - while (iter) { - if (strcmp(iter->type->name, c) == 0) { - if (iter == ty->cast) - return iter; - /* Move iter to the top of the linked list */ - iter->prev->next = iter->next; - if (iter->next) - iter->next->prev = iter->prev; - iter->next = ty->cast; - iter->prev = 0; - if (ty->cast) ty->cast->prev = iter; - ty->cast = iter; - return iter; - } - iter = iter->next; + if (ty) { + swig_cast_info *iter = ty->cast; + while (iter) { + if (strcmp(iter->type->name, c) == 0) { + if (iter == ty->cast) + return iter; + /* Move iter to the top of the linked list */ + iter->prev->next = iter->next; + if (iter->next) + iter->next->prev = iter->prev; + iter->next = ty->cast; + iter->prev = 0; + if (ty->cast) ty->cast->prev = iter; + ty->cast = iter; + return iter; + } + iter = iter->next; + } } - } - return 0; + return 0; } /* @@ -467,26 +467,26 @@ SWIG_TypeCheck(const char *c, swig_type_info *ty) { */ SWIGRUNTIME swig_cast_info * SWIG_TypeCheckStruct(const swig_type_info *from, swig_type_info *ty) { - if (ty) { - swig_cast_info *iter = ty->cast; - while (iter) { - if (iter->type == from) { - if (iter == ty->cast) - return iter; - /* Move iter to the top of the linked list */ - iter->prev->next = iter->next; - if (iter->next) - iter->next->prev = iter->prev; - iter->next = ty->cast; - iter->prev = 0; - if (ty->cast) ty->cast->prev = iter; - ty->cast = iter; - return iter; - } - iter = iter->next; + if (ty) { + swig_cast_info *iter = ty->cast; + while (iter) { + if (iter->type == from) { + if (iter == ty->cast) + return iter; + /* Move iter to the top of the linked list */ + iter->prev->next = iter->next; + if (iter->next) + iter->next->prev = iter->prev; + iter->next = ty->cast; + iter->prev = 0; + if (ty->cast) ty->cast->prev = iter; + ty->cast = iter; + return iter; + } + iter = iter->next; + } } - } - return 0; + return 0; } /* @@ -494,7 +494,7 @@ SWIG_TypeCheckStruct(const swig_type_info *from, swig_type_info *ty) { */ SWIGRUNTIMEINLINE void * SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) { - return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory); + return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory); } /* @@ -502,13 +502,13 @@ SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) { */ SWIGRUNTIME swig_type_info * SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) { - swig_type_info *lastty = ty; - if (!ty || !ty->dcast) return ty; - while (ty && (ty->dcast)) { - ty = (*ty->dcast)(ptr); - if (ty) lastty = ty; - } - return lastty; + swig_type_info *lastty = ty; + if (!ty || !ty->dcast) return ty; + while (ty && (ty->dcast)) { + ty = (*ty->dcast)(ptr); + if (ty) lastty = ty; + } + return lastty; } /* @@ -516,7 +516,7 @@ SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) { */ SWIGRUNTIMEINLINE const char * SWIG_TypeName(const swig_type_info *ty) { - return ty->name; + return ty->name; } /* @@ -525,20 +525,19 @@ SWIG_TypeName(const swig_type_info *ty) { */ SWIGRUNTIME const char * SWIG_TypePrettyName(const swig_type_info *type) { - /* The "str" field contains the equivalent pretty names of the - type, separated by vertical-bar characters. Choose the last - name. It should be the most specific; a fully resolved name - but not necessarily with default template parameters expanded. */ - if (!type) return NULL; - if (type->str != NULL) { - const char *last_name = type->str; - const char *s; - for (s = type->str; *s; s++) - if (*s == '|') last_name = s+1; - return last_name; - } - else - return type->name; + /* The "str" field contains the equivalent pretty names of the + type, separated by vertical-bar characters. Choose the last + name. It should be the most specific; a fully resolved name + but not necessarily with default template parameters expanded. */ + if (!type) return NULL; + if (type->str != NULL) { + const char *last_name = type->str; + const char *s; + for (s = type->str; *s; s++) + if (*s == '|') last_name = s + 1; + return last_name; + } else + return type->name; } /* @@ -546,24 +545,24 @@ SWIG_TypePrettyName(const swig_type_info *type) { */ SWIGRUNTIME void SWIG_TypeClientData(swig_type_info *ti, void *clientdata) { - swig_cast_info *cast = ti->cast; - /* if (ti->clientdata == clientdata) return; */ - ti->clientdata = clientdata; + swig_cast_info *cast = ti->cast; + /* if (ti->clientdata == clientdata) return; */ + ti->clientdata = clientdata; - while (cast) { - if (!cast->converter) { - swig_type_info *tc = cast->type; - if (!tc->clientdata) { - SWIG_TypeClientData(tc, clientdata); - } + while (cast) { + if (!cast->converter) { + swig_type_info *tc = cast->type; + if (!tc->clientdata) { + SWIG_TypeClientData(tc, clientdata); + } + } + cast = cast->next; } - cast = cast->next; - } } SWIGRUNTIME void SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) { - SWIG_TypeClientData(ti, clientdata); - ti->owndata = 1; + SWIG_TypeClientData(ti, clientdata); + ti->owndata = 1; } /* @@ -577,37 +576,37 @@ SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) { SWIGRUNTIME swig_type_info * SWIG_MangledTypeQueryModule(swig_module_info *start, swig_module_info *end, - const char *name) { - swig_module_info *iter = start; - do { - if (iter->size) { - size_t l = 0; - size_t r = iter->size - 1; - do { - /* since l+r >= 0, we can (>> 1) instead (/ 2) */ - size_t i = (l + r) >> 1; - const char *iname = iter->types[i]->name; - if (iname) { - int compare = strcmp(name, iname); - if (compare == 0) { - return iter->types[i]; - } else if (compare < 0) { - if (i) { - r = i - 1; - } else { - break; - } - } else if (compare > 0) { - l = i + 1; - } - } else { - break; /* should never happen */ - } - } while (l <= r); - } - iter = iter->next; - } while (iter != end); - return 0; + const char *name) { + swig_module_info *iter = start; + do { + if (iter->size) { + size_t l = 0; + size_t r = iter->size - 1; + do { + /* since l+r >= 0, we can (>> 1) instead (/ 2) */ + size_t i = (l + r) >> 1; + const char *iname = iter->types[i]->name; + if (iname) { + int compare = strcmp(name, iname); + if (compare == 0) { + return iter->types[i]; + } else if (compare < 0) { + if (i) { + r = i - 1; + } else { + break; + } + } else if (compare > 0) { + l = i + 1; + } + } else { + break; /* should never happen */ + } + } while (l <= r); + } + iter = iter->next; + } while (iter != end); + return 0; } /* @@ -622,27 +621,27 @@ SWIG_MangledTypeQueryModule(swig_module_info *start, SWIGRUNTIME swig_type_info * SWIG_TypeQueryModule(swig_module_info *start, swig_module_info *end, - const char *name) { - /* STEP 1: Search the name field using binary search */ - swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name); - if (ret) { - return ret; - } else { - /* STEP 2: If the type hasn't been found, do a complete search - of the str field (the human readable name) */ - swig_module_info *iter = start; - do { - size_t i = 0; - for (; i < iter->size; ++i) { - if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name))) - return iter->types[i]; - } - iter = iter->next; - } while (iter != end); - } + const char *name) { + /* STEP 1: Search the name field using binary search */ + swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name); + if (ret) { + return ret; + } else { + /* STEP 2: If the type hasn't been found, do a complete search + of the str field (the human readable name) */ + swig_module_info *iter = start; + do { + size_t i = 0; + for (; i < iter->size; ++i) { + if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name))) + return iter->types[i]; + } + iter = iter->next; + } while (iter != end); + } - /* neither found a match */ - return 0; + /* neither found a match */ + return 0; } /* @@ -650,15 +649,15 @@ SWIG_TypeQueryModule(swig_module_info *start, */ SWIGRUNTIME char * SWIG_PackData(char *c, void *ptr, size_t sz) { - static const char hex[17] = "0123456789abcdef"; - const unsigned char *u = (unsigned char *) ptr; - const unsigned char *eu = u + sz; - for (; u != eu; ++u) { - unsigned char uu = *u; - *(c++) = hex[(uu & 0xf0) >> 4]; - *(c++) = hex[uu & 0xf]; - } - return c; + static const char hex[17] = "0123456789abcdef"; + const unsigned char *u = (unsigned char *) ptr; + const unsigned char *eu = u + sz; + for (; u != eu; ++u) { + unsigned char uu = *u; + *(c++) = hex[(uu & 0xf0) >> 4]; + *(c++) = hex[uu & 0xf]; + } + return c; } /* @@ -666,27 +665,27 @@ SWIG_PackData(char *c, void *ptr, size_t sz) { */ SWIGRUNTIME const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { - unsigned char *u = (unsigned char *) ptr; - const unsigned char *eu = u + sz; - for (; u != eu; ++u) { - char d = *(c++); - unsigned char uu; - if ((d >= '0') && (d <= '9')) - uu = (unsigned char)((d - '0') << 4); - else if ((d >= 'a') && (d <= 'f')) - uu = (unsigned char)((d - ('a'-10)) << 4); - else - return (char *) 0; - d = *(c++); - if ((d >= '0') && (d <= '9')) - uu |= (unsigned char)(d - '0'); - else if ((d >= 'a') && (d <= 'f')) - uu |= (unsigned char)(d - ('a'-10)); - else - return (char *) 0; - *u = uu; - } - return c; + unsigned char *u = (unsigned char *) ptr; + const unsigned char *eu = u + sz; + for (; u != eu; ++u) { + char d = *(c++); + unsigned char uu; + if ((d >= '0') && (d <= '9')) + uu = (unsigned char)((d - '0') << 4); + else if ((d >= 'a') && (d <= 'f')) + uu = (unsigned char)((d - ('a' - 10)) << 4); + else + return (char *) 0; + d = *(c++); + if ((d >= '0') && (d <= '9')) + uu |= (unsigned char)(d - '0'); + else if ((d >= 'a') && (d <= 'f')) + uu |= (unsigned char)(d - ('a' - 10)); + else + return (char *) 0; + *u = uu; + } + return c; } /* @@ -694,54 +693,54 @@ SWIG_UnpackData(const char *c, void *ptr, size_t sz) { */ SWIGRUNTIME char * SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) { - char *r = buff; - if ((2*sizeof(void *) + 2) > bsz) return 0; - *(r++) = '_'; - r = SWIG_PackData(r,&ptr,sizeof(void *)); - if (strlen(name) + 1 > (bsz - (r - buff))) return 0; - strcpy(r,name); - return buff; + char *r = buff; + if ((2 * sizeof(void *) + 2) > bsz) return 0; + *(r++) = '_'; + r = SWIG_PackData(r, &ptr, sizeof(void *)); + if (strlen(name) + 1 > (bsz - (r - buff))) return 0; + strcpy(r, name); + return buff; } SWIGRUNTIME const char * SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) { - if (*c != '_') { - if (strcmp(c,"NULL") == 0) { - *ptr = (void *) 0; - return name; - } else { - return 0; + if (*c != '_') { + if (strcmp(c, "NULL") == 0) { + *ptr = (void *) 0; + return name; + } else { + return 0; + } } - } - return SWIG_UnpackData(++c,ptr,sizeof(void *)); + return SWIG_UnpackData(++c, ptr, sizeof(void *)); } SWIGRUNTIME char * SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) { - char *r = buff; - size_t lname = (name ? strlen(name) : 0); - if ((2*sz + 2 + lname) > bsz) return 0; - *(r++) = '_'; - r = SWIG_PackData(r,ptr,sz); - if (lname) { - strncpy(r,name,lname+1); - } else { - *r = 0; - } - return buff; + char *r = buff; + size_t lname = (name ? strlen(name) : 0); + if ((2 * sz + 2 + lname) > bsz) return 0; + *(r++) = '_'; + r = SWIG_PackData(r, ptr, sz); + if (lname) { + strncpy(r, name, lname + 1); + } else { + *r = 0; + } + return buff; } SWIGRUNTIME const char * SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) { - if (*c != '_') { - if (strcmp(c,"NULL") == 0) { - memset(ptr,0,sz); - return name; - } else { - return 0; + if (*c != '_') { + if (strcmp(c, "NULL") == 0) { + memset(ptr, 0, sz); + return name; + } else { + return 0; + } } - } - return SWIG_UnpackData(++c,ptr,sz); + return SWIG_UnpackData(++c, ptr, sz); } #ifdef __cplusplus @@ -798,32 +797,32 @@ extern "C" { struct swig_elua_entry; typedef struct swig_elua_key { - int type; - union { - const char* strkey; - lua_Number numkey; - } key; + int type; + union { + const char *strkey; + lua_Number numkey; + } key; } swig_elua_key; typedef struct swig_elua_val { - int type; - union { - lua_Number number; - const struct swig_elua_entry *table; - const char *string; - lua_CFunction function; - struct { - char member; - long lvalue; - void *pvalue; - swig_type_info **ptype; - } userdata; - } value; + int type; + union { + lua_Number number; + const struct swig_elua_entry *table; + const char *string; + lua_CFunction function; + struct { + char member; + long lvalue; + void *pvalue; + swig_type_info **ptype; + } userdata; + } value; } swig_elua_val; typedef struct swig_elua_entry { - swig_elua_key key; - swig_elua_val value; + swig_elua_key key; + swig_elua_val value; } swig_elua_entry; #define LSTRKEY(x) {LUA_TSTRING, {.strkey = x} } @@ -857,7 +856,7 @@ typedef struct swig_elua_entry { # define SWIG_LUA_CONSTTAB_FLOAT(B, C) LSTRKEY(B), LNUMVAL(C) # define SWIG_LUA_CONSTTAB_STRING(B, C) LSTRKEY(B), LSTRVAL(C) # define SWIG_LUA_CONSTTAB_CHAR(B, C) LSTRKEY(B), LNUMVAL(C) - /* Those two types of constants are not supported in elua */ +/* Those two types of constants are not supported in elua */ #ifndef SWIG_LUA_CONSTTAB_POINTER #warning eLua does not support pointers as constants. By default, nil will be used as value @@ -921,11 +920,11 @@ typedef struct swig_elua_entry { we provide a compatibility implementation for Lua 5.0. */ #if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 501 static const char *(lua_tolstring)(lua_State *L, int idx, size_t *len) { - /* Call lua_tostring() first as it may convert the value from number to - string. */ - const char *result = lua_tostring(L, idx); - if (len) *len = lua_strlen(L, idx); - return result; + /* Call lua_tostring() first as it may convert the value from number to + string. */ + const char *result = lua_tostring(L, idx); + if (len) *len = lua_strlen(L, idx); + return result; } #endif @@ -963,25 +962,23 @@ static const char *(lua_tolstring)(lua_State *L, int idx, size_t *len) { prefixed with the location of the innermost Lua call-point (as formatted by luaL_where). */ SWIGRUNTIME void -SWIG_Lua_pusherrstring (lua_State *L, const char *str) -{ - luaL_where (L, 1); - lua_pushstring (L, str); - lua_concat (L, 2); +SWIG_Lua_pusherrstring(lua_State *L, const char *str) { + luaL_where(L, 1); + lua_pushstring(L, str); + lua_concat(L, 2); } /* Push a formatted string generated from FMT and following args on the Lua stack, like lua_pushfstring, but prefixed with the location of the innermost Lua call-point (as formatted by luaL_where). */ SWIGRUNTIME void -SWIG_Lua_pushferrstring (lua_State *L, const char *fmt, ...) -{ - va_list argp; - va_start(argp, fmt); - luaL_where(L, 1); - lua_pushvfstring(L, fmt, argp); - va_end(argp); - lua_concat(L, 2); +SWIG_Lua_pushferrstring(lua_State *L, const char *fmt, ...) { + va_list argp; + va_start(argp, fmt); + luaL_where(L, 1); + lua_pushvfstring(L, fmt, argp); + va_end(argp); + lua_concat(L, 2); } @@ -998,9 +995,9 @@ SWIG_Lua_pushferrstring (lua_State *L, const char *fmt, ...) /* Structure for variable linking table */ typedef struct { - const char *name; - lua_CFunction get; - lua_CFunction set; + const char *name; + lua_CFunction get; + lua_CFunction set; } swig_lua_var_info; #if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC) @@ -1022,43 +1019,43 @@ typedef struct { #endif typedef struct { - const char *name; - lua_CFunction getmethod; - lua_CFunction setmethod; + const char *name; + lua_CFunction getmethod; + lua_CFunction setmethod; } swig_lua_attribute; struct swig_lua_class; /* Can be used to create namespaces. Currently used to wrap class static methods/variables/constants */ typedef struct swig_lua_namespace { - const char *name; - swig_lua_method *ns_methods; - swig_lua_attribute *ns_attributes; - swig_lua_const_info *ns_constants; - struct swig_lua_class **ns_classes; - struct swig_lua_namespace **ns_namespaces; + const char *name; + swig_lua_method *ns_methods; + swig_lua_attribute *ns_attributes; + swig_lua_const_info *ns_constants; + struct swig_lua_class **ns_classes; + struct swig_lua_namespace **ns_namespaces; } swig_lua_namespace; typedef struct swig_lua_class { - const char *name; /* Name that this class has in Lua */ - const char *fqname; /* Fully qualified name - Scope + class name */ - swig_type_info **type; - lua_CFunction constructor; - void (*destructor)(void *); - swig_lua_method *methods; - swig_lua_attribute *attributes; - swig_lua_namespace *cls_static; - swig_lua_method *metatable; /* 0 for -eluac */ - struct swig_lua_class **bases; - const char **base_names; + const char *name; /* Name that this class has in Lua */ + const char *fqname; /* Fully qualified name - Scope + class name */ + swig_type_info **type; + lua_CFunction constructor; + void (*destructor)(void *); + swig_lua_method *methods; + swig_lua_attribute *attributes; + swig_lua_namespace *cls_static; + swig_lua_method *metatable; /* 0 for -eluac */ + struct swig_lua_class **bases; + const char **base_names; } swig_lua_class; /* this is the struct for wrapping all pointers in SwigLua */ typedef struct { - swig_type_info *type; - int own; /* 1 if owned & must be destroyed */ - void *ptr; + swig_type_info *type; + int own; /* 1 if owned & must be destroyed */ + void *ptr; } swig_lua_userdata; /* this is the struct for wrapping arbitrary packed binary data @@ -1067,9 +1064,9 @@ the data ordering is similar to swig_lua_userdata, but it is currently not possi to tell the two structures apart within SWIG, other than by looking at the type */ typedef struct { - swig_type_info *type; - int own; /* 1 if owned & must be destroyed */ - char data[1]; /* arbitrary amount of data */ + swig_type_info *type; + int own; /* 1 if owned & must be destroyed */ + char data[1]; /* arbitrary amount of data */ } swig_lua_rawdata; /* Common SWIG API */ @@ -1129,21 +1126,21 @@ it gets the address, casts it, then dereferences it */ /* storing/access of swig_module_info */ SWIGRUNTIME swig_module_info * SWIG_Lua_GetModule(lua_State *L) { - swig_module_info *ret = 0; - lua_pushstring(L,"swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME); - lua_rawget(L,LUA_REGISTRYINDEX); - if (lua_islightuserdata(L,-1)) - ret=(swig_module_info*)lua_touserdata(L,-1); - lua_pop(L,1); /* tidy */ - return ret; + swig_module_info *ret = 0; + lua_pushstring(L, "swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME); + lua_rawget(L, LUA_REGISTRYINDEX); + if (lua_islightuserdata(L, -1)) + ret = (swig_module_info *)lua_touserdata(L, -1); + lua_pop(L, 1); /* tidy */ + return ret; } SWIGRUNTIME void SWIG_Lua_SetModule(lua_State *L, swig_module_info *module) { - /* add this all into the Lua registry: */ - lua_pushstring(L,"swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME); - lua_pushlightuserdata(L,(void*)module); - lua_rawset(L,LUA_REGISTRYINDEX); + /* add this all into the Lua registry: */ + lua_pushstring(L, "swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME); + lua_pushlightuserdata(L, (void *)module); + lua_rawset(L, LUA_REGISTRYINDEX); } /* ----------------------------------------------------------------------------- @@ -1153,153 +1150,147 @@ SWIG_Lua_SetModule(lua_State *L, swig_module_info *module) { /* this function is called when trying to set an immutable. default action is to print an error. This can removed with a compile flag SWIGLUA_IGNORE_SET_IMMUTABLE */ -SWIGINTERN int SWIG_Lua_set_immutable(lua_State *L) -{ -/* there should be 1 param passed in: the new value */ +SWIGINTERN int SWIG_Lua_set_immutable(lua_State *L) { + /* there should be 1 param passed in: the new value */ #ifndef SWIGLUA_IGNORE_SET_IMMUTABLE - lua_pop(L,1); /* remove it */ - luaL_error(L,"This variable is immutable"); + lua_pop(L, 1); /* remove it */ + luaL_error(L, "This variable is immutable"); #endif return 0; /* should not return anything */ } #ifdef SWIG_LUA_ELUA_EMULATE -SWIGRUNTIME void SWIG_Lua_NewPointerObj(lua_State *L,void *ptr,swig_type_info *type, int own); -SWIGRUNTIME void SWIG_Lua_NewPackedObj(lua_State *L,void *ptr,size_t size,swig_type_info *type); +SWIGRUNTIME void SWIG_Lua_NewPointerObj(lua_State *L, void *ptr, swig_type_info *type, int own); +SWIGRUNTIME void SWIG_Lua_NewPackedObj(lua_State *L, void *ptr, size_t size, swig_type_info *type); static int swig_lua_elua_emulate_unique_key; /* This function emulates eLua rotables behaviour. It loads a rotable definition into the usual lua table. */ -SWIGINTERN void SWIG_Lua_elua_emulate_register(lua_State *L, const swig_elua_entry *table) -{ - int i, table_parsed, parsed_tables_array, target_table; - assert(lua_istable(L,-1)); - target_table = lua_gettop(L); - /* Get the registry where we put all parsed tables to avoid loops */ - lua_rawgetp(L, LUA_REGISTRYINDEX, &swig_lua_elua_emulate_unique_key); - if(lua_isnil(L,-1)) { - lua_pop(L,1); - lua_newtable(L); - lua_pushvalue(L,-1); - lua_rawsetp(L,LUA_REGISTRYINDEX,(void*)(&swig_lua_elua_emulate_unique_key)); - } - parsed_tables_array = lua_gettop(L); - lua_pushvalue(L,target_table); - lua_rawsetp(L, parsed_tables_array, table); - table_parsed = 0; - const int SWIGUNUSED pairs_start = lua_gettop(L); - for(i = 0;table[i].key.type != LUA_TNIL || table[i].value.type != LUA_TNIL;i++) - { - const swig_elua_entry *entry = table + i; - int is_metatable = 0; - switch(entry->key.type) { - case LUA_TSTRING: - lua_pushstring(L,entry->key.key.strkey); - if(strcmp(entry->key.key.strkey, SWIG_LUA_ELUA_EMUL_METATABLE_KEY) == 0) - is_metatable = 1; - break; - case LUA_TNUMBER: - lua_pushnumber(L,entry->key.key.numkey); - break; - case LUA_TNIL: - lua_pushnil(L); - break; - default: - assert(0); +SWIGINTERN void SWIG_Lua_elua_emulate_register(lua_State *L, const swig_elua_entry *table) { + int i, table_parsed, parsed_tables_array, target_table; + assert(lua_istable(L, -1)); + target_table = lua_gettop(L); + /* Get the registry where we put all parsed tables to avoid loops */ + lua_rawgetp(L, LUA_REGISTRYINDEX, &swig_lua_elua_emulate_unique_key); + if (lua_isnil(L, -1)) { + lua_pop(L, 1); + lua_newtable(L); + lua_pushvalue(L, -1); + lua_rawsetp(L, LUA_REGISTRYINDEX, (void *)(&swig_lua_elua_emulate_unique_key)); } - switch(entry->value.type) { - case LUA_TSTRING: - lua_pushstring(L,entry->value.value.string); - break; - case LUA_TNUMBER: - lua_pushnumber(L,entry->value.value.number); - break; - case LUA_TFUNCTION: - lua_pushcfunction(L,entry->value.value.function); - break; - case LUA_TTABLE: - lua_rawgetp(L,parsed_tables_array, entry->value.value.table); - table_parsed = !lua_isnil(L,-1); - if(!table_parsed) { - lua_pop(L,1); /*remove nil */ - lua_newtable(L); - SWIG_Lua_elua_emulate_register(L,entry->value.value.table); - } - if(is_metatable) { - assert(lua_istable(L,-1)); - lua_pushvalue(L,-1); - lua_setmetatable(L,target_table); + parsed_tables_array = lua_gettop(L); + lua_pushvalue(L, target_table); + lua_rawsetp(L, parsed_tables_array, table); + table_parsed = 0; + const int SWIGUNUSED pairs_start = lua_gettop(L); + for (i = 0; table[i].key.type != LUA_TNIL || table[i].value.type != LUA_TNIL; i++) { + const swig_elua_entry *entry = table + i; + int is_metatable = 0; + switch (entry->key.type) { + case LUA_TSTRING: + lua_pushstring(L, entry->key.key.strkey); + if (strcmp(entry->key.key.strkey, SWIG_LUA_ELUA_EMUL_METATABLE_KEY) == 0) + is_metatable = 1; + break; + case LUA_TNUMBER: + lua_pushnumber(L, entry->key.key.numkey); + break; + case LUA_TNIL: + lua_pushnil(L); + break; + default: + assert(0); } + switch (entry->value.type) { + case LUA_TSTRING: + lua_pushstring(L, entry->value.value.string); + break; + case LUA_TNUMBER: + lua_pushnumber(L, entry->value.value.number); + break; + case LUA_TFUNCTION: + lua_pushcfunction(L, entry->value.value.function); + break; + case LUA_TTABLE: + lua_rawgetp(L, parsed_tables_array, entry->value.value.table); + table_parsed = !lua_isnil(L, -1); + if (!table_parsed) { + lua_pop(L, 1); /*remove nil */ + lua_newtable(L); + SWIG_Lua_elua_emulate_register(L, entry->value.value.table); + } + if (is_metatable) { + assert(lua_istable(L, -1)); + lua_pushvalue(L, -1); + lua_setmetatable(L, target_table); + } - break; - case LUA_TUSERDATA: - if(entry->value.value.userdata.member) - SWIG_NewMemberObj(L,entry->value.value.userdata.pvalue, - entry->value.value.userdata.lvalue, - *(entry->value.value.userdata.ptype)); - else - SWIG_NewPointerObj(L,entry->value.value.userdata.pvalue, - *(entry->value.value.userdata.ptype),0); - break; - case LUA_TNIL: - lua_pushnil(L); - break; - default: - assert(0); + break; + case LUA_TUSERDATA: + if (entry->value.value.userdata.member) + SWIG_NewMemberObj(L, entry->value.value.userdata.pvalue, + entry->value.value.userdata.lvalue, + *(entry->value.value.userdata.ptype)); + else + SWIG_NewPointerObj(L, entry->value.value.userdata.pvalue, + *(entry->value.value.userdata.ptype), 0); + break; + case LUA_TNIL: + lua_pushnil(L); + break; + default: + assert(0); + } + assert(lua_gettop(L) == pairs_start + 2); + lua_rawset(L, target_table); } - assert(lua_gettop(L) == pairs_start + 2); - lua_rawset(L,target_table); - } - lua_pop(L,1); /* Removing parsed tables storage */ - assert(lua_gettop(L) == target_table); + lua_pop(L, 1); /* Removing parsed tables storage */ + assert(lua_gettop(L) == target_table); } -SWIGINTERN void SWIG_Lua_elua_emulate_register_clear(lua_State *L) -{ - lua_pushnil(L); - lua_rawsetp(L, LUA_REGISTRYINDEX, &swig_lua_elua_emulate_unique_key); +SWIGINTERN void SWIG_Lua_elua_emulate_register_clear(lua_State *L) { + lua_pushnil(L); + lua_rawsetp(L, LUA_REGISTRYINDEX, &swig_lua_elua_emulate_unique_key); } SWIGINTERN void SWIG_Lua_get_class_registry(lua_State *L); -SWIGINTERN int SWIG_Lua_emulate_elua_getmetatable(lua_State *L) -{ - SWIG_check_num_args("getmetatable(SWIG eLua emulation)", 1, 1); - SWIG_Lua_get_class_registry(L); - lua_getfield(L,-1,"lua_getmetatable"); - lua_remove(L,-2); /* remove the registry*/ - assert(!lua_isnil(L,-1)); - lua_pushvalue(L,1); - assert(lua_gettop(L) == 3); /* object | function | object again */ - lua_call(L,1,1); - if(!lua_isnil(L,-1)) /*There is an ordinary metatable */ +SWIGINTERN int SWIG_Lua_emulate_elua_getmetatable(lua_State *L) { + SWIG_check_num_args("getmetatable(SWIG eLua emulation)", 1, 1); + SWIG_Lua_get_class_registry(L); + lua_getfield(L, -1, "lua_getmetatable"); + lua_remove(L, -2); /* remove the registry*/ + assert(!lua_isnil(L, -1)); + lua_pushvalue(L, 1); + assert(lua_gettop(L) == 3); /* object | function | object again */ + lua_call(L, 1, 1); + if (!lua_isnil(L, -1)) /*There is an ordinary metatable */ + return 1; + /*if it is a table, then emulate elua behaviour - check for __metatable attribute of a table*/ + assert(lua_gettop(L) == 2); + if (lua_istable(L, -2)) { + lua_pop(L, 1); /*remove the nil*/ + lua_getfield(L, -1, SWIG_LUA_ELUA_EMUL_METATABLE_KEY); + } + assert(lua_gettop(L) == 2); return 1; - /*if it is a table, then emulate elua behaviour - check for __metatable attribute of a table*/ - assert(lua_gettop(L) == 2); - if(lua_istable(L,-2)) { - lua_pop(L,1); /*remove the nil*/ - lua_getfield(L,-1, SWIG_LUA_ELUA_EMUL_METATABLE_KEY); - } - assert(lua_gettop(L) == 2); - return 1; fail: - lua_error(L); - return 0; + lua_error(L); + return 0; } -SWIGINTERN void SWIG_Lua_emulate_elua_swap_getmetatable(lua_State *L) -{ - SWIG_Lua_get_class_registry(L); - lua_pushglobaltable(L); - lua_pushstring(L,"lua_getmetatable"); - lua_getfield(L,-2,"getmetatable"); - assert(!lua_isnil(L,-1)); - lua_rawset(L,-4); - lua_pushstring(L, "getmetatable"); - lua_pushcfunction(L, SWIG_Lua_emulate_elua_getmetatable); - lua_rawset(L,-3); - lua_pop(L,2); +SWIGINTERN void SWIG_Lua_emulate_elua_swap_getmetatable(lua_State *L) { + SWIG_Lua_get_class_registry(L); + lua_pushglobaltable(L); + lua_pushstring(L, "lua_getmetatable"); + lua_getfield(L, -2, "getmetatable"); + assert(!lua_isnil(L, -1)); + lua_rawset(L, -4); + lua_pushstring(L, "getmetatable"); + lua_pushcfunction(L, SWIG_Lua_emulate_elua_getmetatable); + lua_rawset(L, -3); + lua_pop(L, 2); } /* END OF REMOVE */ @@ -1309,120 +1300,115 @@ SWIGINTERN void SWIG_Lua_emulate_elua_swap_getmetatable(lua_State *L) * global variable support code: namespaces and modules (which are the same thing) * ----------------------------------------------------------------------------- */ -SWIGINTERN int SWIG_Lua_namespace_get(lua_State *L) -{ -/* there should be 2 params passed in - (1) table (not the meta table) - (2) string name of the attribute -*/ - assert(lua_istable(L,-2)); /* just in case */ - lua_getmetatable(L,-2); - assert(lua_istable(L,-1)); - SWIG_Lua_get_table(L,".get"); /* find the .get table */ - assert(lua_istable(L,-1)); - /* look for the key in the .get table */ - lua_pushvalue(L,2); /* key */ - lua_rawget(L,-2); - lua_remove(L,-2); /* stack tidy, remove .get table */ - if (lua_iscfunction(L,-1)) - { /* found it so call the fn & return its value */ - lua_call(L,0,1); /* 1 value in (userdata),1 out (result) */ - lua_remove(L,-2); /* stack tidy, remove metatable */ - return 1; - } - lua_pop(L,1); /* remove whatever was there */ - /* ok, so try the .fn table */ - SWIG_Lua_get_table(L,".fn"); /* find the .get table */ - assert(lua_istable(L,-1)); /* just in case */ - lua_pushvalue(L,2); /* key */ - lua_rawget(L,-2); /* look for the fn */ - lua_remove(L,-2); /* stack tidy, remove .fn table */ - if (lua_isfunction(L,-1)) /* note: whether it's a C function or lua function */ - { /* found it so return the fn & let lua call it */ - lua_remove(L,-2); /* stack tidy, remove metatable */ - return 1; - } - lua_pop(L,1); /* remove whatever was there */ - return 0; +SWIGINTERN int SWIG_Lua_namespace_get(lua_State *L) { + /* there should be 2 params passed in + (1) table (not the meta table) + (2) string name of the attribute + */ + assert(lua_istable(L, -2)); /* just in case */ + lua_getmetatable(L, -2); + assert(lua_istable(L, -1)); + SWIG_Lua_get_table(L, ".get"); /* find the .get table */ + assert(lua_istable(L, -1)); + /* look for the key in the .get table */ + lua_pushvalue(L, 2); /* key */ + lua_rawget(L, -2); + lua_remove(L, -2); /* stack tidy, remove .get table */ + if (lua_iscfunction(L, -1)) { + /* found it so call the fn & return its value */ + lua_call(L, 0, 1); /* 1 value in (userdata),1 out (result) */ + lua_remove(L, -2); /* stack tidy, remove metatable */ + return 1; + } + lua_pop(L, 1); /* remove whatever was there */ + /* ok, so try the .fn table */ + SWIG_Lua_get_table(L, ".fn"); /* find the .get table */ + assert(lua_istable(L, -1)); /* just in case */ + lua_pushvalue(L, 2); /* key */ + lua_rawget(L, -2); /* look for the fn */ + lua_remove(L, -2); /* stack tidy, remove .fn table */ + if (lua_isfunction(L, -1)) { /* note: whether it's a C function or lua function */ + /* found it so return the fn & let lua call it */ + lua_remove(L, -2); /* stack tidy, remove metatable */ + return 1; + } + lua_pop(L, 1); /* remove whatever was there */ + return 0; } -SWIGINTERN int SWIG_Lua_namespace_set(lua_State *L) -{ -/* there should be 3 params passed in - (1) table (not the meta table) - (2) string name of the attribute - (3) any for the new value -*/ +SWIGINTERN int SWIG_Lua_namespace_set(lua_State *L) { + /* there should be 3 params passed in + (1) table (not the meta table) + (2) string name of the attribute + (3) any for the new value + */ - assert(lua_istable(L,1)); - lua_getmetatable(L,1); /* get the meta table */ - assert(lua_istable(L,-1)); + assert(lua_istable(L, 1)); + lua_getmetatable(L, 1); /* get the meta table */ + assert(lua_istable(L, -1)); - SWIG_Lua_get_table(L,".set"); /* find the .set table */ - if (lua_istable(L,-1)) - { - /* look for the key in the .set table */ - lua_pushvalue(L,2); /* key */ - lua_rawget(L,-2); - if (lua_iscfunction(L,-1)) - { /* found it so call the fn & return its value */ - lua_pushvalue(L,3); /* value */ - lua_call(L,1,0); - return 0; + SWIG_Lua_get_table(L, ".set"); /* find the .set table */ + if (lua_istable(L, -1)) { + /* look for the key in the .set table */ + lua_pushvalue(L, 2); /* key */ + lua_rawget(L, -2); + if (lua_iscfunction(L, -1)) { + /* found it so call the fn & return its value */ + lua_pushvalue(L, 3); /* value */ + lua_call(L, 1, 0); + return 0; + } + lua_pop(L, 1); /* remove the value */ } - lua_pop(L,1); /* remove the value */ - } - lua_pop(L,1); /* remove the value .set table */ - lua_pop(L,1); /* remote metatable */ - lua_rawset(L,-3); - return 0; + lua_pop(L, 1); /* remove the value .set table */ + lua_pop(L, 1); /* remote metatable */ + lua_rawset(L, -3); + return 0; } #if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) /* In elua this is useless */ SWIGINTERN void SWIG_Lua_InstallConstants(lua_State *L, swig_lua_const_info constants[]); /* forward declaration */ -SWIGINTERN void SWIG_Lua_add_variable(lua_State *L,const char *name,lua_CFunction getFn,lua_CFunction setFn); /* forward declaration */ -SWIGINTERN void SWIG_Lua_class_register(lua_State *L,swig_lua_class *clss); +SWIGINTERN void SWIG_Lua_add_variable(lua_State *L, const char *name, lua_CFunction getFn, lua_CFunction setFn); /* forward declaration */ +SWIGINTERN void SWIG_Lua_class_register(lua_State *L, swig_lua_class *clss); /* helper function - register namespace methods and attributes into namespace */ -SWIGINTERN int SWIG_Lua_add_namespace_details(lua_State *L, swig_lua_namespace *ns) -{ - int i; - /* There must be namespace table (not metatable) at the top of the stack */ - assert(lua_istable(L,-1)); - SWIG_Lua_InstallConstants(L, ns->ns_constants); +SWIGINTERN int SWIG_Lua_add_namespace_details(lua_State *L, swig_lua_namespace *ns) { + int i; + /* There must be namespace table (not metatable) at the top of the stack */ + assert(lua_istable(L, -1)); + SWIG_Lua_InstallConstants(L, ns->ns_constants); - /* add methods to the namespace/module table */ - for(i=0;ns->ns_methods[i].name;i++){ - SWIG_Lua_add_function(L,ns->ns_methods[i].name,ns->ns_methods[i].func); - } - lua_getmetatable(L,-1); + /* add methods to the namespace/module table */ + for (i = 0; ns->ns_methods[i].name; i++) { + SWIG_Lua_add_function(L, ns->ns_methods[i].name, ns->ns_methods[i].func); + } + lua_getmetatable(L, -1); - /* add fns */ - for(i=0;ns->ns_attributes[i].name;i++){ - SWIG_Lua_add_variable(L,ns->ns_attributes[i].name,ns->ns_attributes[i].getmethod,ns->ns_attributes[i].setmethod); - } + /* add fns */ + for (i = 0; ns->ns_attributes[i].name; i++) { + SWIG_Lua_add_variable(L, ns->ns_attributes[i].name, ns->ns_attributes[i].getmethod, ns->ns_attributes[i].setmethod); + } - /* clear stack - remove metatble */ - lua_pop(L,1); - return 0; + /* clear stack - remove metatble */ + lua_pop(L, 1); + return 0; } /* Register all classes in the namespace */ -SWIGINTERN void SWIG_Lua_add_namespace_classes(lua_State *L, swig_lua_namespace *ns) -{ - swig_lua_class **classes; +SWIGINTERN void SWIG_Lua_add_namespace_classes(lua_State *L, swig_lua_namespace *ns) { + swig_lua_class **classes; - /* There must be a module/namespace table at the top of the stack */ - assert(lua_istable(L,-1)); + /* There must be a module/namespace table at the top of the stack */ + assert(lua_istable(L, -1)); - classes = ns->ns_classes; + classes = ns->ns_classes; - if( classes != 0 ) { - while(*classes != 0) { - SWIG_Lua_class_register(L, *classes); - classes++; + if (classes != 0) { + while (*classes != 0) { + SWIG_Lua_class_register(L, *classes); + classes++; + } } - } } /* Helper function. Creates namespace table and adds it to module table @@ -1430,55 +1416,54 @@ SWIGINTERN void SWIG_Lua_add_namespace_classes(lua_State *L, swig_lua_namespace when function is called). Function always returns newly registered table on top of the stack. */ -SWIGINTERN void SWIG_Lua_namespace_register(lua_State *L, swig_lua_namespace *ns, int reg) -{ - swig_lua_namespace **sub_namespace; - /* 1 argument - table on the top of the stack */ - const int SWIGUNUSED begin = lua_gettop(L); - assert(lua_istable(L,-1)); /* just in case. This is supposed to be module table or parent namespace table */ - lua_checkstack(L,5); - lua_newtable(L); /* namespace itself */ - lua_newtable(L); /* metatable for namespace */ +SWIGINTERN void SWIG_Lua_namespace_register(lua_State *L, swig_lua_namespace *ns, int reg) { + swig_lua_namespace **sub_namespace; + /* 1 argument - table on the top of the stack */ + const int SWIGUNUSED begin = lua_gettop(L); + assert(lua_istable(L, -1)); /* just in case. This is supposed to be module table or parent namespace table */ + lua_checkstack(L, 5); + lua_newtable(L); /* namespace itself */ + lua_newtable(L); /* metatable for namespace */ - /* add a table called ".get" */ - lua_pushstring(L,".get"); - lua_newtable(L); - lua_rawset(L,-3); - /* add a table called ".set" */ - lua_pushstring(L,".set"); - lua_newtable(L); - lua_rawset(L,-3); - /* add a table called ".fn" */ - lua_pushstring(L,".fn"); - lua_newtable(L); - lua_rawset(L,-3); + /* add a table called ".get" */ + lua_pushstring(L, ".get"); + lua_newtable(L); + lua_rawset(L, -3); + /* add a table called ".set" */ + lua_pushstring(L, ".set"); + lua_newtable(L); + lua_rawset(L, -3); + /* add a table called ".fn" */ + lua_pushstring(L, ".fn"); + lua_newtable(L); + lua_rawset(L, -3); - /* add accessor fns for using the .get,.set&.fn */ - SWIG_Lua_add_function(L,"__index",SWIG_Lua_namespace_get); - SWIG_Lua_add_function(L,"__newindex",SWIG_Lua_namespace_set); + /* add accessor fns for using the .get,.set&.fn */ + SWIG_Lua_add_function(L, "__index", SWIG_Lua_namespace_get); + SWIG_Lua_add_function(L, "__newindex", SWIG_Lua_namespace_set); - lua_setmetatable(L,-2); /* set metatable */ + lua_setmetatable(L, -2); /* set metatable */ - /* Register all functions, variables etc */ - SWIG_Lua_add_namespace_details(L,ns); - /* Register classes */ - SWIG_Lua_add_namespace_classes(L,ns); + /* Register all functions, variables etc */ + SWIG_Lua_add_namespace_details(L, ns); + /* Register classes */ + SWIG_Lua_add_namespace_classes(L, ns); - sub_namespace = ns->ns_namespaces; - if( sub_namespace != 0) { - while(*sub_namespace != 0) { - SWIG_Lua_namespace_register(L, *sub_namespace, 1); - lua_pop(L,1); /* removing sub-namespace table */ - sub_namespace++; + sub_namespace = ns->ns_namespaces; + if (sub_namespace != 0) { + while (*sub_namespace != 0) { + SWIG_Lua_namespace_register(L, *sub_namespace, 1); + lua_pop(L, 1); /* removing sub-namespace table */ + sub_namespace++; + } } - } - if (reg) { - lua_pushstring(L,ns->name); - lua_pushvalue(L,-2); - lua_rawset(L,-4); /* add namespace to module table */ - } - assert(lua_gettop(L) == begin+1); + if (reg) { + lua_pushstring(L, ns->name); + lua_pushvalue(L, -2); + lua_rawset(L, -4); /* add namespace to module table */ + } + assert(lua_gettop(L) == begin + 1); } #endif /* SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA */ @@ -1486,13 +1471,12 @@ SWIGINTERN void SWIG_Lua_namespace_register(lua_State *L, swig_lua_namespace *ns * global variable support code: classes * ----------------------------------------------------------------------------- */ -SWIGINTERN void SWIG_Lua_get_class_metatable(lua_State *L,const char *cname); +SWIGINTERN void SWIG_Lua_get_class_metatable(lua_State *L, const char *cname); -typedef int (*swig_lua_base_iterator_func)(lua_State*,swig_type_info*, int, int *ret); +typedef int (*swig_lua_base_iterator_func)(lua_State *, swig_type_info *, int, int *ret); -SWIGINTERN int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info * SWIGUNUSED swig_type, - int first_arg, swig_lua_base_iterator_func func, int *const ret) -{ +SWIGINTERN int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info *SWIGUNUSED swig_type, + int first_arg, swig_lua_base_iterator_func func, int *const ret) { /* first_arg - position of the object in stack. Everything that is above are arguments * and is passed to every evocation of the func */ int last_arg = lua_gettop(L);/* position of last argument */ @@ -1501,88 +1485,87 @@ SWIGINTERN int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info * SWIGUNUSED int result = SWIG_ERROR; int bases_table; (void)swig_type; - lua_getmetatable(L,first_arg); + lua_getmetatable(L, first_arg); /* initialise base search */ #if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) - SWIG_Lua_get_table(L,".bases"); - assert(lua_istable(L,-1)); - bases_count = lua_rawlen(L,-1); + SWIG_Lua_get_table(L, ".bases"); + assert(lua_istable(L, -1)); + bases_count = lua_rawlen(L, -1); bases_table = lua_gettop(L); #else /* In elua .bases table doesn't exist. Use table from swig_lua_class */ (void)bases_table; - assert(swig_type!=0); - swig_module_info *module=SWIG_GetModule(L); - swig_lua_class **bases= ((swig_lua_class*)(swig_type->clientdata))->bases; - const char **base_names= ((swig_lua_class*)(swig_type->clientdata))->base_names; + assert(swig_type != 0); + swig_module_info *module = SWIG_GetModule(L); + swig_lua_class **bases = ((swig_lua_class *)(swig_type->clientdata))->bases; + const char **base_names = ((swig_lua_class *)(swig_type->clientdata))->base_names; bases_count = 0; - for(;base_names[bases_count]; - bases_count++);/* get length of bases */ + for (; base_names[bases_count]; + bases_count++);/* get length of bases */ #endif - if(ret) - *ret = 0; - if(bases_count>0) - { - int to_remove; - size_t i; - int j; - int subcall_last_arg; - int subcall_first_arg = lua_gettop(L) + 1;/* Here a copy of first_arg and arguments begin */ - int valid = 1; - swig_type_info *base_swig_type = 0; - for(j=first_arg;j<=last_arg;j++) - lua_pushvalue(L,j); - subcall_last_arg = lua_gettop(L); + if (ret) + *ret = 0; + if (bases_count > 0) { + int to_remove; + size_t i; + int j; + int subcall_last_arg; + int subcall_first_arg = lua_gettop(L) + 1;/* Here a copy of first_arg and arguments begin */ + int valid = 1; + swig_type_info *base_swig_type = 0; + for (j = first_arg; j <= last_arg; j++) + lua_pushvalue(L, j); + subcall_last_arg = lua_gettop(L); - /* Trick: temporarily replacing original metatable with metatable for base class and call getter */ - for(i=0;ifqname); - base_swig_type = SWIG_TypeQueryModule(module,module,base_names[i]); - assert(base_swig_type != 0); - } + swig_lua_class *base_class = bases[i]; + if (!base_class) { + valid = 0; + } else { + valid = 1; + SWIG_Lua_get_class_metatable(L, base_class->fqname); + base_swig_type = SWIG_TypeQueryModule(module, module, base_names[i]); + assert(base_swig_type != 0); + } #endif - if(!valid) - continue; - assert(lua_isuserdata(L, subcall_first_arg)); - assert(lua_istable(L,-1)); - lua_setmetatable(L,subcall_first_arg); /* Set new metatable */ - assert(lua_gettop(L) == subcall_last_arg); - result = func(L, base_swig_type,subcall_first_arg, ret); /* Forward call */ - if(result != SWIG_ERROR) { - break; + if (!valid) + continue; + assert(lua_isuserdata(L, subcall_first_arg)); + assert(lua_istable(L, -1)); + lua_setmetatable(L, subcall_first_arg); /* Set new metatable */ + assert(lua_gettop(L) == subcall_last_arg); + result = func(L, base_swig_type, subcall_first_arg, ret); /* Forward call */ + if (result != SWIG_ERROR) { + break; + } } - } - /* Restore original metatable */ - lua_pushvalue(L,original_metatable); - lua_setmetatable(L,first_arg); - /* Clear - remove everything between last_arg and subcall_last_arg including */ - to_remove = subcall_last_arg - last_arg; - for(j=0;jtype; - result = SWIG_Lua_class_do_get(L,type,1,&ret); - if(result == SWIG_OK) - return ret; +SWIGINTERN int SWIG_Lua_class_get(lua_State *L) { + /* there should be 2 params passed in + (1) userdata (not the meta table) + (2) string name of the attribute + */ + int result; + swig_lua_userdata *usr; + swig_type_info *type; + int ret = 0; + assert(lua_isuserdata(L, 1)); + usr = (swig_lua_userdata *)lua_touserdata(L, 1); /* get data */ + type = usr->type; + result = SWIG_Lua_class_do_get(L, type, 1, &ret); + if (result == SWIG_OK) + return ret; - result = SWIG_Lua_class_do_get_item(L,type,1,&ret); - if(result == SWIG_OK) - return ret; + result = SWIG_Lua_class_do_get_item(L, type, 1, &ret); + if (result == SWIG_OK) + return ret; - return 0; + return 0; } /* helper for the class.set method, performs the lookup of class attributes * It returns error code. Number of function return values is passed inside 'ret' */ -SWIGINTERN int SWIG_Lua_class_do_set(lua_State *L, swig_type_info *type, int first_arg, int *ret) -{ -/* there should be 3 params passed in - (1) table (not the meta table) - (2) string name of the attribute - (3) any for the new value - */ +SWIGINTERN int SWIG_Lua_class_do_set(lua_State *L, swig_type_info *type, int first_arg, int *ret) { + /* there should be 3 params passed in + (1) table (not the meta table) + (2) string name of the attribute + (3) any for the new value + */ - int bases_search_result; - int substack_start = lua_gettop(L) - 3; - lua_checkstack(L,5); - assert(lua_isuserdata(L,substack_start+1)); /* just in case */ - lua_getmetatable(L,substack_start+1); /* get the meta table */ - assert(lua_istable(L,-1)); /* just in case */ - if(ret) - *ret = 0; /* it is setter - number of return values is always 0 */ + int bases_search_result; + int substack_start = lua_gettop(L) - 3; + lua_checkstack(L, 5); + assert(lua_isuserdata(L, substack_start + 1)); /* just in case */ + lua_getmetatable(L, substack_start + 1); /* get the meta table */ + assert(lua_istable(L, -1)); /* just in case */ + if (ret) + *ret = 0; /* it is setter - number of return values is always 0 */ - SWIG_Lua_get_table(L,".set"); /* find the .set table */ - if (lua_istable(L,-1)) - { - /* look for the key in the .set table */ - lua_pushvalue(L,substack_start+2); /* key */ - lua_rawget(L,-2); - lua_remove(L,-2); /* tidy stack, remove .set table */ - if (lua_iscfunction(L,-1)) - { /* found it so call the fn & return its value */ - lua_pushvalue(L,substack_start+1); /* userdata */ - lua_pushvalue(L,substack_start+3); /* value */ - lua_call(L,2,0); - lua_remove(L,substack_start+4); /*remove metatable*/ - return SWIG_OK; + SWIG_Lua_get_table(L, ".set"); /* find the .set table */ + if (lua_istable(L, -1)) { + /* look for the key in the .set table */ + lua_pushvalue(L, substack_start + 2); /* key */ + lua_rawget(L, -2); + lua_remove(L, -2); /* tidy stack, remove .set table */ + if (lua_iscfunction(L, -1)) { + /* found it so call the fn & return its value */ + lua_pushvalue(L, substack_start + 1); /* userdata */ + lua_pushvalue(L, substack_start + 3); /* value */ + lua_call(L, 2, 0); + lua_remove(L, substack_start + 4); /*remove metatable*/ + return SWIG_OK; + } + lua_pop(L, 1); /* remove the value */ + } else { + lua_pop(L, 1); /* remove the answer for .set table request*/ } - lua_pop(L,1); /* remove the value */ - } else { - lua_pop(L,1); /* remove the answer for .set table request*/ - } - /* NEW: looks for the __setitem() fn - this is a user provided set fn */ - SWIG_Lua_get_table(L,"__setitem"); /* find the fn */ - if (lua_iscfunction(L,-1)) /* if it's there */ - { /* found it so call the fn & return its value */ - lua_pushvalue(L,substack_start+1); /* the userdata */ - lua_pushvalue(L,substack_start+2); /* the parameter */ - lua_pushvalue(L,substack_start+3); /* the value */ - lua_call(L,3,0); /* 3 values in ,0 out */ - lua_remove(L,-2); /* stack tidy, remove metatable */ - return SWIG_OK; - } - lua_pop(L,1); /* remove value */ + /* NEW: looks for the __setitem() fn + this is a user provided set fn */ + SWIG_Lua_get_table(L, "__setitem"); /* find the fn */ + if (lua_iscfunction(L, -1)) { /* if it's there */ + /* found it so call the fn & return its value */ + lua_pushvalue(L, substack_start + 1); /* the userdata */ + lua_pushvalue(L, substack_start + 2); /* the parameter */ + lua_pushvalue(L, substack_start + 3); /* the value */ + lua_call(L, 3, 0); /* 3 values in ,0 out */ + lua_remove(L, -2); /* stack tidy, remove metatable */ + return SWIG_OK; + } + lua_pop(L, 1); /* remove value */ - lua_pop(L,1); /* remove metatable */ - /* Search among bases */ - bases_search_result = SWIG_Lua_iterate_bases(L,type,first_arg,SWIG_Lua_class_do_set,ret); - if(ret) - assert(*ret == 0); - assert(lua_gettop(L) == substack_start + 3); - return bases_search_result; + lua_pop(L, 1); /* remove metatable */ + /* Search among bases */ + bases_search_result = SWIG_Lua_iterate_bases(L, type, first_arg, SWIG_Lua_class_do_set, ret); + if (ret) + assert(*ret == 0); + assert(lua_gettop(L) == substack_start + 3); + return bases_search_result; } /* This is the actual method exported to Lua. It calls SWIG_Lua_class_do_set and correctly * handles return values. */ -SWIGINTERN int SWIG_Lua_class_set(lua_State *L) -{ -/* There should be 3 params passed in - (1) table (not the meta table) - (2) string name of the attribute - (3) any for the new value - */ - int ret = 0; - int result; - swig_lua_userdata *usr; - swig_type_info *type; - assert(lua_isuserdata(L,1)); - usr=(swig_lua_userdata*)lua_touserdata(L,1); /* get data */ - type = usr->type; - result = SWIG_Lua_class_do_set(L,type,1,&ret); - if(result != SWIG_OK) { - SWIG_Lua_pushferrstring(L,"Assignment not possible. No setter/member with this name. For custom assignments implement __setitem method."); - lua_error(L); - } else { - assert(ret==0); - } - return 0; +SWIGINTERN int SWIG_Lua_class_set(lua_State *L) { + /* There should be 3 params passed in + (1) table (not the meta table) + (2) string name of the attribute + (3) any for the new value + */ + int ret = 0; + int result; + swig_lua_userdata *usr; + swig_type_info *type; + assert(lua_isuserdata(L, 1)); + usr = (swig_lua_userdata *)lua_touserdata(L, 1); /* get data */ + type = usr->type; + result = SWIG_Lua_class_do_set(L, type, 1, &ret); + if (result != SWIG_OK) { + SWIG_Lua_pushferrstring(L, "Assignment not possible. No setter/member with this name. For custom assignments implement __setitem method."); + lua_error(L); + } else { + assert(ret == 0); + } + return 0; } /* the class.destruct method called by the interpreter */ -SWIGINTERN int SWIG_Lua_class_destruct(lua_State *L) -{ -/* there should be 1 params passed in - (1) userdata (not the meta table) */ - swig_lua_userdata *usr; - swig_lua_class *clss; - assert(lua_isuserdata(L,-1)); /* just in case */ - usr=(swig_lua_userdata*)lua_touserdata(L,-1); /* get it */ - /* if must be destroyed & has a destructor */ - if (usr->own) /* if must be destroyed */ - { - clss=(swig_lua_class*)usr->type->clientdata; /* get the class */ - if (clss && clss->destructor) /* there is a destroy fn */ - { - clss->destructor(usr->ptr); /* bye bye */ +SWIGINTERN int SWIG_Lua_class_destruct(lua_State *L) { + /* there should be 1 params passed in + (1) userdata (not the meta table) */ + swig_lua_userdata *usr; + swig_lua_class *clss; + assert(lua_isuserdata(L, -1)); /* just in case */ + usr = (swig_lua_userdata *)lua_touserdata(L, -1); /* get it */ + /* if must be destroyed & has a destructor */ + if (usr->own) { /* if must be destroyed */ + clss = (swig_lua_class *)usr->type->clientdata; /* get the class */ + if (clss && clss->destructor) { /* there is a destroy fn */ + clss->destructor(usr->ptr); /* bye bye */ + } } - } - return 0; + return 0; } /* the class.__tostring method called by the interpreter and print */ -SWIGINTERN int SWIG_Lua_class_tostring(lua_State *L) -{ -/* there should be 1 param passed in - (1) userdata (not the metatable) */ - swig_lua_userdata* userData; - assert(lua_isuserdata(L,1)); /* just in case */ - userData = (swig_lua_userdata*)lua_touserdata(L,1); /* get the userdata address */ +SWIGINTERN int SWIG_Lua_class_tostring(lua_State *L) { + /* there should be 1 param passed in + (1) userdata (not the metatable) */ + swig_lua_userdata *userData; + assert(lua_isuserdata(L, 1)); /* just in case */ + userData = (swig_lua_userdata *)lua_touserdata(L, 1); /* get the userdata address */ - lua_pushfstring(L, "", userData->type->str, userData->ptr); - return 1; + lua_pushfstring(L, "", userData->type->str, userData->ptr); + return 1; } /* to manually disown some userdata */ -SWIGINTERN int SWIG_Lua_class_disown(lua_State *L) -{ -/* there should be 1 params passed in - (1) userdata (not the meta table) */ - swig_lua_userdata *usr; - assert(lua_isuserdata(L,-1)); /* just in case */ - usr=(swig_lua_userdata*)lua_touserdata(L,-1); /* get it */ +SWIGINTERN int SWIG_Lua_class_disown(lua_State *L) { + /* there should be 1 params passed in + (1) userdata (not the meta table) */ + swig_lua_userdata *usr; + assert(lua_isuserdata(L, -1)); /* just in case */ + usr = (swig_lua_userdata *)lua_touserdata(L, -1); /* get it */ - usr->own = 0; /* clear our ownership */ - return 0; + usr->own = 0; /* clear our ownership */ + return 0; } /* lua callable function to compare userdata's value the issue is that two userdata may point to the same thing but to lua, they are different objects */ -SWIGRUNTIME int SWIG_Lua_class_equal(lua_State *L) -{ - int result; - swig_lua_userdata *usr1,*usr2; - if (!lua_isuserdata(L,1) || !lua_isuserdata(L,2)) /* just in case */ - return 0; /* nil reply */ - usr1=(swig_lua_userdata*)lua_touserdata(L,1); /* get data */ - usr2=(swig_lua_userdata*)lua_touserdata(L,2); /* get data */ - /*result=(usr1->ptr==usr2->ptr && usr1->type==usr2->type); only works if type is the same*/ - result=(usr1->ptr==usr2->ptr); - lua_pushboolean(L,result); - return 1; +SWIGRUNTIME int SWIG_Lua_class_equal(lua_State *L) { + int result; + swig_lua_userdata *usr1, *usr2; + if (!lua_isuserdata(L, 1) || !lua_isuserdata(L, 2)) /* just in case */ + return 0; /* nil reply */ + usr1 = (swig_lua_userdata *)lua_touserdata(L, 1); /* get data */ + usr2 = (swig_lua_userdata *)lua_touserdata(L, 2); /* get data */ + /*result=(usr1->ptr==usr2->ptr && usr1->type==usr2->type); only works if type is the same*/ + result = (usr1->ptr == usr2->ptr); + lua_pushboolean(L, result); + return 1; } /* populate table at the top of the stack with metamethods that ought to be inherited */ -SWIGINTERN void SWIG_Lua_populate_inheritable_metamethods(lua_State *L) -{ - SWIG_Lua_add_boolean(L, "__add", 1); - SWIG_Lua_add_boolean(L, "__sub", 1); - SWIG_Lua_add_boolean(L, "__mul", 1); - SWIG_Lua_add_boolean(L, "__div", 1); - SWIG_Lua_add_boolean(L, "__mod", 1); - SWIG_Lua_add_boolean(L, "__pow", 1); - SWIG_Lua_add_boolean(L, "__unm", 1); - SWIG_Lua_add_boolean(L, "__len", 1 ); - SWIG_Lua_add_boolean(L, "__concat", 1 ); - SWIG_Lua_add_boolean(L, "__eq", 1); - SWIG_Lua_add_boolean(L, "__lt", 1); - SWIG_Lua_add_boolean(L, "__le", 1); - SWIG_Lua_add_boolean(L, "__call", 1); - SWIG_Lua_add_boolean(L, "__tostring", 1); - SWIG_Lua_add_boolean(L, "__gc", 0); +SWIGINTERN void SWIG_Lua_populate_inheritable_metamethods(lua_State *L) { + SWIG_Lua_add_boolean(L, "__add", 1); + SWIG_Lua_add_boolean(L, "__sub", 1); + SWIG_Lua_add_boolean(L, "__mul", 1); + SWIG_Lua_add_boolean(L, "__div", 1); + SWIG_Lua_add_boolean(L, "__mod", 1); + SWIG_Lua_add_boolean(L, "__pow", 1); + SWIG_Lua_add_boolean(L, "__unm", 1); + SWIG_Lua_add_boolean(L, "__len", 1); + SWIG_Lua_add_boolean(L, "__concat", 1); + SWIG_Lua_add_boolean(L, "__eq", 1); + SWIG_Lua_add_boolean(L, "__lt", 1); + SWIG_Lua_add_boolean(L, "__le", 1); + SWIG_Lua_add_boolean(L, "__call", 1); + SWIG_Lua_add_boolean(L, "__tostring", 1); + SWIG_Lua_add_boolean(L, "__gc", 0); } /* creates the swig registry */ -SWIGINTERN void SWIG_Lua_create_class_registry(lua_State *L) -{ - /* create main SWIG registry table */ - lua_pushstring(L,"SWIG"); - lua_newtable(L); - /* populate it with some predefined data */ - - /* .library table. Placeholder */ - lua_pushstring(L,".library"); - lua_newtable(L); - { - /* list of metamethods that class inherits from its bases */ - lua_pushstring(L,"inheritable_metamethods"); +SWIGINTERN void SWIG_Lua_create_class_registry(lua_State *L) { + /* create main SWIG registry table */ + lua_pushstring(L, "SWIG"); lua_newtable(L); - /* populate with list of metamethods */ - SWIG_Lua_populate_inheritable_metamethods(L); - lua_rawset(L,-3); - } - lua_rawset(L,-3); + /* populate it with some predefined data */ - lua_rawset(L,LUA_REGISTRYINDEX); + /* .library table. Placeholder */ + lua_pushstring(L, ".library"); + lua_newtable(L); + { + /* list of metamethods that class inherits from its bases */ + lua_pushstring(L, "inheritable_metamethods"); + lua_newtable(L); + /* populate with list of metamethods */ + SWIG_Lua_populate_inheritable_metamethods(L); + lua_rawset(L, -3); + } + lua_rawset(L, -3); + + lua_rawset(L, LUA_REGISTRYINDEX); } /* gets the swig registry (or creates it) */ -SWIGINTERN void SWIG_Lua_get_class_registry(lua_State *L) -{ - /* add this all into the swig registry: */ - lua_pushstring(L,"SWIG"); - lua_rawget(L,LUA_REGISTRYINDEX); /* get the registry */ - if (!lua_istable(L,-1)) /* not there */ - { /* must be first time, so add it */ - lua_pop(L,1); /* remove the result */ - SWIG_Lua_create_class_registry(L); - /* then get it */ - lua_pushstring(L,"SWIG"); - lua_rawget(L,LUA_REGISTRYINDEX); - } +SWIGINTERN void SWIG_Lua_get_class_registry(lua_State *L) { + /* add this all into the swig registry: */ + lua_pushstring(L, "SWIG"); + lua_rawget(L, LUA_REGISTRYINDEX); /* get the registry */ + if (!lua_istable(L, -1)) { /* not there */ + /* must be first time, so add it */ + lua_pop(L, 1); /* remove the result */ + SWIG_Lua_create_class_registry(L); + /* then get it */ + lua_pushstring(L, "SWIG"); + lua_rawget(L, LUA_REGISTRYINDEX); + } } -SWIGINTERN void SWIG_Lua_get_inheritable_metamethods(lua_State *L) -{ - SWIG_Lua_get_class_registry(L); - lua_pushstring(L, ".library"); - lua_rawget(L,-2); - assert( !lua_isnil(L,-1) ); - lua_pushstring(L, "inheritable_metamethods"); - lua_rawget(L,-2); +SWIGINTERN void SWIG_Lua_get_inheritable_metamethods(lua_State *L) { + SWIG_Lua_get_class_registry(L); + lua_pushstring(L, ".library"); + lua_rawget(L, -2); + assert(!lua_isnil(L, -1)); + lua_pushstring(L, "inheritable_metamethods"); + lua_rawget(L, -2); - /* Remove class registry and library table */ - lua_remove(L,-2); - lua_remove(L,-2); + /* Remove class registry and library table */ + lua_remove(L, -2); + lua_remove(L, -2); } /* Helper function to get the classes metatable from the register */ -SWIGINTERN void SWIG_Lua_get_class_metatable(lua_State *L,const char *cname) -{ - SWIG_Lua_get_class_registry(L); /* get the registry */ - lua_pushstring(L,cname); /* get the name */ - lua_rawget(L,-2); /* get it */ - lua_remove(L,-2); /* tidy up (remove registry) */ +SWIGINTERN void SWIG_Lua_get_class_metatable(lua_State *L, const char *cname) { + SWIG_Lua_get_class_registry(L); /* get the registry */ + lua_pushstring(L, cname); /* get the name */ + lua_rawget(L, -2); /* get it */ + lua_remove(L, -2); /* tidy up (remove registry) */ } /* Set up the base classes pointers. @@ -1949,165 +1915,151 @@ It cannot be done at compile time, as this will not work with hireachies spread over more than one swig file. Therefore it must be done at runtime, querying the SWIG type system. */ -SWIGINTERN void SWIG_Lua_init_base_class(lua_State *L,swig_lua_class *clss) -{ - int i=0; - swig_module_info *module=SWIG_GetModule(L); - for(i=0;clss->base_names[i];i++) - { - if (clss->bases[i]==0) /* not found yet */ - { - /* lookup and cache the base class */ - swig_type_info *info = SWIG_TypeQueryModule(module,module,clss->base_names[i]); - if (info) clss->bases[i] = (swig_lua_class *) info->clientdata; +SWIGINTERN void SWIG_Lua_init_base_class(lua_State *L, swig_lua_class *clss) { + int i = 0; + swig_module_info *module = SWIG_GetModule(L); + for (i = 0; clss->base_names[i]; i++) { + if (clss->bases[i] == 0) { /* not found yet */ + /* lookup and cache the base class */ + swig_type_info *info = SWIG_TypeQueryModule(module, module, clss->base_names[i]); + if (info) clss->bases[i] = (swig_lua_class *) info->clientdata; + } } - } } #if defined(SWIG_LUA_SQUASH_BASES) && (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) /* Merges two tables */ -SWIGINTERN void SWIG_Lua_merge_tables_by_index(lua_State *L, int target, int source) -{ - /* iterating */ - lua_pushnil(L); - while (lua_next(L,source) != 0) { - /* -1 - value, -2 - index */ - /* have to copy to assign */ - lua_pushvalue(L,-2); /* copy of index */ - lua_pushvalue(L,-2); /* copy of value */ - lua_rawset(L, target); - lua_pop(L,1); - /* only key is left */ - } +SWIGINTERN void SWIG_Lua_merge_tables_by_index(lua_State *L, int target, int source) { + /* iterating */ + lua_pushnil(L); + while (lua_next(L, source) != 0) { + /* -1 - value, -2 - index */ + /* have to copy to assign */ + lua_pushvalue(L, -2); /* copy of index */ + lua_pushvalue(L, -2); /* copy of value */ + lua_rawset(L, target); + lua_pop(L, 1); + /* only key is left */ + } } /* Merges two tables with given name. original - index of target metatable, base - index of source metatable */ -SWIGINTERN void SWIG_Lua_merge_tables(lua_State *L, const char* name, int original, int base) -{ - /* push original[name], then base[name] */ - lua_pushstring(L,name); - lua_rawget(L,original); - int original_table = lua_gettop(L); - lua_pushstring(L,name); - lua_rawget(L,base); - int base_table = lua_gettop(L); - SWIG_Lua_merge_tables_by_index(L, original_table, base_table); - /* clearing stack */ - lua_pop(L,2); +SWIGINTERN void SWIG_Lua_merge_tables(lua_State *L, const char *name, int original, int base) { + /* push original[name], then base[name] */ + lua_pushstring(L, name); + lua_rawget(L, original); + int original_table = lua_gettop(L); + lua_pushstring(L, name); + lua_rawget(L, base); + int base_table = lua_gettop(L); + SWIG_Lua_merge_tables_by_index(L, original_table, base_table); + /* clearing stack */ + lua_pop(L, 2); } /* Function takes all symbols from base and adds it to derived class. It's just a helper. */ -SWIGINTERN void SWIG_Lua_class_squash_base(lua_State *L, swig_lua_class *base_cls) -{ - /* There is one parameter - original, i.e. 'derived' class metatable */ - assert(lua_istable(L,-1)); - int original = lua_gettop(L); - SWIG_Lua_get_class_metatable(L,base_cls->fqname); - int base = lua_gettop(L); - SWIG_Lua_merge_tables(L, ".fn", original, base ); - SWIG_Lua_merge_tables(L, ".set", original, base ); - SWIG_Lua_merge_tables(L, ".get", original, base ); - lua_pop(L,1); +SWIGINTERN void SWIG_Lua_class_squash_base(lua_State *L, swig_lua_class *base_cls) { + /* There is one parameter - original, i.e. 'derived' class metatable */ + assert(lua_istable(L, -1)); + int original = lua_gettop(L); + SWIG_Lua_get_class_metatable(L, base_cls->fqname); + int base = lua_gettop(L); + SWIG_Lua_merge_tables(L, ".fn", original, base); + SWIG_Lua_merge_tables(L, ".set", original, base); + SWIG_Lua_merge_tables(L, ".get", original, base); + lua_pop(L, 1); } /* Function squashes all symbols from 'clss' bases into itself */ -SWIGINTERN void SWIG_Lua_class_squash_bases(lua_State *L, swig_lua_class *clss) -{ - int i; - SWIG_Lua_get_class_metatable(L,clss->fqname); - for(i=0;clss->base_names[i];i++) - { - if (clss->bases[i]==0) /* Somehow it's not found. Skip it */ - continue; - /* Thing is: all bases are already registered. Thus they have already executed - * this function. So we just need to squash them into us, because their bases - * are already squashed into them. No need for recursion here! - */ - SWIG_Lua_class_squash_base(L, clss->bases[i]); - } - lua_pop(L,1); /*tidy stack*/ +SWIGINTERN void SWIG_Lua_class_squash_bases(lua_State *L, swig_lua_class *clss) { + int i; + SWIG_Lua_get_class_metatable(L, clss->fqname); + for (i = 0; clss->base_names[i]; i++) { + if (clss->bases[i] == 0) /* Somehow it's not found. Skip it */ + continue; + /* Thing is: all bases are already registered. Thus they have already executed + * this function. So we just need to squash them into us, because their bases + * are already squashed into them. No need for recursion here! + */ + SWIG_Lua_class_squash_base(L, clss->bases[i]); + } + lua_pop(L, 1); /*tidy stack*/ } #endif #if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) /* In elua this is useless */ /* helper add a variable to a registered class */ -SWIGINTERN void SWIG_Lua_add_variable(lua_State *L,const char *name,lua_CFunction getFn,lua_CFunction setFn) -{ - assert(lua_istable(L,-1)); /* just in case */ - SWIG_Lua_get_table(L,".get"); /* find the .get table */ - assert(lua_istable(L,-1)); /* just in case */ - SWIG_Lua_add_function(L,name,getFn); - lua_pop(L,1); /* tidy stack (remove table) */ - if (setFn) - { - SWIG_Lua_get_table(L,".set"); /* find the .set table */ - assert(lua_istable(L,-1)); /* just in case */ - SWIG_Lua_add_function(L,name,setFn); - lua_pop(L,1); /* tidy stack (remove table) */ - } +SWIGINTERN void SWIG_Lua_add_variable(lua_State *L, const char *name, lua_CFunction getFn, lua_CFunction setFn) { + assert(lua_istable(L, -1)); /* just in case */ + SWIG_Lua_get_table(L, ".get"); /* find the .get table */ + assert(lua_istable(L, -1)); /* just in case */ + SWIG_Lua_add_function(L, name, getFn); + lua_pop(L, 1); /* tidy stack (remove table) */ + if (setFn) { + SWIG_Lua_get_table(L, ".set"); /* find the .set table */ + assert(lua_istable(L, -1)); /* just in case */ + SWIG_Lua_add_function(L, name, setFn); + lua_pop(L, 1); /* tidy stack (remove table) */ + } } /* helper to recursively add class static details (static attributes, operations and constants) */ -SWIGINTERN void SWIG_Lua_add_class_static_details(lua_State *L, swig_lua_class *clss) -{ - int i = 0; - /* The class namespace table must be on the top of the stack */ - assert(lua_istable(L,-1)); - /* call all the base classes first: we can then override these later: */ - for(i=0;clss->bases[i];i++) - { - SWIG_Lua_add_class_static_details(L,clss->bases[i]); - } +SWIGINTERN void SWIG_Lua_add_class_static_details(lua_State *L, swig_lua_class *clss) { + int i = 0; + /* The class namespace table must be on the top of the stack */ + assert(lua_istable(L, -1)); + /* call all the base classes first: we can then override these later: */ + for (i = 0; clss->bases[i]; i++) { + SWIG_Lua_add_class_static_details(L, clss->bases[i]); + } - SWIG_Lua_add_namespace_details(L, clss->cls_static); + SWIG_Lua_add_namespace_details(L, clss->cls_static); } SWIGINTERN void SWIG_Lua_add_class_user_metamethods(lua_State *L, swig_lua_class *clss); /* forward declaration */ /* helper to recursively add class details (attributes & operations) */ -SWIGINTERN void SWIG_Lua_add_class_instance_details(lua_State *L, swig_lua_class *clss) -{ - int i; - size_t bases_count = 0; - /* Add bases to .bases table */ - SWIG_Lua_get_table(L,".bases"); - assert(lua_istable(L,-1)); /* just in case */ - for(i=0;clss->bases[i];i++) - { - SWIG_Lua_get_class_metatable(L,clss->bases[i]->fqname); - /* Base class must be already registered */ - assert(lua_istable(L,-1)); - lua_rawseti(L,-2,i+1); /* In lua indexing starts from 1 */ - bases_count++; - } - assert(lua_rawlen(L,-1) == bases_count); - lua_pop(L,1); /* remove .bases table */ - /* add attributes */ - for(i=0;clss->attributes[i].name;i++){ - SWIG_Lua_add_variable(L,clss->attributes[i].name,clss->attributes[i].getmethod,clss->attributes[i].setmethod); - } - /* add methods to the metatable */ - SWIG_Lua_get_table(L,".fn"); /* find the .fn table */ - assert(lua_istable(L,-1)); /* just in case */ - for(i=0;clss->methods[i].name;i++){ - SWIG_Lua_add_function(L,clss->methods[i].name,clss->methods[i].func); - } - lua_pop(L,1); /* tidy stack (remove table) */ - /* add operator overloads - This adds methods from metatable array to metatable. Can mess up garbage - collectind if someone defines __gc method - */ - if(clss->metatable) { - for(i=0;clss->metatable[i].name;i++) { - SWIG_Lua_add_function(L,clss->metatable[i].name,clss->metatable[i].func); +SWIGINTERN void SWIG_Lua_add_class_instance_details(lua_State *L, swig_lua_class *clss) { + int i; + size_t bases_count = 0; + /* Add bases to .bases table */ + SWIG_Lua_get_table(L, ".bases"); + assert(lua_istable(L, -1)); /* just in case */ + for (i = 0; clss->bases[i]; i++) { + SWIG_Lua_get_class_metatable(L, clss->bases[i]->fqname); + /* Base class must be already registered */ + assert(lua_istable(L, -1)); + lua_rawseti(L, -2, i + 1); /* In lua indexing starts from 1 */ + bases_count++; + } + assert(lua_rawlen(L, -1) == bases_count); + lua_pop(L, 1); /* remove .bases table */ + /* add attributes */ + for (i = 0; clss->attributes[i].name; i++) { + SWIG_Lua_add_variable(L, clss->attributes[i].name, clss->attributes[i].getmethod, clss->attributes[i].setmethod); + } + /* add methods to the metatable */ + SWIG_Lua_get_table(L, ".fn"); /* find the .fn table */ + assert(lua_istable(L, -1)); /* just in case */ + for (i = 0; clss->methods[i].name; i++) { + SWIG_Lua_add_function(L, clss->methods[i].name, clss->methods[i].func); + } + lua_pop(L, 1); /* tidy stack (remove table) */ + /* add operator overloads + This adds methods from metatable array to metatable. Can mess up garbage + collectind if someone defines __gc method + */ + if (clss->metatable) { + for (i = 0; clss->metatable[i].name; i++) { + SWIG_Lua_add_function(L, clss->metatable[i].name, clss->metatable[i].func); + } } - } #if !defined(SWIG_LUA_SQUASH_BASES) - /* Adding metamethods that are defined in base classes. If bases were squashed - * then it is obviously unnecessary - */ - SWIG_Lua_add_class_user_metamethods(L, clss); + /* Adding metamethods that are defined in base classes. If bases were squashed + * then it is obviously unnecessary + */ + SWIG_Lua_add_class_user_metamethods(L, clss); #endif } @@ -2137,70 +2089,67 @@ SWIGRUNTIME int SWIG_Lua_resolve_metamethod(lua_State *L); /*forward declaration * SWIG_Lua_resolve_metamethod * */ SWIGINTERN int SWIG_Lua_do_resolve_metamethod(lua_State *L, const swig_lua_class *clss, int metamethod_name_idx, - int skip_check) -{ - /* This function is called recursively */ - int result = 0; - int i = 0; + int skip_check) { + /* This function is called recursively */ + int result = 0; + int i = 0; - if (!skip_check) { - SWIG_Lua_get_class_metatable(L, clss->fqname); - lua_pushvalue(L, metamethod_name_idx); - lua_rawget(L,-2); - /* If this is cfunction and it is equal to SWIG_Lua_resolve_metamethod then - * this isn't the function we are looking for :) - * lua_tocfunction will return NULL if not cfunction - */ - if (!lua_isnil(L,-1) && lua_tocfunction(L,-1) != SWIG_Lua_resolve_metamethod ) { - lua_remove(L,-2); /* removing class metatable */ - return 1; + if (!skip_check) { + SWIG_Lua_get_class_metatable(L, clss->fqname); + lua_pushvalue(L, metamethod_name_idx); + lua_rawget(L, -2); + /* If this is cfunction and it is equal to SWIG_Lua_resolve_metamethod then + * this isn't the function we are looking for :) + * lua_tocfunction will return NULL if not cfunction + */ + if (!lua_isnil(L, -1) && lua_tocfunction(L, -1) != SWIG_Lua_resolve_metamethod) { + lua_remove(L, -2); /* removing class metatable */ + return 1; + } + lua_pop(L, 2); /* remove class metatable and query result */ } - lua_pop(L,2); /* remove class metatable and query result */ - } - /* Forwarding calls to bases */ - for(i=0;clss->bases[i];i++) - { - result = SWIG_Lua_do_resolve_metamethod(L, clss->bases[i], metamethod_name_idx, 0); - if (result) - break; - } + /* Forwarding calls to bases */ + for (i = 0; clss->bases[i]; i++) { + result = SWIG_Lua_do_resolve_metamethod(L, clss->bases[i], metamethod_name_idx, 0); + if (result) + break; + } - return result; + return result; } /* The proxy function for metamethod. All parameters are passed as cclosure. Searches for actual method * and calls it */ -SWIGRUNTIME int SWIG_Lua_resolve_metamethod(lua_State *L) -{ - int numargs; - int metamethod_name_idx; - const swig_lua_class* clss; - int result; +SWIGRUNTIME int SWIG_Lua_resolve_metamethod(lua_State *L) { + int numargs; + int metamethod_name_idx; + const swig_lua_class *clss; + int result; - lua_checkstack(L,5); - numargs = lua_gettop(L); /* number of arguments to pass to actual metamethod */ + lua_checkstack(L, 5); + numargs = lua_gettop(L); /* number of arguments to pass to actual metamethod */ - /* Get upvalues from closure */ - lua_pushvalue(L, lua_upvalueindex(1)); /*Get function name*/ - metamethod_name_idx = lua_gettop(L); + /* Get upvalues from closure */ + lua_pushvalue(L, lua_upvalueindex(1)); /*Get function name*/ + metamethod_name_idx = lua_gettop(L); - lua_pushvalue(L, lua_upvalueindex(2)); - clss = (const swig_lua_class*)(lua_touserdata(L,-1)); - lua_pop(L,1); /* remove lightuserdata with clss from stack */ + lua_pushvalue(L, lua_upvalueindex(2)); + clss = (const swig_lua_class *)(lua_touserdata(L, -1)); + lua_pop(L, 1); /* remove lightuserdata with clss from stack */ - /* Actual work */ - result = SWIG_Lua_do_resolve_metamethod(L, clss, metamethod_name_idx, 1); - if (!result) { - SWIG_Lua_pushferrstring(L,"The metamethod proxy is set, but it failed to find actual metamethod. Memory corruption is most likely explanation."); - lua_error(L); - return 0; - } + /* Actual work */ + result = SWIG_Lua_do_resolve_metamethod(L, clss, metamethod_name_idx, 1); + if (!result) { + SWIG_Lua_pushferrstring(L, "The metamethod proxy is set, but it failed to find actual metamethod. Memory corruption is most likely explanation."); + lua_error(L); + return 0; + } - lua_remove(L,-2); /* remove metamethod key */ - lua_insert(L,1); /* move function to correct position */ - lua_call(L, numargs, LUA_MULTRET); - return lua_gettop(L); /* return all results */ + lua_remove(L, -2); /* remove metamethod key */ + lua_insert(L, 1); /* move function to correct position */ + lua_call(L, numargs, LUA_MULTRET); + return lua_gettop(L); /* return all results */ } @@ -2208,292 +2157,281 @@ SWIGRUNTIME int SWIG_Lua_resolve_metamethod(lua_State *L) * Returns 1 if successfully added, 0 if not added because no base class has it, -1 * if method is defined in the class metatable itself */ -SWIGINTERN int SWIG_Lua_add_class_user_metamethod(lua_State *L, swig_lua_class *clss, const int metatable_index) -{ - int key_index; - int success = 0; - int i = 0; +SWIGINTERN int SWIG_Lua_add_class_user_metamethod(lua_State *L, swig_lua_class *clss, const int metatable_index) { + int key_index; + int success = 0; + int i = 0; - /* metamethod name - on the top of the stack */ - assert(lua_isstring(L,-1)); + /* metamethod name - on the top of the stack */ + assert(lua_isstring(L, -1)); - key_index = lua_gettop(L); + key_index = lua_gettop(L); - /* Check whether method is already defined in metatable */ - lua_pushvalue(L,key_index); /* copy of the key */ - lua_gettable(L,metatable_index); - if( !lua_isnil(L,-1) ) { - lua_pop(L,1); - return -1; - } - lua_pop(L,1); - - /* Iterating over immediate bases */ - for(i=0;clss->bases[i];i++) - { - const swig_lua_class *base = clss->bases[i]; - SWIG_Lua_get_class_metatable(L, base->fqname); - lua_pushvalue(L, key_index); - lua_rawget(L, -2); - if( !lua_isnil(L,-1) ) { - lua_pushvalue(L, key_index); - - /* Add proxy function */ - lua_pushvalue(L, key_index); /* first closure value is function name */ - lua_pushlightuserdata(L, clss); /* second closure value is swig_lua_class structure */ - lua_pushcclosure(L, SWIG_Lua_resolve_metamethod, 2); - - lua_rawset(L, metatable_index); - success = 1; + /* Check whether method is already defined in metatable */ + lua_pushvalue(L, key_index); /* copy of the key */ + lua_gettable(L, metatable_index); + if (!lua_isnil(L, -1)) { + lua_pop(L, 1); + return -1; } - lua_pop(L,1); /* remove function or nil */ - lua_pop(L,1); /* remove base class metatable */ + lua_pop(L, 1); - if( success ) - break; - } + /* Iterating over immediate bases */ + for (i = 0; clss->bases[i]; i++) { + const swig_lua_class *base = clss->bases[i]; + SWIG_Lua_get_class_metatable(L, base->fqname); + lua_pushvalue(L, key_index); + lua_rawget(L, -2); + if (!lua_isnil(L, -1)) { + lua_pushvalue(L, key_index); - return success; + /* Add proxy function */ + lua_pushvalue(L, key_index); /* first closure value is function name */ + lua_pushlightuserdata(L, clss); /* second closure value is swig_lua_class structure */ + lua_pushcclosure(L, SWIG_Lua_resolve_metamethod, 2); + + lua_rawset(L, metatable_index); + success = 1; + } + lua_pop(L, 1); /* remove function or nil */ + lua_pop(L, 1); /* remove base class metatable */ + + if (success) + break; + } + + return success; } -SWIGINTERN void SWIG_Lua_add_class_user_metamethods(lua_State *L, swig_lua_class *clss) -{ - int metatable_index; - int metamethods_info_index; - int tostring_undefined; - int eq_undefined = 0; +SWIGINTERN void SWIG_Lua_add_class_user_metamethods(lua_State *L, swig_lua_class *clss) { + int metatable_index; + int metamethods_info_index; + int tostring_undefined; + int eq_undefined = 0; - SWIG_Lua_get_class_metatable(L, clss->fqname); - metatable_index = lua_gettop(L); - SWIG_Lua_get_inheritable_metamethods(L); - assert(lua_istable(L,-1)); - metamethods_info_index = lua_gettop(L); - lua_pushnil(L); /* first key */ - while(lua_next(L, metamethods_info_index) != 0 ) { - /* key at index -2, value at index -1 */ - const int is_inheritable = lua_toboolean(L,-2); - lua_pop(L,1); /* remove value - we don't need it anymore */ + SWIG_Lua_get_class_metatable(L, clss->fqname); + metatable_index = lua_gettop(L); + SWIG_Lua_get_inheritable_metamethods(L); + assert(lua_istable(L, -1)); + metamethods_info_index = lua_gettop(L); + lua_pushnil(L); /* first key */ + while (lua_next(L, metamethods_info_index) != 0) { + /* key at index -2, value at index -1 */ + const int is_inheritable = lua_toboolean(L, -2); + lua_pop(L, 1); /* remove value - we don't need it anymore */ - if(is_inheritable) { /* if metamethod is inheritable */ - SWIG_Lua_add_class_user_metamethod(L,clss,metatable_index); + if (is_inheritable) { /* if metamethod is inheritable */ + SWIG_Lua_add_class_user_metamethod(L, clss, metatable_index); + } } - } - lua_pop(L,1); /* remove inheritable metamethods table */ + lua_pop(L, 1); /* remove inheritable metamethods table */ - /* Special handling for __tostring method */ - lua_pushstring(L, "__tostring"); - lua_pushvalue(L,-1); - lua_rawget(L,metatable_index); - tostring_undefined = lua_isnil(L,-1); - lua_pop(L,1); - if( tostring_undefined ) { - lua_pushcfunction(L, SWIG_Lua_class_tostring); - lua_rawset(L, metatable_index); - } else { - lua_pop(L,1); /* remove copy of the key */ - } + /* Special handling for __tostring method */ + lua_pushstring(L, "__tostring"); + lua_pushvalue(L, -1); + lua_rawget(L, metatable_index); + tostring_undefined = lua_isnil(L, -1); + lua_pop(L, 1); + if (tostring_undefined) { + lua_pushcfunction(L, SWIG_Lua_class_tostring); + lua_rawset(L, metatable_index); + } else { + lua_pop(L, 1); /* remove copy of the key */ + } - /* Special handling for __eq method */ - lua_pushstring(L, "__eq"); - lua_pushvalue(L,-1); - lua_rawget(L,metatable_index); - eq_undefined = lua_isnil(L,-1); - lua_pop(L,1); - if( eq_undefined ) { - lua_pushcfunction(L, SWIG_Lua_class_equal); - lua_rawset(L, metatable_index); - } else { - lua_pop(L,1); /* remove copy of the key */ - } - /* Warning: __index and __newindex are SWIG-defined. For user-defined operator[] - * a __getitem/__setitem method should be defined - */ - lua_pop(L,1); /* pop class metatable */ + /* Special handling for __eq method */ + lua_pushstring(L, "__eq"); + lua_pushvalue(L, -1); + lua_rawget(L, metatable_index); + eq_undefined = lua_isnil(L, -1); + lua_pop(L, 1); + if (eq_undefined) { + lua_pushcfunction(L, SWIG_Lua_class_equal); + lua_rawset(L, metatable_index); + } else { + lua_pop(L, 1); /* remove copy of the key */ + } + /* Warning: __index and __newindex are SWIG-defined. For user-defined operator[] + * a __getitem/__setitem method should be defined + */ + lua_pop(L, 1); /* pop class metatable */ } /* Register class static methods,attributes etc as well as constructor proxy */ -SWIGINTERN void SWIG_Lua_class_register_static(lua_State *L, swig_lua_class *clss) -{ - const int SWIGUNUSED begin = lua_gettop(L); - lua_checkstack(L,5); /* just in case */ - assert(lua_istable(L,-1)); /* just in case */ - assert(strcmp(clss->name, clss->cls_static->name) == 0); /* in class those 2 must be equal */ +SWIGINTERN void SWIG_Lua_class_register_static(lua_State *L, swig_lua_class *clss) { + const int SWIGUNUSED begin = lua_gettop(L); + lua_checkstack(L, 5); /* just in case */ + assert(lua_istable(L, -1)); /* just in case */ + assert(strcmp(clss->name, clss->cls_static->name) == 0); /* in class those 2 must be equal */ - SWIG_Lua_namespace_register(L,clss->cls_static, 1); + SWIG_Lua_namespace_register(L, clss->cls_static, 1); - assert(lua_istable(L,-1)); /* just in case */ + assert(lua_istable(L, -1)); /* just in case */ - /* add its constructor to module with the name of the class - so you can do MyClass(...) as well as new_MyClass(...) - BUT only if a constructor is defined - (this overcomes the problem of pure virtual classes without constructors)*/ - if (clss->constructor) - { - lua_getmetatable(L,-1); - assert(lua_istable(L,-1)); /* just in case */ - SWIG_Lua_add_function(L,"__call", clss->constructor); - lua_pop(L,1); - } + /* add its constructor to module with the name of the class + so you can do MyClass(...) as well as new_MyClass(...) + BUT only if a constructor is defined + (this overcomes the problem of pure virtual classes without constructors)*/ + if (clss->constructor) { + lua_getmetatable(L, -1); + assert(lua_istable(L, -1)); /* just in case */ + SWIG_Lua_add_function(L, "__call", clss->constructor); + lua_pop(L, 1); + } - assert(lua_istable(L,-1)); /* just in case */ - SWIG_Lua_add_class_static_details(L, clss); + assert(lua_istable(L, -1)); /* just in case */ + SWIG_Lua_add_class_static_details(L, clss); - /* clear stack */ - lua_pop(L,1); - assert( lua_gettop(L) == begin ); + /* clear stack */ + lua_pop(L, 1); + assert(lua_gettop(L) == begin); } /* Performs the instance (non-static) class registration process. Metatable for class is created * and added to the class registry. */ -SWIGINTERN void SWIG_Lua_class_register_instance(lua_State *L,swig_lua_class *clss) -{ - const int SWIGUNUSED begin = lua_gettop(L); - int i; - /* if name already there (class is already registered) then do nothing */ - SWIG_Lua_get_class_registry(L); /* get the registry */ - lua_pushstring(L,clss->fqname); /* get the name */ - lua_rawget(L,-2); - if(!lua_isnil(L,-1)) { - lua_pop(L,2); - assert(lua_gettop(L)==begin); - return; - } - lua_pop(L,2); /* tidy stack */ - /* Recursively initialize all bases */ - for(i=0;clss->bases[i];i++) - { - SWIG_Lua_class_register_instance(L,clss->bases[i]); - } - /* Again, get registry and push name */ - SWIG_Lua_get_class_registry(L); /* get the registry */ - lua_pushstring(L,clss->fqname); /* get the name */ - lua_newtable(L); /* create the metatable */ -#if defined(SWIG_LUA_SQUASH_BASES) && (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) - /* If squashing is requested, then merges all bases metatable into this one. - * It would get us all special methods: __getitem, __add etc. - * This would set .fn, .type, and other .xxx incorrectly, but we will overwrite it right away - */ - { - int new_metatable_index = lua_absindex(L,-1); - for(i=0;clss->bases[i];i++) - { - int base_metatable; - SWIG_Lua_get_class_metatable(L,clss->bases[i]->fqname); - base_metatable = lua_absindex(L,-1); - SWIG_Lua_merge_tables_by_index(L,new_metatable_index, base_metatable); - lua_pop(L,1); +SWIGINTERN void SWIG_Lua_class_register_instance(lua_State *L, swig_lua_class *clss) { + const int SWIGUNUSED begin = lua_gettop(L); + int i; + /* if name already there (class is already registered) then do nothing */ + SWIG_Lua_get_class_registry(L); /* get the registry */ + lua_pushstring(L, clss->fqname); /* get the name */ + lua_rawget(L, -2); + if (!lua_isnil(L, -1)) { + lua_pop(L, 2); + assert(lua_gettop(L) == begin); + return; } - } - /* And now we will overwrite all incorrectly set data */ + lua_pop(L, 2); /* tidy stack */ + /* Recursively initialize all bases */ + for (i = 0; clss->bases[i]; i++) { + SWIG_Lua_class_register_instance(L, clss->bases[i]); + } + /* Again, get registry and push name */ + SWIG_Lua_get_class_registry(L); /* get the registry */ + lua_pushstring(L, clss->fqname); /* get the name */ + lua_newtable(L); /* create the metatable */ +#if defined(SWIG_LUA_SQUASH_BASES) && (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) + /* If squashing is requested, then merges all bases metatable into this one. + * It would get us all special methods: __getitem, __add etc. + * This would set .fn, .type, and other .xxx incorrectly, but we will overwrite it right away + */ + { + int new_metatable_index = lua_absindex(L, -1); + for (i = 0; clss->bases[i]; i++) { + int base_metatable; + SWIG_Lua_get_class_metatable(L, clss->bases[i]->fqname); + base_metatable = lua_absindex(L, -1); + SWIG_Lua_merge_tables_by_index(L, new_metatable_index, base_metatable); + lua_pop(L, 1); + } + } + /* And now we will overwrite all incorrectly set data */ #endif - /* add string of class name called ".type" */ - lua_pushstring(L,".type"); - lua_pushstring(L,clss->fqname); - lua_rawset(L,-3); - /* add a table called bases */ - lua_pushstring(L,".bases"); - lua_newtable(L); - lua_rawset(L,-3); - /* add a table called ".get" */ - lua_pushstring(L,".get"); - lua_newtable(L); - lua_rawset(L,-3); - /* add a table called ".set" */ - lua_pushstring(L,".set"); - lua_newtable(L); - lua_rawset(L,-3); - /* add a table called ".fn" */ - lua_pushstring(L,".fn"); - lua_newtable(L); - /* add manual disown method */ - SWIG_Lua_add_function(L,"__disown",SWIG_Lua_class_disown); - lua_rawset(L,-3); - /* add accessor fns for using the .get,.set&.fn */ - SWIG_Lua_add_function(L,"__index",SWIG_Lua_class_get); - SWIG_Lua_add_function(L,"__newindex",SWIG_Lua_class_set); - SWIG_Lua_add_function(L,"__gc",SWIG_Lua_class_destruct); - /* add it */ - lua_rawset(L,-3); /* metatable into registry */ - lua_pop(L,1); /* tidy stack (remove registry) */ - assert(lua_gettop(L) == begin); + /* add string of class name called ".type" */ + lua_pushstring(L, ".type"); + lua_pushstring(L, clss->fqname); + lua_rawset(L, -3); + /* add a table called bases */ + lua_pushstring(L, ".bases"); + lua_newtable(L); + lua_rawset(L, -3); + /* add a table called ".get" */ + lua_pushstring(L, ".get"); + lua_newtable(L); + lua_rawset(L, -3); + /* add a table called ".set" */ + lua_pushstring(L, ".set"); + lua_newtable(L); + lua_rawset(L, -3); + /* add a table called ".fn" */ + lua_pushstring(L, ".fn"); + lua_newtable(L); + /* add manual disown method */ + SWIG_Lua_add_function(L, "__disown", SWIG_Lua_class_disown); + lua_rawset(L, -3); + /* add accessor fns for using the .get,.set&.fn */ + SWIG_Lua_add_function(L, "__index", SWIG_Lua_class_get); + SWIG_Lua_add_function(L, "__newindex", SWIG_Lua_class_set); + SWIG_Lua_add_function(L, "__gc", SWIG_Lua_class_destruct); + /* add it */ + lua_rawset(L, -3); /* metatable into registry */ + lua_pop(L, 1); /* tidy stack (remove registry) */ + assert(lua_gettop(L) == begin); #if defined(SWIG_LUA_SQUASH_BASES) && (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) - /* Now merge all symbols from .fn, .set, .get etc from bases to our tables */ - SWIG_Lua_class_squash_bases(L,clss); + /* Now merge all symbols from .fn, .set, .get etc from bases to our tables */ + SWIG_Lua_class_squash_bases(L, clss); #endif - SWIG_Lua_get_class_metatable(L,clss->fqname); - SWIG_Lua_add_class_instance_details(L,clss); /* recursive adding of details (atts & ops) */ - lua_pop(L,1); /* tidy stack (remove class metatable) */ - assert( lua_gettop(L) == begin ); + SWIG_Lua_get_class_metatable(L, clss->fqname); + SWIG_Lua_add_class_instance_details(L, clss); /* recursive adding of details (atts & ops) */ + lua_pop(L, 1); /* tidy stack (remove class metatable) */ + assert(lua_gettop(L) == begin); } -SWIGINTERN void SWIG_Lua_class_register(lua_State *L,swig_lua_class *clss) -{ - int SWIGUNUSED begin; - assert(lua_istable(L,-1)); /* This is a table (module or namespace) where classes will be added */ - SWIG_Lua_class_register_instance(L,clss); - SWIG_Lua_class_register_static(L,clss); +SWIGINTERN void SWIG_Lua_class_register(lua_State *L, swig_lua_class *clss) { + int SWIGUNUSED begin; + assert(lua_istable(L, -1)); /* This is a table (module or namespace) where classes will be added */ + SWIG_Lua_class_register_instance(L, clss); + SWIG_Lua_class_register_static(L, clss); - /* Add links from static part to instance part and vice versa */ - /* [SWIG registry] [Module] - * "MyClass" ----> [MyClass metatable] <===== "MyClass" -+> [static part] - * ".get" ----> ... | | getmetatable()----| - * ".set" ----> ... | | | - * ".static" --------------)----------------/ [static part metatable] - * | ".get" --> ... - * | ".set" --> .... - * |=============================== ".instance" - */ - begin = lua_gettop(L); - lua_pushstring(L,clss->cls_static->name); - lua_rawget(L,-2); /* get class static table */ - assert(lua_istable(L,-1)); - lua_getmetatable(L,-1); - assert(lua_istable(L,-1)); /* get class static metatable */ - lua_pushstring(L,".instance"); /* prepare key */ + /* Add links from static part to instance part and vice versa */ + /* [SWIG registry] [Module] + * "MyClass" ----> [MyClass metatable] <===== "MyClass" -+> [static part] + * ".get" ----> ... | | getmetatable()----| + * ".set" ----> ... | | | + * ".static" --------------)----------------/ [static part metatable] + * | ".get" --> ... + * | ".set" --> .... + * |=============================== ".instance" + */ + begin = lua_gettop(L); + lua_pushstring(L, clss->cls_static->name); + lua_rawget(L, -2); /* get class static table */ + assert(lua_istable(L, -1)); + lua_getmetatable(L, -1); + assert(lua_istable(L, -1)); /* get class static metatable */ + lua_pushstring(L, ".instance"); /* prepare key */ - SWIG_Lua_get_class_metatable(L,clss->fqname); /* get class metatable */ - assert(lua_istable(L,-1)); - lua_pushstring(L,".static"); /* prepare key */ - lua_pushvalue(L, -4); /* push static class TABLE */ - assert(lua_istable(L,-1)); - lua_rawset(L,-3); /* assign static class table(!NOT metatable) as ".static" member of class metatable */ - lua_rawset(L,-3); /* assign class metatable as ".instance" member of class static METATABLE */ - lua_pop(L,2); - assert(lua_gettop(L) == begin); + SWIG_Lua_get_class_metatable(L, clss->fqname); /* get class metatable */ + assert(lua_istable(L, -1)); + lua_pushstring(L, ".static"); /* prepare key */ + lua_pushvalue(L, -4); /* push static class TABLE */ + assert(lua_istable(L, -1)); + lua_rawset(L, -3); /* assign static class table(!NOT metatable) as ".static" member of class metatable */ + lua_rawset(L, -3); /* assign class metatable as ".instance" member of class static METATABLE */ + lua_pop(L, 2); + assert(lua_gettop(L) == begin); } #endif /* SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA */ #if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC) -SWIGINTERN void SWIG_Lua_elua_class_register_instance(lua_State *L, swig_lua_class *clss) -{ - const int SWIGUNUSED begin = lua_gettop(L); - int i; - /* if name already there (class is already registered) then do nothing */ - SWIG_Lua_get_class_registry(L); /* get the registry */ - lua_pushstring(L,clss->fqname); /* get the name */ - lua_rawget(L,-2); - if(!lua_isnil(L,-1)) { - lua_pop(L,2); - assert(lua_gettop(L)==begin); - return; - } - lua_pop(L,2); /* tidy stack */ - /* Recursively initialize all bases */ - for(i=0;clss->bases[i];i++) - { - SWIG_Lua_elua_class_register_instance(L,clss->bases[i]); - } - /* Again, get registry and push name */ - SWIG_Lua_get_class_registry(L); /* get the registry */ - lua_pushstring(L,clss->fqname); /* get the name */ - assert(clss->metatable); - lua_pushrotable(L, (void*)(clss->metatable)); /* create the metatable */ - lua_rawset(L,-3); - lua_pop(L,1); - assert(lua_gettop(L) == begin); +SWIGINTERN void SWIG_Lua_elua_class_register_instance(lua_State *L, swig_lua_class *clss) { + const int SWIGUNUSED begin = lua_gettop(L); + int i; + /* if name already there (class is already registered) then do nothing */ + SWIG_Lua_get_class_registry(L); /* get the registry */ + lua_pushstring(L, clss->fqname); /* get the name */ + lua_rawget(L, -2); + if (!lua_isnil(L, -1)) { + lua_pop(L, 2); + assert(lua_gettop(L) == begin); + return; + } + lua_pop(L, 2); /* tidy stack */ + /* Recursively initialize all bases */ + for (i = 0; clss->bases[i]; i++) { + SWIG_Lua_elua_class_register_instance(L, clss->bases[i]); + } + /* Again, get registry and push name */ + SWIG_Lua_get_class_registry(L); /* get the registry */ + lua_pushstring(L, clss->fqname); /* get the name */ + assert(clss->metatable); + lua_pushrotable(L, (void *)(clss->metatable)); /* create the metatable */ + lua_rawset(L, -3); + lua_pop(L, 1); + assert(lua_gettop(L) == begin); } #endif /* elua && eluac */ @@ -2502,147 +2440,124 @@ SWIGINTERN void SWIG_Lua_elua_class_register_instance(lua_State *L, swig_lua_cla * ----------------------------------------------------------------------------- */ /* helper to add metatable to new lua object */ -SWIGINTERN void SWIG_Lua_AddMetatable(lua_State *L,swig_type_info *type) -{ - if (type->clientdata) /* there is clientdata: so add the metatable */ - { - SWIG_Lua_get_class_metatable(L,((swig_lua_class*)(type->clientdata))->fqname); - if (lua_istable(L,-1)) - { - lua_setmetatable(L,-2); +SWIGINTERN void SWIG_Lua_AddMetatable(lua_State *L, swig_type_info *type) { + if (type->clientdata) { /* there is clientdata: so add the metatable */ + SWIG_Lua_get_class_metatable(L, ((swig_lua_class *)(type->clientdata))->fqname); + if (lua_istable(L, -1)) { + lua_setmetatable(L, -2); + } else { + lua_pop(L, 1); + } } - else - { - lua_pop(L,1); - } - } } /* pushes a new object into the lua stack */ -SWIGRUNTIME void SWIG_Lua_NewPointerObj(lua_State *L,void *ptr,swig_type_info *type, int own) -{ - swig_lua_userdata *usr; - if (!ptr){ - lua_pushnil(L); - return; - } - usr=(swig_lua_userdata*)lua_newuserdata(L,sizeof(swig_lua_userdata)); /* get data */ - usr->ptr=ptr; /* set the ptr */ - usr->type=type; - usr->own=own; +SWIGRUNTIME void SWIG_Lua_NewPointerObj(lua_State *L, void *ptr, swig_type_info *type, int own) { + swig_lua_userdata *usr; + if (!ptr) { + lua_pushnil(L); + return; + } + usr = (swig_lua_userdata *)lua_newuserdata(L, sizeof(swig_lua_userdata)); /* get data */ + usr->ptr = ptr; /* set the ptr */ + usr->type = type; + usr->own = own; #if (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC) - SWIG_Lua_AddMetatable(L,type); /* add metatable */ + SWIG_Lua_AddMetatable(L, type); /* add metatable */ #endif } /* takes a object from the lua stack & converts it into an object of the correct type (if possible) */ -SWIGRUNTIME int SWIG_Lua_ConvertPtr(lua_State *L,int index,void **ptr,swig_type_info *type,int flags) -{ - int ret = SWIG_ERROR; - swig_lua_userdata *usr; - swig_cast_info *cast; - /* special case: lua nil => NULL pointer */ - if (lua_isnil(L,index)) - { - *ptr=0; - return (flags & SWIG_POINTER_NO_NULL) ? SWIG_NullReferenceError : SWIG_OK; - } - if (lua_islightuserdata(L,index)) - { - *ptr=lua_touserdata(L,index); - return (flags & SWIG_POINTER_NO_NULL) ? SWIG_NullReferenceError : SWIG_OK; - } - usr=(swig_lua_userdata*)lua_touserdata(L,index); /* get data */ - if (usr) - { - if (((flags & SWIG_POINTER_RELEASE) == SWIG_POINTER_RELEASE) && !usr->own) - { - return SWIG_ERROR_RELEASE_NOT_OWNED; +SWIGRUNTIME int SWIG_Lua_ConvertPtr(lua_State *L, int index, void **ptr, swig_type_info *type, int flags) { + int ret = SWIG_ERROR; + swig_lua_userdata *usr; + swig_cast_info *cast; + /* special case: lua nil => NULL pointer */ + if (lua_isnil(L, index)) { + *ptr = 0; + return (flags & SWIG_POINTER_NO_NULL) ? SWIG_NullReferenceError : SWIG_OK; } - if (flags & SWIG_POINTER_DISOWN) /* must disown the object */ - { - usr->own = 0; + if (lua_islightuserdata(L, index)) { + *ptr = lua_touserdata(L, index); + return (flags & SWIG_POINTER_NO_NULL) ? SWIG_NullReferenceError : SWIG_OK; } - if (!type) /* special cast void*, no casting fn */ - { - *ptr=usr->ptr; - ret = SWIG_OK; + usr = (swig_lua_userdata *)lua_touserdata(L, index); /* get data */ + if (usr) { + if (((flags & SWIG_POINTER_RELEASE) == SWIG_POINTER_RELEASE) && !usr->own) { + return SWIG_ERROR_RELEASE_NOT_OWNED; + } + if (flags & SWIG_POINTER_DISOWN) { /* must disown the object */ + usr->own = 0; + } + if (!type) { /* special cast void*, no casting fn */ + *ptr = usr->ptr; + ret = SWIG_OK; + } else { + cast = SWIG_TypeCheck(usr->type->name, type); /* performs normal type checking */ + if (cast) { + int newmemory = 0; + *ptr = SWIG_TypeCast(cast, usr->ptr, &newmemory); + assert(!newmemory); /* newmemory handling not yet implemented */ + ret = SWIG_OK; + } + } + if ((ret == SWIG_OK) && (flags & SWIG_POINTER_CLEAR)) { + usr->ptr = 0; + } } - else - { - cast=SWIG_TypeCheck(usr->type->name,type); /* performs normal type checking */ - if (cast) - { - int newmemory = 0; - *ptr=SWIG_TypeCast(cast,usr->ptr,&newmemory); - assert(!newmemory); /* newmemory handling not yet implemented */ - ret = SWIG_OK; - } - } - if ((ret == SWIG_OK) && (flags & SWIG_POINTER_CLEAR)) - { - usr->ptr = 0; - } - } - return ret; + return ret; } -SWIGRUNTIME void* SWIG_Lua_MustGetPtr(lua_State *L,int index,swig_type_info *type,int flags, - int argnum,const char *func_name){ - void *result = 0; - if (!SWIG_IsOK(SWIG_ConvertPtr(L,index,&result,type,flags))){ - luaL_error (L,"Error in %s, expected a %s at argument number %d\n", - func_name,(type && type->str)?type->str:"void*",argnum); - } - return result; +SWIGRUNTIME void *SWIG_Lua_MustGetPtr(lua_State *L, int index, swig_type_info *type, int flags, + int argnum, const char *func_name) { + void *result = 0; + if (!SWIG_IsOK(SWIG_ConvertPtr(L, index, &result, type, flags))) { + luaL_error(L, "Error in %s, expected a %s at argument number %d\n", + func_name, (type && type->str) ? type->str : "void*", argnum); + } + return result; } /* pushes a packed userdata. user for member fn pointers only */ -SWIGRUNTIME void SWIG_Lua_NewPackedObj(lua_State *L,void *ptr,size_t size,swig_type_info *type) -{ - swig_lua_rawdata *raw; - assert(ptr); /* not acceptable to pass in a NULL value */ - raw=(swig_lua_rawdata*)lua_newuserdata(L,sizeof(swig_lua_rawdata)-1+size); /* alloc data */ - raw->type=type; - raw->own=0; - memcpy(raw->data,ptr,size); /* copy the data */ - SWIG_Lua_AddMetatable(L,type); /* add metatable */ +SWIGRUNTIME void SWIG_Lua_NewPackedObj(lua_State *L, void *ptr, size_t size, swig_type_info *type) { + swig_lua_rawdata *raw; + assert(ptr); /* not acceptable to pass in a NULL value */ + raw = (swig_lua_rawdata *)lua_newuserdata(L, sizeof(swig_lua_rawdata) - 1 + size); /* alloc data */ + raw->type = type; + raw->own = 0; + memcpy(raw->data, ptr, size); /* copy the data */ + SWIG_Lua_AddMetatable(L, type); /* add metatable */ } /* converts a packed userdata. user for member fn pointers only */ -SWIGRUNTIME int SWIG_Lua_ConvertPacked(lua_State *L,int index,void *ptr,size_t size,swig_type_info *type) -{ - swig_lua_rawdata *raw; - raw=(swig_lua_rawdata*)lua_touserdata(L,index); /* get data */ - if (!raw) return SWIG_ERROR; /* error */ - if (type==0 || type==raw->type) /* void* or identical type */ - { - memcpy(ptr,raw->data,size); /* copy it */ - return SWIG_OK; /* ok */ - } - return SWIG_ERROR; /* error */ +SWIGRUNTIME int SWIG_Lua_ConvertPacked(lua_State *L, int index, void *ptr, size_t size, swig_type_info *type) { + swig_lua_rawdata *raw; + raw = (swig_lua_rawdata *)lua_touserdata(L, index); /* get data */ + if (!raw) return SWIG_ERROR; /* error */ + if (type == 0 || type == raw->type) { /* void* or identical type */ + memcpy(ptr, raw->data, size); /* copy it */ + return SWIG_OK; /* ok */ + } + return SWIG_ERROR; /* error */ } /* a function to get the typestring of a piece of data */ -SWIGRUNTIME const char *SWIG_Lua_typename(lua_State *L, int tp) -{ - swig_lua_userdata *usr; - if (lua_isuserdata(L,tp)) - { - usr=(swig_lua_userdata*)lua_touserdata(L,tp); /* get data */ - if (usr && usr->type && usr->type->str) - return usr->type->str; - return "userdata (unknown type)"; - } - return lua_typename(L,lua_type(L,tp)); +SWIGRUNTIME const char *SWIG_Lua_typename(lua_State *L, int tp) { + swig_lua_userdata *usr; + if (lua_isuserdata(L, tp)) { + usr = (swig_lua_userdata *)lua_touserdata(L, tp); /* get data */ + if (usr && usr->type && usr->type->str) + return usr->type->str; + return "userdata (unknown type)"; + } + return lua_typename(L, lua_type(L, tp)); } /* lua callable function to get the userdata's type */ -SWIGRUNTIME int SWIG_Lua_type(lua_State *L) -{ - lua_pushstring(L,SWIG_Lua_typename(L,1)); - return 1; +SWIGRUNTIME int SWIG_Lua_type(lua_State *L) { + lua_pushstring(L, SWIG_Lua_typename(L, 1)); + return 1; } /* ----------------------------------------------------------------------------- @@ -2653,46 +2568,46 @@ SWIGRUNTIME int SWIG_Lua_type(lua_State *L) /* Install Constants */ SWIGINTERN void SWIG_Lua_InstallConstants(lua_State *L, swig_lua_const_info constants[]) { - int i; - for (i = 0; constants[i].type; i++) { - switch(constants[i].type) { - case SWIG_LUA_INT: - lua_pushstring(L,constants[i].name); - lua_pushinteger(L,(lua_Integer)constants[i].lvalue); - lua_rawset(L,-3); - break; - case SWIG_LUA_FLOAT: - lua_pushstring(L,constants[i].name); - lua_pushnumber(L,(lua_Number)constants[i].dvalue); - lua_rawset(L,-3); - break; - case SWIG_LUA_CHAR: - lua_pushstring(L,constants[i].name); - { - char c = (char)constants[i].lvalue; - lua_pushlstring(L,&c,1); - } - lua_rawset(L,-3); - break; - case SWIG_LUA_STRING: - lua_pushstring(L,constants[i].name); - lua_pushstring(L,(char *) constants[i].pvalue); - lua_rawset(L,-3); - break; - case SWIG_LUA_POINTER: - lua_pushstring(L,constants[i].name); - SWIG_NewPointerObj(L,constants[i].pvalue, *(constants[i]).ptype,0); - lua_rawset(L,-3); - break; - case SWIG_LUA_BINARY: - lua_pushstring(L,constants[i].name); - SWIG_NewMemberObj(L,constants[i].pvalue,constants[i].lvalue,*(constants[i]).ptype); - lua_rawset(L,-3); - break; - default: - break; + int i; + for (i = 0; constants[i].type; i++) { + switch (constants[i].type) { + case SWIG_LUA_INT: + lua_pushstring(L, constants[i].name); + lua_pushinteger(L, (lua_Integer)constants[i].lvalue); + lua_rawset(L, -3); + break; + case SWIG_LUA_FLOAT: + lua_pushstring(L, constants[i].name); + lua_pushnumber(L, (lua_Number)constants[i].dvalue); + lua_rawset(L, -3); + break; + case SWIG_LUA_CHAR: + lua_pushstring(L, constants[i].name); + { + char c = (char)constants[i].lvalue; + lua_pushlstring(L, &c, 1); + } + lua_rawset(L, -3); + break; + case SWIG_LUA_STRING: + lua_pushstring(L, constants[i].name); + lua_pushstring(L, (char *) constants[i].pvalue); + lua_rawset(L, -3); + break; + case SWIG_LUA_POINTER: + lua_pushstring(L, constants[i].name); + SWIG_NewPointerObj(L, constants[i].pvalue, *(constants[i]).ptype, 0); + lua_rawset(L, -3); + break; + case SWIG_LUA_BINARY: + lua_pushstring(L, constants[i].name); + SWIG_NewMemberObj(L, constants[i].pvalue, constants[i].lvalue, *(constants[i]).ptype); + lua_rawset(L, -3); + break; + default: + break; + } } - } } #endif @@ -2710,19 +2625,19 @@ In lua 5.1.X it's luaL_dostring() */ SWIGINTERN int SWIG_Lua_dostring(lua_State *L, const char *str) { - int ok,top; - if (str==0 || str[0]==0) return 0; /* nothing to do */ - top=lua_gettop(L); /* save stack */ + int ok, top; + if (str == 0 || str[0] == 0) return 0; /* nothing to do */ + top = lua_gettop(L); /* save stack */ #if (defined(LUA_VERSION_NUM) && (LUA_VERSION_NUM>=501)) - ok=luaL_dostring(L,str); /* looks like this is lua 5.1.X or later, good */ + ok = luaL_dostring(L, str); /* looks like this is lua 5.1.X or later, good */ #else - ok=lua_dostring(L,str); /* might be lua 5.0.x, using lua_dostring */ + ok = lua_dostring(L, str); /* might be lua 5.0.x, using lua_dostring */ #endif - if (ok!=0) { - SWIG_DOSTRING_FAIL(lua_tostring(L,-1)); - } - lua_settop(L,top); /* restore the stack */ - return ok; + if (ok != 0) { + SWIG_DOSTRING_FAIL(lua_tostring(L, -1)); + } + lua_settop(L, top); /* restore the stack */ + return ok; } #ifdef __cplusplus @@ -2752,179 +2667,188 @@ static swig_module_info swig_module = {swig_types, 1, 0, 0, 0, 0}; #include "pm3.h" #include "comms.h" -SWIGINTERN pm3 *new_pm3__SWIG_0(void){ +SWIGINTERN pm3 *new_pm3__SWIG_0(void) { // printf("SWIG pm3 constructor, get current pm3\n"); - pm3_device_t * p = pm3_get_current_dev(); - p->script_embedded = 1; - return p; - } - -SWIGINTERN int SWIG_lua_isnilstring(lua_State *L, int idx) { - int ret = lua_isstring(L, idx); - if (!ret) - ret = lua_isnil(L, idx); - return ret; + pm3_device_t *p = pm3_get_current_dev(); + p->script_embedded = 1; + return p; } -SWIGINTERN pm3 *new_pm3__SWIG_1(char *port){ +SWIGINTERN int SWIG_lua_isnilstring(lua_State *L, int idx) { + int ret = lua_isstring(L, idx); + if (!ret) + ret = lua_isnil(L, idx); + return ret; +} + +SWIGINTERN pm3 *new_pm3__SWIG_1(char *port) { // printf("SWIG pm3 constructor with port, open pm3\n"); - pm3_device_t * p = pm3_open(port); - p->script_embedded = 0; - return p; - } -SWIGINTERN void delete_pm3(pm3 *self){ - if (self->script_embedded) { + pm3_device_t *p = pm3_open(port); + p->script_embedded = 0; + return p; +} +SWIGINTERN void delete_pm3(pm3 *self) { + if (self->script_embedded) { // printf("SWIG pm3 destructor, nothing to do\n"); - } else { + } else { // printf("SWIG pm3 destructor, close pm3\n"); - pm3_close(self); - } - } + pm3_close(self); + } +} #ifdef __cplusplus extern "C" { #endif -static int _wrap_new_pm3__SWIG_0(lua_State* L) { - int SWIG_arg = 0; - pm3 *result = 0 ; - - SWIG_check_num_args("pm3::pm3",0,0) - result = (pm3 *)new_pm3__SWIG_0(); - SWIG_NewPointerObj(L,result,SWIGTYPE_p_pm3,1); SWIG_arg++; - return SWIG_arg; - - fail: SWIGUNUSED; - lua_error(L); - return 0; +static int _wrap_new_pm3__SWIG_0(lua_State *L) { + int SWIG_arg = 0; + pm3 *result = 0 ; + + SWIG_check_num_args("pm3::pm3", 0, 0) + result = (pm3 *)new_pm3__SWIG_0(); + SWIG_NewPointerObj(L, result, SWIGTYPE_p_pm3, 1); + SWIG_arg++; + return SWIG_arg; + +fail: + SWIGUNUSED; + lua_error(L); + return 0; } -static int _wrap_new_pm3__SWIG_1(lua_State* L) { - int SWIG_arg = 0; - char *arg1 = (char *) 0 ; - pm3 *result = 0 ; - - SWIG_check_num_args("pm3::pm3",1,1) - if(!SWIG_lua_isnilstring(L,1)) SWIG_fail_arg("pm3::pm3",1,"char *"); - arg1 = (char *)lua_tostring(L, 1); - result = (pm3 *)new_pm3__SWIG_1(arg1); - SWIG_NewPointerObj(L,result,SWIGTYPE_p_pm3,1); SWIG_arg++; - return SWIG_arg; - - fail: SWIGUNUSED; - lua_error(L); - return 0; +static int _wrap_new_pm3__SWIG_1(lua_State *L) { + int SWIG_arg = 0; + char *arg1 = (char *) 0 ; + pm3 *result = 0 ; + + SWIG_check_num_args("pm3::pm3", 1, 1) + if (!SWIG_lua_isnilstring(L, 1)) SWIG_fail_arg("pm3::pm3", 1, "char *"); + arg1 = (char *)lua_tostring(L, 1); + result = (pm3 *)new_pm3__SWIG_1(arg1); + SWIG_NewPointerObj(L, result, SWIGTYPE_p_pm3, 1); + SWIG_arg++; + return SWIG_arg; + +fail: + SWIGUNUSED; + lua_error(L); + return 0; } -static int _wrap_new_pm3(lua_State* L) { - int argc; - int argv[2]={ - 1,2 - }; - - argc = lua_gettop(L); - if (argc == 0) { - return _wrap_new_pm3__SWIG_0(L); - } - if (argc == 1) { - int _v = 0; - { - _v = SWIG_lua_isnilstring(L,argv[0]); +static int _wrap_new_pm3(lua_State *L) { + int argc; + int argv[2] = { + 1, 2 + }; + + argc = lua_gettop(L); + if (argc == 0) { + return _wrap_new_pm3__SWIG_0(L); } - if (_v) { - return _wrap_new_pm3__SWIG_1(L); + if (argc == 1) { + int _v = 0; + { + _v = SWIG_lua_isnilstring(L, argv[0]); + } + if (_v) { + return _wrap_new_pm3__SWIG_1(L); + } } - } - - SWIG_Lua_pusherrstring(L,"Wrong arguments for overloaded function 'new_pm3'\n" - " Possible C/C++ prototypes are:\n" - " pm3::pm3()\n" - " pm3::pm3(char *)\n"); - lua_error(L);return 0; + + SWIG_Lua_pusherrstring(L, "Wrong arguments for overloaded function 'new_pm3'\n" + " Possible C/C++ prototypes are:\n" + " pm3::pm3()\n" + " pm3::pm3(char *)\n"); + lua_error(L); + return 0; } -static int _wrap_pm3_console(lua_State* L) { - int SWIG_arg = 0; - pm3 *arg1 = (pm3 *) 0 ; - char *arg2 = (char *) 0 ; - int result; - - SWIG_check_num_args("pm3::console",2,2) - if(!SWIG_isptrtype(L,1)) SWIG_fail_arg("pm3::console",1,"pm3 *"); - if(!SWIG_lua_isnilstring(L,2)) SWIG_fail_arg("pm3::console",2,"char *"); - - if (!SWIG_IsOK(SWIG_ConvertPtr(L,1,(void**)&arg1,SWIGTYPE_p_pm3,0))){ - SWIG_fail_ptr("pm3_console",1,SWIGTYPE_p_pm3); - } - - arg2 = (char *)lua_tostring(L, 2); - result = (int)pm3_console(arg1,arg2); - lua_pushnumber(L, (lua_Number) result); SWIG_arg++; - return SWIG_arg; - - fail: SWIGUNUSED; - lua_error(L); - return 0; +static int _wrap_pm3_console(lua_State *L) { + int SWIG_arg = 0; + pm3 *arg1 = (pm3 *) 0 ; + char *arg2 = (char *) 0 ; + int result; + + SWIG_check_num_args("pm3::console", 2, 2) + if (!SWIG_isptrtype(L, 1)) SWIG_fail_arg("pm3::console", 1, "pm3 *"); + if (!SWIG_lua_isnilstring(L, 2)) SWIG_fail_arg("pm3::console", 2, "char *"); + + if (!SWIG_IsOK(SWIG_ConvertPtr(L, 1, (void **)&arg1, SWIGTYPE_p_pm3, 0))) { + SWIG_fail_ptr("pm3_console", 1, SWIGTYPE_p_pm3); + } + + arg2 = (char *)lua_tostring(L, 2); + result = (int)pm3_console(arg1, arg2); + lua_pushnumber(L, (lua_Number) result); + SWIG_arg++; + return SWIG_arg; + +fail: + SWIGUNUSED; + lua_error(L); + return 0; } -static int _wrap_pm3_name_get(lua_State* L) { - int SWIG_arg = 0; - pm3 *arg1 = (pm3 *) 0 ; - char *result = 0 ; - - SWIG_check_num_args("pm3::name",1,1) - if(!SWIG_isptrtype(L,1)) SWIG_fail_arg("pm3::name",1,"pm3 *"); - - if (!SWIG_IsOK(SWIG_ConvertPtr(L,1,(void**)&arg1,SWIGTYPE_p_pm3,0))){ - SWIG_fail_ptr("pm3_name_get",1,SWIGTYPE_p_pm3); - } - - result = (char *)pm3_name_get(arg1); - lua_pushstring(L,(const char *)result); SWIG_arg++; - return SWIG_arg; - - fail: SWIGUNUSED; - lua_error(L); - return 0; +static int _wrap_pm3_name_get(lua_State *L) { + int SWIG_arg = 0; + pm3 *arg1 = (pm3 *) 0 ; + char *result = 0 ; + + SWIG_check_num_args("pm3::name", 1, 1) + if (!SWIG_isptrtype(L, 1)) SWIG_fail_arg("pm3::name", 1, "pm3 *"); + + if (!SWIG_IsOK(SWIG_ConvertPtr(L, 1, (void **)&arg1, SWIGTYPE_p_pm3, 0))) { + SWIG_fail_ptr("pm3_name_get", 1, SWIGTYPE_p_pm3); + } + + result = (char *)pm3_name_get(arg1); + lua_pushstring(L, (const char *)result); + SWIG_arg++; + return SWIG_arg; + +fail: + SWIGUNUSED; + lua_error(L); + return 0; } static void swig_delete_pm3(void *obj) { -pm3 *arg1 = (pm3 *) obj; -delete_pm3(arg1); + pm3 *arg1 = (pm3 *) obj; + delete_pm3(arg1); } static int _proxy__wrap_new_pm3(lua_State *L) { - assert(lua_istable(L,1)); - lua_pushcfunction(L,_wrap_new_pm3); - assert(!lua_isnil(L,-1)); - lua_replace(L,1); /* replace our table with real constructor */ - lua_call(L,lua_gettop(L)-1,1); + assert(lua_istable(L, 1)); + lua_pushcfunction(L, _wrap_new_pm3); + assert(!lua_isnil(L, -1)); + lua_replace(L, 1); /* replace our table with real constructor */ + lua_call(L, lua_gettop(L) - 1, 1); return 1; } static swig_lua_attribute swig_pm3_attributes[] = { { "name", _wrap_pm3_name_get, SWIG_Lua_set_immutable }, - {0,0,0} + {0, 0, 0} }; -static swig_lua_method swig_pm3_methods[]= { +static swig_lua_method swig_pm3_methods[] = { { "console", _wrap_pm3_console}, - {0,0} + {0, 0} }; static swig_lua_method swig_pm3_meta[] = { - {0,0} + {0, 0} }; static swig_lua_attribute swig_pm3_Sf_SwigStatic_attributes[] = { - {0,0,0} + {0, 0, 0} }; -static swig_lua_const_info swig_pm3_Sf_SwigStatic_constants[]= { - {0,0,0,0,0,0} +static swig_lua_const_info swig_pm3_Sf_SwigStatic_constants[] = { + {0, 0, 0, 0, 0, 0} }; -static swig_lua_method swig_pm3_Sf_SwigStatic_methods[]= { - {0,0} +static swig_lua_method swig_pm3_Sf_SwigStatic_methods[] = { + {0, 0} }; -static swig_lua_class* swig_pm3_Sf_SwigStatic_classes[]= { +static swig_lua_class *swig_pm3_Sf_SwigStatic_classes[] = { 0 }; @@ -2938,22 +2862,22 @@ static swig_lua_namespace swig_pm3_Sf_SwigStatic = { }; static swig_lua_class *swig_pm3_bases[] = {0}; static const char *swig_pm3_base_names[] = {0}; -static swig_lua_class _wrap_class_pm3 = { "pm3", "pm3", &SWIGTYPE_p_pm3,_proxy__wrap_new_pm3, swig_delete_pm3, swig_pm3_methods, swig_pm3_attributes, &swig_pm3_Sf_SwigStatic, swig_pm3_meta, swig_pm3_bases, swig_pm3_base_names }; +static swig_lua_class _wrap_class_pm3 = { "pm3", "pm3", &SWIGTYPE_p_pm3, _proxy__wrap_new_pm3, swig_delete_pm3, swig_pm3_methods, swig_pm3_attributes, &swig_pm3_Sf_SwigStatic, swig_pm3_meta, swig_pm3_bases, swig_pm3_base_names }; static swig_lua_attribute swig_SwigModule_attributes[] = { - {0,0,0} + {0, 0, 0} }; -static swig_lua_const_info swig_SwigModule_constants[]= { - {0,0,0,0,0,0} +static swig_lua_const_info swig_SwigModule_constants[] = { + {0, 0, 0, 0, 0, 0} }; -static swig_lua_method swig_SwigModule_methods[]= { - {0,0} +static swig_lua_method swig_SwigModule_methods[] = { + {0, 0} }; -static swig_lua_class* swig_SwigModule_classes[]= { -&_wrap_class_pm3, +static swig_lua_class *swig_SwigModule_classes[] = { + &_wrap_class_pm3, 0 }; -static swig_lua_namespace* swig_SwigModule_namespaces[] = { +static swig_lua_namespace *swig_SwigModule_namespaces[] = { 0 }; @@ -2971,16 +2895,16 @@ static swig_lua_namespace swig_SwigModule = { /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */ -static swig_type_info _swigt__p_pm3 = {"_p_pm3", "pm3 *", 0, 0, (void*)&_wrap_class_pm3, 0}; +static swig_type_info _swigt__p_pm3 = {"_p_pm3", "pm3 *", 0, 0, (void *) &_wrap_class_pm3, 0}; static swig_type_info *swig_type_initial[] = { - &_swigt__p_pm3, + &_swigt__p_pm3, }; -static swig_cast_info _swigc__p_pm3[] = { {&_swigt__p_pm3, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_pm3[] = { {&_swigt__p_pm3, 0, 0, 0}, {0, 0, 0, 0}}; static swig_cast_info *swig_cast_initial[] = { - _swigc__p_pm3, + _swigc__p_pm3, }; @@ -3044,144 +2968,144 @@ extern "C" { SWIGRUNTIME void SWIG_InitializeModule(SWIG_INIT_CLIENT_DATA_TYPE clientdata) { - size_t i; - swig_module_info *module_head, *iter; - int init; + size_t i; + swig_module_info *module_head, *iter; + int init; - /* check to see if the circular list has been setup, if not, set it up */ - if (swig_module.next==0) { - /* Initialize the swig_module */ - swig_module.type_initial = swig_type_initial; - swig_module.cast_initial = swig_cast_initial; - swig_module.next = &swig_module; - init = 1; - } else { - init = 0; - } - - /* Try and load any already created modules */ - module_head = SWIG_GetModule(clientdata); - if (!module_head) { - /* This is the first module loaded for this interpreter */ - /* so set the swig module into the interpreter */ - SWIG_SetModule(clientdata, &swig_module); - } else { - /* the interpreter has loaded a SWIG module, but has it loaded this one? */ - iter=module_head; - do { - if (iter==&swig_module) { - /* Our module is already in the list, so there's nothing more to do. */ - return; - } - iter=iter->next; - } while (iter!= module_head); - - /* otherwise we must add our module into the list */ - swig_module.next = module_head->next; - module_head->next = &swig_module; - } - - /* When multiple interpreters are used, a module could have already been initialized in - a different interpreter, but not yet have a pointer in this interpreter. - In this case, we do not want to continue adding types... everything should be - set up already */ - if (init == 0) return; - - /* Now work on filling in swig_module.types */ -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: size %lu\n", (unsigned long)swig_module.size); -#endif - for (i = 0; i < swig_module.size; ++i) { - swig_type_info *type = 0; - swig_type_info *ret; - swig_cast_info *cast; - -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: type %lu %s\n", (unsigned long)i, swig_module.type_initial[i]->name); -#endif - - /* if there is another module already loaded */ - if (swig_module.next != &swig_module) { - type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name); - } - if (type) { - /* Overwrite clientdata field */ -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: found type %s\n", type->name); -#endif - if (swig_module.type_initial[i]->clientdata) { - type->clientdata = swig_module.type_initial[i]->clientdata; -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name); -#endif - } + /* check to see if the circular list has been setup, if not, set it up */ + if (swig_module.next == 0) { + /* Initialize the swig_module */ + swig_module.type_initial = swig_type_initial; + swig_module.cast_initial = swig_cast_initial; + swig_module.next = &swig_module; + init = 1; } else { - type = swig_module.type_initial[i]; + init = 0; } - /* Insert casting types */ - cast = swig_module.cast_initial[i]; - while (cast->type) { + /* Try and load any already created modules */ + module_head = SWIG_GetModule(clientdata); + if (!module_head) { + /* This is the first module loaded for this interpreter */ + /* so set the swig module into the interpreter */ + SWIG_SetModule(clientdata, &swig_module); + } else { + /* the interpreter has loaded a SWIG module, but has it loaded this one? */ + iter = module_head; + do { + if (iter == &swig_module) { + /* Our module is already in the list, so there's nothing more to do. */ + return; + } + iter = iter->next; + } while (iter != module_head); - /* Don't need to add information already in the list */ - ret = 0; -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: look cast %s\n", cast->type->name); -#endif - if (swig_module.next != &swig_module) { - ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name); -#ifdef SWIGRUNTIME_DEBUG - if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name); -#endif - } - if (ret) { - if (type == swig_module.type_initial[i]) { -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: skip old type %s\n", ret->name); -#endif - cast->type = ret; - ret = 0; - } else { - /* Check for casting already in the list */ - swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type); -#ifdef SWIGRUNTIME_DEBUG - if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name); -#endif - if (!ocast) ret = 0; - } - } + /* otherwise we must add our module into the list */ + swig_module.next = module_head->next; + module_head->next = &swig_module; + } - if (!ret) { + /* When multiple interpreters are used, a module could have already been initialized in + a different interpreter, but not yet have a pointer in this interpreter. + In this case, we do not want to continue adding types... everything should be + set up already */ + if (init == 0) return; + + /* Now work on filling in swig_module.types */ #ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name); + printf("SWIG_InitializeModule: size %lu\n", (unsigned long)swig_module.size); #endif - if (type->cast) { - type->cast->prev = cast; - cast->next = type->cast; + for (i = 0; i < swig_module.size; ++i) { + swig_type_info *type = 0; + swig_type_info *ret; + swig_cast_info *cast; + +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: type %lu %s\n", (unsigned long)i, swig_module.type_initial[i]->name); +#endif + + /* if there is another module already loaded */ + if (swig_module.next != &swig_module) { + type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name); } - type->cast = cast; - } - cast++; + if (type) { + /* Overwrite clientdata field */ +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: found type %s\n", type->name); +#endif + if (swig_module.type_initial[i]->clientdata) { + type->clientdata = swig_module.type_initial[i]->clientdata; +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name); +#endif + } + } else { + type = swig_module.type_initial[i]; + } + + /* Insert casting types */ + cast = swig_module.cast_initial[i]; + while (cast->type) { + + /* Don't need to add information already in the list */ + ret = 0; +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: look cast %s\n", cast->type->name); +#endif + if (swig_module.next != &swig_module) { + ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name); +#ifdef SWIGRUNTIME_DEBUG + if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name); +#endif + } + if (ret) { + if (type == swig_module.type_initial[i]) { +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: skip old type %s\n", ret->name); +#endif + cast->type = ret; + ret = 0; + } else { + /* Check for casting already in the list */ + swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type); +#ifdef SWIGRUNTIME_DEBUG + if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name); +#endif + if (!ocast) ret = 0; + } + } + + if (!ret) { +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name); +#endif + if (type->cast) { + type->cast->prev = cast; + cast->next = type->cast; + } + type->cast = cast; + } + cast++; + } + /* Set entry in modules->types array equal to the type */ + swig_module.types[i] = type; } - /* Set entry in modules->types array equal to the type */ - swig_module.types[i] = type; - } - swig_module.types[i] = 0; + swig_module.types[i] = 0; #ifdef SWIGRUNTIME_DEBUG - printf("**** SWIG_InitializeModule: Cast List ******\n"); - for (i = 0; i < swig_module.size; ++i) { - int j = 0; - swig_cast_info *cast = swig_module.cast_initial[i]; - printf("SWIG_InitializeModule: type %lu %s\n", (unsigned long)i, swig_module.type_initial[i]->name); - while (cast->type) { - printf("SWIG_InitializeModule: cast type %s\n", cast->type->name); - cast++; - ++j; + printf("**** SWIG_InitializeModule: Cast List ******\n"); + for (i = 0; i < swig_module.size; ++i) { + int j = 0; + swig_cast_info *cast = swig_module.cast_initial[i]; + printf("SWIG_InitializeModule: type %lu %s\n", (unsigned long)i, swig_module.type_initial[i]->name); + while (cast->type) { + printf("SWIG_InitializeModule: cast type %s\n", cast->type->name); + cast++; + ++j; + } + printf("---- Total casts: %d\n", j); } - printf("---- Total casts: %d\n",j); - } - printf("**** SWIG_InitializeModule: Cast List ******\n"); + printf("**** SWIG_InitializeModule: Cast List ******\n"); #endif } @@ -3192,30 +3116,31 @@ SWIG_InitializeModule(SWIG_INIT_CLIENT_DATA_TYPE clientdata) { */ SWIGRUNTIME void SWIG_PropagateClientData(void) { - size_t i; - swig_cast_info *equiv; - static int init_run = 0; + size_t i; + swig_cast_info *equiv; + static int init_run = 0; - if (init_run) return; - init_run = 1; + if (init_run) return; + init_run = 1; - for (i = 0; i < swig_module.size; i++) { - if (swig_module.types[i]->clientdata) { - equiv = swig_module.types[i]->cast; - while (equiv) { - if (!equiv->converter) { - if (equiv->type && !equiv->type->clientdata) - SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata); + for (i = 0; i < swig_module.size; i++) { + if (swig_module.types[i]->clientdata) { + equiv = swig_module.types[i]->cast; + while (equiv) { + if (!equiv->converter) { + if (equiv->type && !equiv->type->clientdata) + SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata); + } + equiv = equiv->next; + } } - equiv = equiv->next; - } } - } } #ifdef __cplusplus #if 0 -{ /* c-mode */ +{ + /* c-mode */ #endif } #endif @@ -3223,8 +3148,8 @@ SWIG_PropagateClientData(void) { /* Forward declaration of where the user's %init{} gets inserted */ -void SWIG_init_user(lua_State* L ); - +void SWIG_init_user(lua_State *L); + #ifdef __cplusplus extern "C" { #endif @@ -3233,74 +3158,74 @@ extern "C" { the function is always called SWIG_init, but an earlier #define will rename it */ #if ((SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC)) -LUALIB_API int SWIG_init(lua_State* L) +LUALIB_API int SWIG_init(lua_State *L) #else -SWIGEXPORT int SWIG_init(lua_State* L) /* default Lua action */ +SWIGEXPORT int SWIG_init(lua_State *L) /* default Lua action */ #endif { #if (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC) /* valid for both Lua and eLua */ - int i; - int globalRegister = 0; - /* start with global table */ - lua_pushglobaltable (L); - /* SWIG's internal initialisation */ - SWIG_InitializeModule((void*)L); - SWIG_PropagateClientData(); + int i; + int globalRegister = 0; + /* start with global table */ + lua_pushglobaltable(L); + /* SWIG's internal initialisation */ + SWIG_InitializeModule((void *)L); + SWIG_PropagateClientData(); #endif #if ((SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUA) && (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC)) || defined(SWIG_LUA_ELUA_EMULATE) - /* add a global fn */ - SWIG_Lua_add_function(L,"swig_type",SWIG_Lua_type); - SWIG_Lua_add_function(L,"swig_equals",SWIG_Lua_class_equal); + /* add a global fn */ + SWIG_Lua_add_function(L, "swig_type", SWIG_Lua_type); + SWIG_Lua_add_function(L, "swig_equals", SWIG_Lua_class_equal); #endif #if (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC) - /* set up base class pointers (the hierarchy) */ - for (i = 0; swig_types[i]; i++){ - if (swig_types[i]->clientdata){ - SWIG_Lua_init_base_class(L,(swig_lua_class*)(swig_types[i]->clientdata)); + /* set up base class pointers (the hierarchy) */ + for (i = 0; swig_types[i]; i++) { + if (swig_types[i]->clientdata) { + SWIG_Lua_init_base_class(L, (swig_lua_class *)(swig_types[i]->clientdata)); + } } - } #ifdef SWIG_LUA_MODULE_GLOBAL - globalRegister = 1; + globalRegister = 1; #endif #if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) - SWIG_Lua_namespace_register(L,&swig_SwigModule, globalRegister); + SWIG_Lua_namespace_register(L, &swig_SwigModule, globalRegister); #endif #if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUA) || (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_ELUAC) - for (i = 0; swig_types[i]; i++){ - if (swig_types[i]->clientdata){ - SWIG_Lua_elua_class_register_instance(L,(swig_lua_class*)(swig_types[i]->clientdata)); + for (i = 0; swig_types[i]; i++) { + if (swig_types[i]->clientdata) { + SWIG_Lua_elua_class_register_instance(L, (swig_lua_class *)(swig_types[i]->clientdata)); + } } - } #endif #if defined(SWIG_LUA_ELUA_EMULATE) - lua_newtable(L); - SWIG_Lua_elua_emulate_register(L,swig_SwigModule.ns_methods); - SWIG_Lua_elua_emulate_register_clear(L); - if(globalRegister) { - lua_pushstring(L,swig_SwigModule.name); - lua_pushvalue(L,-2); - lua_rawset(L,-4); - } + lua_newtable(L); + SWIG_Lua_elua_emulate_register(L, swig_SwigModule.ns_methods); + SWIG_Lua_elua_emulate_register_clear(L); + if (globalRegister) { + lua_pushstring(L, swig_SwigModule.name); + lua_pushvalue(L, -2); + lua_rawset(L, -4); + } #endif #endif #if (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC) - /* invoke user-specific initialization */ - SWIG_init_user(L); - /* end module */ - /* Note: We do not clean up the stack here (Lua will do this for us). At this - point, we have the globals table and out module table on the stack. Returning - one value makes the module table the result of the require command. */ - return 1; + /* invoke user-specific initialization */ + SWIG_init_user(L); + /* end module */ + /* Note: We do not clean up the stack here (Lua will do this for us). At this + point, we have the globals table and out module table on the stack. Returning + one value makes the module table the result of the require command. */ + return 1; #else - return 0; + return 0; #endif } @@ -3309,12 +3234,11 @@ SWIGEXPORT int SWIG_init(lua_State* L) /* default Lua action */ #endif -const char* SWIG_LUACODE= - ""; +const char *SWIG_LUACODE = + ""; -void SWIG_init_user(lua_State* L) -{ - /* exec Lua code if applicable */ - SWIG_Lua_dostring(L,SWIG_LUACODE); +void SWIG_init_user(lua_State *L) { + /* exec Lua code if applicable */ + SWIG_Lua_dostring(L, SWIG_LUACODE); } diff --git a/client/src/pm3_pywrap.c b/client/src/pm3_pywrap.c index 8975a5ee0..06e68747a 100644 --- a/client/src/pm3_pywrap.c +++ b/client/src/pm3_pywrap.c @@ -139,7 +139,7 @@ # define SWIG_NULLPTR nullptr #else # define SWIG_NULLPTR NULL -#endif +#endif /* ----------------------------------------------------------------------------- * swigcompat.swg @@ -377,10 +377,10 @@ # define SWIG_CASTRANKMASK ((SWIG_CASTRANKLIMIT) -1) # define SWIG_CastRank(r) (r & SWIG_CASTRANKMASK) SWIGINTERNINLINE int SWIG_AddCast(int r) { - return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r; + return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r; } SWIGINTERNINLINE int SWIG_CheckState(int r) { - return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; + return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; } #else /* no cast-rank mode */ # define SWIG_AddCast(r) (r) @@ -399,32 +399,32 @@ typedef struct swig_type_info *(*swig_dycast_func)(void **); /* Structure to store information on one type */ typedef struct swig_type_info { - const char *name; /* mangled name of this type */ - const char *str; /* human readable name of this type */ - swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ - struct swig_cast_info *cast; /* linked list of types that can cast into this type */ - void *clientdata; /* language specific type data */ - int owndata; /* flag if the structure owns the clientdata */ + const char *name; /* mangled name of this type */ + const char *str; /* human readable name of this type */ + swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ + struct swig_cast_info *cast; /* linked list of types that can cast into this type */ + void *clientdata; /* language specific type data */ + int owndata; /* flag if the structure owns the clientdata */ } swig_type_info; /* Structure to store a type and conversion function used for casting */ typedef struct swig_cast_info { - swig_type_info *type; /* pointer to type that is equivalent to this type */ - swig_converter_func converter; /* function to cast the void pointers */ - struct swig_cast_info *next; /* pointer to next cast in linked list */ - struct swig_cast_info *prev; /* pointer to the previous cast */ + swig_type_info *type; /* pointer to type that is equivalent to this type */ + swig_converter_func converter; /* function to cast the void pointers */ + struct swig_cast_info *next; /* pointer to next cast in linked list */ + struct swig_cast_info *prev; /* pointer to the previous cast */ } swig_cast_info; /* Structure used to store module information * Each module generates one structure like this, and the runtime collects * all of these structures and stores them in a circularly linked list.*/ typedef struct swig_module_info { - swig_type_info **types; /* Array of pointers to swig_type_info structures that are in this module */ - size_t size; /* Number of types in this module */ - struct swig_module_info *next; /* Pointer to next element in circularly linked list */ - swig_type_info **type_initial; /* Array of initially generated type structures */ - swig_cast_info **cast_initial; /* Array of initially generated casting structures */ - void *clientdata; /* Language specific module data */ + swig_type_info **types; /* Array of pointers to swig_type_info structures that are in this module */ + size_t size; /* Number of types in this module */ + struct swig_module_info *next; /* Pointer to next element in circularly linked list */ + swig_type_info **type_initial; /* Array of initially generated type structures */ + swig_cast_info **cast_initial; /* Array of initially generated casting structures */ + void *clientdata; /* Language specific module data */ } swig_module_info; /* @@ -436,13 +436,13 @@ typedef struct swig_module_info { */ SWIGRUNTIME int SWIG_TypeNameComp(const char *f1, const char *l1, - const char *f2, const char *l2) { - for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) { - while ((*f1 == ' ') && (f1 != l1)) ++f1; - while ((*f2 == ' ') && (f2 != l2)) ++f2; - if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1; - } - return (int)((l1 - f1) - (l2 - f2)); + const char *f2, const char *l2) { + for (; (f1 != l1) && (f2 != l2); ++f1, ++f2) { + while ((*f1 == ' ') && (f1 != l1)) ++f1; + while ((*f2 == ' ') && (f2 != l2)) ++f2; + if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1; + } + return (int)((l1 - f1) - (l2 - f2)); } /* @@ -451,17 +451,17 @@ SWIG_TypeNameComp(const char *f1, const char *l1, */ SWIGRUNTIME int SWIG_TypeCmp(const char *nb, const char *tb) { - int equiv = 1; - const char* te = tb + strlen(tb); - const char* ne = nb; - while (equiv != 0 && *ne) { - for (nb = ne; *ne; ++ne) { - if (*ne == '|') break; + int equiv = 1; + const char *te = tb + strlen(tb); + const char *ne = nb; + while (equiv != 0 && *ne) { + for (nb = ne; *ne; ++ne) { + if (*ne == '|') break; + } + equiv = SWIG_TypeNameComp(nb, ne, tb, te); + if (*ne) ++ne; } - equiv = SWIG_TypeNameComp(nb, ne, tb, te); - if (*ne) ++ne; - } - return equiv; + return equiv; } /* @@ -470,7 +470,7 @@ SWIG_TypeCmp(const char *nb, const char *tb) { */ SWIGRUNTIME int SWIG_TypeEquiv(const char *nb, const char *tb) { - return SWIG_TypeCmp(nb, tb) == 0 ? 1 : 0; + return SWIG_TypeCmp(nb, tb) == 0 ? 1 : 0; } /* @@ -478,26 +478,26 @@ SWIG_TypeEquiv(const char *nb, const char *tb) { */ SWIGRUNTIME swig_cast_info * SWIG_TypeCheck(const char *c, swig_type_info *ty) { - if (ty) { - swig_cast_info *iter = ty->cast; - while (iter) { - if (strcmp(iter->type->name, c) == 0) { - if (iter == ty->cast) - return iter; - /* Move iter to the top of the linked list */ - iter->prev->next = iter->next; - if (iter->next) - iter->next->prev = iter->prev; - iter->next = ty->cast; - iter->prev = 0; - if (ty->cast) ty->cast->prev = iter; - ty->cast = iter; - return iter; - } - iter = iter->next; + if (ty) { + swig_cast_info *iter = ty->cast; + while (iter) { + if (strcmp(iter->type->name, c) == 0) { + if (iter == ty->cast) + return iter; + /* Move iter to the top of the linked list */ + iter->prev->next = iter->next; + if (iter->next) + iter->next->prev = iter->prev; + iter->next = ty->cast; + iter->prev = 0; + if (ty->cast) ty->cast->prev = iter; + ty->cast = iter; + return iter; + } + iter = iter->next; + } } - } - return 0; + return 0; } /* @@ -505,26 +505,26 @@ SWIG_TypeCheck(const char *c, swig_type_info *ty) { */ SWIGRUNTIME swig_cast_info * SWIG_TypeCheckStruct(const swig_type_info *from, swig_type_info *ty) { - if (ty) { - swig_cast_info *iter = ty->cast; - while (iter) { - if (iter->type == from) { - if (iter == ty->cast) - return iter; - /* Move iter to the top of the linked list */ - iter->prev->next = iter->next; - if (iter->next) - iter->next->prev = iter->prev; - iter->next = ty->cast; - iter->prev = 0; - if (ty->cast) ty->cast->prev = iter; - ty->cast = iter; - return iter; - } - iter = iter->next; + if (ty) { + swig_cast_info *iter = ty->cast; + while (iter) { + if (iter->type == from) { + if (iter == ty->cast) + return iter; + /* Move iter to the top of the linked list */ + iter->prev->next = iter->next; + if (iter->next) + iter->next->prev = iter->prev; + iter->next = ty->cast; + iter->prev = 0; + if (ty->cast) ty->cast->prev = iter; + ty->cast = iter; + return iter; + } + iter = iter->next; + } } - } - return 0; + return 0; } /* @@ -532,7 +532,7 @@ SWIG_TypeCheckStruct(const swig_type_info *from, swig_type_info *ty) { */ SWIGRUNTIMEINLINE void * SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) { - return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory); + return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory); } /* @@ -540,13 +540,13 @@ SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) { */ SWIGRUNTIME swig_type_info * SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) { - swig_type_info *lastty = ty; - if (!ty || !ty->dcast) return ty; - while (ty && (ty->dcast)) { - ty = (*ty->dcast)(ptr); - if (ty) lastty = ty; - } - return lastty; + swig_type_info *lastty = ty; + if (!ty || !ty->dcast) return ty; + while (ty && (ty->dcast)) { + ty = (*ty->dcast)(ptr); + if (ty) lastty = ty; + } + return lastty; } /* @@ -554,7 +554,7 @@ SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) { */ SWIGRUNTIMEINLINE const char * SWIG_TypeName(const swig_type_info *ty) { - return ty->name; + return ty->name; } /* @@ -563,20 +563,19 @@ SWIG_TypeName(const swig_type_info *ty) { */ SWIGRUNTIME const char * SWIG_TypePrettyName(const swig_type_info *type) { - /* The "str" field contains the equivalent pretty names of the - type, separated by vertical-bar characters. Choose the last - name. It should be the most specific; a fully resolved name - but not necessarily with default template parameters expanded. */ - if (!type) return NULL; - if (type->str != NULL) { - const char *last_name = type->str; - const char *s; - for (s = type->str; *s; s++) - if (*s == '|') last_name = s+1; - return last_name; - } - else - return type->name; + /* The "str" field contains the equivalent pretty names of the + type, separated by vertical-bar characters. Choose the last + name. It should be the most specific; a fully resolved name + but not necessarily with default template parameters expanded. */ + if (!type) return NULL; + if (type->str != NULL) { + const char *last_name = type->str; + const char *s; + for (s = type->str; *s; s++) + if (*s == '|') last_name = s + 1; + return last_name; + } else + return type->name; } /* @@ -584,24 +583,24 @@ SWIG_TypePrettyName(const swig_type_info *type) { */ SWIGRUNTIME void SWIG_TypeClientData(swig_type_info *ti, void *clientdata) { - swig_cast_info *cast = ti->cast; - /* if (ti->clientdata == clientdata) return; */ - ti->clientdata = clientdata; + swig_cast_info *cast = ti->cast; + /* if (ti->clientdata == clientdata) return; */ + ti->clientdata = clientdata; - while (cast) { - if (!cast->converter) { - swig_type_info *tc = cast->type; - if (!tc->clientdata) { - SWIG_TypeClientData(tc, clientdata); - } + while (cast) { + if (!cast->converter) { + swig_type_info *tc = cast->type; + if (!tc->clientdata) { + SWIG_TypeClientData(tc, clientdata); + } + } + cast = cast->next; } - cast = cast->next; - } } SWIGRUNTIME void SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) { - SWIG_TypeClientData(ti, clientdata); - ti->owndata = 1; + SWIG_TypeClientData(ti, clientdata); + ti->owndata = 1; } /* @@ -615,37 +614,37 @@ SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) { SWIGRUNTIME swig_type_info * SWIG_MangledTypeQueryModule(swig_module_info *start, swig_module_info *end, - const char *name) { - swig_module_info *iter = start; - do { - if (iter->size) { - size_t l = 0; - size_t r = iter->size - 1; - do { - /* since l+r >= 0, we can (>> 1) instead (/ 2) */ - size_t i = (l + r) >> 1; - const char *iname = iter->types[i]->name; - if (iname) { - int compare = strcmp(name, iname); - if (compare == 0) { - return iter->types[i]; - } else if (compare < 0) { - if (i) { - r = i - 1; - } else { - break; - } - } else if (compare > 0) { - l = i + 1; - } - } else { - break; /* should never happen */ - } - } while (l <= r); - } - iter = iter->next; - } while (iter != end); - return 0; + const char *name) { + swig_module_info *iter = start; + do { + if (iter->size) { + size_t l = 0; + size_t r = iter->size - 1; + do { + /* since l+r >= 0, we can (>> 1) instead (/ 2) */ + size_t i = (l + r) >> 1; + const char *iname = iter->types[i]->name; + if (iname) { + int compare = strcmp(name, iname); + if (compare == 0) { + return iter->types[i]; + } else if (compare < 0) { + if (i) { + r = i - 1; + } else { + break; + } + } else if (compare > 0) { + l = i + 1; + } + } else { + break; /* should never happen */ + } + } while (l <= r); + } + iter = iter->next; + } while (iter != end); + return 0; } /* @@ -660,27 +659,27 @@ SWIG_MangledTypeQueryModule(swig_module_info *start, SWIGRUNTIME swig_type_info * SWIG_TypeQueryModule(swig_module_info *start, swig_module_info *end, - const char *name) { - /* STEP 1: Search the name field using binary search */ - swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name); - if (ret) { - return ret; - } else { - /* STEP 2: If the type hasn't been found, do a complete search - of the str field (the human readable name) */ - swig_module_info *iter = start; - do { - size_t i = 0; - for (; i < iter->size; ++i) { - if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name))) - return iter->types[i]; - } - iter = iter->next; - } while (iter != end); - } + const char *name) { + /* STEP 1: Search the name field using binary search */ + swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name); + if (ret) { + return ret; + } else { + /* STEP 2: If the type hasn't been found, do a complete search + of the str field (the human readable name) */ + swig_module_info *iter = start; + do { + size_t i = 0; + for (; i < iter->size; ++i) { + if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name))) + return iter->types[i]; + } + iter = iter->next; + } while (iter != end); + } - /* neither found a match */ - return 0; + /* neither found a match */ + return 0; } /* @@ -688,15 +687,15 @@ SWIG_TypeQueryModule(swig_module_info *start, */ SWIGRUNTIME char * SWIG_PackData(char *c, void *ptr, size_t sz) { - static const char hex[17] = "0123456789abcdef"; - const unsigned char *u = (unsigned char *) ptr; - const unsigned char *eu = u + sz; - for (; u != eu; ++u) { - unsigned char uu = *u; - *(c++) = hex[(uu & 0xf0) >> 4]; - *(c++) = hex[uu & 0xf]; - } - return c; + static const char hex[17] = "0123456789abcdef"; + const unsigned char *u = (unsigned char *) ptr; + const unsigned char *eu = u + sz; + for (; u != eu; ++u) { + unsigned char uu = *u; + *(c++) = hex[(uu & 0xf0) >> 4]; + *(c++) = hex[uu & 0xf]; + } + return c; } /* @@ -704,27 +703,27 @@ SWIG_PackData(char *c, void *ptr, size_t sz) { */ SWIGRUNTIME const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { - unsigned char *u = (unsigned char *) ptr; - const unsigned char *eu = u + sz; - for (; u != eu; ++u) { - char d = *(c++); - unsigned char uu; - if ((d >= '0') && (d <= '9')) - uu = (unsigned char)((d - '0') << 4); - else if ((d >= 'a') && (d <= 'f')) - uu = (unsigned char)((d - ('a'-10)) << 4); - else - return (char *) 0; - d = *(c++); - if ((d >= '0') && (d <= '9')) - uu |= (unsigned char)(d - '0'); - else if ((d >= 'a') && (d <= 'f')) - uu |= (unsigned char)(d - ('a'-10)); - else - return (char *) 0; - *u = uu; - } - return c; + unsigned char *u = (unsigned char *) ptr; + const unsigned char *eu = u + sz; + for (; u != eu; ++u) { + char d = *(c++); + unsigned char uu; + if ((d >= '0') && (d <= '9')) + uu = (unsigned char)((d - '0') << 4); + else if ((d >= 'a') && (d <= 'f')) + uu = (unsigned char)((d - ('a' - 10)) << 4); + else + return (char *) 0; + d = *(c++); + if ((d >= '0') && (d <= '9')) + uu |= (unsigned char)(d - '0'); + else if ((d >= 'a') && (d <= 'f')) + uu |= (unsigned char)(d - ('a' - 10)); + else + return (char *) 0; + *u = uu; + } + return c; } /* @@ -732,54 +731,54 @@ SWIG_UnpackData(const char *c, void *ptr, size_t sz) { */ SWIGRUNTIME char * SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) { - char *r = buff; - if ((2*sizeof(void *) + 2) > bsz) return 0; - *(r++) = '_'; - r = SWIG_PackData(r,&ptr,sizeof(void *)); - if (strlen(name) + 1 > (bsz - (r - buff))) return 0; - strcpy(r,name); - return buff; + char *r = buff; + if ((2 * sizeof(void *) + 2) > bsz) return 0; + *(r++) = '_'; + r = SWIG_PackData(r, &ptr, sizeof(void *)); + if (strlen(name) + 1 > (bsz - (r - buff))) return 0; + strcpy(r, name); + return buff; } SWIGRUNTIME const char * SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) { - if (*c != '_') { - if (strcmp(c,"NULL") == 0) { - *ptr = (void *) 0; - return name; - } else { - return 0; + if (*c != '_') { + if (strcmp(c, "NULL") == 0) { + *ptr = (void *) 0; + return name; + } else { + return 0; + } } - } - return SWIG_UnpackData(++c,ptr,sizeof(void *)); + return SWIG_UnpackData(++c, ptr, sizeof(void *)); } SWIGRUNTIME char * SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) { - char *r = buff; - size_t lname = (name ? strlen(name) : 0); - if ((2*sz + 2 + lname) > bsz) return 0; - *(r++) = '_'; - r = SWIG_PackData(r,ptr,sz); - if (lname) { - strncpy(r,name,lname+1); - } else { - *r = 0; - } - return buff; + char *r = buff; + size_t lname = (name ? strlen(name) : 0); + if ((2 * sz + 2 + lname) > bsz) return 0; + *(r++) = '_'; + r = SWIG_PackData(r, ptr, sz); + if (lname) { + strncpy(r, name, lname + 1); + } else { + *r = 0; + } + return buff; } SWIGRUNTIME const char * SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) { - if (*c != '_') { - if (strcmp(c,"NULL") == 0) { - memset(ptr,0,sz); - return name; - } else { - return 0; + if (*c != '_') { + if (strcmp(c, "NULL") == 0) { + memset(ptr, 0, sz); + return name; + } else { + return 0; + } } - } - return SWIG_UnpackData(++c,ptr,sz); + return SWIG_UnpackData(++c, ptr, sz); } #ifdef __cplusplus @@ -814,7 +813,7 @@ SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) { #define PyString_FromString(x) PyUnicode_FromString(x) #define PyString_Format(fmt, args) PyUnicode_Format(fmt, args) #define PyString_AsString(str) PyBytes_AsString(str) -#define PyString_Size(str) PyBytes_Size(str) +#define PyString_Size(str) PyBytes_Size(str) #define PyString_InternFromString(key) PyUnicode_InternFromString(key) #define Py_TPFLAGS_HAVE_CLASS Py_TPFLAGS_BASETYPE #define _PyLong_FromSsize_t(x) PyLong_FromSsize_t(x) @@ -836,34 +835,32 @@ SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) { /* Wrapper around PyUnicode_AsUTF8AndSize - call Py_XDECREF on the returned pbytes when finished with the returned string */ SWIGINTERN const char * -SWIG_PyUnicode_AsUTF8AndSize(PyObject *str, Py_ssize_t *psize, PyObject **pbytes) -{ +SWIG_PyUnicode_AsUTF8AndSize(PyObject *str, Py_ssize_t *psize, PyObject **pbytes) { #if PY_VERSION_HEX >= 0x03030000 # if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x030A0000 - *pbytes = NULL; - return PyUnicode_AsUTF8AndSize(str, psize); + *pbytes = NULL; + return PyUnicode_AsUTF8AndSize(str, psize); # else - *pbytes = PyUnicode_AsUTF8String(str); - const char *chars = *pbytes ? PyBytes_AsString(*pbytes) : NULL; - if (chars && psize) - *psize = PyBytes_Size(*pbytes); - return chars; + *pbytes = PyUnicode_AsUTF8String(str); + const char *chars = *pbytes ? PyBytes_AsString(*pbytes) : NULL; + if (chars && psize) + *psize = PyBytes_Size(*pbytes); + return chars; # endif #else - char *chars = NULL; - *pbytes = NULL; - PyString_AsStringAndSize(str, &chars, psize); - return chars; + char *chars = NULL; + *pbytes = NULL; + PyString_AsStringAndSize(str, &chars, psize); + return chars; #endif } -SWIGINTERN PyObject* -SWIG_Python_str_FromChar(const char *c) -{ +SWIGINTERN PyObject * +SWIG_Python_str_FromChar(const char *c) { #if PY_VERSION_HEX >= 0x03000000 - return PyUnicode_FromString(c); + return PyUnicode_FromString(c); #else - return PyString_FromString(c); + return PyString_FromString(c); #endif } @@ -904,110 +901,107 @@ SWIG_Python_str_FromChar(const char *c) * error manipulation * ----------------------------------------------------------------------------- */ -SWIGRUNTIME PyObject* +SWIGRUNTIME PyObject * SWIG_Python_ErrorType(int code) { - PyObject* type = 0; - switch(code) { - case SWIG_MemoryError: - type = PyExc_MemoryError; - break; - case SWIG_IOError: - type = PyExc_IOError; - break; - case SWIG_RuntimeError: - type = PyExc_RuntimeError; - break; - case SWIG_IndexError: - type = PyExc_IndexError; - break; - case SWIG_TypeError: - type = PyExc_TypeError; - break; - case SWIG_DivisionByZero: - type = PyExc_ZeroDivisionError; - break; - case SWIG_OverflowError: - type = PyExc_OverflowError; - break; - case SWIG_SyntaxError: - type = PyExc_SyntaxError; - break; - case SWIG_ValueError: - type = PyExc_ValueError; - break; - case SWIG_SystemError: - type = PyExc_SystemError; - break; - case SWIG_AttributeError: - type = PyExc_AttributeError; - break; - default: - type = PyExc_RuntimeError; - } - return type; + PyObject *type = 0; + switch (code) { + case SWIG_MemoryError: + type = PyExc_MemoryError; + break; + case SWIG_IOError: + type = PyExc_IOError; + break; + case SWIG_RuntimeError: + type = PyExc_RuntimeError; + break; + case SWIG_IndexError: + type = PyExc_IndexError; + break; + case SWIG_TypeError: + type = PyExc_TypeError; + break; + case SWIG_DivisionByZero: + type = PyExc_ZeroDivisionError; + break; + case SWIG_OverflowError: + type = PyExc_OverflowError; + break; + case SWIG_SyntaxError: + type = PyExc_SyntaxError; + break; + case SWIG_ValueError: + type = PyExc_ValueError; + break; + case SWIG_SystemError: + type = PyExc_SystemError; + break; + case SWIG_AttributeError: + type = PyExc_AttributeError; + break; + default: + type = PyExc_RuntimeError; + } + return type; } SWIGRUNTIME void -SWIG_Python_AddErrorMsg(const char* mesg) -{ - PyObject *type = 0; - PyObject *value = 0; - PyObject *traceback = 0; +SWIG_Python_AddErrorMsg(const char *mesg) { + PyObject *type = 0; + PyObject *value = 0; + PyObject *traceback = 0; - if (PyErr_Occurred()) - PyErr_Fetch(&type, &value, &traceback); - if (value) { - PyObject *old_str = PyObject_Str(value); - PyObject *bytes = NULL; - const char *tmp = SWIG_PyUnicode_AsUTF8AndSize(old_str, NULL, &bytes); - PyErr_Clear(); - Py_XINCREF(type); - if (tmp) - PyErr_Format(type, "%s %s", tmp, mesg); - else - PyErr_Format(type, "%s", mesg); - Py_XDECREF(bytes); - Py_DECREF(old_str); - Py_DECREF(value); - } else { - PyErr_SetString(PyExc_RuntimeError, mesg); - } + if (PyErr_Occurred()) + PyErr_Fetch(&type, &value, &traceback); + if (value) { + PyObject *old_str = PyObject_Str(value); + PyObject *bytes = NULL; + const char *tmp = SWIG_PyUnicode_AsUTF8AndSize(old_str, NULL, &bytes); + PyErr_Clear(); + Py_XINCREF(type); + if (tmp) + PyErr_Format(type, "%s %s", tmp, mesg); + else + PyErr_Format(type, "%s", mesg); + Py_XDECREF(bytes); + Py_DECREF(old_str); + Py_DECREF(value); + } else { + PyErr_SetString(PyExc_RuntimeError, mesg); + } } SWIGRUNTIME int -SWIG_Python_TypeErrorOccurred(PyObject *obj) -{ - PyObject *error; - if (obj) - return 0; - error = PyErr_Occurred(); - return error && PyErr_GivenExceptionMatches(error, PyExc_TypeError); +SWIG_Python_TypeErrorOccurred(PyObject *obj) { + PyObject *error; + if (obj) + return 0; + error = PyErr_Occurred(); + return error && PyErr_GivenExceptionMatches(error, PyExc_TypeError); } SWIGRUNTIME void -SWIG_Python_RaiseOrModifyTypeError(const char *message) -{ - if (SWIG_Python_TypeErrorOccurred(NULL)) { - /* Use existing TypeError to preserve stacktrace and enhance with given message */ - PyObject *newvalue; - PyObject *type = NULL, *value = NULL, *traceback = NULL; - PyErr_Fetch(&type, &value, &traceback); +SWIG_Python_RaiseOrModifyTypeError(const char *message) { + if (SWIG_Python_TypeErrorOccurred(NULL)) { + /* Use existing TypeError to preserve stacktrace and enhance with given message */ + PyObject *newvalue; + PyObject *type = NULL, *value = NULL, *traceback = NULL; + PyErr_Fetch(&type, &value, &traceback); #if PY_VERSION_HEX >= 0x03000000 - newvalue = PyUnicode_FromFormat("%S\nAdditional information:\n%s", value, message); + newvalue = PyUnicode_FromFormat("%S\nAdditional information:\n%s", value, message); #else - newvalue = PyString_FromFormat("%s\nAdditional information:\n%s", PyString_AsString(value), message); + newvalue = PyString_FromFormat("%s\nAdditional information:\n%s", PyString_AsString(value), message); #endif - if (newvalue) { - Py_XDECREF(value); - PyErr_Restore(type, newvalue, traceback); + if (newvalue) { + Py_XDECREF(value); + PyErr_Restore(type, newvalue, traceback); + } else { + PyErr_Restore(type, value, traceback); + } } else { - PyErr_Restore(type, value, traceback); + /* Raise TypeError using given message */ + PyErr_SetString(PyExc_TypeError, message); } - } else { - /* Raise TypeError using given message */ - PyErr_SetString(PyExc_TypeError, message); - } } #if defined(SWIG_PYTHON_NO_THREADS) @@ -1028,22 +1022,22 @@ SWIG_Python_RaiseOrModifyTypeError(const char *message) # endif # endif # ifdef __cplusplus /* C++ code */ - class SWIG_Python_Thread_Block { - bool status; - PyGILState_STATE state; - public: - void end() { if (status) { PyGILState_Release(state); status = false;} } - SWIG_Python_Thread_Block() : status(true), state(PyGILState_Ensure()) {} - ~SWIG_Python_Thread_Block() { end(); } - }; - class SWIG_Python_Thread_Allow { - bool status; - PyThreadState *save; - public: - void end() { if (status) { status = false; PyEval_RestoreThread(save); }} - SWIG_Python_Thread_Allow() : status(true), save(PyEval_SaveThread()) {} - ~SWIG_Python_Thread_Allow() { end(); } - }; +class SWIG_Python_Thread_Block { + bool status; + PyGILState_STATE state; + public: + void end() { if (status) { PyGILState_Release(state); status = false;} } + SWIG_Python_Thread_Block() : status(true), state(PyGILState_Ensure()) {} + ~SWIG_Python_Thread_Block() { end(); } +}; +class SWIG_Python_Thread_Allow { + bool status; + PyThreadState *save; + public: + void end() { if (status) { status = false; PyEval_RestoreThread(save); }} + SWIG_Python_Thread_Allow() : status(true), save(PyEval_SaveThread()) {} + ~SWIG_Python_Thread_Allow() { end(); } +}; # define SWIG_PYTHON_THREAD_BEGIN_BLOCK SWIG_Python_Thread_Block _swig_thread_block # define SWIG_PYTHON_THREAD_END_BLOCK _swig_thread_block.end() # define SWIG_PYTHON_THREAD_BEGIN_ALLOW SWIG_Python_Thread_Allow _swig_thread_allow @@ -1097,12 +1091,12 @@ extern "C" { /* Constant information structure */ typedef struct swig_const_info { - int type; - const char *name; - long lvalue; - double dvalue; - void *pvalue; - swig_type_info **ptype; + int type; + const char *name; + long lvalue; + double dvalue; + void *pvalue; + swig_type_info **ptype; } swig_const_info; #ifdef __cplusplus @@ -1142,7 +1136,7 @@ typedef struct swig_const_info { #define SWIG_InternalNewPointerObj(ptr, type, flags) SWIG_Python_NewPointerObj(NULL, ptr, type, flags) -#define SWIG_CheckImplicit(ty) SWIG_Python_CheckImplicit(ty) +#define SWIG_CheckImplicit(ty) SWIG_Python_CheckImplicit(ty) #define SWIG_AcquirePtr(ptr, src) SWIG_Python_AcquirePtr(ptr, src) #define swig_owntype int @@ -1169,30 +1163,30 @@ typedef struct swig_const_info { #define SWIG_SetModule(clientdata, pointer) SWIG_Python_SetModule(pointer) #define SWIG_NewClientData(obj) SwigPyClientData_New(obj) -#define SWIG_SetErrorObj SWIG_Python_SetErrorObj -#define SWIG_SetErrorMsg SWIG_Python_SetErrorMsg -#define SWIG_ErrorType(code) SWIG_Python_ErrorType(code) -#define SWIG_Error(code, msg) SWIG_Python_SetErrorMsg(SWIG_ErrorType(code), msg) -#define SWIG_fail goto fail +#define SWIG_SetErrorObj SWIG_Python_SetErrorObj +#define SWIG_SetErrorMsg SWIG_Python_SetErrorMsg +#define SWIG_ErrorType(code) SWIG_Python_ErrorType(code) +#define SWIG_Error(code, msg) SWIG_Python_SetErrorMsg(SWIG_ErrorType(code), msg) +#define SWIG_fail goto fail /* Runtime API implementation */ /* Error manipulation */ -SWIGINTERN void +SWIGINTERN void SWIG_Python_SetErrorObj(PyObject *errtype, PyObject *obj) { - SWIG_PYTHON_THREAD_BEGIN_BLOCK; - PyErr_SetObject(errtype, obj); - Py_DECREF(obj); - SWIG_PYTHON_THREAD_END_BLOCK; + SWIG_PYTHON_THREAD_BEGIN_BLOCK; + PyErr_SetObject(errtype, obj); + Py_DECREF(obj); + SWIG_PYTHON_THREAD_END_BLOCK; } -SWIGINTERN void +SWIGINTERN void SWIG_Python_SetErrorMsg(PyObject *errtype, const char *msg) { - SWIG_PYTHON_THREAD_BEGIN_BLOCK; - PyErr_SetString(errtype, msg); - SWIG_PYTHON_THREAD_END_BLOCK; + SWIG_PYTHON_THREAD_BEGIN_BLOCK; + PyErr_SetString(errtype, msg); + SWIG_PYTHON_THREAD_END_BLOCK; } #define SWIG_Python_Raise(obj, type, desc) SWIG_Python_SetErrorObj(SWIG_Python_ExceptionType(desc), obj) @@ -1203,114 +1197,113 @@ SWIG_Python_SetErrorMsg(PyObject *errtype, const char *msg) { SWIGINTERN void SwigPyBuiltin_AddPublicSymbol(PyObject *seq, const char *key) { - PyObject *s = PyString_InternFromString(key); - PyList_Append(seq, s); - Py_DECREF(s); + PyObject *s = PyString_InternFromString(key); + PyList_Append(seq, s); + Py_DECREF(s); } SWIGINTERN void -SWIG_Python_SetConstant(PyObject *d, PyObject *public_interface, const char *name, PyObject *obj) { - PyDict_SetItemString(d, name, obj); - Py_DECREF(obj); - if (public_interface) - SwigPyBuiltin_AddPublicSymbol(public_interface, name); +SWIG_Python_SetConstant(PyObject *d, PyObject *public_interface, const char *name, PyObject *obj) { + PyDict_SetItemString(d, name, obj); + Py_DECREF(obj); + if (public_interface) + SwigPyBuiltin_AddPublicSymbol(public_interface, name); } #else SWIGINTERN void -SWIG_Python_SetConstant(PyObject *d, const char *name, PyObject *obj) { - PyDict_SetItemString(d, name, obj); - Py_DECREF(obj); +SWIG_Python_SetConstant(PyObject *d, const char *name, PyObject *obj) { + PyDict_SetItemString(d, name, obj); + Py_DECREF(obj); } #endif /* Append a value to the result obj */ -SWIGINTERN PyObject* -SWIG_Python_AppendOutput(PyObject* result, PyObject* obj) { - if (!result) { - result = obj; - } else if (result == Py_None) { - Py_DECREF(result); - result = obj; - } else { - if (!PyList_Check(result)) { - PyObject *o2 = result; - result = PyList_New(1); - if (result) { - PyList_SET_ITEM(result, 0, o2); - } else { +SWIGINTERN PyObject * +SWIG_Python_AppendOutput(PyObject *result, PyObject *obj) { + if (!result) { + result = obj; + } else if (result == Py_None) { + Py_DECREF(result); + result = obj; + } else { + if (!PyList_Check(result)) { + PyObject *o2 = result; + result = PyList_New(1); + if (result) { + PyList_SET_ITEM(result, 0, o2); + } else { + Py_DECREF(obj); + return o2; + } + } + PyList_Append(result, obj); Py_DECREF(obj); - return o2; - } } - PyList_Append(result,obj); - Py_DECREF(obj); - } - return result; + return result; } /* Unpack the argument tuple */ SWIGINTERN Py_ssize_t -SWIG_Python_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, PyObject **objs) -{ - if (!args) { - if (!min && !max) { - return 1; - } else { - PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got none", - name, (min == max ? "" : "at least "), (int)min); - return 0; +SWIG_Python_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, PyObject **objs) { + if (!args) { + if (!min && !max) { + return 1; + } else { + PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got none", + name, (min == max ? "" : "at least "), (int)min); + return 0; + } } - } - if (!PyTuple_Check(args)) { - if (min <= 1 && max >= 1) { - Py_ssize_t i; - objs[0] = args; - for (i = 1; i < max; ++i) { - objs[i] = 0; - } - return 2; - } - PyErr_SetString(PyExc_SystemError, "UnpackTuple() argument list is not a tuple"); - return 0; - } else { - Py_ssize_t l = PyTuple_GET_SIZE(args); - if (l < min) { - PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", - name, (min == max ? "" : "at least "), (int)min, (int)l); - return 0; - } else if (l > max) { - PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", - name, (min == max ? "" : "at most "), (int)max, (int)l); - return 0; + if (!PyTuple_Check(args)) { + if (min <= 1 && max >= 1) { + Py_ssize_t i; + objs[0] = args; + for (i = 1; i < max; ++i) { + objs[i] = 0; + } + return 2; + } + PyErr_SetString(PyExc_SystemError, "UnpackTuple() argument list is not a tuple"); + return 0; } else { - Py_ssize_t i; - for (i = 0; i < l; ++i) { - objs[i] = PyTuple_GET_ITEM(args, i); - } - for (; l < max; ++l) { - objs[l] = 0; - } - return i + 1; - } - } + Py_ssize_t l = PyTuple_GET_SIZE(args); + if (l < min) { + PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", + name, (min == max ? "" : "at least "), (int)min, (int)l); + return 0; + } else if (l > max) { + PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", + name, (min == max ? "" : "at most "), (int)max, (int)l); + return 0; + } else { + Py_ssize_t i; + for (i = 0; i < l; ++i) { + objs[i] = PyTuple_GET_ITEM(args, i); + } + for (; l < max; ++l) { + objs[l] = 0; + } + return i + 1; + } + } } SWIGINTERN int SWIG_Python_CheckNoKeywords(PyObject *kwargs, const char *name) { - int no_kwargs = 1; - if (kwargs) { - assert(PyDict_Check(kwargs)); - if (PyDict_Size(kwargs) > 0) { - PyErr_Format(PyExc_TypeError, "%s() does not take keyword arguments", name); - no_kwargs = 0; + int no_kwargs = 1; + if (kwargs) { + assert(PyDict_Check(kwargs)); + if (PyDict_Size(kwargs) > 0) { + PyErr_Format(PyExc_TypeError, "%s() does not take keyword arguments", name); + no_kwargs = 0; + } } - } - return no_kwargs; + return no_kwargs; } /* A functor is a function object with one single object argument */ @@ -1334,247 +1327,247 @@ extern "C" { #define SWIG_newvarlink() SWIG_Python_newvarlink() #define SWIG_addvarlink(p, name, get_attr, set_attr) SWIG_Python_addvarlink(p, name, get_attr, set_attr) #define SWIG_InstallConstants(d, constants) SWIG_Python_InstallConstants(d, constants) - + /* ----------------------------------------------------------------------------- * global variable support code. * ----------------------------------------------------------------------------- */ - -typedef struct swig_globalvar { - char *name; /* Name of global variable */ - PyObject *(*get_attr)(void); /* Return the current value */ - int (*set_attr)(PyObject *); /* Set the value */ - struct swig_globalvar *next; + +typedef struct swig_globalvar { + char *name; /* Name of global variable */ + PyObject *(*get_attr)(void); /* Return the current value */ + int (*set_attr)(PyObject *); /* Set the value */ + struct swig_globalvar *next; } swig_globalvar; typedef struct swig_varlinkobject { - PyObject_HEAD - swig_globalvar *vars; + PyObject_HEAD + swig_globalvar *vars; } swig_varlinkobject; SWIGINTERN PyObject * swig_varlink_repr(PyObject *SWIGUNUSEDPARM(v)) { #if PY_VERSION_HEX >= 0x03000000 - return PyUnicode_InternFromString(""); + return PyUnicode_InternFromString(""); #else - return PyString_FromString(""); + return PyString_FromString(""); #endif } SWIGINTERN PyObject * swig_varlink_str(PyObject *o) { - swig_varlinkobject *v = (swig_varlinkobject *) o; + swig_varlinkobject *v = (swig_varlinkobject *) o; #if PY_VERSION_HEX >= 0x03000000 - PyObject *str = PyUnicode_InternFromString("("); - PyObject *tail; - PyObject *joined; - swig_globalvar *var; - for (var = v->vars; var; var=var->next) { - tail = PyUnicode_FromString(var->name); - joined = PyUnicode_Concat(str, tail); - Py_DecRef(str); - Py_DecRef(tail); - str = joined; - if (var->next) { - tail = PyUnicode_InternFromString(", "); + PyObject *str = PyUnicode_InternFromString("("); + PyObject *tail; + PyObject *joined; + swig_globalvar *var; + for (var = v->vars; var; var = var->next) { + tail = PyUnicode_FromString(var->name); joined = PyUnicode_Concat(str, tail); Py_DecRef(str); Py_DecRef(tail); str = joined; + if (var->next) { + tail = PyUnicode_InternFromString(", "); + joined = PyUnicode_Concat(str, tail); + Py_DecRef(str); + Py_DecRef(tail); + str = joined; + } } - } - tail = PyUnicode_InternFromString(")"); - joined = PyUnicode_Concat(str, tail); - Py_DecRef(str); - Py_DecRef(tail); - str = joined; + tail = PyUnicode_InternFromString(")"); + joined = PyUnicode_Concat(str, tail); + Py_DecRef(str); + Py_DecRef(tail); + str = joined; #else - PyObject *str = PyString_FromString("("); - swig_globalvar *var; - for (var = v->vars; var; var=var->next) { - PyString_ConcatAndDel(&str,PyString_FromString(var->name)); - if (var->next) PyString_ConcatAndDel(&str,PyString_FromString(", ")); - } - PyString_ConcatAndDel(&str,PyString_FromString(")")); + PyObject *str = PyString_FromString("("); + swig_globalvar *var; + for (var = v->vars; var; var = var->next) { + PyString_ConcatAndDel(&str, PyString_FromString(var->name)); + if (var->next) PyString_ConcatAndDel(&str, PyString_FromString(", ")); + } + PyString_ConcatAndDel(&str, PyString_FromString(")")); #endif - return str; + return str; } SWIGINTERN void swig_varlink_dealloc(PyObject *o) { - swig_varlinkobject *v = (swig_varlinkobject *) o; - swig_globalvar *var = v->vars; - while (var) { - swig_globalvar *n = var->next; - free(var->name); - free(var); - var = n; - } + swig_varlinkobject *v = (swig_varlinkobject *) o; + swig_globalvar *var = v->vars; + while (var) { + swig_globalvar *n = var->next; + free(var->name); + free(var); + var = n; + } } SWIGINTERN PyObject * swig_varlink_getattr(PyObject *o, char *n) { - swig_varlinkobject *v = (swig_varlinkobject *) o; - PyObject *res = NULL; - swig_globalvar *var = v->vars; - while (var) { - if (strcmp(var->name,n) == 0) { - res = (*var->get_attr)(); - break; + swig_varlinkobject *v = (swig_varlinkobject *) o; + PyObject *res = NULL; + swig_globalvar *var = v->vars; + while (var) { + if (strcmp(var->name, n) == 0) { + res = (*var->get_attr)(); + break; + } + var = var->next; } - var = var->next; - } - if (res == NULL && !PyErr_Occurred()) { - PyErr_Format(PyExc_AttributeError, "Unknown C global variable '%s'", n); - } - return res; + if (res == NULL && !PyErr_Occurred()) { + PyErr_Format(PyExc_AttributeError, "Unknown C global variable '%s'", n); + } + return res; } SWIGINTERN int swig_varlink_setattr(PyObject *o, char *n, PyObject *p) { - swig_varlinkobject *v = (swig_varlinkobject *) o; - int res = 1; - swig_globalvar *var = v->vars; - while (var) { - if (strcmp(var->name,n) == 0) { - res = (*var->set_attr)(p); - break; + swig_varlinkobject *v = (swig_varlinkobject *) o; + int res = 1; + swig_globalvar *var = v->vars; + while (var) { + if (strcmp(var->name, n) == 0) { + res = (*var->set_attr)(p); + break; + } + var = var->next; } - var = var->next; - } - if (res == 1 && !PyErr_Occurred()) { - PyErr_Format(PyExc_AttributeError, "Unknown C global variable '%s'", n); - } - return res; + if (res == 1 && !PyErr_Occurred()) { + PyErr_Format(PyExc_AttributeError, "Unknown C global variable '%s'", n); + } + return res; } -SWIGINTERN PyTypeObject* +SWIGINTERN PyTypeObject * swig_varlink_type(void) { - static char varlink__doc__[] = "Swig var link object"; + static char varlink__doc__[] = "Swig var link object"; #ifndef Py_LIMITED_API - static PyTypeObject varlink_type; - static int type_init = 0; - if (!type_init) { - const PyTypeObject tmp = { + static PyTypeObject varlink_type; + static int type_init = 0; + if (!type_init) { + const PyTypeObject tmp = { #if PY_VERSION_HEX >= 0x03000000 - PyVarObject_HEAD_INIT(NULL, 0) + PyVarObject_HEAD_INIT(NULL, 0) #else - PyObject_HEAD_INIT(NULL) - 0, /* ob_size */ + PyObject_HEAD_INIT(NULL) + 0, /* ob_size */ #endif - "swigvarlink", /* tp_name */ - sizeof(swig_varlinkobject), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor) swig_varlink_dealloc, /* tp_dealloc */ + "swigvarlink", /* tp_name */ + sizeof(swig_varlinkobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor) swig_varlink_dealloc, /* tp_dealloc */ #if PY_VERSION_HEX < 0x030800b4 - (printfunc)0, /*tp_print*/ + (printfunc)0, /*tp_print*/ #else - (Py_ssize_t)0, /*tp_vectorcall_offset*/ + (Py_ssize_t)0, /*tp_vectorcall_offset*/ #endif - (getattrfunc) swig_varlink_getattr, /* tp_getattr */ - (setattrfunc) swig_varlink_setattr, /* tp_setattr */ - 0, /* tp_compare */ - (reprfunc) swig_varlink_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - 0, /* tp_call */ - (reprfunc) swig_varlink_str, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - 0, /* tp_flags */ - varlink__doc__, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* tp_iter -> tp_weaklist */ - 0, /* tp_del */ - 0, /* tp_version_tag */ + (getattrfunc) swig_varlink_getattr, /* tp_getattr */ + (setattrfunc) swig_varlink_setattr, /* tp_setattr */ + 0, /* tp_compare */ + (reprfunc) swig_varlink_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + (reprfunc) swig_varlink_str, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + 0, /* tp_flags */ + varlink__doc__, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* tp_iter -> tp_weaklist */ + 0, /* tp_del */ + 0, /* tp_version_tag */ #if PY_VERSION_HEX >= 0x03040000 - 0, /* tp_finalize */ + 0, /* tp_finalize */ #endif #if PY_VERSION_HEX >= 0x03080000 - 0, /* tp_vectorcall */ + 0, /* tp_vectorcall */ #endif #if (PY_VERSION_HEX >= 0x03080000) && (PY_VERSION_HEX < 0x03090000) - 0, /* tp_print */ + 0, /* tp_print */ #endif #if PY_VERSION_HEX >= 0x030C0000 - 0, /* tp_watched */ + 0, /* tp_watched */ #endif #ifdef COUNT_ALLOCS - 0, /* tp_allocs */ - 0, /* tp_frees */ - 0, /* tp_maxalloc */ - 0, /* tp_prev */ - 0 /* tp_next */ + 0, /* tp_allocs */ + 0, /* tp_frees */ + 0, /* tp_maxalloc */ + 0, /* tp_prev */ + 0 /* tp_next */ #endif - }; - varlink_type = tmp; - type_init = 1; - if (PyType_Ready(&varlink_type) < 0) - return NULL; - } - return &varlink_type; + }; + varlink_type = tmp; + type_init = 1; + if (PyType_Ready(&varlink_type) < 0) + return NULL; + } + return &varlink_type; #else - PyType_Slot slots[] = { - { Py_tp_dealloc, (void *)swig_varlink_dealloc }, - { Py_tp_repr, (void *)swig_varlink_repr }, - { Py_tp_getattr, (void *)swig_varlink_getattr }, - { Py_tp_setattr, (void *)swig_varlink_setattr }, - { Py_tp_str, (void *)swig_varlink_str }, - { Py_tp_doc, (void *)varlink__doc__ }, - { 0, NULL } - }; - PyType_Spec spec = { - "swigvarlink", - sizeof(swig_varlinkobject), - 0, - Py_TPFLAGS_DEFAULT, - slots - }; - return (PyTypeObject *)PyType_FromSpec(&spec); + PyType_Slot slots[] = { + { Py_tp_dealloc, (void *)swig_varlink_dealloc }, + { Py_tp_repr, (void *)swig_varlink_repr }, + { Py_tp_getattr, (void *)swig_varlink_getattr }, + { Py_tp_setattr, (void *)swig_varlink_setattr }, + { Py_tp_str, (void *)swig_varlink_str }, + { Py_tp_doc, (void *)varlink__doc__ }, + { 0, NULL } + }; + PyType_Spec spec = { + "swigvarlink", + sizeof(swig_varlinkobject), + 0, + Py_TPFLAGS_DEFAULT, + slots + }; + return (PyTypeObject *)PyType_FromSpec(&spec); #endif } /* Create a variable linking object for use later */ SWIGINTERN PyObject * SWIG_Python_newvarlink(void) { - swig_varlinkobject *result = PyObject_New(swig_varlinkobject, swig_varlink_type()); - if (result) { - result->vars = 0; - } - return ((PyObject*) result); + swig_varlinkobject *result = PyObject_New(swig_varlinkobject, swig_varlink_type()); + if (result) { + result->vars = 0; + } + return ((PyObject *) result); } -SWIGINTERN void -SWIG_Python_addvarlink(PyObject *p, const char *name, PyObject *(*get_attr)(void), int (*set_attr)(PyObject *p)) { - swig_varlinkobject *v = (swig_varlinkobject *) p; - swig_globalvar *gv = (swig_globalvar *) malloc(sizeof(swig_globalvar)); - if (gv) { - size_t size = strlen(name)+1; - gv->name = (char *)malloc(size); - if (gv->name) { - memcpy(gv->name, name, size); - gv->get_attr = get_attr; - gv->set_attr = set_attr; - gv->next = v->vars; +SWIGINTERN void +SWIG_Python_addvarlink(PyObject *p, const char *name, PyObject * (*get_attr)(void), int (*set_attr)(PyObject *p)) { + swig_varlinkobject *v = (swig_varlinkobject *) p; + swig_globalvar *gv = (swig_globalvar *) malloc(sizeof(swig_globalvar)); + if (gv) { + size_t size = strlen(name) + 1; + gv->name = (char *)malloc(size); + if (gv->name) { + memcpy(gv->name, name, size); + gv->get_attr = get_attr; + gv->set_attr = set_attr; + gv->next = v->vars; + } } - } - v->vars = gv; + v->vars = gv; } static PyObject *Swig_Globals_global = NULL; - + SWIGINTERN PyObject * SWIG_globals(void) { - if (Swig_Globals_global == NULL) { - Swig_Globals_global = SWIG_newvarlink(); - } - return Swig_Globals_global; + if (Swig_Globals_global == NULL) { + Swig_Globals_global = SWIG_newvarlink(); + } + return Swig_Globals_global; } #ifdef __cplusplus @@ -1600,114 +1593,110 @@ extern "C" { /* The python void return value */ -SWIGRUNTIMEINLINE PyObject * -SWIG_Py_Void(void) -{ - PyObject *none = Py_None; - Py_INCREF(none); - return none; +SWIGRUNTIMEINLINE PyObject * +SWIG_Py_Void(void) { + PyObject *none = Py_None; + Py_INCREF(none); + return none; } /* SwigPyClientData */ typedef struct { - PyObject *klass; - PyObject *newraw; - PyObject *newargs; - PyObject *destroy; - int delargs; - int implicitconv; - PyTypeObject *pytype; + PyObject *klass; + PyObject *newraw; + PyObject *newargs; + PyObject *destroy; + int delargs; + int implicitconv; + PyTypeObject *pytype; } SwigPyClientData; -SWIGRUNTIMEINLINE int -SWIG_Python_CheckImplicit(swig_type_info *ty) -{ - SwigPyClientData *data = (SwigPyClientData *)ty->clientdata; - int fail = data ? data->implicitconv : 0; - if (fail) - PyErr_SetString(PyExc_TypeError, "Implicit conversion is prohibited for explicit constructors."); - return fail; +SWIGRUNTIMEINLINE int +SWIG_Python_CheckImplicit(swig_type_info *ty) { + SwigPyClientData *data = (SwigPyClientData *)ty->clientdata; + int fail = data ? data->implicitconv : 0; + if (fail) + PyErr_SetString(PyExc_TypeError, "Implicit conversion is prohibited for explicit constructors."); + return fail; } SWIGRUNTIMEINLINE PyObject * SWIG_Python_ExceptionType(swig_type_info *desc) { - SwigPyClientData *data = desc ? (SwigPyClientData *) desc->clientdata : 0; - PyObject *klass = data ? data->klass : 0; - return (klass ? klass : PyExc_RuntimeError); + SwigPyClientData *data = desc ? (SwigPyClientData *) desc->clientdata : 0; + PyObject *klass = data ? data->klass : 0; + return (klass ? klass : PyExc_RuntimeError); } -SWIGRUNTIME SwigPyClientData * -SwigPyClientData_New(PyObject* obj) -{ - if (!obj) { - return 0; - } else { - SwigPyClientData *data = (SwigPyClientData *)malloc(sizeof(SwigPyClientData)); - /* the klass element */ - data->klass = obj; - Py_INCREF(data->klass); - /* the newraw method and newargs arguments used to create a new raw instance */ - if (PyClass_Check(obj)) { - data->newraw = 0; - Py_INCREF(obj); - data->newargs = obj; +SWIGRUNTIME SwigPyClientData * +SwigPyClientData_New(PyObject *obj) { + if (!obj) { + return 0; } else { - data->newraw = PyObject_GetAttrString(data->klass, "__new__"); - if (data->newraw) { - data->newargs = PyTuple_New(1); - if (data->newargs) { - Py_INCREF(obj); - PyTuple_SET_ITEM(data->newargs, 0, obj); + SwigPyClientData *data = (SwigPyClientData *)malloc(sizeof(SwigPyClientData)); + /* the klass element */ + data->klass = obj; + Py_INCREF(data->klass); + /* the newraw method and newargs arguments used to create a new raw instance */ + if (PyClass_Check(obj)) { + data->newraw = 0; + Py_INCREF(obj); + data->newargs = obj; } else { - Py_DECREF(data->newraw); - Py_DECREF(data->klass); - free(data); - return 0; + data->newraw = PyObject_GetAttrString(data->klass, "__new__"); + if (data->newraw) { + data->newargs = PyTuple_New(1); + if (data->newargs) { + Py_INCREF(obj); + PyTuple_SET_ITEM(data->newargs, 0, obj); + } else { + Py_DECREF(data->newraw); + Py_DECREF(data->klass); + free(data); + return 0; + } + } else { + Py_INCREF(obj); + data->newargs = obj; + } } - } else { - Py_INCREF(obj); - data->newargs = obj; - } + /* the destroy method, aka as the C++ delete method */ + data->destroy = PyObject_GetAttrString(data->klass, "__swig_destroy__"); + if (PyErr_Occurred()) { + PyErr_Clear(); + data->destroy = 0; + } + if (data->destroy) { + data->delargs = !(PyCFunction_GET_FLAGS(data->destroy) & METH_O); + } else { + data->delargs = 0; + } + data->implicitconv = 0; + data->pytype = 0; + return data; } - /* the destroy method, aka as the C++ delete method */ - data->destroy = PyObject_GetAttrString(data->klass, "__swig_destroy__"); - if (PyErr_Occurred()) { - PyErr_Clear(); - data->destroy = 0; - } - if (data->destroy) { - data->delargs = !(PyCFunction_GET_FLAGS(data->destroy) & METH_O); - } else { - data->delargs = 0; - } - data->implicitconv = 0; - data->pytype = 0; - return data; - } } -SWIGRUNTIME void -SwigPyClientData_Del(SwigPyClientData *data) -{ - Py_XDECREF(data->klass); - Py_XDECREF(data->newraw); - Py_XDECREF(data->newargs); - Py_XDECREF(data->destroy); - free(data); +SWIGRUNTIME void +SwigPyClientData_Del(SwigPyClientData *data) { + Py_XDECREF(data->klass); + Py_XDECREF(data->newraw); + Py_XDECREF(data->newargs); + Py_XDECREF(data->destroy); + free(data); } /* =============== SwigPyObject =====================*/ typedef struct { - PyObject_HEAD - void *ptr; - swig_type_info *ty; - int own; - PyObject *next; + PyObject_HEAD + void *ptr; + swig_type_info *ty; + int own; + PyObject *next; #ifdef SWIGPYTHON_BUILTIN - PyObject *dict; + PyObject *dict; #endif } SwigPyObject; @@ -1715,160 +1704,151 @@ typedef struct { #ifdef SWIGPYTHON_BUILTIN SWIGRUNTIME PyObject * -SwigPyObject_get___dict__(PyObject *v, PyObject *SWIGUNUSEDPARM(args)) -{ - SwigPyObject *sobj = (SwigPyObject *)v; +SwigPyObject_get___dict__(PyObject *v, PyObject *SWIGUNUSEDPARM(args)) { + SwigPyObject *sobj = (SwigPyObject *)v; - if (!sobj->dict) - sobj->dict = PyDict_New(); + if (!sobj->dict) + sobj->dict = PyDict_New(); - Py_XINCREF(sobj->dict); - return sobj->dict; + Py_XINCREF(sobj->dict); + return sobj->dict; } #endif SWIGRUNTIME PyObject * -SwigPyObject_long(SwigPyObject *v) -{ - return PyLong_FromVoidPtr(v->ptr); +SwigPyObject_long(SwigPyObject *v) { + return PyLong_FromVoidPtr(v->ptr); } SWIGRUNTIME PyObject * -SwigPyObject_format(const char* fmt, SwigPyObject *v) -{ - PyObject *res = NULL; - PyObject *args = PyTuple_New(1); - if (args) { - PyObject *val = SwigPyObject_long(v); - if (val) { - PyObject *ofmt; - PyTuple_SET_ITEM(args, 0, val); - ofmt = SWIG_Python_str_FromChar(fmt); - if (ofmt) { +SwigPyObject_format(const char *fmt, SwigPyObject *v) { + PyObject *res = NULL; + PyObject *args = PyTuple_New(1); + if (args) { + PyObject *val = SwigPyObject_long(v); + if (val) { + PyObject *ofmt; + PyTuple_SET_ITEM(args, 0, val); + ofmt = SWIG_Python_str_FromChar(fmt); + if (ofmt) { #if PY_VERSION_HEX >= 0x03000000 - res = PyUnicode_Format(ofmt,args); + res = PyUnicode_Format(ofmt, args); #else - res = PyString_Format(ofmt,args); + res = PyString_Format(ofmt, args); #endif - Py_DECREF(ofmt); - } + Py_DECREF(ofmt); + } + } + Py_DECREF(args); } - Py_DECREF(args); - } - return res; + return res; } SWIGRUNTIME PyObject * -SwigPyObject_oct(SwigPyObject *v) -{ - return SwigPyObject_format("%o",v); +SwigPyObject_oct(SwigPyObject *v) { + return SwigPyObject_format("%o", v); } SWIGRUNTIME PyObject * -SwigPyObject_hex(SwigPyObject *v) -{ - return SwigPyObject_format("%x",v); +SwigPyObject_hex(SwigPyObject *v) { + return SwigPyObject_format("%x", v); } SWIGRUNTIME PyObject * -SwigPyObject_repr(SwigPyObject *v) -{ - const char *name = SWIG_TypePrettyName(v->ty); - PyObject *repr = SWIG_Python_str_FromFormat("", (name ? name : "unknown"), (void *)v); - if (repr && v->next) { - PyObject *nrep = SwigPyObject_repr((SwigPyObject *)v->next); - if (nrep) { +SwigPyObject_repr(SwigPyObject *v) { + const char *name = SWIG_TypePrettyName(v->ty); + PyObject *repr = SWIG_Python_str_FromFormat("", (name ? name : "unknown"), (void *)v); + if (repr && v->next) { + PyObject *nrep = SwigPyObject_repr((SwigPyObject *)v->next); + if (nrep) { # if PY_VERSION_HEX >= 0x03000000 - PyObject *joined = PyUnicode_Concat(repr, nrep); - Py_DecRef(repr); - Py_DecRef(nrep); - repr = joined; + PyObject *joined = PyUnicode_Concat(repr, nrep); + Py_DecRef(repr); + Py_DecRef(nrep); + repr = joined; # else - PyString_ConcatAndDel(&repr,nrep); + PyString_ConcatAndDel(&repr, nrep); # endif - } else { - Py_DecRef(repr); - repr = NULL; + } else { + Py_DecRef(repr); + repr = NULL; + } } - } - return repr; + return repr; } /* We need a version taking two PyObject* parameters so it's a valid * PyCFunction to use in swigobject_methods[]. */ SWIGRUNTIME PyObject * -SwigPyObject_repr2(PyObject *v, PyObject *SWIGUNUSEDPARM(args)) -{ - return SwigPyObject_repr((SwigPyObject*)v); +SwigPyObject_repr2(PyObject *v, PyObject *SWIGUNUSEDPARM(args)) { + return SwigPyObject_repr((SwigPyObject *)v); } SWIGRUNTIME int -SwigPyObject_compare(SwigPyObject *v, SwigPyObject *w) -{ - void *i = v->ptr; - void *j = w->ptr; - return (i < j) ? -1 : ((i > j) ? 1 : 0); +SwigPyObject_compare(SwigPyObject *v, SwigPyObject *w) { + void *i = v->ptr; + void *j = w->ptr; + return (i < j) ? -1 : ((i > j) ? 1 : 0); } /* Added for Python 3.x, would it also be useful for Python 2.x? */ -SWIGRUNTIME PyObject* -SwigPyObject_richcompare(SwigPyObject *v, SwigPyObject *w, int op) -{ - PyObject* res = NULL; - if (!PyErr_Occurred()) { - if (op != Py_EQ && op != Py_NE) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; +SWIGRUNTIME PyObject * +SwigPyObject_richcompare(SwigPyObject *v, SwigPyObject *w, int op) { + PyObject *res = NULL; + if (!PyErr_Occurred()) { + if (op != Py_EQ && op != Py_NE) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + res = PyBool_FromLong((SwigPyObject_compare(v, w) == 0) == (op == Py_EQ) ? 1 : 0); } - res = PyBool_FromLong( (SwigPyObject_compare(v, w)==0) == (op == Py_EQ) ? 1 : 0); - } - return res; + return res; } -SWIGRUNTIME PyTypeObject* SwigPyObject_TypeOnce(void); +SWIGRUNTIME PyTypeObject *SwigPyObject_TypeOnce(void); #ifdef SWIGPYTHON_BUILTIN static swig_type_info *SwigPyObject_stype = 0; -SWIGRUNTIME PyTypeObject* +SWIGRUNTIME PyTypeObject * SwigPyObject_type(void) { SwigPyClientData *cd; assert(SwigPyObject_stype); - cd = (SwigPyClientData*) SwigPyObject_stype->clientdata; + cd = (SwigPyClientData *) SwigPyObject_stype->clientdata; assert(cd); assert(cd->pytype); return cd->pytype; } #else -SWIGRUNTIME PyTypeObject* +SWIGRUNTIME PyTypeObject * SwigPyObject_type(void) { - static PyTypeObject *SWIG_STATIC_POINTER(type) = SwigPyObject_TypeOnce(); - return type; + static PyTypeObject *SWIG_STATIC_POINTER(type) = SwigPyObject_TypeOnce(); + return type; } #endif SWIGRUNTIMEINLINE int SwigPyObject_Check(PyObject *op) { - PyTypeObject *target_tp = SwigPyObject_type(); - PyTypeObject *op_type = Py_TYPE(op); + PyTypeObject *target_tp = SwigPyObject_type(); + PyTypeObject *op_type = Py_TYPE(op); #ifdef SWIGPYTHON_BUILTIN - if (PyType_IsSubtype(op_type, target_tp)) - return 1; - return (strcmp(op_type->tp_name, "SwigPyObject") == 0); + if (PyType_IsSubtype(op_type, target_tp)) + return 1; + return (strcmp(op_type->tp_name, "SwigPyObject") == 0); #else - if (op_type == target_tp) - return 1; + if (op_type == target_tp) + return 1; # ifdef Py_LIMITED_API - int cmp; - PyObject *tp_name = PyObject_GetAttrString((PyObject *)op_type, "__name__"); - if (!tp_name) - return 0; - cmp = PyUnicode_CompareWithASCIIString(tp_name, "SwigPyObject"); - Py_DECREF(tp_name); - return cmp == 0; + int cmp; + PyObject *tp_name = PyObject_GetAttrString((PyObject *)op_type, "__name__"); + if (!tp_name) + return 0; + cmp = PyUnicode_CompareWithASCIIString(tp_name, "SwigPyObject"); + Py_DECREF(tp_name); + return cmp == 0; # else - return (strcmp(op_type->tp_name, "SwigPyObject") == 0); + return (strcmp(op_type->tp_name, "SwigPyObject") == 0); # endif #endif } @@ -1876,320 +1856,313 @@ SwigPyObject_Check(PyObject *op) { SWIGRUNTIME PyObject * SwigPyObject_New(void *ptr, swig_type_info *ty, int own); -static PyObject* Swig_Capsule_global = NULL; +static PyObject *Swig_Capsule_global = NULL; SWIGRUNTIME void -SwigPyObject_dealloc(PyObject *v) -{ - SwigPyObject *sobj = (SwigPyObject *) v; - PyObject *next = sobj->next; - if (sobj->own == SWIG_POINTER_OWN) { - swig_type_info *ty = sobj->ty; - SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0; - PyObject *destroy = data ? data->destroy : 0; - if (destroy) { - /* destroy is always a VARARGS method */ - PyObject *res; +SwigPyObject_dealloc(PyObject *v) { + SwigPyObject *sobj = (SwigPyObject *) v; + PyObject *next = sobj->next; + if (sobj->own == SWIG_POINTER_OWN) { + swig_type_info *ty = sobj->ty; + SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0; + PyObject *destroy = data ? data->destroy : 0; + if (destroy) { + /* destroy is always a VARARGS method */ + PyObject *res; - /* PyObject_CallFunction() has the potential to silently drop - the active exception. In cases of unnamed temporary - variable or where we just finished iterating over a generator - StopIteration will be active right now, and this needs to - remain true upon return from SwigPyObject_dealloc. So save - and restore. */ - - PyObject *type = NULL, *value = NULL, *traceback = NULL; - PyErr_Fetch(&type, &value, &traceback); + /* PyObject_CallFunction() has the potential to silently drop + the active exception. In cases of unnamed temporary + variable or where we just finished iterating over a generator + StopIteration will be active right now, and this needs to + remain true upon return from SwigPyObject_dealloc. So save + and restore. */ - if (data->delargs) { - /* we need to create a temporary object to carry the destroy operation */ - PyObject *tmp = SwigPyObject_New(sobj->ptr, ty, 0); - if (tmp) { - res = SWIG_Python_CallFunctor(destroy, tmp); - } else { - res = 0; + PyObject *type = NULL, *value = NULL, *traceback = NULL; + PyErr_Fetch(&type, &value, &traceback); + + if (data->delargs) { + /* we need to create a temporary object to carry the destroy operation */ + PyObject *tmp = SwigPyObject_New(sobj->ptr, ty, 0); + if (tmp) { + res = SWIG_Python_CallFunctor(destroy, tmp); + } else { + res = 0; + } + Py_XDECREF(tmp); + } else { + PyCFunction meth = PyCFunction_GET_FUNCTION(destroy); + PyObject *mself = PyCFunction_GET_SELF(destroy); + res = ((*meth)(mself, v)); + } + if (!res) + PyErr_WriteUnraisable(destroy); + + PyErr_Restore(type, value, traceback); + + Py_XDECREF(res); } - Py_XDECREF(tmp); - } else { - PyCFunction meth = PyCFunction_GET_FUNCTION(destroy); - PyObject *mself = PyCFunction_GET_SELF(destroy); - res = ((*meth)(mself, v)); - } - if (!res) - PyErr_WriteUnraisable(destroy); - - PyErr_Restore(type, value, traceback); - - Py_XDECREF(res); - } #if !defined(SWIG_PYTHON_SILENT_MEMLEAK) - else { - const char *name = SWIG_TypePrettyName(ty); - printf("swig/python detected a memory leak of type '%s', no destructor found.\n", (name ? name : "unknown")); + else { + const char *name = SWIG_TypePrettyName(ty); + printf("swig/python detected a memory leak of type '%s', no destructor found.\n", (name ? name : "unknown")); + } +#endif + Py_XDECREF(Swig_Capsule_global); } -#endif - Py_XDECREF(Swig_Capsule_global); - } - Py_XDECREF(next); + Py_XDECREF(next); #ifdef SWIGPYTHON_BUILTIN - Py_XDECREF(sobj->dict); + Py_XDECREF(sobj->dict); #endif - PyObject_DEL(v); + PyObject_DEL(v); } -SWIGRUNTIME PyObject* -SwigPyObject_append(PyObject* v, PyObject* next) -{ - SwigPyObject *sobj = (SwigPyObject *) v; - if (!SwigPyObject_Check(next)) { - PyErr_SetString(PyExc_TypeError, "Attempt to append a non SwigPyObject"); - return NULL; - } - ((SwigPyObject *)next)->next = sobj->next; - sobj->next = next; - Py_INCREF(next); - return SWIG_Py_Void(); -} - -SWIGRUNTIME PyObject* -SwigPyObject_next(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) -{ - SwigPyObject *sobj = (SwigPyObject *) v; - if (sobj->next) { - Py_INCREF(sobj->next); - return sobj->next; - } else { +SWIGRUNTIME PyObject * +SwigPyObject_append(PyObject *v, PyObject *next) { + SwigPyObject *sobj = (SwigPyObject *) v; + if (!SwigPyObject_Check(next)) { + PyErr_SetString(PyExc_TypeError, "Attempt to append a non SwigPyObject"); + return NULL; + } + ((SwigPyObject *)next)->next = sobj->next; + sobj->next = next; + Py_INCREF(next); return SWIG_Py_Void(); - } } -SWIGINTERN PyObject* -SwigPyObject_disown(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) -{ - SwigPyObject *sobj = (SwigPyObject *)v; - sobj->own = 0; - return SWIG_Py_Void(); +SWIGRUNTIME PyObject * +SwigPyObject_next(PyObject *v, PyObject *SWIGUNUSEDPARM(args)) { + SwigPyObject *sobj = (SwigPyObject *) v; + if (sobj->next) { + Py_INCREF(sobj->next); + return sobj->next; + } else { + return SWIG_Py_Void(); + } } -SWIGINTERN PyObject* -SwigPyObject_acquire(PyObject* v, PyObject *SWIGUNUSEDPARM(args)) -{ - SwigPyObject *sobj = (SwigPyObject *)v; - sobj->own = SWIG_POINTER_OWN; - return SWIG_Py_Void(); -} - -SWIGINTERN PyObject* -SwigPyObject_own(PyObject *v, PyObject *args) -{ - PyObject *val = 0; - if (!PyArg_UnpackTuple(args, "own", 0, 1, &val)) { - return NULL; - } else { +SWIGINTERN PyObject * +SwigPyObject_disown(PyObject *v, PyObject *SWIGUNUSEDPARM(args)) { SwigPyObject *sobj = (SwigPyObject *)v; - PyObject *obj = PyBool_FromLong(sobj->own); - if (val) { - if (PyObject_IsTrue(val)) { - Py_DECREF(SwigPyObject_acquire(v,args)); - } else { - Py_DECREF(SwigPyObject_disown(v,args)); - } - } - return obj; - } + sobj->own = 0; + return SWIG_Py_Void(); +} + +SWIGINTERN PyObject * +SwigPyObject_acquire(PyObject *v, PyObject *SWIGUNUSEDPARM(args)) { + SwigPyObject *sobj = (SwigPyObject *)v; + sobj->own = SWIG_POINTER_OWN; + return SWIG_Py_Void(); +} + +SWIGINTERN PyObject * +SwigPyObject_own(PyObject *v, PyObject *args) { + PyObject *val = 0; + if (!PyArg_UnpackTuple(args, "own", 0, 1, &val)) { + return NULL; + } else { + SwigPyObject *sobj = (SwigPyObject *)v; + PyObject *obj = PyBool_FromLong(sobj->own); + if (val) { + if (PyObject_IsTrue(val)) { + Py_DECREF(SwigPyObject_acquire(v, args)); + } else { + Py_DECREF(SwigPyObject_disown(v, args)); + } + } + return obj; + } } static PyMethodDef swigobject_methods[] = { - {"disown", SwigPyObject_disown, METH_NOARGS, "releases ownership of the pointer"}, - {"acquire", SwigPyObject_acquire, METH_NOARGS, "acquires ownership of the pointer"}, - {"own", SwigPyObject_own, METH_VARARGS, "returns/sets ownership of the pointer"}, - {"append", SwigPyObject_append, METH_O, "appends another 'this' object"}, - {"next", SwigPyObject_next, METH_NOARGS, "returns the next 'this' object"}, - {"__repr__",SwigPyObject_repr2, METH_NOARGS, "returns object representation"}, - {0, 0, 0, 0} + {"disown", SwigPyObject_disown, METH_NOARGS, "releases ownership of the pointer"}, + {"acquire", SwigPyObject_acquire, METH_NOARGS, "acquires ownership of the pointer"}, + {"own", SwigPyObject_own, METH_VARARGS, "returns/sets ownership of the pointer"}, + {"append", SwigPyObject_append, METH_O, "appends another 'this' object"}, + {"next", SwigPyObject_next, METH_NOARGS, "returns the next 'this' object"}, + {"__repr__", SwigPyObject_repr2, METH_NOARGS, "returns object representation"}, + {0, 0, 0, 0} }; -SWIGRUNTIME PyTypeObject* +SWIGRUNTIME PyTypeObject * SwigPyObject_TypeOnce(void) { - static char swigobject_doc[] = "Swig object carries a C/C++ instance pointer"; + static char swigobject_doc[] = "Swig object carries a C/C++ instance pointer"; #ifndef Py_LIMITED_API - static PyNumberMethods SwigPyObject_as_number = { - (binaryfunc)0, /*nb_add*/ - (binaryfunc)0, /*nb_subtract*/ - (binaryfunc)0, /*nb_multiply*/ - /* nb_divide removed in Python 3 */ + static PyNumberMethods SwigPyObject_as_number = { + (binaryfunc)0, /*nb_add*/ + (binaryfunc)0, /*nb_subtract*/ + (binaryfunc)0, /*nb_multiply*/ + /* nb_divide removed in Python 3 */ #if PY_VERSION_HEX < 0x03000000 - (binaryfunc)0, /*nb_divide*/ + (binaryfunc)0, /*nb_divide*/ #endif - (binaryfunc)0, /*nb_remainder*/ - (binaryfunc)0, /*nb_divmod*/ - (ternaryfunc)0,/*nb_power*/ - (unaryfunc)0, /*nb_negative*/ - (unaryfunc)0, /*nb_positive*/ - (unaryfunc)0, /*nb_absolute*/ - (inquiry)0, /*nb_nonzero*/ - 0, /*nb_invert*/ - 0, /*nb_lshift*/ - 0, /*nb_rshift*/ - 0, /*nb_and*/ - 0, /*nb_xor*/ - 0, /*nb_or*/ + (binaryfunc)0, /*nb_remainder*/ + (binaryfunc)0, /*nb_divmod*/ + (ternaryfunc)0,/*nb_power*/ + (unaryfunc)0, /*nb_negative*/ + (unaryfunc)0, /*nb_positive*/ + (unaryfunc)0, /*nb_absolute*/ + (inquiry)0, /*nb_nonzero*/ + 0, /*nb_invert*/ + 0, /*nb_lshift*/ + 0, /*nb_rshift*/ + 0, /*nb_and*/ + 0, /*nb_xor*/ + 0, /*nb_or*/ #if PY_VERSION_HEX < 0x03000000 - 0, /*nb_coerce*/ + 0, /*nb_coerce*/ #endif - (unaryfunc)SwigPyObject_long, /*nb_int*/ + (unaryfunc)SwigPyObject_long, /*nb_int*/ #if PY_VERSION_HEX < 0x03000000 - (unaryfunc)SwigPyObject_long, /*nb_long*/ + (unaryfunc)SwigPyObject_long, /*nb_long*/ #else - 0, /*nb_reserved*/ + 0, /*nb_reserved*/ #endif - (unaryfunc)0, /*nb_float*/ + (unaryfunc)0, /*nb_float*/ #if PY_VERSION_HEX < 0x03000000 - (unaryfunc)SwigPyObject_oct, /*nb_oct*/ - (unaryfunc)SwigPyObject_hex, /*nb_hex*/ + (unaryfunc)SwigPyObject_oct, /*nb_oct*/ + (unaryfunc)SwigPyObject_hex, /*nb_hex*/ #endif #if PY_VERSION_HEX >= 0x03050000 /* 3.5 */ - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_matrix_multiply */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* nb_inplace_add -> nb_inplace_matrix_multiply */ #elif PY_VERSION_HEX >= 0x03000000 /* 3.0 */ - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index, nb_inplace_divide removed */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* nb_inplace_add -> nb_index, nb_inplace_divide removed */ #else - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index */ -#endif - }; - - static PyTypeObject swigpyobject_type; - static int type_init = 0; - if (!type_init) { - const PyTypeObject tmp = { -#if PY_VERSION_HEX >= 0x03000000 - PyVarObject_HEAD_INIT(NULL, 0) -#else - PyObject_HEAD_INIT(NULL) - 0, /* ob_size */ -#endif - "SwigPyObject", /* tp_name */ - sizeof(SwigPyObject), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)SwigPyObject_dealloc, /* tp_dealloc */ -#if PY_VERSION_HEX < 0x030800b4 - (printfunc)0, /*tp_print*/ -#else - (Py_ssize_t)0, /*tp_vectorcall_offset*/ -#endif - (getattrfunc)0, /* tp_getattr */ - (setattrfunc)0, /* tp_setattr */ -#if PY_VERSION_HEX >= 0x03000000 - 0, /* tp_reserved in 3.0.1, tp_compare in 3.0.0 but not used */ -#else - (cmpfunc)SwigPyObject_compare, /* tp_compare */ -#endif - (reprfunc)SwigPyObject_repr, /* tp_repr */ - &SwigPyObject_as_number, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)0, /* tp_hash */ - (ternaryfunc)0, /* tp_call */ - 0, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - swigobject_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - (richcmpfunc)SwigPyObject_richcompare,/* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - swigobject_methods, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - 0, /* tp_free */ - 0, /* tp_is_gc */ - 0, /* tp_bases */ - 0, /* tp_mro */ - 0, /* tp_cache */ - 0, /* tp_subclasses */ - 0, /* tp_weaklist */ - 0, /* tp_del */ - 0, /* tp_version_tag */ -#if PY_VERSION_HEX >= 0x03040000 - 0, /* tp_finalize */ -#endif -#if PY_VERSION_HEX >= 0x03080000 - 0, /* tp_vectorcall */ -#endif -#if (PY_VERSION_HEX >= 0x03080000) && (PY_VERSION_HEX < 0x03090000) - 0, /* tp_print */ -#endif -#if PY_VERSION_HEX >= 0x030C0000 - 0, /* tp_watched */ -#endif -#ifdef COUNT_ALLOCS - 0, /* tp_allocs */ - 0, /* tp_frees */ - 0, /* tp_maxalloc */ - 0, /* tp_prev */ - 0 /* tp_next */ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* nb_inplace_add -> nb_index */ #endif }; - swigpyobject_type = tmp; - type_init = 1; - if (PyType_Ready(&swigpyobject_type) != 0) - return NULL; - } - return &swigpyobject_type; + + static PyTypeObject swigpyobject_type; + static int type_init = 0; + if (!type_init) { + const PyTypeObject tmp = { +#if PY_VERSION_HEX >= 0x03000000 + PyVarObject_HEAD_INIT(NULL, 0) #else - PyType_Slot slots[] = { - { Py_tp_dealloc, (void *)SwigPyObject_dealloc }, - { Py_tp_repr, (void *)SwigPyObject_repr }, - { Py_tp_getattro, (void *)PyObject_GenericGetAttr }, - { Py_tp_doc, (void *)swigobject_doc }, - { Py_tp_richcompare, (void *)SwigPyObject_richcompare }, - { Py_tp_methods, (void *)swigobject_methods }, - { Py_nb_int, (void *)SwigPyObject_long }, - { 0, NULL } - }; - PyType_Spec spec = { - "SwigPyObject", - sizeof(SwigPyObject), - 0, - Py_TPFLAGS_DEFAULT, - slots - }; - return (PyTypeObject *)PyType_FromSpec(&spec); + PyObject_HEAD_INIT(NULL) + 0, /* ob_size */ +#endif + "SwigPyObject", /* tp_name */ + sizeof(SwigPyObject), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)SwigPyObject_dealloc, /* tp_dealloc */ +#if PY_VERSION_HEX < 0x030800b4 + (printfunc)0, /*tp_print*/ +#else + (Py_ssize_t)0, /*tp_vectorcall_offset*/ +#endif + (getattrfunc)0, /* tp_getattr */ + (setattrfunc)0, /* tp_setattr */ +#if PY_VERSION_HEX >= 0x03000000 + 0, /* tp_reserved in 3.0.1, tp_compare in 3.0.0 but not used */ +#else + (cmpfunc)SwigPyObject_compare, /* tp_compare */ +#endif + (reprfunc)SwigPyObject_repr, /* tp_repr */ + &SwigPyObject_as_number, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)0, /* tp_hash */ + (ternaryfunc)0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + swigobject_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + (richcmpfunc)SwigPyObject_richcompare,/* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + swigobject_methods, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ + 0, /* tp_is_gc */ + 0, /* tp_bases */ + 0, /* tp_mro */ + 0, /* tp_cache */ + 0, /* tp_subclasses */ + 0, /* tp_weaklist */ + 0, /* tp_del */ + 0, /* tp_version_tag */ +#if PY_VERSION_HEX >= 0x03040000 + 0, /* tp_finalize */ +#endif +#if PY_VERSION_HEX >= 0x03080000 + 0, /* tp_vectorcall */ +#endif +#if (PY_VERSION_HEX >= 0x03080000) && (PY_VERSION_HEX < 0x03090000) + 0, /* tp_print */ +#endif +#if PY_VERSION_HEX >= 0x030C0000 + 0, /* tp_watched */ +#endif +#ifdef COUNT_ALLOCS + 0, /* tp_allocs */ + 0, /* tp_frees */ + 0, /* tp_maxalloc */ + 0, /* tp_prev */ + 0 /* tp_next */ +#endif + }; + swigpyobject_type = tmp; + type_init = 1; + if (PyType_Ready(&swigpyobject_type) != 0) + return NULL; + } + return &swigpyobject_type; +#else + PyType_Slot slots[] = { + { Py_tp_dealloc, (void *)SwigPyObject_dealloc }, + { Py_tp_repr, (void *)SwigPyObject_repr }, + { Py_tp_getattro, (void *)PyObject_GenericGetAttr }, + { Py_tp_doc, (void *)swigobject_doc }, + { Py_tp_richcompare, (void *)SwigPyObject_richcompare }, + { Py_tp_methods, (void *)swigobject_methods }, + { Py_nb_int, (void *)SwigPyObject_long }, + { 0, NULL } + }; + PyType_Spec spec = { + "SwigPyObject", + sizeof(SwigPyObject), + 0, + Py_TPFLAGS_DEFAULT, + slots + }; + return (PyTypeObject *)PyType_FromSpec(&spec); #endif } SWIGRUNTIME PyObject * -SwigPyObject_New(void *ptr, swig_type_info *ty, int own) -{ - SwigPyObject *sobj = PyObject_New(SwigPyObject, SwigPyObject_type()); - if (sobj) { - sobj->ptr = ptr; - sobj->ty = ty; - sobj->own = own; - sobj->next = 0; +SwigPyObject_New(void *ptr, swig_type_info *ty, int own) { + SwigPyObject *sobj = PyObject_New(SwigPyObject, SwigPyObject_type()); + if (sobj) { + sobj->ptr = ptr; + sobj->ty = ty; + sobj->own = own; + sobj->next = 0; #ifdef SWIGPYTHON_BUILTIN - sobj->dict = 0; + sobj->dict = 0; #endif - if (own == SWIG_POINTER_OWN) { - /* Obtain a reference to the Python capsule wrapping the module information, so that the - * module information is correctly destroyed after all SWIG python objects have been freed - * by the GC (and corresponding destructors invoked) */ - Py_XINCREF(Swig_Capsule_global); + if (own == SWIG_POINTER_OWN) { + /* Obtain a reference to the Python capsule wrapping the module information, so that the + * module information is correctly destroyed after all SWIG python objects have been freed + * by the GC (and corresponding destructors invoked) */ + Py_XINCREF(Swig_Capsule_global); + } } - } - return (PyObject *)sobj; + return (PyObject *)sobj; } /* ----------------------------------------------------------------------------- @@ -2197,223 +2170,217 @@ SwigPyObject_New(void *ptr, swig_type_info *ty, int own) * ----------------------------------------------------------------------------- */ typedef struct { - PyObject_HEAD - void *pack; - swig_type_info *ty; - size_t size; + PyObject_HEAD + void *pack; + swig_type_info *ty; + size_t size; } SwigPyPacked; SWIGRUNTIME PyObject * -SwigPyPacked_repr(SwigPyPacked *v) -{ - char result[SWIG_BUFFER_SIZE]; - if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) { - return SWIG_Python_str_FromFormat("", result, v->ty->name); - } else { - return SWIG_Python_str_FromFormat("", v->ty->name); - } +SwigPyPacked_repr(SwigPyPacked *v) { + char result[SWIG_BUFFER_SIZE]; + if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) { + return SWIG_Python_str_FromFormat("", result, v->ty->name); + } else { + return SWIG_Python_str_FromFormat("", v->ty->name); + } } SWIGRUNTIME PyObject * -SwigPyPacked_str(SwigPyPacked *v) -{ - char result[SWIG_BUFFER_SIZE]; - if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))){ - return SWIG_Python_str_FromFormat("%s%s", result, v->ty->name); - } else { - return SWIG_Python_str_FromChar(v->ty->name); - } +SwigPyPacked_str(SwigPyPacked *v) { + char result[SWIG_BUFFER_SIZE]; + if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) { + return SWIG_Python_str_FromFormat("%s%s", result, v->ty->name); + } else { + return SWIG_Python_str_FromChar(v->ty->name); + } } SWIGRUNTIME int -SwigPyPacked_compare(SwigPyPacked *v, SwigPyPacked *w) -{ - size_t i = v->size; - size_t j = w->size; - int s = (i < j) ? -1 : ((i > j) ? 1 : 0); - return s ? s : strncmp((const char *)v->pack, (const char *)w->pack, 2*v->size); +SwigPyPacked_compare(SwigPyPacked *v, SwigPyPacked *w) { + size_t i = v->size; + size_t j = w->size; + int s = (i < j) ? -1 : ((i > j) ? 1 : 0); + return s ? s : strncmp((const char *)v->pack, (const char *)w->pack, 2 * v->size); } -SWIGRUNTIME PyTypeObject* SwigPyPacked_TypeOnce(void); +SWIGRUNTIME PyTypeObject *SwigPyPacked_TypeOnce(void); -SWIGRUNTIME PyTypeObject* +SWIGRUNTIME PyTypeObject * SwigPyPacked_type(void) { - static PyTypeObject *SWIG_STATIC_POINTER(type) = SwigPyPacked_TypeOnce(); - return type; + static PyTypeObject *SWIG_STATIC_POINTER(type) = SwigPyPacked_TypeOnce(); + return type; } SWIGRUNTIMEINLINE int SwigPyPacked_Check(PyObject *op) { - PyTypeObject* op_type = Py_TYPE(op); - if (op_type == SwigPyPacked_TypeOnce()) - return 1; + PyTypeObject *op_type = Py_TYPE(op); + if (op_type == SwigPyPacked_TypeOnce()) + return 1; #ifdef Py_LIMITED_API - int cmp; - PyObject *tp_name = PyObject_GetAttrString((PyObject *)op_type, "__name__"); - if (!tp_name) - return 0; - cmp = PyUnicode_CompareWithASCIIString(tp_name, "SwigPyPacked"); - Py_DECREF(tp_name); - return cmp == 0; + int cmp; + PyObject *tp_name = PyObject_GetAttrString((PyObject *)op_type, "__name__"); + if (!tp_name) + return 0; + cmp = PyUnicode_CompareWithASCIIString(tp_name, "SwigPyPacked"); + Py_DECREF(tp_name); + return cmp == 0; #else - return (strcmp(op_type->tp_name, "SwigPyPacked") == 0); + return (strcmp(op_type->tp_name, "SwigPyPacked") == 0); #endif } SWIGRUNTIME void -SwigPyPacked_dealloc(PyObject *v) -{ - if (SwigPyPacked_Check(v)) { - SwigPyPacked *sobj = (SwigPyPacked *) v; - free(sobj->pack); - } - PyObject_DEL(v); +SwigPyPacked_dealloc(PyObject *v) { + if (SwigPyPacked_Check(v)) { + SwigPyPacked *sobj = (SwigPyPacked *) v; + free(sobj->pack); + } + PyObject_DEL(v); } -SWIGRUNTIME PyTypeObject* +SWIGRUNTIME PyTypeObject * SwigPyPacked_TypeOnce(void) { - static char swigpacked_doc[] = "Swig object carries a C/C++ instance pointer"; + static char swigpacked_doc[] = "Swig object carries a C/C++ instance pointer"; #ifndef Py_LIMITED_API - static PyTypeObject swigpypacked_type; - static int type_init = 0; - if (!type_init) { - const PyTypeObject tmp = { + static PyTypeObject swigpypacked_type; + static int type_init = 0; + if (!type_init) { + const PyTypeObject tmp = { #if PY_VERSION_HEX>=0x03000000 - PyVarObject_HEAD_INIT(NULL, 0) + PyVarObject_HEAD_INIT(NULL, 0) #else - PyObject_HEAD_INIT(NULL) - 0, /* ob_size */ + PyObject_HEAD_INIT(NULL) + 0, /* ob_size */ #endif - "SwigPyPacked", /* tp_name */ - sizeof(SwigPyPacked), /* tp_basicsize */ - 0, /* tp_itemsize */ - (destructor)SwigPyPacked_dealloc, /* tp_dealloc */ + "SwigPyPacked", /* tp_name */ + sizeof(SwigPyPacked), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)SwigPyPacked_dealloc, /* tp_dealloc */ #if PY_VERSION_HEX < 0x030800b4 - (printfunc)0, /*tp_print*/ + (printfunc)0, /*tp_print*/ #else - (Py_ssize_t)0, /*tp_vectorcall_offset*/ + (Py_ssize_t)0, /*tp_vectorcall_offset*/ #endif - (getattrfunc)0, /* tp_getattr */ - (setattrfunc)0, /* tp_setattr */ + (getattrfunc)0, /* tp_getattr */ + (setattrfunc)0, /* tp_setattr */ #if PY_VERSION_HEX>=0x03000000 - 0, /* tp_reserved in 3.0.1 */ + 0, /* tp_reserved in 3.0.1 */ #else - (cmpfunc)SwigPyPacked_compare, /* tp_compare */ + (cmpfunc)SwigPyPacked_compare, /* tp_compare */ #endif - (reprfunc)SwigPyPacked_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - (hashfunc)0, /* tp_hash */ - (ternaryfunc)0, /* tp_call */ - (reprfunc)SwigPyPacked_str, /* tp_str */ - PyObject_GenericGetAttr, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - swigpacked_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ - 0, /* tp_free */ - 0, /* tp_is_gc */ - 0, /* tp_bases */ - 0, /* tp_mro */ - 0, /* tp_cache */ - 0, /* tp_subclasses */ - 0, /* tp_weaklist */ - 0, /* tp_del */ - 0, /* tp_version_tag */ + (reprfunc)SwigPyPacked_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + (hashfunc)0, /* tp_hash */ + (ternaryfunc)0, /* tp_call */ + (reprfunc)SwigPyPacked_str, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + swigpacked_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + 0, /* tp_init */ + 0, /* tp_alloc */ + 0, /* tp_new */ + 0, /* tp_free */ + 0, /* tp_is_gc */ + 0, /* tp_bases */ + 0, /* tp_mro */ + 0, /* tp_cache */ + 0, /* tp_subclasses */ + 0, /* tp_weaklist */ + 0, /* tp_del */ + 0, /* tp_version_tag */ #if PY_VERSION_HEX >= 0x03040000 - 0, /* tp_finalize */ + 0, /* tp_finalize */ #endif #if PY_VERSION_HEX >= 0x03080000 - 0, /* tp_vectorcall */ + 0, /* tp_vectorcall */ #endif #if (PY_VERSION_HEX >= 0x03080000) && (PY_VERSION_HEX < 0x03090000) - 0, /* tp_print */ + 0, /* tp_print */ #endif #if PY_VERSION_HEX >= 0x030C0000 - 0, /* tp_watched */ + 0, /* tp_watched */ #endif #ifdef COUNT_ALLOCS - 0, /* tp_allocs */ - 0, /* tp_frees */ - 0, /* tp_maxalloc */ - 0, /* tp_prev */ - 0 /* tp_next */ + 0, /* tp_allocs */ + 0, /* tp_frees */ + 0, /* tp_maxalloc */ + 0, /* tp_prev */ + 0 /* tp_next */ #endif - }; - swigpypacked_type = tmp; - type_init = 1; - if (PyType_Ready(&swigpypacked_type) != 0) - return NULL; - } - return &swigpypacked_type; + }; + swigpypacked_type = tmp; + type_init = 1; + if (PyType_Ready(&swigpypacked_type) != 0) + return NULL; + } + return &swigpypacked_type; #else - PyType_Slot slots[] = { - { Py_tp_dealloc, (void *)SwigPyPacked_dealloc }, - { Py_tp_repr, (void *)SwigPyPacked_repr }, - { Py_tp_str, (void *)SwigPyPacked_str }, - { Py_tp_getattro, (void *)PyObject_GenericGetAttr }, - { Py_tp_doc, (void *)swigpacked_doc }, - { 0, NULL } - }; - PyType_Spec spec = { - "SwigPyPacked", - sizeof(SwigPyPacked), - 0, - Py_TPFLAGS_DEFAULT, - slots - }; - return (PyTypeObject *)PyType_FromSpec(&spec); + PyType_Slot slots[] = { + { Py_tp_dealloc, (void *)SwigPyPacked_dealloc }, + { Py_tp_repr, (void *)SwigPyPacked_repr }, + { Py_tp_str, (void *)SwigPyPacked_str }, + { Py_tp_getattro, (void *)PyObject_GenericGetAttr }, + { Py_tp_doc, (void *)swigpacked_doc }, + { 0, NULL } + }; + PyType_Spec spec = { + "SwigPyPacked", + sizeof(SwigPyPacked), + 0, + Py_TPFLAGS_DEFAULT, + slots + }; + return (PyTypeObject *)PyType_FromSpec(&spec); #endif } SWIGRUNTIME PyObject * -SwigPyPacked_New(void *ptr, size_t size, swig_type_info *ty) -{ - SwigPyPacked *sobj = PyObject_New(SwigPyPacked, SwigPyPacked_type()); - if (sobj) { - void *pack = malloc(size); - if (pack) { - memcpy(pack, ptr, size); - sobj->pack = pack; - sobj->ty = ty; - sobj->size = size; - } else { - PyObject_DEL((PyObject *) sobj); - sobj = 0; +SwigPyPacked_New(void *ptr, size_t size, swig_type_info *ty) { + SwigPyPacked *sobj = PyObject_New(SwigPyPacked, SwigPyPacked_type()); + if (sobj) { + void *pack = malloc(size); + if (pack) { + memcpy(pack, ptr, size); + sobj->pack = pack; + sobj->ty = ty; + sobj->size = size; + } else { + PyObject_DEL((PyObject *) sobj); + sobj = 0; + } } - } - return (PyObject *) sobj; + return (PyObject *) sobj; } SWIGRUNTIME swig_type_info * -SwigPyPacked_UnpackData(PyObject *obj, void *ptr, size_t size) -{ - if (SwigPyPacked_Check(obj)) { - SwigPyPacked *sobj = (SwigPyPacked *)obj; - if (sobj->size != size) return 0; - memcpy(ptr, sobj->pack, size); - return sobj->ty; - } else { - return 0; - } +SwigPyPacked_UnpackData(PyObject *obj, void *ptr, size_t size) { + if (SwigPyPacked_Check(obj)) { + SwigPyPacked *sobj = (SwigPyPacked *)obj; + if (sobj->size != size) return 0; + memcpy(ptr, sobj->pack, size); + return sobj->ty; + } else { + return 0; + } } /* ----------------------------------------------------------------------------- @@ -2423,81 +2390,79 @@ SwigPyPacked_UnpackData(PyObject *obj, void *ptr, size_t size) static PyObject *Swig_This_global = NULL; SWIGRUNTIME PyObject * -SWIG_This(void) -{ - if (Swig_This_global == NULL) - Swig_This_global = SWIG_Python_str_FromChar("this"); - return Swig_This_global; +SWIG_This(void) { + if (Swig_This_global == NULL) + Swig_This_global = SWIG_Python_str_FromChar("this"); + return Swig_This_global; } /* #define SWIG_PYTHON_SLOW_GETSET_THIS */ /* TODO: I don't know how to implement the fast getset in Python 3 right now */ #if PY_VERSION_HEX>=0x03000000 -#define SWIG_PYTHON_SLOW_GETSET_THIS +#define SWIG_PYTHON_SLOW_GETSET_THIS #endif SWIGRUNTIME SwigPyObject * -SWIG_Python_GetSwigThis(PyObject *pyobj) -{ - PyObject *obj; +SWIG_Python_GetSwigThis(PyObject *pyobj) { + PyObject *obj; - if (SwigPyObject_Check(pyobj)) - return (SwigPyObject *) pyobj; + if (SwigPyObject_Check(pyobj)) + return (SwigPyObject *) pyobj; #ifdef SWIGPYTHON_BUILTIN - (void)obj; + (void)obj; # ifdef PyWeakref_CheckProxy - if (PyWeakref_CheckProxy(pyobj)) { - pyobj = PyWeakref_GET_OBJECT(pyobj); - if (pyobj && SwigPyObject_Check(pyobj)) - return (SwigPyObject*) pyobj; - } + if (PyWeakref_CheckProxy(pyobj)) { + pyobj = PyWeakref_GET_OBJECT(pyobj); + if (pyobj && SwigPyObject_Check(pyobj)) + return (SwigPyObject *) pyobj; + } # endif - return NULL; + return NULL; #else - obj = 0; + obj = 0; #if !defined(SWIG_PYTHON_SLOW_GETSET_THIS) - if (PyInstance_Check(pyobj)) { - obj = _PyInstance_Lookup(pyobj, SWIG_This()); - } else { - PyObject **dictptr = _PyObject_GetDictPtr(pyobj); - if (dictptr != NULL) { - PyObject *dict = *dictptr; - obj = dict ? PyDict_GetItem(dict, SWIG_This()) : 0; + if (PyInstance_Check(pyobj)) { + obj = _PyInstance_Lookup(pyobj, SWIG_This()); } else { + PyObject **dictptr = _PyObject_GetDictPtr(pyobj); + if (dictptr != NULL) { + PyObject *dict = *dictptr; + obj = dict ? PyDict_GetItem(dict, SWIG_This()) : 0; + } else { #ifdef PyWeakref_CheckProxy - if (PyWeakref_CheckProxy(pyobj)) { - PyObject *wobj = PyWeakref_GET_OBJECT(pyobj); - return wobj ? SWIG_Python_GetSwigThis(wobj) : 0; - } + if (PyWeakref_CheckProxy(pyobj)) { + PyObject *wobj = PyWeakref_GET_OBJECT(pyobj); + return wobj ? SWIG_Python_GetSwigThis(wobj) : 0; + } #endif - obj = PyObject_GetAttr(pyobj,SWIG_This()); - if (obj) { - Py_DECREF(obj); - } else { - if (PyErr_Occurred()) PyErr_Clear(); - return 0; - } + obj = PyObject_GetAttr(pyobj, SWIG_This()); + if (obj) { + Py_DECREF(obj); + } else { + if (PyErr_Occurred()) PyErr_Clear(); + return 0; + } + } } - } #else - obj = PyObject_GetAttr(pyobj,SWIG_This()); - if (obj) { - Py_DECREF(obj); - } else { - if (PyErr_Occurred()) PyErr_Clear(); - return 0; - } + obj = PyObject_GetAttr(pyobj, SWIG_This()); + if (obj) { + Py_DECREF(obj); + } else { + if (PyErr_Occurred()) PyErr_Clear(); + return 0; + } #endif - if (obj && !SwigPyObject_Check(obj)) { - /* a PyObject is called 'this', try to get the 'real this' - SwigPyObject from it */ - return SWIG_Python_GetSwigThis(obj); - } - return (SwigPyObject *)obj; + if (obj && !SwigPyObject_Check(obj)) { + /* a PyObject is called 'this', try to get the 'real this' + SwigPyObject from it */ + return SWIG_Python_GetSwigThis(obj); + } + return (SwigPyObject *)obj; #endif } @@ -2505,183 +2470,183 @@ SWIG_Python_GetSwigThis(PyObject *pyobj) SWIGRUNTIME int SWIG_Python_AcquirePtr(PyObject *obj, int own) { - if (own == SWIG_POINTER_OWN) { - SwigPyObject *sobj = SWIG_Python_GetSwigThis(obj); - if (sobj) { - int oldown = sobj->own; - sobj->own = own; - return oldown; + if (own == SWIG_POINTER_OWN) { + SwigPyObject *sobj = SWIG_Python_GetSwigThis(obj); + if (sobj) { + int oldown = sobj->own; + sobj->own = own; + return oldown; + } } - } - return 0; + return 0; } /* Convert a pointer value */ SWIGRUNTIME int SWIG_Python_ConvertPtrAndOwn(PyObject *obj, void **ptr, swig_type_info *ty, int flags, int *own) { - int res; - SwigPyObject *sobj; - int implicit_conv = (flags & SWIG_POINTER_IMPLICIT_CONV) != 0; + int res; + SwigPyObject *sobj; + int implicit_conv = (flags & SWIG_POINTER_IMPLICIT_CONV) != 0; - if (!obj) - return SWIG_ERROR; - if (obj == Py_None && !implicit_conv) { - if (ptr) - *ptr = 0; - return (flags & SWIG_POINTER_NO_NULL) ? SWIG_NullReferenceError : SWIG_OK; - } - - res = SWIG_ERROR; - - sobj = SWIG_Python_GetSwigThis(obj); - if (own) - *own = 0; - while (sobj) { - void *vptr = sobj->ptr; - if (ty) { - swig_type_info *to = sobj->ty; - if (to == ty) { - /* no type cast needed */ - if (ptr) *ptr = vptr; - break; - } else { - swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); - if (!tc) { - sobj = (SwigPyObject *)sobj->next; - } else { - if (ptr) { - int newmemory = 0; - *ptr = SWIG_TypeCast(tc,vptr,&newmemory); - if (newmemory == SWIG_CAST_NEW_MEMORY) { - assert(own); /* badly formed typemap which will lead to a memory leak - it must set and use own to delete *ptr */ - if (own) - *own = *own | SWIG_CAST_NEW_MEMORY; - } - } - break; - } - } - } else { - if (ptr) *ptr = vptr; - break; - } - } - if (sobj) { - if (((flags & SWIG_POINTER_RELEASE) == SWIG_POINTER_RELEASE) && !sobj->own) { - res = SWIG_ERROR_RELEASE_NOT_OWNED; - } else { - if (own) - *own = *own | sobj->own; - if (flags & SWIG_POINTER_DISOWN) { - sobj->own = 0; - } - if (flags & SWIG_POINTER_CLEAR) { - sobj->ptr = 0; - } - res = SWIG_OK; - } - } else { - if (implicit_conv) { - SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0; - if (data && !data->implicitconv) { - PyObject *klass = data->klass; - if (klass) { - PyObject *impconv; - data->implicitconv = 1; /* avoid recursion and call 'explicit' constructors*/ - impconv = SWIG_Python_CallFunctor(klass, obj); - data->implicitconv = 0; - if (PyErr_Occurred()) { - PyErr_Clear(); - impconv = 0; - } - if (impconv) { - SwigPyObject *iobj = SWIG_Python_GetSwigThis(impconv); - if (iobj) { - void *vptr; - res = SWIG_Python_ConvertPtrAndOwn((PyObject*)iobj, &vptr, ty, 0, 0); - if (SWIG_IsOK(res)) { - if (ptr) { - *ptr = vptr; - /* transfer the ownership to 'ptr' */ - iobj->own = 0; - res = SWIG_AddCast(res); - res = SWIG_AddNewMask(res); - } else { - res = SWIG_AddCast(res); - } - } - } - Py_DECREF(impconv); - } - } - } - if (!SWIG_IsOK(res) && obj == Py_None) { + if (!obj) + return SWIG_ERROR; + if (obj == Py_None && !implicit_conv) { if (ptr) - *ptr = 0; - if (PyErr_Occurred()) - PyErr_Clear(); - res = SWIG_OK; - } + *ptr = 0; + return (flags & SWIG_POINTER_NO_NULL) ? SWIG_NullReferenceError : SWIG_OK; } - } - return res; + + res = SWIG_ERROR; + + sobj = SWIG_Python_GetSwigThis(obj); + if (own) + *own = 0; + while (sobj) { + void *vptr = sobj->ptr; + if (ty) { + swig_type_info *to = sobj->ty; + if (to == ty) { + /* no type cast needed */ + if (ptr) *ptr = vptr; + break; + } else { + swig_cast_info *tc = SWIG_TypeCheck(to->name, ty); + if (!tc) { + sobj = (SwigPyObject *)sobj->next; + } else { + if (ptr) { + int newmemory = 0; + *ptr = SWIG_TypeCast(tc, vptr, &newmemory); + if (newmemory == SWIG_CAST_NEW_MEMORY) { + assert(own); /* badly formed typemap which will lead to a memory leak - it must set and use own to delete *ptr */ + if (own) + *own = *own | SWIG_CAST_NEW_MEMORY; + } + } + break; + } + } + } else { + if (ptr) *ptr = vptr; + break; + } + } + if (sobj) { + if (((flags & SWIG_POINTER_RELEASE) == SWIG_POINTER_RELEASE) && !sobj->own) { + res = SWIG_ERROR_RELEASE_NOT_OWNED; + } else { + if (own) + *own = *own | sobj->own; + if (flags & SWIG_POINTER_DISOWN) { + sobj->own = 0; + } + if (flags & SWIG_POINTER_CLEAR) { + sobj->ptr = 0; + } + res = SWIG_OK; + } + } else { + if (implicit_conv) { + SwigPyClientData *data = ty ? (SwigPyClientData *) ty->clientdata : 0; + if (data && !data->implicitconv) { + PyObject *klass = data->klass; + if (klass) { + PyObject *impconv; + data->implicitconv = 1; /* avoid recursion and call 'explicit' constructors*/ + impconv = SWIG_Python_CallFunctor(klass, obj); + data->implicitconv = 0; + if (PyErr_Occurred()) { + PyErr_Clear(); + impconv = 0; + } + if (impconv) { + SwigPyObject *iobj = SWIG_Python_GetSwigThis(impconv); + if (iobj) { + void *vptr; + res = SWIG_Python_ConvertPtrAndOwn((PyObject *)iobj, &vptr, ty, 0, 0); + if (SWIG_IsOK(res)) { + if (ptr) { + *ptr = vptr; + /* transfer the ownership to 'ptr' */ + iobj->own = 0; + res = SWIG_AddCast(res); + res = SWIG_AddNewMask(res); + } else { + res = SWIG_AddCast(res); + } + } + } + Py_DECREF(impconv); + } + } + } + if (!SWIG_IsOK(res) && obj == Py_None) { + if (ptr) + *ptr = 0; + if (PyErr_Occurred()) + PyErr_Clear(); + res = SWIG_OK; + } + } + } + return res; } /* Convert a function ptr value */ SWIGRUNTIME int SWIG_Python_ConvertFunctionPtr(PyObject *obj, void **ptr, swig_type_info *ty) { - if (!PyCFunction_Check(obj)) { - return SWIG_ConvertPtr(obj, ptr, ty, 0); - } else { - void *vptr = 0; - swig_cast_info *tc; - - /* here we get the method pointer for callbacks */ -#ifndef Py_LIMITED_API - const char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc); -#else - PyObject* pystr_doc = PyObject_GetAttrString(obj, "__doc__"); - PyObject *bytes = NULL; - const char *doc = pystr_doc ? SWIG_PyUnicode_AsUTF8AndSize(pystr_doc, NULL, &bytes) : 0; -#endif - const char *desc = doc ? strstr(doc, "swig_ptr: ") : 0; - if (desc) - desc = ty ? SWIG_UnpackVoidPtr(desc + 10, &vptr, ty->name) : 0; -#ifdef Py_LIMITED_API - Py_XDECREF(bytes); - Py_XDECREF(pystr_doc); -#endif - if (!desc) - return SWIG_ERROR; - tc = SWIG_TypeCheck(desc,ty); - if (tc) { - int newmemory = 0; - *ptr = SWIG_TypeCast(tc,vptr,&newmemory); - assert(!newmemory); /* newmemory handling not yet implemented */ + if (!PyCFunction_Check(obj)) { + return SWIG_ConvertPtr(obj, ptr, ty, 0); } else { - return SWIG_ERROR; + void *vptr = 0; + swig_cast_info *tc; + + /* here we get the method pointer for callbacks */ +#ifndef Py_LIMITED_API + const char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc); +#else + PyObject *pystr_doc = PyObject_GetAttrString(obj, "__doc__"); + PyObject *bytes = NULL; + const char *doc = pystr_doc ? SWIG_PyUnicode_AsUTF8AndSize(pystr_doc, NULL, &bytes) : 0; +#endif + const char *desc = doc ? strstr(doc, "swig_ptr: ") : 0; + if (desc) + desc = ty ? SWIG_UnpackVoidPtr(desc + 10, &vptr, ty->name) : 0; +#ifdef Py_LIMITED_API + Py_XDECREF(bytes); + Py_XDECREF(pystr_doc); +#endif + if (!desc) + return SWIG_ERROR; + tc = SWIG_TypeCheck(desc, ty); + if (tc) { + int newmemory = 0; + *ptr = SWIG_TypeCast(tc, vptr, &newmemory); + assert(!newmemory); /* newmemory handling not yet implemented */ + } else { + return SWIG_ERROR; + } + return SWIG_OK; } - return SWIG_OK; - } } /* Convert a packed pointer value */ SWIGRUNTIME int SWIG_Python_ConvertPacked(PyObject *obj, void *ptr, size_t sz, swig_type_info *ty) { - swig_type_info *to = SwigPyPacked_UnpackData(obj, ptr, sz); - if (!to) return SWIG_ERROR; - if (ty) { - if (to != ty) { - /* check type cast? */ - swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); - if (!tc) return SWIG_ERROR; + swig_type_info *to = SwigPyPacked_UnpackData(obj, ptr, sz); + if (!to) return SWIG_ERROR; + if (ty) { + if (to != ty) { + /* check type cast? */ + swig_cast_info *tc = SWIG_TypeCheck(to->name, ty); + if (!tc) return SWIG_ERROR; + } } - } - return SWIG_OK; -} + return SWIG_OK; +} /* ----------------------------------------------------------------------------- * Create a new pointer object @@ -2692,181 +2657,179 @@ SWIG_Python_ConvertPacked(PyObject *obj, void *ptr, size_t sz, swig_type_info *t 'this' attribute. */ -SWIGRUNTIME PyObject* -SWIG_Python_NewShadowInstance(SwigPyClientData *data, PyObject *swig_this) -{ - PyObject *inst = 0; - PyObject *newraw = data->newraw; - if (newraw) { - inst = PyObject_Call(newraw, data->newargs, NULL); - if (inst) { -#if !defined(SWIG_PYTHON_SLOW_GETSET_THIS) - PyObject **dictptr = _PyObject_GetDictPtr(inst); - if (dictptr != NULL) { - PyObject *dict = *dictptr; - if (dict == NULL) { - dict = PyDict_New(); - *dictptr = dict; - } - if (dict) { - PyDict_SetItem(dict, SWIG_This(), swig_this); - } else{ - Py_DECREF(inst); - inst = 0; - } - } -#else - if (PyObject_SetAttr(inst, SWIG_This(), swig_this) == -1) { - Py_DECREF(inst); - inst = 0; - } -#endif - } - } else { -#if PY_VERSION_HEX >= 0x03000000 - PyObject *empty_args = PyTuple_New(0); - if (empty_args) { - PyObject *empty_kwargs = PyDict_New(); - if (empty_kwargs) { -#ifndef Py_LIMITED_API - newfunc newfn = ((PyTypeObject *)data->newargs)->tp_new; -#else - newfunc newfn = (newfunc)PyType_GetSlot((PyTypeObject *)data->newargs, Py_tp_new); -#endif - inst = newfn((PyTypeObject *)data->newargs, empty_args, empty_kwargs); - Py_DECREF(empty_kwargs); +SWIGRUNTIME PyObject * +SWIG_Python_NewShadowInstance(SwigPyClientData *data, PyObject *swig_this) { + PyObject *inst = 0; + PyObject *newraw = data->newraw; + if (newraw) { + inst = PyObject_Call(newraw, data->newargs, NULL); if (inst) { - if (PyObject_SetAttr(inst, SWIG_This(), swig_this) == -1) { - Py_DECREF(inst); - inst = 0; - } else { - PyType_Modified(Py_TYPE(inst)); - } - } - } - Py_DECREF(empty_args); - } +#if !defined(SWIG_PYTHON_SLOW_GETSET_THIS) + PyObject **dictptr = _PyObject_GetDictPtr(inst); + if (dictptr != NULL) { + PyObject *dict = *dictptr; + if (dict == NULL) { + dict = PyDict_New(); + *dictptr = dict; + } + if (dict) { + PyDict_SetItem(dict, SWIG_This(), swig_this); + } else { + Py_DECREF(inst); + inst = 0; + } + } #else - PyObject *dict = PyDict_New(); - if (dict) { - PyDict_SetItem(dict, SWIG_This(), swig_this); - inst = PyInstance_NewRaw(data->newargs, dict); - Py_DECREF(dict); - } + if (PyObject_SetAttr(inst, SWIG_This(), swig_this) == -1) { + Py_DECREF(inst); + inst = 0; + } #endif - } - return inst; + } + } else { +#if PY_VERSION_HEX >= 0x03000000 + PyObject *empty_args = PyTuple_New(0); + if (empty_args) { + PyObject *empty_kwargs = PyDict_New(); + if (empty_kwargs) { +#ifndef Py_LIMITED_API + newfunc newfn = ((PyTypeObject *)data->newargs)->tp_new; +#else + newfunc newfn = (newfunc)PyType_GetSlot((PyTypeObject *)data->newargs, Py_tp_new); +#endif + inst = newfn((PyTypeObject *)data->newargs, empty_args, empty_kwargs); + Py_DECREF(empty_kwargs); + if (inst) { + if (PyObject_SetAttr(inst, SWIG_This(), swig_this) == -1) { + Py_DECREF(inst); + inst = 0; + } else { + PyType_Modified(Py_TYPE(inst)); + } + } + } + Py_DECREF(empty_args); + } +#else + PyObject *dict = PyDict_New(); + if (dict) { + PyDict_SetItem(dict, SWIG_This(), swig_this); + inst = PyInstance_NewRaw(data->newargs, dict); + Py_DECREF(dict); + } +#endif + } + return inst; } SWIGRUNTIME int -SWIG_Python_SetSwigThis(PyObject *inst, PyObject *swig_this) -{ +SWIG_Python_SetSwigThis(PyObject *inst, PyObject *swig_this) { #if !defined(SWIG_PYTHON_SLOW_GETSET_THIS) - PyObject **dictptr = _PyObject_GetDictPtr(inst); - if (dictptr != NULL) { - PyObject *dict = *dictptr; - if (dict == NULL) { - dict = PyDict_New(); - *dictptr = dict; + PyObject **dictptr = _PyObject_GetDictPtr(inst); + if (dictptr != NULL) { + PyObject *dict = *dictptr; + if (dict == NULL) { + dict = PyDict_New(); + *dictptr = dict; + } + if (dict) { + return PyDict_SetItem(dict, SWIG_This(), swig_this); + } else { + return -1; + } } - if (dict) { - return PyDict_SetItem(dict, SWIG_This(), swig_this); - } else{ - return -1; - } - } #endif - return PyObject_SetAttr(inst, SWIG_This(), swig_this); -} + return PyObject_SetAttr(inst, SWIG_This(), swig_this); +} SWIGINTERN PyObject * SWIG_Python_InitShadowInstance(PyObject *args) { - PyObject *obj[2]; - if (!SWIG_Python_UnpackTuple(args, "swiginit", 2, 2, obj)) { - return NULL; - } else { - SwigPyObject *sthis = SWIG_Python_GetSwigThis(obj[0]); - if (sthis) { - Py_DECREF(SwigPyObject_append((PyObject*) sthis, obj[1])); - } else { - if (SWIG_Python_SetSwigThis(obj[0], obj[1]) != 0) + PyObject *obj[2]; + if (!SWIG_Python_UnpackTuple(args, "swiginit", 2, 2, obj)) { return NULL; + } else { + SwigPyObject *sthis = SWIG_Python_GetSwigThis(obj[0]); + if (sthis) { + Py_DECREF(SwigPyObject_append((PyObject *) sthis, obj[1])); + } else { + if (SWIG_Python_SetSwigThis(obj[0], obj[1]) != 0) + return NULL; + } + return SWIG_Py_Void(); } - return SWIG_Py_Void(); - } } /* Create a new pointer object */ SWIGRUNTIME PyObject * SWIG_Python_NewPointerObj(PyObject *self, void *ptr, swig_type_info *type, int flags) { - SwigPyClientData *clientdata; - PyObject * robj; - int own; + SwigPyClientData *clientdata; + PyObject *robj; + int own; - if (!ptr) - return SWIG_Py_Void(); + if (!ptr) + return SWIG_Py_Void(); - clientdata = type ? (SwigPyClientData *)(type->clientdata) : 0; - own = (flags & SWIG_POINTER_OWN) ? SWIG_POINTER_OWN : 0; - if (clientdata && clientdata->pytype) { - SwigPyObject *newobj; - if (flags & SWIG_BUILTIN_TP_INIT) { - newobj = (SwigPyObject*) self; - if (newobj->ptr) { + clientdata = type ? (SwigPyClientData *)(type->clientdata) : 0; + own = (flags & SWIG_POINTER_OWN) ? SWIG_POINTER_OWN : 0; + if (clientdata && clientdata->pytype) { + SwigPyObject *newobj; + if (flags & SWIG_BUILTIN_TP_INIT) { + newobj = (SwigPyObject *) self; + if (newobj->ptr) { #ifndef Py_LIMITED_API - allocfunc alloc = clientdata->pytype->tp_alloc; + allocfunc alloc = clientdata->pytype->tp_alloc; #else - allocfunc alloc = (allocfunc)PyType_GetSlot(clientdata->pytype, Py_tp_alloc); + allocfunc alloc = (allocfunc)PyType_GetSlot(clientdata->pytype, Py_tp_alloc); #endif - PyObject *next_self = alloc(clientdata->pytype, 0); - while (newobj->next) - newobj = (SwigPyObject *) newobj->next; - newobj->next = next_self; - newobj = (SwigPyObject *)next_self; + PyObject *next_self = alloc(clientdata->pytype, 0); + while (newobj->next) + newobj = (SwigPyObject *) newobj->next; + newobj->next = next_self; + newobj = (SwigPyObject *)next_self; #ifdef SWIGPYTHON_BUILTIN - newobj->dict = 0; + newobj->dict = 0; #endif - } - } else { - newobj = PyObject_New(SwigPyObject, clientdata->pytype); + } + } else { + newobj = PyObject_New(SwigPyObject, clientdata->pytype); #ifdef SWIGPYTHON_BUILTIN - if (newobj) { - newobj->dict = 0; - } + if (newobj) { + newobj->dict = 0; + } #endif + } + if (newobj) { + newobj->ptr = ptr; + newobj->ty = type; + newobj->own = own; + newobj->next = 0; + return (PyObject *) newobj; + } + return SWIG_Py_Void(); } - if (newobj) { - newobj->ptr = ptr; - newobj->ty = type; - newobj->own = own; - newobj->next = 0; - return (PyObject*) newobj; + + assert(!(flags & SWIG_BUILTIN_TP_INIT)); + + robj = SwigPyObject_New(ptr, type, own); + if (robj && clientdata && !(flags & SWIG_POINTER_NOSHADOW)) { + PyObject *inst = SWIG_Python_NewShadowInstance(clientdata, robj); + Py_DECREF(robj); + robj = inst; } - return SWIG_Py_Void(); - } - - assert(!(flags & SWIG_BUILTIN_TP_INIT)); - - robj = SwigPyObject_New(ptr, type, own); - if (robj && clientdata && !(flags & SWIG_POINTER_NOSHADOW)) { - PyObject *inst = SWIG_Python_NewShadowInstance(clientdata, robj); - Py_DECREF(robj); - robj = inst; - } - return robj; + return robj; } /* Create a new packed object */ SWIGRUNTIMEINLINE PyObject * SWIG_Python_NewPackedObj(void *ptr, size_t sz, swig_type_info *type) { - return ptr ? SwigPyPacked_New((void *) ptr, sz, type) : SWIG_Py_Void(); + return ptr ? SwigPyPacked_New((void *) ptr, sz, type) : SWIG_Py_Void(); } /* -----------------------------------------------------------------------------* - * Get type list + * Get type list * -----------------------------------------------------------------------------*/ #ifdef SWIG_LINK_RUNTIME @@ -2878,105 +2841,103 @@ static PyObject *Swig_TypeCache_global = NULL; /* The python cached type query */ SWIGRUNTIME PyObject * SWIG_Python_TypeCache(void) { - if (Swig_TypeCache_global == NULL) { - Swig_TypeCache_global = PyDict_New(); - } - return Swig_TypeCache_global; + if (Swig_TypeCache_global == NULL) { + Swig_TypeCache_global = PyDict_New(); + } + return Swig_TypeCache_global; } SWIGRUNTIME swig_module_info * SWIG_Python_GetModule(void *SWIGUNUSEDPARM(clientdata)) { #ifdef SWIG_LINK_RUNTIME - static void *type_pointer = (void *)0; - /* first check if module already created */ - if (!type_pointer) { - type_pointer = SWIG_ReturnGlobalTypeList((void *)0); - } + static void *type_pointer = (void *)0; + /* first check if module already created */ + if (!type_pointer) { + type_pointer = SWIG_ReturnGlobalTypeList((void *)0); + } #else - void *type_pointer = PyCapsule_Import(SWIGPY_CAPSULE_NAME, 0); - if (PyErr_Occurred()) { - PyErr_Clear(); - type_pointer = (void *)0; - } + void *type_pointer = PyCapsule_Import(SWIGPY_CAPSULE_NAME, 0); + if (PyErr_Occurred()) { + PyErr_Clear(); + type_pointer = (void *)0; + } #endif - return (swig_module_info *) type_pointer; + return (swig_module_info *) type_pointer; } static int interpreter_counter = 0; /* how many (sub-)interpreters are using swig_module's types */ SWIGRUNTIME void -SWIG_Python_DestroyModule(PyObject *obj) -{ - swig_module_info *swig_module = (swig_module_info *) PyCapsule_GetPointer(obj, SWIGPY_CAPSULE_NAME); - swig_type_info **types = swig_module->types; - size_t i; - if (--interpreter_counter != 0) /* another sub-interpreter may still be using the swig_module's types */ - return; - for (i =0; i < swig_module->size; ++i) { - swig_type_info *ty = types[i]; - if (ty->owndata) { - SwigPyClientData *data = (SwigPyClientData *) ty->clientdata; - ty->clientdata = 0; - if (data) SwigPyClientData_Del(data); +SWIG_Python_DestroyModule(PyObject *obj) { + swig_module_info *swig_module = (swig_module_info *) PyCapsule_GetPointer(obj, SWIGPY_CAPSULE_NAME); + swig_type_info **types = swig_module->types; + size_t i; + if (--interpreter_counter != 0) /* another sub-interpreter may still be using the swig_module's types */ + return; + for (i = 0; i < swig_module->size; ++i) { + swig_type_info *ty = types[i]; + if (ty->owndata) { + SwigPyClientData *data = (SwigPyClientData *) ty->clientdata; + ty->clientdata = 0; + if (data) SwigPyClientData_Del(data); + } } - } - Py_DECREF(SWIG_This()); - Swig_This_global = NULL; - Py_DECREF(SWIG_globals()); - Swig_Globals_global = NULL; - Py_DECREF(SWIG_Python_TypeCache()); - Swig_TypeCache_global = NULL; - Swig_Capsule_global = NULL; + Py_DECREF(SWIG_This()); + Swig_This_global = NULL; + Py_DECREF(SWIG_globals()); + Swig_Globals_global = NULL; + Py_DECREF(SWIG_Python_TypeCache()); + Swig_TypeCache_global = NULL; + Swig_Capsule_global = NULL; } SWIGRUNTIME void SWIG_Python_SetModule(swig_module_info *swig_module) { #if PY_VERSION_HEX >= 0x03000000 - /* Add a dummy module object into sys.modules */ - PyObject *module = PyImport_AddModule("swig_runtime_data" SWIG_RUNTIME_VERSION); + /* Add a dummy module object into sys.modules */ + PyObject *module = PyImport_AddModule("swig_runtime_data" SWIG_RUNTIME_VERSION); #else - static PyMethodDef swig_empty_runtime_method_table[] = { {NULL, NULL, 0, NULL} }; /* Sentinel */ - PyObject *module = Py_InitModule("swig_runtime_data" SWIG_RUNTIME_VERSION, swig_empty_runtime_method_table); + static PyMethodDef swig_empty_runtime_method_table[] = { {NULL, NULL, 0, NULL} }; /* Sentinel */ + PyObject *module = Py_InitModule("swig_runtime_data" SWIG_RUNTIME_VERSION, swig_empty_runtime_method_table); #endif - PyObject *pointer = PyCapsule_New((void *) swig_module, SWIGPY_CAPSULE_NAME, SWIG_Python_DestroyModule); - if (pointer && module) { - if (PyModule_AddObject(module, SWIGPY_CAPSULE_ATTR_NAME, pointer) == 0) { - ++interpreter_counter; - Swig_Capsule_global = pointer; + PyObject *pointer = PyCapsule_New((void *) swig_module, SWIGPY_CAPSULE_NAME, SWIG_Python_DestroyModule); + if (pointer && module) { + if (PyModule_AddObject(module, SWIGPY_CAPSULE_ATTR_NAME, pointer) == 0) { + ++interpreter_counter; + Swig_Capsule_global = pointer; + } else { + Py_DECREF(pointer); + } } else { - Py_DECREF(pointer); + Py_XDECREF(pointer); } - } else { - Py_XDECREF(pointer); - } } SWIGRUNTIME swig_type_info * -SWIG_Python_TypeQuery(const char *type) -{ - PyObject *cache = SWIG_Python_TypeCache(); - PyObject *key = SWIG_Python_str_FromChar(type); - PyObject *obj = PyDict_GetItem(cache, key); - swig_type_info *descriptor; - if (obj) { - descriptor = (swig_type_info *) PyCapsule_GetPointer(obj, NULL); - } else { - swig_module_info *swig_module = SWIG_GetModule(0); - descriptor = SWIG_TypeQueryModule(swig_module, swig_module, type); - if (descriptor) { - obj = PyCapsule_New((void*) descriptor, NULL, NULL); - if (obj) { - PyDict_SetItem(cache, key, obj); - Py_DECREF(obj); - } +SWIG_Python_TypeQuery(const char *type) { + PyObject *cache = SWIG_Python_TypeCache(); + PyObject *key = SWIG_Python_str_FromChar(type); + PyObject *obj = PyDict_GetItem(cache, key); + swig_type_info *descriptor; + if (obj) { + descriptor = (swig_type_info *) PyCapsule_GetPointer(obj, NULL); + } else { + swig_module_info *swig_module = SWIG_GetModule(0); + descriptor = SWIG_TypeQueryModule(swig_module, swig_module, type); + if (descriptor) { + obj = PyCapsule_New((void *) descriptor, NULL, NULL); + if (obj) { + PyDict_SetItem(cache, key, obj); + Py_DECREF(obj); + } + } } - } - Py_DECREF(key); - return descriptor; + Py_DECREF(key); + return descriptor; } -/* +/* For backward compatibility only */ #define SWIG_POINTER_EXCEPTION 0 @@ -2984,159 +2945,155 @@ SWIG_Python_TypeQuery(const char *type) #define SWIG_MustGetPtr(p, type, argnum, flags) SWIG_Python_MustGetPtr(p, type, argnum, flags) SWIGRUNTIME int -SWIG_Python_AddErrMesg(const char* mesg, int infront) -{ - if (PyErr_Occurred()) { - PyObject *type = 0; - PyObject *value = 0; - PyObject *traceback = 0; - PyErr_Fetch(&type, &value, &traceback); - if (value) { - PyObject *old_str = PyObject_Str(value); - PyObject *bytes = NULL; - const char *tmp = SWIG_PyUnicode_AsUTF8AndSize(old_str, NULL, &bytes); - const char *errmesg = tmp ? tmp : "Invalid error message"; - Py_XINCREF(type); - PyErr_Clear(); - if (infront) { - PyErr_Format(type, "%s %s", mesg, errmesg); - } else { - PyErr_Format(type, "%s %s", errmesg, mesg); - } - Py_XDECREF(bytes); - Py_DECREF(old_str); +SWIG_Python_AddErrMesg(const char *mesg, int infront) { + if (PyErr_Occurred()) { + PyObject *type = 0; + PyObject *value = 0; + PyObject *traceback = 0; + PyErr_Fetch(&type, &value, &traceback); + if (value) { + PyObject *old_str = PyObject_Str(value); + PyObject *bytes = NULL; + const char *tmp = SWIG_PyUnicode_AsUTF8AndSize(old_str, NULL, &bytes); + const char *errmesg = tmp ? tmp : "Invalid error message"; + Py_XINCREF(type); + PyErr_Clear(); + if (infront) { + PyErr_Format(type, "%s %s", mesg, errmesg); + } else { + PyErr_Format(type, "%s %s", errmesg, mesg); + } + Py_XDECREF(bytes); + Py_DECREF(old_str); + } + return 1; + } else { + return 0; } - return 1; - } else { - return 0; - } } - + SWIGRUNTIME int -SWIG_Python_ArgFail(int argnum) -{ - if (PyErr_Occurred()) { - /* add information about failing argument */ - char mesg[256]; - PyOS_snprintf(mesg, sizeof(mesg), "argument number %d:", argnum); - return SWIG_Python_AddErrMesg(mesg, 1); - } else { - return 0; - } +SWIG_Python_ArgFail(int argnum) { + if (PyErr_Occurred()) { + /* add information about failing argument */ + char mesg[256]; + PyOS_snprintf(mesg, sizeof(mesg), "argument number %d:", argnum); + return SWIG_Python_AddErrMesg(mesg, 1); + } else { + return 0; + } } SWIGRUNTIMEINLINE const char * -SwigPyObject_GetDesc(PyObject *self) -{ - SwigPyObject *v = (SwigPyObject *)self; - swig_type_info *ty = v ? v->ty : 0; - return ty ? ty->str : ""; +SwigPyObject_GetDesc(PyObject *self) { + SwigPyObject *v = (SwigPyObject *)self; + swig_type_info *ty = v ? v->ty : 0; + return ty ? ty->str : ""; } SWIGRUNTIME void -SWIG_Python_TypeError(const char *type, PyObject *obj) -{ - if (type) { +SWIG_Python_TypeError(const char *type, PyObject *obj) { + if (type) { #if defined(SWIG_COBJECT_TYPES) - if (obj && SwigPyObject_Check(obj)) { - const char *otype = (const char *) SwigPyObject_GetDesc(obj); - if (otype) { - PyErr_Format(PyExc_TypeError, "a '%s' is expected, 'SwigPyObject(%s)' is received", - type, otype); - return; - } - } else -#endif - { -#ifndef Py_LIMITED_API - /* tp_name is not accessible */ - const char *otype = (obj ? obj->ob_type->tp_name : 0); - if (otype) { - PyObject *str = PyObject_Str(obj); - PyObject *bytes = NULL; - const char *cstr = str ? SWIG_PyUnicode_AsUTF8AndSize(str, NULL, &bytes) : 0; - if (cstr) { - PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s(%s)' is received", - type, otype, cstr); - } else { - PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s' is received", - type, otype); - } - Py_XDECREF(bytes); - Py_XDECREF(str); - return; - } + if (obj && SwigPyObject_Check(obj)) { + const char *otype = (const char *) SwigPyObject_GetDesc(obj); + if (otype) { + PyErr_Format(PyExc_TypeError, "a '%s' is expected, 'SwigPyObject(%s)' is received", + type, otype); + return; + } + } else #endif - } - PyErr_Format(PyExc_TypeError, "a '%s' is expected", type); - } else { - PyErr_Format(PyExc_TypeError, "unexpected type is received"); - } + { +#ifndef Py_LIMITED_API + /* tp_name is not accessible */ + const char *otype = (obj ? obj->ob_type->tp_name : 0); + if (otype) { + PyObject *str = PyObject_Str(obj); + PyObject *bytes = NULL; + const char *cstr = str ? SWIG_PyUnicode_AsUTF8AndSize(str, NULL, &bytes) : 0; + if (cstr) { + PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s(%s)' is received", + type, otype, cstr); + } else { + PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s' is received", + type, otype); + } + Py_XDECREF(bytes); + Py_XDECREF(str); + return; + } +#endif + } + PyErr_Format(PyExc_TypeError, "a '%s' is expected", type); + } else { + PyErr_Format(PyExc_TypeError, "unexpected type is received"); + } } /* Convert a pointer value, signal an exception on a type mismatch */ SWIGRUNTIME void * SWIG_Python_MustGetPtr(PyObject *obj, swig_type_info *ty, int SWIGUNUSEDPARM(argnum), int flags) { - void *result; - if (SWIG_Python_ConvertPtr(obj, &result, ty, flags) == -1) { - PyErr_Clear(); - } - return result; + void *result; + if (SWIG_Python_ConvertPtr(obj, &result, ty, flags) == -1) { + PyErr_Clear(); + } + return result; } #ifdef SWIGPYTHON_BUILTIN SWIGRUNTIME int SWIG_Python_NonDynamicSetAttr(PyObject *obj, PyObject *name, PyObject *value) { - PyTypeObject *tp = obj->ob_type; - PyObject *descr; - PyObject *encoded_name; - descrsetfunc f; - int res = -1; + PyTypeObject *tp = obj->ob_type; + PyObject *descr; + PyObject *encoded_name; + descrsetfunc f; + int res = -1; # ifdef Py_USING_UNICODE - if (PyString_Check(name)) { - name = PyUnicode_Decode(PyString_AsString(name), PyString_Size(name), NULL, NULL); - if (!name) - return -1; - } else if (!PyUnicode_Check(name)) -# else - if (!PyString_Check(name)) -# endif - { - PyErr_Format(PyExc_TypeError, "attribute name must be string, not '%.200s'", name->ob_type->tp_name); - return -1; - } else { - Py_INCREF(name); - } - - if (!tp->tp_dict) { - if (PyType_Ready(tp) != 0) - goto done; - } - - descr = _PyType_Lookup(tp, name); - f = NULL; - if (descr != NULL) - f = descr->ob_type->tp_descr_set; - if (!f) { if (PyString_Check(name)) { - encoded_name = name; - Py_INCREF(name); + name = PyUnicode_Decode(PyString_AsString(name), PyString_Size(name), NULL, NULL); + if (!name) + return -1; + } else if (!PyUnicode_Check(name)) +# else + if (!PyString_Check(name)) +# endif + { + PyErr_Format(PyExc_TypeError, "attribute name must be string, not '%.200s'", name->ob_type->tp_name); + return -1; } else { - encoded_name = PyUnicode_AsUTF8String(name); - if (!encoded_name) - goto done; + Py_INCREF(name); } - PyErr_Format(PyExc_AttributeError, "'%.100s' object has no attribute '%.200s'", tp->tp_name, PyString_AsString(encoded_name)); - Py_DECREF(encoded_name); - } else { - res = f(descr, obj, value); - } - - done: - Py_DECREF(name); - return res; + + if (!tp->tp_dict) { + if (PyType_Ready(tp) != 0) + goto done; + } + + descr = _PyType_Lookup(tp, name); + f = NULL; + if (descr != NULL) + f = descr->ob_type->tp_descr_set; + if (!f) { + if (PyString_Check(name)) { + encoded_name = name; + Py_INCREF(name); + } else { + encoded_name = PyUnicode_AsUTF8String(name); + if (!encoded_name) + goto done; + } + PyErr_Format(PyExc_AttributeError, "'%.100s' object has no attribute '%.200s'", tp->tp_name, PyString_AsString(encoded_name)); + Py_DECREF(encoded_name); + } else { + res = f(descr, obj, value); + } + +done: + Py_DECREF(name); + return res; } #endif @@ -3147,9 +3104,9 @@ SWIG_Python_NonDynamicSetAttr(PyObject *obj, PyObject *name, PyObject *value) { -#define SWIG_exception_fail(code, msg) do { SWIG_Error(code, msg); SWIG_fail; } while(0) +#define SWIG_exception_fail(code, msg) do { SWIG_Error(code, msg); SWIG_fail; } while(0) -#define SWIG_contract_assert(expr, msg) do { if (!(expr)) { SWIG_Error(SWIG_RuntimeError, msg); SWIG_fail; } } while (0) +#define SWIG_contract_assert(expr, msg) do { if (!(expr)) { SWIG_Error(SWIG_RuntimeError, msg); SWIG_fail; } } while (0) @@ -3181,373 +3138,371 @@ static swig_module_info swig_module = {swig_types, 2, 0, 0, 0, 0}; #endif #define SWIG_name "_pm3" -#define SWIG_as_voidptr(a) (void *)((const void *)(a)) -#define SWIG_as_voidptrptr(a) ((void)SWIG_as_voidptr(*a),(void**)(a)) +#define SWIG_as_voidptr(a) (void *)((const void *)(a)) +#define SWIG_as_voidptrptr(a) ((void)SWIG_as_voidptr(*a),(void**)(a)) /* Include the header in the wrapper code */ #include "pm3.h" #include "comms.h" -SWIGINTERN pm3 *new_pm3__SWIG_0(void){ +SWIGINTERN pm3 *new_pm3__SWIG_0(void) { // printf("SWIG pm3 constructor, get current pm3\n"); - pm3_device_t * p = pm3_get_current_dev(); - p->script_embedded = 1; - return p; - } + pm3_device_t *p = pm3_get_current_dev(); + p->script_embedded = 1; + return p; +} -SWIGINTERN swig_type_info* -SWIG_pchar_descriptor(void) -{ - static int init = 0; - static swig_type_info* info = 0; - if (!init) { - info = SWIG_TypeQuery("_p_char"); - init = 1; - } - return info; +SWIGINTERN swig_type_info * +SWIG_pchar_descriptor(void) { + static int init = 0; + static swig_type_info *info = 0; + if (!init) { + info = SWIG_TypeQuery("_p_char"); + init = 1; + } + return info; } /* Return string from Python obj. NOTE: obj must remain in scope in order to use the returned cptr (but only when alloc is set to SWIG_OLDOBJ) */ SWIGINTERN int -SWIG_AsCharPtrAndSize(PyObject *obj, char **cptr, size_t *psize, int *alloc) -{ +SWIG_AsCharPtrAndSize(PyObject *obj, char **cptr, size_t *psize, int *alloc) { #if PY_VERSION_HEX>=0x03000000 #if defined(SWIG_PYTHON_STRICT_BYTE_CHAR) - if (PyBytes_Check(obj)) + if (PyBytes_Check(obj)) #else - if (PyUnicode_Check(obj)) + if (PyUnicode_Check(obj)) #endif -#else - if (PyString_Check(obj)) +#else + if (PyString_Check(obj)) #endif - { - char *cstr; Py_ssize_t len; - PyObject *bytes = NULL; - int ret = SWIG_OK; - if (alloc) - *alloc = SWIG_OLDOBJ; + { + char *cstr; + Py_ssize_t len; + PyObject *bytes = NULL; + int ret = SWIG_OK; + if (alloc) + *alloc = SWIG_OLDOBJ; #if PY_VERSION_HEX>=0x03000000 && defined(SWIG_PYTHON_STRICT_BYTE_CHAR) - if (PyBytes_AsStringAndSize(obj, &cstr, &len) == -1) - return SWIG_TypeError; + if (PyBytes_AsStringAndSize(obj, &cstr, &len) == -1) + return SWIG_TypeError; #else - cstr = (char *)SWIG_PyUnicode_AsUTF8AndSize(obj, &len, &bytes); - if (!cstr) - return SWIG_TypeError; - /* The returned string is only duplicated if the char * returned is not owned and memory managed by obj */ - if (bytes && cptr) { - if (alloc) { - cstr = (char *)memcpy(malloc((len + 1)*sizeof(char)), cstr, sizeof(char)*(len + 1)); - *alloc = SWIG_NEWOBJ; - } else { - /* alloc must be set in order to clean up allocated memory */ - return SWIG_RuntimeError; - } - } + cstr = (char *)SWIG_PyUnicode_AsUTF8AndSize(obj, &len, &bytes); + if (!cstr) + return SWIG_TypeError; + /* The returned string is only duplicated if the char * returned is not owned and memory managed by obj */ + if (bytes && cptr) { + if (alloc) { + cstr = (char *)memcpy(malloc((len + 1) * sizeof(char)), cstr, sizeof(char) * (len + 1)); + *alloc = SWIG_NEWOBJ; + } else { + /* alloc must be set in order to clean up allocated memory */ + return SWIG_RuntimeError; + } + } #endif - if (cptr) *cptr = cstr; - if (psize) *psize = len + 1; - Py_XDECREF(bytes); - return ret; - } else { + if (cptr) *cptr = cstr; + if (psize) *psize = len + 1; + Py_XDECREF(bytes); + return ret; + } else { #if defined(SWIG_PYTHON_2_UNICODE) #if defined(SWIG_PYTHON_STRICT_BYTE_CHAR) #error "Cannot use both SWIG_PYTHON_2_UNICODE and SWIG_PYTHON_STRICT_BYTE_CHAR at once" #endif #if PY_VERSION_HEX<0x03000000 - if (PyUnicode_Check(obj)) { - char *cstr; Py_ssize_t len; - if (!alloc && cptr) { - return SWIG_RuntimeError; - } - obj = PyUnicode_AsUTF8String(obj); - if (!obj) - return SWIG_TypeError; - if (PyString_AsStringAndSize(obj, &cstr, &len) != -1) { - if (cptr) { - if (alloc) *alloc = SWIG_NEWOBJ; - *cptr = (char *)memcpy(malloc((len + 1)*sizeof(char)), cstr, sizeof(char)*(len + 1)); + if (PyUnicode_Check(obj)) { + char *cstr; + Py_ssize_t len; + if (!alloc && cptr) { + return SWIG_RuntimeError; + } + obj = PyUnicode_AsUTF8String(obj); + if (!obj) + return SWIG_TypeError; + if (PyString_AsStringAndSize(obj, &cstr, &len) != -1) { + if (cptr) { + if (alloc) *alloc = SWIG_NEWOBJ; + *cptr = (char *)memcpy(malloc((len + 1) * sizeof(char)), cstr, sizeof(char) * (len + 1)); + } + if (psize) *psize = len + 1; + + Py_XDECREF(obj); + return SWIG_OK; + } else { + Py_XDECREF(obj); + } } - if (psize) *psize = len + 1; - - Py_XDECREF(obj); - return SWIG_OK; - } else { - Py_XDECREF(obj); - } - } #endif #endif - swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); - if (pchar_descriptor) { - void* vptr = 0; - if (SWIG_ConvertPtr(obj, &vptr, pchar_descriptor, 0) == SWIG_OK) { - if (cptr) *cptr = (char *) vptr; - if (psize) *psize = vptr ? (strlen((char *)vptr) + 1) : 0; - if (alloc) *alloc = SWIG_OLDOBJ; - return SWIG_OK; - } + swig_type_info *pchar_descriptor = SWIG_pchar_descriptor(); + if (pchar_descriptor) { + void *vptr = 0; + if (SWIG_ConvertPtr(obj, &vptr, pchar_descriptor, 0) == SWIG_OK) { + if (cptr) *cptr = (char *) vptr; + if (psize) *psize = vptr ? (strlen((char *)vptr) + 1) : 0; + if (alloc) *alloc = SWIG_OLDOBJ; + return SWIG_OK; + } + } } - } - return SWIG_TypeError; + return SWIG_TypeError; } -SWIGINTERN pm3 *new_pm3__SWIG_1(char *port){ +SWIGINTERN pm3 *new_pm3__SWIG_1(char *port) { // printf("SWIG pm3 constructor with port, open pm3\n"); - pm3_device_t * p = pm3_open(port); - p->script_embedded = 0; - return p; - } -SWIGINTERN void delete_pm3(pm3 *self){ - if (self->script_embedded) { + pm3_device_t *p = pm3_open(port); + p->script_embedded = 0; + return p; +} +SWIGINTERN void delete_pm3(pm3 *self) { + if (self->script_embedded) { // printf("SWIG pm3 destructor, nothing to do\n"); - } else { + } else { // printf("SWIG pm3 destructor, close pm3\n"); - pm3_close(self); - } - } + pm3_close(self); + } +} -SWIGINTERNINLINE PyObject* - SWIG_From_int (int value) -{ - return PyInt_FromLong((long) value); +SWIGINTERNINLINE PyObject * +SWIG_From_int(int value) { + return PyInt_FromLong((long) value); } SWIGINTERNINLINE PyObject * -SWIG_FromCharPtrAndSize(const char* carray, size_t size) -{ - if (carray) { - if (size > INT_MAX) { - swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); - return pchar_descriptor ? - SWIG_InternalNewPointerObj((char *)(carray), pchar_descriptor, 0) : SWIG_Py_Void(); - } else { +SWIG_FromCharPtrAndSize(const char *carray, size_t size) { + if (carray) { + if (size > INT_MAX) { + swig_type_info *pchar_descriptor = SWIG_pchar_descriptor(); + return pchar_descriptor ? + SWIG_InternalNewPointerObj((char *)(carray), pchar_descriptor, 0) : SWIG_Py_Void(); + } else { #if PY_VERSION_HEX >= 0x03000000 #if defined(SWIG_PYTHON_STRICT_BYTE_CHAR) - return PyBytes_FromStringAndSize(carray, (Py_ssize_t)(size)); + return PyBytes_FromStringAndSize(carray, (Py_ssize_t)(size)); #else - return PyUnicode_DecodeUTF8(carray, (Py_ssize_t)(size), "surrogateescape"); + return PyUnicode_DecodeUTF8(carray, (Py_ssize_t)(size), "surrogateescape"); #endif #else - return PyString_FromStringAndSize(carray, (Py_ssize_t)(size)); + return PyString_FromStringAndSize(carray, (Py_ssize_t)(size)); #endif + } + } else { + return SWIG_Py_Void(); } - } else { - return SWIG_Py_Void(); - } } -SWIGINTERNINLINE PyObject * -SWIG_FromCharPtr(const char *cptr) -{ - return SWIG_FromCharPtrAndSize(cptr, (cptr ? strlen(cptr) : 0)); +SWIGINTERNINLINE PyObject * +SWIG_FromCharPtr(const char *cptr) { + return SWIG_FromCharPtrAndSize(cptr, (cptr ? strlen(cptr) : 0)); } #ifdef __cplusplus extern "C" { #endif SWIGINTERN PyObject *_wrap_new_pm3__SWIG_0(PyObject *self, Py_ssize_t nobjs, PyObject **SWIGUNUSEDPARM(swig_obj)) { - PyObject *resultobj = 0; - pm3 *result = 0 ; - - (void)self; - if ((nobjs < 0) || (nobjs > 0)) SWIG_fail; - result = (pm3 *)new_pm3__SWIG_0(); - resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_pm3, SWIG_POINTER_NEW | 0 ); - return resultobj; + PyObject *resultobj = 0; + pm3 *result = 0 ; + + (void)self; + if ((nobjs < 0) || (nobjs > 0)) SWIG_fail; + result = (pm3 *)new_pm3__SWIG_0(); + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_pm3, SWIG_POINTER_NEW | 0); + return resultobj; fail: - return NULL; + return NULL; } SWIGINTERN PyObject *_wrap_new_pm3__SWIG_1(PyObject *self, Py_ssize_t nobjs, PyObject **swig_obj) { - PyObject *resultobj = 0; - char *arg1 = (char *) 0 ; - int res1 ; - char *buf1 = 0 ; - int alloc1 = 0 ; - pm3 *result = 0 ; - - (void)self; - if ((nobjs < 1) || (nobjs > 1)) SWIG_fail; - res1 = SWIG_AsCharPtrAndSize(swig_obj[0], &buf1, NULL, &alloc1); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new_pm3" "', argument " "1"" of type '" "char *""'"); - } - arg1 = (char *)(buf1); - result = (pm3 *)new_pm3__SWIG_1(arg1); - resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_pm3, SWIG_POINTER_NEW | 0 ); - if (alloc1 == SWIG_NEWOBJ) free((char*)buf1); - return resultobj; + PyObject *resultobj = 0; + char *arg1 = (char *) 0 ; + int res1 ; + char *buf1 = 0 ; + int alloc1 = 0 ; + pm3 *result = 0 ; + + (void)self; + if ((nobjs < 1) || (nobjs > 1)) SWIG_fail; + res1 = SWIG_AsCharPtrAndSize(swig_obj[0], &buf1, NULL, &alloc1); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new_pm3" "', argument " "1"" of type '" "char *""'"); + } + arg1 = (char *)(buf1); + result = (pm3 *)new_pm3__SWIG_1(arg1); + resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_pm3, SWIG_POINTER_NEW | 0); + if (alloc1 == SWIG_NEWOBJ) free((char *)buf1); + return resultobj; fail: - if (alloc1 == SWIG_NEWOBJ) free((char*)buf1); - return NULL; + if (alloc1 == SWIG_NEWOBJ) free((char *)buf1); + return NULL; } SWIGINTERN PyObject *_wrap_new_pm3(PyObject *self, PyObject *args) { - Py_ssize_t argc; - PyObject *argv[2] = { - 0 - }; - - if (!(argc = SWIG_Python_UnpackTuple(args, "new_pm3", 0, 1, argv))) SWIG_fail; - --argc; - if (argc == 0) { - return _wrap_new_pm3__SWIG_0(self, argc, argv); - } - if (argc == 1) { - int _v = 0; - int res = SWIG_AsCharPtrAndSize(argv[0], 0, NULL, 0); - _v = SWIG_CheckState(res); - if (_v) { - return _wrap_new_pm3__SWIG_1(self, argc, argv); + Py_ssize_t argc; + PyObject *argv[2] = { + 0 + }; + + if (!(argc = SWIG_Python_UnpackTuple(args, "new_pm3", 0, 1, argv))) SWIG_fail; + --argc; + if (argc == 0) { + return _wrap_new_pm3__SWIG_0(self, argc, argv); } - } - + if (argc == 1) { + int _v = 0; + int res = SWIG_AsCharPtrAndSize(argv[0], 0, NULL, 0); + _v = SWIG_CheckState(res); + if (_v) { + return _wrap_new_pm3__SWIG_1(self, argc, argv); + } + } + fail: - SWIG_Python_RaiseOrModifyTypeError("Wrong number or type of arguments for overloaded function 'new_pm3'.\n" - " Possible C/C++ prototypes are:\n" - " pm3::pm3()\n" - " pm3::pm3(char *)\n"); - return 0; + SWIG_Python_RaiseOrModifyTypeError("Wrong number or type of arguments for overloaded function 'new_pm3'.\n" + " Possible C/C++ prototypes are:\n" + " pm3::pm3()\n" + " pm3::pm3(char *)\n"); + return 0; } SWIGINTERN PyObject *_wrap_delete_pm3(PyObject *self, PyObject *args) { - PyObject *resultobj = 0; - pm3 *arg1 = (pm3 *) 0 ; - void *argp1 = 0 ; - int res1 = 0 ; - PyObject *swig_obj[1] ; - - (void)self; - if (!args) SWIG_fail; - swig_obj[0] = args; - res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_pm3, SWIG_POINTER_DISOWN | 0 ); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_pm3" "', argument " "1"" of type '" "pm3 *""'"); - } - arg1 = (pm3 *)(argp1); - delete_pm3(arg1); - resultobj = SWIG_Py_Void(); - return resultobj; + PyObject *resultobj = 0; + pm3 *arg1 = (pm3 *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_pm3, SWIG_POINTER_DISOWN | 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_pm3" "', argument " "1"" of type '" "pm3 *""'"); + } + arg1 = (pm3 *)(argp1); + delete_pm3(arg1); + resultobj = SWIG_Py_Void(); + return resultobj; fail: - return NULL; + return NULL; } SWIGINTERN PyObject *_wrap_pm3_console(PyObject *self, PyObject *args) { - PyObject *resultobj = 0; - pm3 *arg1 = (pm3 *) 0 ; - char *arg2 = (char *) 0 ; - void *argp1 = 0 ; - int res1 = 0 ; - int res2 ; - char *buf2 = 0 ; - int alloc2 = 0 ; - PyObject *swig_obj[2] ; - int result; - - (void)self; - if (!SWIG_Python_UnpackTuple(args, "pm3_console", 2, 2, swig_obj)) SWIG_fail; - res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_pm3, 0 | 0 ); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "pm3_console" "', argument " "1"" of type '" "pm3 *""'"); - } - arg1 = (pm3 *)(argp1); - res2 = SWIG_AsCharPtrAndSize(swig_obj[1], &buf2, NULL, &alloc2); - if (!SWIG_IsOK(res2)) { - SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "pm3_console" "', argument " "2"" of type '" "char *""'"); - } - arg2 = (char *)(buf2); - result = (int)pm3_console(arg1,arg2); - resultobj = SWIG_From_int((int)(result)); - if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); - return resultobj; + PyObject *resultobj = 0; + pm3 *arg1 = (pm3 *) 0 ; + char *arg2 = (char *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + int res2 ; + char *buf2 = 0 ; + int alloc2 = 0 ; + PyObject *swig_obj[2] ; + int result; + + (void)self; + if (!SWIG_Python_UnpackTuple(args, "pm3_console", 2, 2, swig_obj)) SWIG_fail; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_pm3, 0 | 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "pm3_console" "', argument " "1"" of type '" "pm3 *""'"); + } + arg1 = (pm3 *)(argp1); + res2 = SWIG_AsCharPtrAndSize(swig_obj[1], &buf2, NULL, &alloc2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "pm3_console" "', argument " "2"" of type '" "char *""'"); + } + arg2 = (char *)(buf2); + result = (int)pm3_console(arg1, arg2); + resultobj = SWIG_From_int((int)(result)); + if (alloc2 == SWIG_NEWOBJ) free((char *)buf2); + return resultobj; fail: - if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); - return NULL; + if (alloc2 == SWIG_NEWOBJ) free((char *)buf2); + return NULL; } SWIGINTERN PyObject *_wrap_pm3_name_get(PyObject *self, PyObject *args) { - PyObject *resultobj = 0; - pm3 *arg1 = (pm3 *) 0 ; - void *argp1 = 0 ; - int res1 = 0 ; - PyObject *swig_obj[1] ; - char *result = 0 ; - - (void)self; - if (!args) SWIG_fail; - swig_obj[0] = args; - res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_pm3, 0 | 0 ); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "pm3_name_get" "', argument " "1"" of type '" "pm3 *""'"); - } - arg1 = (pm3 *)(argp1); - result = (char *)pm3_name_get(arg1); - resultobj = SWIG_FromCharPtr((const char *)result); - return resultobj; + PyObject *resultobj = 0; + pm3 *arg1 = (pm3 *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + PyObject *swig_obj[1] ; + char *result = 0 ; + + (void)self; + if (!args) SWIG_fail; + swig_obj[0] = args; + res1 = SWIG_ConvertPtr(swig_obj[0], &argp1, SWIGTYPE_p_pm3, 0 | 0); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "pm3_name_get" "', argument " "1"" of type '" "pm3 *""'"); + } + arg1 = (pm3 *)(argp1); + result = (char *)pm3_name_get(arg1); + resultobj = SWIG_FromCharPtr((const char *)result); + return resultobj; fail: - return NULL; + return NULL; } SWIGINTERN PyObject *pm3_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { - PyObject *obj; - if (!SWIG_Python_UnpackTuple(args, "swigregister", 1, 1, &obj)) return NULL; - SWIG_TypeNewClientData(SWIGTYPE_p_pm3, SWIG_NewClientData(obj)); - return SWIG_Py_Void(); + PyObject *obj; + if (!SWIG_Python_UnpackTuple(args, "swigregister", 1, 1, &obj)) return NULL; + SWIG_TypeNewClientData(SWIGTYPE_p_pm3, SWIG_NewClientData(obj)); + return SWIG_Py_Void(); } SWIGINTERN PyObject *pm3_swiginit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { - return SWIG_Python_InitShadowInstance(args); + return SWIG_Python_InitShadowInstance(args); } static PyMethodDef SwigMethods[] = { - { "new_pm3", _wrap_new_pm3, METH_VARARGS, NULL}, - { "delete_pm3", _wrap_delete_pm3, METH_O, NULL}, - { "pm3_console", _wrap_pm3_console, METH_VARARGS, NULL}, - { "pm3_name_get", _wrap_pm3_name_get, METH_O, NULL}, - { "pm3_swigregister", pm3_swigregister, METH_O, NULL}, - { "pm3_swiginit", pm3_swiginit, METH_VARARGS, NULL}, - { NULL, NULL, 0, NULL } + { "new_pm3", _wrap_new_pm3, METH_VARARGS, NULL}, + { "delete_pm3", _wrap_delete_pm3, METH_O, NULL}, + { "pm3_console", _wrap_pm3_console, METH_VARARGS, NULL}, + { "pm3_name_get", _wrap_pm3_name_get, METH_O, NULL}, + { "pm3_swigregister", pm3_swigregister, METH_O, NULL}, + { "pm3_swiginit", pm3_swiginit, METH_VARARGS, NULL}, + { NULL, NULL, 0, NULL } }; /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */ -static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, (void*)0, 0}; -static swig_type_info _swigt__p_pm3 = {"_p_pm3", "pm3 *", 0, 0, (void*)0, 0}; +static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, (void *)0, 0}; +static swig_type_info _swigt__p_pm3 = {"_p_pm3", "pm3 *", 0, 0, (void *)0, 0}; static swig_type_info *swig_type_initial[] = { - &_swigt__p_char, - &_swigt__p_pm3, + &_swigt__p_char, + &_swigt__p_pm3, }; -static swig_cast_info _swigc__p_char[] = { {&_swigt__p_char, 0, 0, 0},{0, 0, 0, 0}}; -static swig_cast_info _swigc__p_pm3[] = { {&_swigt__p_pm3, 0, 0, 0},{0, 0, 0, 0}}; +static swig_cast_info _swigc__p_char[] = { {&_swigt__p_char, 0, 0, 0}, {0, 0, 0, 0}}; +static swig_cast_info _swigc__p_pm3[] = { {&_swigt__p_pm3, 0, 0, 0}, {0, 0, 0, 0}}; static swig_cast_info *swig_cast_initial[] = { - _swigc__p_char, - _swigc__p_pm3, + _swigc__p_char, + _swigc__p_pm3, }; /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */ static swig_const_info swig_const_table[] = { -{0, 0, 0, 0.0, 0, 0}}; + {0, 0, 0, 0.0, 0, 0} +}; #ifdef __cplusplus } @@ -3610,143 +3565,143 @@ extern "C" { SWIGRUNTIME void SWIG_InitializeModule(SWIG_INIT_CLIENT_DATA_TYPE clientdata) { - size_t i; - swig_module_info *module_head, *iter; - int init; - - /* check to see if the circular list has been setup, if not, set it up */ - if (swig_module.next==0) { - /* Initialize the swig_module */ - swig_module.type_initial = swig_type_initial; - swig_module.cast_initial = swig_cast_initial; - swig_module.next = &swig_module; - init = 1; - } else { - init = 0; - } - - /* Try and load any already created modules */ - module_head = SWIG_GetModule(clientdata); - if (!module_head) { - /* This is the first module loaded for this interpreter */ - /* so set the swig module into the interpreter */ - SWIG_SetModule(clientdata, &swig_module); - } else { - /* the interpreter has loaded a SWIG module, but has it loaded this one? */ - iter=module_head; - do { - if (iter==&swig_module) { - /* Our module is already in the list, so there's nothing more to do. */ - return; - } - iter=iter->next; - } while (iter!= module_head); - - /* otherwise we must add our module into the list */ - swig_module.next = module_head->next; - module_head->next = &swig_module; - } - - /* When multiple interpreters are used, a module could have already been initialized in - a different interpreter, but not yet have a pointer in this interpreter. - In this case, we do not want to continue adding types... everything should be - set up already */ - if (init == 0) return; - - /* Now work on filling in swig_module.types */ -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: size %lu\n", (unsigned long)swig_module.size); -#endif - for (i = 0; i < swig_module.size; ++i) { - swig_type_info *type = 0; - swig_type_info *ret; - swig_cast_info *cast; - -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: type %lu %s\n", (unsigned long)i, swig_module.type_initial[i]->name); -#endif - - /* if there is another module already loaded */ - if (swig_module.next != &swig_module) { - type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name); - } - if (type) { - /* Overwrite clientdata field */ -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: found type %s\n", type->name); -#endif - if (swig_module.type_initial[i]->clientdata) { - type->clientdata = swig_module.type_initial[i]->clientdata; -#ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name); -#endif - } + size_t i; + swig_module_info *module_head, *iter; + int init; + + /* check to see if the circular list has been setup, if not, set it up */ + if (swig_module.next == 0) { + /* Initialize the swig_module */ + swig_module.type_initial = swig_type_initial; + swig_module.cast_initial = swig_cast_initial; + swig_module.next = &swig_module; + init = 1; } else { - type = swig_module.type_initial[i]; + init = 0; } - - /* Insert casting types */ - cast = swig_module.cast_initial[i]; - while (cast->type) { - /* Don't need to add information already in the list */ - ret = 0; + + /* Try and load any already created modules */ + module_head = SWIG_GetModule(clientdata); + if (!module_head) { + /* This is the first module loaded for this interpreter */ + /* so set the swig module into the interpreter */ + SWIG_SetModule(clientdata, &swig_module); + } else { + /* the interpreter has loaded a SWIG module, but has it loaded this one? */ + iter = module_head; + do { + if (iter == &swig_module) { + /* Our module is already in the list, so there's nothing more to do. */ + return; + } + iter = iter->next; + } while (iter != module_head); + + /* otherwise we must add our module into the list */ + swig_module.next = module_head->next; + module_head->next = &swig_module; + } + + /* When multiple interpreters are used, a module could have already been initialized in + a different interpreter, but not yet have a pointer in this interpreter. + In this case, we do not want to continue adding types... everything should be + set up already */ + if (init == 0) return; + + /* Now work on filling in swig_module.types */ #ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: look cast %s\n", cast->type->name); + printf("SWIG_InitializeModule: size %lu\n", (unsigned long)swig_module.size); #endif - if (swig_module.next != &swig_module) { - ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name); + for (i = 0; i < swig_module.size; ++i) { + swig_type_info *type = 0; + swig_type_info *ret; + swig_cast_info *cast; + #ifdef SWIGRUNTIME_DEBUG - if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name); + printf("SWIG_InitializeModule: type %lu %s\n", (unsigned long)i, swig_module.type_initial[i]->name); #endif - } - if (ret) { - if (type == swig_module.type_initial[i]) { + + /* if there is another module already loaded */ + if (swig_module.next != &swig_module) { + type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name); + } + if (type) { + /* Overwrite clientdata field */ #ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: skip old type %s\n", ret->name); + printf("SWIG_InitializeModule: found type %s\n", type->name); #endif - cast->type = ret; - ret = 0; + if (swig_module.type_initial[i]->clientdata) { + type->clientdata = swig_module.type_initial[i]->clientdata; +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name); +#endif + } } else { - /* Check for casting already in the list */ - swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type); -#ifdef SWIGRUNTIME_DEBUG - if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name); -#endif - if (!ocast) ret = 0; + type = swig_module.type_initial[i]; } - } - - if (!ret) { + + /* Insert casting types */ + cast = swig_module.cast_initial[i]; + while (cast->type) { + /* Don't need to add information already in the list */ + ret = 0; #ifdef SWIGRUNTIME_DEBUG - printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name); + printf("SWIG_InitializeModule: look cast %s\n", cast->type->name); #endif - if (type->cast) { - type->cast->prev = cast; - cast->next = type->cast; - } - type->cast = cast; - } - cast++; - } - /* Set entry in modules->types array equal to the type */ - swig_module.types[i] = type; - } - swig_module.types[i] = 0; - + if (swig_module.next != &swig_module) { + ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name); #ifdef SWIGRUNTIME_DEBUG - printf("**** SWIG_InitializeModule: Cast List ******\n"); - for (i = 0; i < swig_module.size; ++i) { - int j = 0; - swig_cast_info *cast = swig_module.cast_initial[i]; - printf("SWIG_InitializeModule: type %lu %s\n", (unsigned long)i, swig_module.type_initial[i]->name); - while (cast->type) { - printf("SWIG_InitializeModule: cast type %s\n", cast->type->name); - cast++; - ++j; + if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name); +#endif + } + if (ret) { + if (type == swig_module.type_initial[i]) { +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: skip old type %s\n", ret->name); +#endif + cast->type = ret; + ret = 0; + } else { + /* Check for casting already in the list */ + swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type); +#ifdef SWIGRUNTIME_DEBUG + if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name); +#endif + if (!ocast) ret = 0; + } + } + + if (!ret) { +#ifdef SWIGRUNTIME_DEBUG + printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name); +#endif + if (type->cast) { + type->cast->prev = cast; + cast->next = type->cast; + } + type->cast = cast; + } + cast++; + } + /* Set entry in modules->types array equal to the type */ + swig_module.types[i] = type; } - printf("---- Total casts: %d\n",j); - } - printf("**** SWIG_InitializeModule: Cast List ******\n"); + swig_module.types[i] = 0; + +#ifdef SWIGRUNTIME_DEBUG + printf("**** SWIG_InitializeModule: Cast List ******\n"); + for (i = 0; i < swig_module.size; ++i) { + int j = 0; + swig_cast_info *cast = swig_module.cast_initial[i]; + printf("SWIG_InitializeModule: type %lu %s\n", (unsigned long)i, swig_module.type_initial[i]->name); + while (cast->type) { + printf("SWIG_InitializeModule: cast type %s\n", cast->type->name); + cast++; + ++j; + } + printf("---- Total casts: %d\n", j); + } + printf("**** SWIG_InitializeModule: Cast List ******\n"); #endif } @@ -3757,31 +3712,31 @@ SWIG_InitializeModule(SWIG_INIT_CLIENT_DATA_TYPE clientdata) { */ SWIGRUNTIME void SWIG_PropagateClientData(void) { - size_t i; - swig_cast_info *equiv; - static int init_run = 0; - - if (init_run) return; - init_run = 1; - - for (i = 0; i < swig_module.size; i++) { - if (swig_module.types[i]->clientdata) { - equiv = swig_module.types[i]->cast; - while (equiv) { - if (!equiv->converter) { - if (equiv->type && !equiv->type->clientdata) - SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata); + size_t i; + swig_cast_info *equiv; + static int init_run = 0; + + if (init_run) return; + init_run = 1; + + for (i = 0; i < swig_module.size; i++) { + if (swig_module.types[i]->clientdata) { + equiv = swig_module.types[i]->cast; + while (equiv) { + if (!equiv->converter) { + if (equiv->type && !equiv->type->clientdata) + SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata); + } + equiv = equiv->next; + } } - equiv = equiv->next; - } } - } } #ifdef __cplusplus #if 0 { - /* c-mode */ + /* c-mode */ #endif } #endif @@ -3791,80 +3746,80 @@ SWIG_PropagateClientData(void) { #ifdef __cplusplus extern "C" { #endif - - /* ----------------------------------------------------------------------------- - * constants/methods manipulation - * ----------------------------------------------------------------------------- */ - - /* Install Constants */ - SWIGINTERN void - SWIG_Python_InstallConstants(PyObject *d, swig_const_info constants[]) { + +/* ----------------------------------------------------------------------------- + * constants/methods manipulation + * ----------------------------------------------------------------------------- */ + +/* Install Constants */ +SWIGINTERN void +SWIG_Python_InstallConstants(PyObject *d, swig_const_info constants[]) { PyObject *obj = 0; size_t i; for (i = 0; constants[i].type; ++i) { - switch(constants[i].type) { - case SWIG_PY_POINTER: - obj = SWIG_InternalNewPointerObj(constants[i].pvalue, *(constants[i]).ptype,0); - break; - case SWIG_PY_BINARY: - obj = SWIG_NewPackedObj(constants[i].pvalue, constants[i].lvalue, *(constants[i].ptype)); - break; - default: - obj = 0; - break; - } - if (obj) { - PyDict_SetItemString(d, constants[i].name, obj); - Py_DECREF(obj); - } + switch (constants[i].type) { + case SWIG_PY_POINTER: + obj = SWIG_InternalNewPointerObj(constants[i].pvalue, *(constants[i]).ptype, 0); + break; + case SWIG_PY_BINARY: + obj = SWIG_NewPackedObj(constants[i].pvalue, constants[i].lvalue, *(constants[i].ptype)); + break; + default: + obj = 0; + break; + } + if (obj) { + PyDict_SetItemString(d, constants[i].name, obj); + Py_DECREF(obj); + } } - } - - /* ----------------------------------------------------------------------------- - * Patch %callback methods' docstrings to hold the callback ptrs - * -----------------------------------------------------------------------------*/ - - SWIGINTERN void - SWIG_Python_FixMethods(PyMethodDef *methods, const swig_const_info *const_table, swig_type_info **types, swig_type_info **types_initial) { +} + +/* ----------------------------------------------------------------------------- + * Patch %callback methods' docstrings to hold the callback ptrs + * -----------------------------------------------------------------------------*/ + +SWIGINTERN void +SWIG_Python_FixMethods(PyMethodDef *methods, const swig_const_info *const_table, swig_type_info **types, swig_type_info **types_initial) { size_t i; for (i = 0; methods[i].ml_name; ++i) { - const char *c = methods[i].ml_doc; - if (!c) continue; - c = strstr(c, "swig_ptr: "); - if (c) { - int j; - const swig_const_info *ci = 0; - const char *name = c + 10; - for (j = 0; const_table[j].type; ++j) { - if (strncmp(const_table[j].name, name, - strlen(const_table[j].name)) == 0) { - ci = &(const_table[j]); - break; - } - } - if (ci) { - void *ptr = (ci->type == SWIG_PY_POINTER) ? ci->pvalue : 0; - if (ptr) { - size_t shift = (ci->ptype) - types; - swig_type_info *ty = types_initial[shift]; - size_t ldoc = (c - methods[i].ml_doc); - size_t lptr = strlen(ty->name)+2*sizeof(void*)+2; - char *ndoc = (char*)malloc(ldoc + lptr + 10); - if (ndoc) { - char *buff = ndoc; - memcpy(buff, methods[i].ml_doc, ldoc); - buff += ldoc; - memcpy(buff, "swig_ptr: ", 10); - buff += 10; - SWIG_PackVoidPtr(buff, ptr, ty->name, lptr); - methods[i].ml_doc = ndoc; + const char *c = methods[i].ml_doc; + if (!c) continue; + c = strstr(c, "swig_ptr: "); + if (c) { + int j; + const swig_const_info *ci = 0; + const char *name = c + 10; + for (j = 0; const_table[j].type; ++j) { + if (strncmp(const_table[j].name, name, + strlen(const_table[j].name)) == 0) { + ci = &(const_table[j]); + break; + } + } + if (ci) { + void *ptr = (ci->type == SWIG_PY_POINTER) ? ci->pvalue : 0; + if (ptr) { + size_t shift = (ci->ptype) - types; + swig_type_info *ty = types_initial[shift]; + size_t ldoc = (c - methods[i].ml_doc); + size_t lptr = strlen(ty->name) + 2 * sizeof(void *) +2; + char *ndoc = (char *)malloc(ldoc + lptr + 10); + if (ndoc) { + char *buff = ndoc; + memcpy(buff, methods[i].ml_doc, ldoc); + buff += ldoc; + memcpy(buff, "swig_ptr: ", 10); + buff += 10; + SWIG_PackVoidPtr(buff, ptr, ty->name, lptr); + methods[i].ml_doc = ndoc; + } + } } - } } - } } - } - +} + #ifdef __cplusplus } #endif @@ -3880,137 +3835,137 @@ extern "C" { extern "C" #endif -SWIGEXPORT +SWIGEXPORT #if PY_VERSION_HEX >= 0x03000000 -PyObject* +PyObject * #else void #endif SWIG_init(void) { - PyObject *m, *d, *md, *globals; - + PyObject *m, *d, *md, *globals; + #if PY_VERSION_HEX >= 0x03000000 - static struct PyModuleDef SWIG_module = { - PyModuleDef_HEAD_INIT, - SWIG_name, - NULL, - -1, - SwigMethods, - NULL, - NULL, - NULL, - NULL - }; + static struct PyModuleDef SWIG_module = { + PyModuleDef_HEAD_INIT, + SWIG_name, + NULL, + -1, + SwigMethods, + NULL, + NULL, + NULL, + NULL + }; #endif - + #if defined(SWIGPYTHON_BUILTIN) - static SwigPyClientData SwigPyObject_clientdata = { - 0, 0, 0, 0, 0, 0, 0 - }; - static PyGetSetDef this_getset_def = { - (char *)"this", &SwigPyBuiltin_ThisClosure, NULL, NULL, NULL - }; - static SwigPyGetSet thisown_getset_closure = { - SwigPyObject_own, - SwigPyObject_own - }; - static PyGetSetDef thisown_getset_def = { - (char *)"thisown", SwigPyBuiltin_GetterClosure, SwigPyBuiltin_SetterClosure, NULL, &thisown_getset_closure - }; - PyTypeObject *builtin_pytype; - int builtin_base_count; - swig_type_info *builtin_basetype; - PyObject *tuple; - PyGetSetDescrObject *static_getset; - PyTypeObject *metatype; - PyTypeObject *swigpyobject; - SwigPyClientData *cd; - PyObject *public_interface, *public_symbol; - PyObject *this_descr; - PyObject *thisown_descr; - PyObject *self = 0; - int i; - - (void)builtin_pytype; - (void)builtin_base_count; - (void)builtin_basetype; - (void)tuple; - (void)static_getset; - (void)self; - - /* Metaclass is used to implement static member variables */ - metatype = SwigPyObjectType(); - assert(metatype); + static SwigPyClientData SwigPyObject_clientdata = { + 0, 0, 0, 0, 0, 0, 0 + }; + static PyGetSetDef this_getset_def = { + (char *)"this", &SwigPyBuiltin_ThisClosure, NULL, NULL, NULL + }; + static SwigPyGetSet thisown_getset_closure = { + SwigPyObject_own, + SwigPyObject_own + }; + static PyGetSetDef thisown_getset_def = { + (char *)"thisown", SwigPyBuiltin_GetterClosure, SwigPyBuiltin_SetterClosure, NULL, &thisown_getset_closure + }; + PyTypeObject *builtin_pytype; + int builtin_base_count; + swig_type_info *builtin_basetype; + PyObject *tuple; + PyGetSetDescrObject *static_getset; + PyTypeObject *metatype; + PyTypeObject *swigpyobject; + SwigPyClientData *cd; + PyObject *public_interface, *public_symbol; + PyObject *this_descr; + PyObject *thisown_descr; + PyObject *self = 0; + int i; + + (void)builtin_pytype; + (void)builtin_base_count; + (void)builtin_basetype; + (void)tuple; + (void)static_getset; + (void)self; + + /* Metaclass is used to implement static member variables */ + metatype = SwigPyObjectType(); + assert(metatype); #endif - - (void)globals; - - /* Create singletons now to avoid potential deadlocks with multi-threaded usage after module initialization */ - SWIG_This(); - SWIG_Python_TypeCache(); - SwigPyPacked_type(); + + (void)globals; + + /* Create singletons now to avoid potential deadlocks with multi-threaded usage after module initialization */ + SWIG_This(); + SWIG_Python_TypeCache(); + SwigPyPacked_type(); #ifndef SWIGPYTHON_BUILTIN - SwigPyObject_type(); + SwigPyObject_type(); #endif - - /* Fix SwigMethods to carry the callback ptrs when needed */ - SWIG_Python_FixMethods(SwigMethods, swig_const_table, swig_types, swig_type_initial); - + + /* Fix SwigMethods to carry the callback ptrs when needed */ + SWIG_Python_FixMethods(SwigMethods, swig_const_table, swig_types, swig_type_initial); + #if PY_VERSION_HEX >= 0x03000000 - m = PyModule_Create(&SWIG_module); + m = PyModule_Create(&SWIG_module); #else - m = Py_InitModule(SWIG_name, SwigMethods); + m = Py_InitModule(SWIG_name, SwigMethods); #endif - - md = d = PyModule_GetDict(m); - (void)md; - - SWIG_InitializeModule(0); - + + md = d = PyModule_GetDict(m); + (void)md; + + SWIG_InitializeModule(0); + #ifdef SWIGPYTHON_BUILTIN - swigpyobject = SwigPyObject_TypeOnce(); - - SwigPyObject_stype = SWIG_MangledTypeQuery("_p_SwigPyObject"); - assert(SwigPyObject_stype); - cd = (SwigPyClientData*) SwigPyObject_stype->clientdata; - if (!cd) { - SwigPyObject_stype->clientdata = &SwigPyObject_clientdata; - SwigPyObject_clientdata.pytype = swigpyobject; - } else if (swigpyobject->tp_basicsize != cd->pytype->tp_basicsize) { - PyErr_SetString(PyExc_RuntimeError, "Import error: attempted to load two incompatible swig-generated modules."); + swigpyobject = SwigPyObject_TypeOnce(); + + SwigPyObject_stype = SWIG_MangledTypeQuery("_p_SwigPyObject"); + assert(SwigPyObject_stype); + cd = (SwigPyClientData *) SwigPyObject_stype->clientdata; + if (!cd) { + SwigPyObject_stype->clientdata = &SwigPyObject_clientdata; + SwigPyObject_clientdata.pytype = swigpyobject; + } else if (swigpyobject->tp_basicsize != cd->pytype->tp_basicsize) { + PyErr_SetString(PyExc_RuntimeError, "Import error: attempted to load two incompatible swig-generated modules."); # if PY_VERSION_HEX >= 0x03000000 - return NULL; + return NULL; # else - return; + return; # endif - } - - /* All objects have a 'this' attribute */ - this_descr = PyDescr_NewGetSet(SwigPyObject_type(), &this_getset_def); - (void)this_descr; - - /* All objects have a 'thisown' attribute */ - thisown_descr = PyDescr_NewGetSet(SwigPyObject_type(), &thisown_getset_def); - (void)thisown_descr; - - public_interface = PyList_New(0); - public_symbol = 0; - (void)public_symbol; - - PyDict_SetItemString(md, "__all__", public_interface); - Py_DECREF(public_interface); - for (i = 0; SwigMethods[i].ml_name != NULL; ++i) - SwigPyBuiltin_AddPublicSymbol(public_interface, SwigMethods[i].ml_name); - for (i = 0; swig_const_table[i].name != 0; ++i) - SwigPyBuiltin_AddPublicSymbol(public_interface, swig_const_table[i].name); + } + + /* All objects have a 'this' attribute */ + this_descr = PyDescr_NewGetSet(SwigPyObject_type(), &this_getset_def); + (void)this_descr; + + /* All objects have a 'thisown' attribute */ + thisown_descr = PyDescr_NewGetSet(SwigPyObject_type(), &thisown_getset_def); + (void)thisown_descr; + + public_interface = PyList_New(0); + public_symbol = 0; + (void)public_symbol; + + PyDict_SetItemString(md, "__all__", public_interface); + Py_DECREF(public_interface); + for (i = 0; SwigMethods[i].ml_name != NULL; ++i) + SwigPyBuiltin_AddPublicSymbol(public_interface, SwigMethods[i].ml_name); + for (i = 0; swig_const_table[i].name != 0; ++i) + SwigPyBuiltin_AddPublicSymbol(public_interface, swig_const_table[i].name); #endif - - SWIG_InstallConstants(d,swig_const_table); - + + SWIG_InstallConstants(d, swig_const_table); + #if PY_VERSION_HEX >= 0x03000000 - return m; + return m; #else - return; + return; #endif } diff --git a/client/src/pm3line_vocabulary.h b/client/src/pm3line_vocabulary.h index 737faec98..d2adac558 100644 --- a/client/src/pm3line_vocabulary.h +++ b/client/src/pm3line_vocabulary.h @@ -75,6 +75,15 @@ const static vocabulary_t vocabulary[] = { { 1, "analyse foo" }, { 1, "analyse units" }, { 1, "data help" }, + { 1, "data clear" }, + { 1, "data hide" }, + { 1, "data load" }, + { 1, "data num" }, + { 1, "data plot" }, + { 1, "data print" }, + { 1, "data save" }, + { 1, "data setdebugmode" }, + { 1, "data xor" }, { 1, "data biphaserawdecode" }, { 1, "data detectclock" }, { 1, "data fsktonrz" }, @@ -83,43 +92,32 @@ const static vocabulary_t vocabulary[] = { { 1, "data rawdemod" }, { 1, "data askedgedetect" }, { 1, "data autocorr" }, + { 1, "data convertbitstream" }, + { 1, "data cthreshold" }, { 1, "data dirthreshold" }, { 1, "data decimate" }, { 1, "data envelope" }, - { 1, "data undecimate" }, - { 1, "data hide" }, + { 1, "data grid" }, + { 1, "data getbitstream" }, { 1, "data hpf" }, { 1, "data iir" }, - { 1, "data grid" }, { 1, "data ltrim" }, { 1, "data mtrim" }, { 1, "data norm" }, - { 1, "data plot" }, - { 1, "data cthreshold" }, { 1, "data rtrim" }, { 1, "data setgraphmarkers" }, { 1, "data shiftgraphzero" }, { 1, "data timescale" }, + { 1, "data undecimate" }, { 1, "data zerocrossings" }, - { 1, "data convertbitstream" }, - { 1, "data getbitstream" }, { 1, "data asn1" }, { 1, "data atr" }, - { 1, "data bin2hex" }, { 0, "data bitsamples" }, { 1, "data bmap" }, - { 1, "data clear" }, { 1, "data crypto" }, { 1, "data diff" }, { 0, "data hexsamples" }, - { 1, "data hex2bin" }, - { 1, "data load" }, - { 1, "data num" }, - { 1, "data print" }, { 0, "data samples" }, - { 1, "data save" }, - { 1, "data setdebugmode" }, - { 1, "data xor" }, { 1, "emv help" }, { 1, "emv list" }, { 1, "emv test" }, @@ -558,11 +556,11 @@ const static vocabulary_t vocabulary[] = { { 0, "lf sniff" }, { 0, "lf tune" }, { 1, "lf awid help" }, + { 0, "lf awid brute" }, + { 0, "lf awid clone" }, { 1, "lf awid demod" }, { 0, "lf awid reader" }, - { 0, "lf awid clone" }, { 0, "lf awid sim" }, - { 0, "lf awid brute" }, { 0, "lf awid watch" }, { 1, "lf cotag help" }, { 1, "lf cotag demod" }, @@ -647,16 +645,19 @@ const static vocabulary_t vocabulary[] = { { 1, "lf hitag help" }, { 1, "lf hitag list" }, { 0, "lf hitag info" }, + { 1, "lf hitag selftest" }, { 0, "lf hitag dump" }, { 0, "lf hitag read" }, + { 0, "lf hitag sniff" }, { 1, "lf hitag view" }, { 0, "lf hitag wrbl" }, - { 0, "lf hitag sniff" }, - { 0, "lf hitag cc" }, - { 0, "lf hitag ta" }, { 0, "lf hitag eload" }, { 0, "lf hitag eview" }, { 0, "lf hitag sim" }, + { 0, "lf hitag cc" }, + { 0, "lf hitag chk" }, + { 1, "lf hitag lookup" }, + { 0, "lf hitag ta" }, { 1, "lf idteck help" }, { 1, "lf idteck demod" }, { 0, "lf idteck reader" }, diff --git a/client/src/proxgui.cpp b/client/src/proxgui.cpp index 9d326f636..29eb79d7a 100644 --- a/client/src/proxgui.cpp +++ b/client/src/proxgui.cpp @@ -138,12 +138,12 @@ extern "C" void InitGraphics(int argc, char **argv, char *script_cmds_file, char } void add_temporary_marker(uint32_t position, const char *label) { - if(g_TempMarkerSize == 0) { //Initialize the marker array - g_TempMarkers = (marker_t*)calloc(1, sizeof(marker_t)); + if (g_TempMarkerSize == 0) { //Initialize the marker array + g_TempMarkers = (marker_t *)calloc(1, sizeof(marker_t)); } else { //add more space to the marker array using realloc() - marker_t *temp = (marker_t*)realloc(g_TempMarkers, ((g_TempMarkerSize + 1) * sizeof(marker_t))); + marker_t *temp = (marker_t *)realloc(g_TempMarkers, ((g_TempMarkerSize + 1) * sizeof(marker_t))); - if(temp == NULL) { //Unable to reallocate memory for a new marker + if (temp == NULL) { //Unable to reallocate memory for a new marker PrintAndLogEx(FAILED, "Unable to allocate memory for a new temporary marker!"); free(temp); return; @@ -155,10 +155,10 @@ void add_temporary_marker(uint32_t position, const char *label) { g_TempMarkers[g_TempMarkerSize].pos = position; - char *markerLabel = (char*)calloc(1, strlen(label) + 1); + char *markerLabel = (char *)calloc(1, strlen(label) + 1); strcpy(markerLabel, label); - if(strlen(markerLabel) > 30) { + if (strlen(markerLabel) > 30) { PrintAndLogEx(WARNING, "Label for temporary marker too long! Trunicating..."); markerLabel[30] = '\0'; } @@ -171,7 +171,7 @@ void add_temporary_marker(uint32_t position, const char *label) { } void remove_temporary_markers(void) { - if(g_TempMarkerSize == 0) return; + if (g_TempMarkerSize == 0) return; memset(g_TempMarkers, 0x00, (g_TempMarkerSize * sizeof(marker_t))); free(g_TempMarkers); diff --git a/client/src/proxguiqt.cpp b/client/src/proxguiqt.cpp index 3d7b23fc4..3c2b5ae92 100644 --- a/client/src/proxguiqt.cpp +++ b/client/src/proxguiqt.cpp @@ -598,7 +598,7 @@ void Plot::setMaxAndStart(int *buffer, size_t len, QRect plotRect) { } void Plot::appendMax(int *buffer, size_t len, QRect plotRect) { - if(len == 0) { + if (len == 0) { return; } @@ -750,12 +750,12 @@ void Plot::PlotGraph(int *buffer, size_t len, QRect plotRect, QRect annotationRe painter->drawPath(penPath); char str[200]; snprintf(str, sizeof(str), "max=%d min=%d mean=%" PRId64 " n=%u/%zu", - vMax, - vMin, - vMean, - g_GraphStop - g_GraphStart, - len - ); + vMax, + vMin, + vMean, + g_GraphStop - g_GraphStart, + len + ); painter->drawText(20, annotationRect.bottom() - (48 - (12 * graphNum)), str); } @@ -781,37 +781,37 @@ void Plot::drawAnnotations(QRect annotationRect, QPainter *painter) { //Print the Graph Information char graphText[] = "@%u..%u dt=%i %s zoom=%2.3f"; - length = ((sizeof(graphText))+(sizeof(uint32_t)*3)+sizeof(scalestr)+sizeof(float_t)); + length = ((sizeof(graphText)) + (sizeof(uint32_t) * 3) + sizeof(scalestr) + sizeof(float_t)); - annotation = (char*)calloc(1, length); + annotation = (char *)calloc(1, length); snprintf(annotation, length, graphText, - g_GraphStart, - g_GraphStop, - g_MarkerB.pos - g_MarkerA.pos, - scalestr, - g_GraphPixelsPerPoint - ); + g_GraphStart, + g_GraphStop, + g_MarkerB.pos - g_MarkerA.pos, + scalestr, + g_GraphPixelsPerPoint + ); painter->setPen(GREEN); painter->drawText(82, annotationRect.bottom() - 62, annotation); //Print Grid Information if the grid is enabled - if(g_PlotGridX > 0) { + if (g_PlotGridX > 0) { free(annotation); const char *gridLocked = (g_GridLocked ? "Locked" : "Unlocked"); char gridText[] = "GridX=%lf GridY=%lf (%s) GridXoffset=%lf"; - length = (sizeof(gridText) + (sizeof(double)*3) + sizeof(gridLocked)); + length = (sizeof(gridText) + (sizeof(double) * 3) + sizeof(gridLocked)); - annotation = (char*)calloc(1, length); + annotation = (char *)calloc(1, length); snprintf(annotation, length, gridText, - g_DefaultGridX, - g_DefaultGridY, - gridLocked, - g_GridOffset - ); + g_DefaultGridX, + g_DefaultGridY, + gridLocked, + g_GridOffset + ); painter->setPen(WHITE); painter->drawText(800, annotationRect.bottom() - 62, annotation); @@ -822,21 +822,21 @@ void Plot::drawAnnotations(QRect annotationRect, QPainter *painter) { uint32_t pos = 0, loc = 375; painter->setPen(WHITE); - if(g_MarkerA.pos > 0) { + if (g_MarkerA.pos > 0) { free(annotation); - length = (sizeof(markerText) + (sizeof(uint32_t)*3) + sizeof(" ") + 1); + length = (sizeof(markerText) + (sizeof(uint32_t) * 3) + sizeof(" ") + 1); pos = g_MarkerA.pos; bool flag = false; size_t value; - annotation = (char*)calloc(1, length); - char *textA = (char*)calloc(1, length); + annotation = (char *)calloc(1, length); + char *textA = (char *)calloc(1, length); strcat(textA, markerText); strcat(textA, " (%s%u)"); - if(g_GraphBuffer[pos] <= g_OperationBuffer[pos]) { + if (g_GraphBuffer[pos] <= g_OperationBuffer[pos]) { flag = true; value = (g_OperationBuffer[pos] - g_GraphBuffer[pos]); } else { @@ -844,65 +844,65 @@ void Plot::drawAnnotations(QRect annotationRect, QPainter *painter) { } snprintf(annotation, length, textA, - "A", - pos, - g_GraphBuffer[pos], - flag ? "+" : "-", - value - ); + "A", + pos, + g_GraphBuffer[pos], + flag ? "+" : "-", + value + ); painter->drawText(loc, annotationRect.bottom() - 48, annotation); free(textA); } - if(g_MarkerB.pos > 0) { + if (g_MarkerB.pos > 0) { free(annotation); - length = ((sizeof(markerText))+(sizeof(uint32_t)*2)+1); + length = ((sizeof(markerText)) + (sizeof(uint32_t) * 2) + 1); pos = g_MarkerB.pos; - annotation = (char*)calloc(1, length); + annotation = (char *)calloc(1, length); snprintf(annotation, length, markerText, - "B", - pos, - g_GraphBuffer[pos] - ); + "B", + pos, + g_GraphBuffer[pos] + ); painter->drawText(loc, annotationRect.bottom() - 36, annotation); } - if(g_MarkerC.pos > 0) { + if (g_MarkerC.pos > 0) { free(annotation); - length = ((sizeof(markerText))+(sizeof(uint32_t)*2)+1); + length = ((sizeof(markerText)) + (sizeof(uint32_t) * 2) + 1); pos = g_MarkerC.pos; - annotation = (char*)calloc(1, length); + annotation = (char *)calloc(1, length); snprintf(annotation, length, markerText, - "C", - pos, - g_GraphBuffer[pos] - ); + "C", + pos, + g_GraphBuffer[pos] + ); painter->drawText(loc, annotationRect.bottom() - 24, annotation); } - if(g_MarkerD.pos > 0) { + if (g_MarkerD.pos > 0) { free(annotation); - length = ((sizeof(markerText))+(sizeof(uint32_t)*2)+1); + length = ((sizeof(markerText)) + (sizeof(uint32_t) * 2) + 1); pos = g_MarkerD.pos; - annotation = (char*)calloc(1, length); + annotation = (char *)calloc(1, length); snprintf(annotation, length, markerText, - "D", - pos, - g_GraphBuffer[pos] - ); + "D", + pos, + g_GraphBuffer[pos] + ); painter->drawText(loc, annotationRect.bottom() - 12, annotation); } @@ -951,7 +951,7 @@ void Plot::plotGridLines(QPainter *painter, QRect r) { } void Plot::plotOperations(int *buffer, size_t len, QPainter *painter, QRect plotRect) { - if(len == 0) { + if (len == 0) { return; } @@ -973,10 +973,10 @@ void Plot::plotOperations(int *buffer, size_t len, QPainter *painter, QRect plot y = yCoordOf(current, plotRect, gs_absVMax); //We only want to graph changes between the Graph Buffer and the Operation Buffer - if(current == g_GraphBuffer[pos]) { + if (current == g_GraphBuffer[pos]) { //If this point is the same, but the last point is different, we want to plot that line //as well - if((pos == 0) || (prev == g_GraphBuffer[pos - 1])) { + if ((pos == 0) || (prev == g_GraphBuffer[pos - 1])) { continue; } } else { @@ -1045,8 +1045,8 @@ void Plot::paintEvent(QPaintEvent *event) { // End graph drawing //Draw the markers - if(g_TempMarkerSize > 0) { - for(int i = 0; i < g_TempMarkerSize; i++) { + if (g_TempMarkerSize > 0) { + for (int i = 0; i < g_TempMarkerSize; i++) { draw_marker(g_TempMarkers[i], plotRect, GRAY100, &painter); } } @@ -1074,15 +1074,15 @@ void Plot::draw_marker(marker_t marker, QRect plotRect, QColor color, QPainter * painter->setPen(color); //If the marker is outside the buffer length, reset - if(marker.pos > g_GraphTraceLen) { + if (marker.pos > g_GraphTraceLen) { marker.pos = 0; } //Make sure the marker is inside the current plot view to render - if(marker.pos > g_GraphStart && xCoordOf(marker.pos, plotRect) < plotRect.right()) { + if (marker.pos > g_GraphStart && xCoordOf(marker.pos, plotRect) < plotRect.right()) { painter->drawLine(xCoordOf(marker.pos, plotRect), plotRect.top(), xCoordOf(marker.pos, plotRect), plotRect.bottom()); - if(strlen(marker.label) > 0) { + if (strlen(marker.label) > 0) { painter->drawText(xCoordOf(marker.pos, plotRect) + 1, plotRect.top() + 12, marker.label); } } @@ -1295,7 +1295,7 @@ void Plot::keyPressEvent(QKeyEvent *event) { offset = 1; } else { offset = int(ZOOM_LIMIT / g_GraphPixelsPerPoint); - } + } } switch (event->key()) { @@ -1393,9 +1393,9 @@ void Plot::keyPressEvent(QKeyEvent *event) { PrintAndLogEx(NORMAL, " %-*s%s", 25 + 9 + 9, _RED_("[ ") "/" _RED_(" ]"), "Move yellow marker left/right by 1 sample"); PrintAndLogEx(NORMAL, " %-*s%s", 25 + 9 + 9, _RED_("{ ") "/" _RED_(" }"), "Move pink marker left/right by 1 sample"); PrintAndLogEx(NORMAL, " %-*s%s", 25 + 9, " + " _RED_("Ctrl"), "... by 5 samples"); - PrintAndLogEx(NORMAL, " %-*s%s", 25 + 9 +9, _RED_("= ") "/" _RED_(" -"), "Add/Subtract to the plot point (Operation Buffer) over the yellow marker by 1"); + PrintAndLogEx(NORMAL, " %-*s%s", 25 + 9 + 9, _RED_("= ") "/" _RED_(" -"), "Add/Subtract to the plot point (Operation Buffer) over the yellow marker by 1"); PrintAndLogEx(NORMAL, " %-*s%s", 25 + 9, " + " _RED_("Ctrl"), "... by 5"); - PrintAndLogEx(NORMAL, " %-*s%s", 25 + 9 +9, _RED_("+ ") "/" _RED_(" _"), "Add/Subtract to the plot point (Graph Buffer) over the yellow marker by 1"); + PrintAndLogEx(NORMAL, " %-*s%s", 25 + 9 + 9, _RED_("+ ") "/" _RED_(" _"), "Add/Subtract to the plot point (Graph Buffer) over the yellow marker by 1"); PrintAndLogEx(NORMAL, " %-*s%s", 25 + 9, " + " _RED_("Ctrl"), "... by 5"); PrintAndLogEx(NORMAL, " %-*s%s", 25 + 9, _RED_("h"), "Show this help"); PrintAndLogEx(NORMAL, " %-*s%s", 25 + 9, _RED_("q"), "Close plot window"); @@ -1441,9 +1441,9 @@ void Plot::keyPressEvent(QKeyEvent *event) { if (g_GraphStart > startMax) g_GraphStart = startMax; break; - + case Qt::Key_Equal: - if(event->modifiers() & Qt::ControlModifier) { + if (event->modifiers() & Qt::ControlModifier) { g_OperationBuffer[g_MarkerA.pos] += 5; } else { g_OperationBuffer[g_MarkerA.pos] += 1; @@ -1451,9 +1451,9 @@ void Plot::keyPressEvent(QKeyEvent *event) { RepaintGraphWindow(); break; - + case Qt::Key_Minus: - if(event->modifiers() & Qt::ControlModifier) { + if (event->modifiers() & Qt::ControlModifier) { g_OperationBuffer[g_MarkerA.pos] -= 5; } else { g_OperationBuffer[g_MarkerA.pos] -= 1; @@ -1463,7 +1463,7 @@ void Plot::keyPressEvent(QKeyEvent *event) { break; case Qt::Key_Plus: - if(event->modifiers() & Qt::ControlModifier) { + if (event->modifiers() & Qt::ControlModifier) { g_GraphBuffer[g_MarkerA.pos] += 5; } else { g_GraphBuffer[g_MarkerA.pos] += 1; @@ -1471,9 +1471,9 @@ void Plot::keyPressEvent(QKeyEvent *event) { RepaintGraphWindow(); break; - + case Qt::Key_Underscore: - if(event->modifiers() & Qt::ControlModifier) { + if (event->modifiers() & Qt::ControlModifier) { g_GraphBuffer[g_MarkerA.pos] -= 5; } else { g_GraphBuffer[g_MarkerA.pos] -= 1; @@ -1483,77 +1483,77 @@ void Plot::keyPressEvent(QKeyEvent *event) { break; case Qt::Key_BracketLeft: { - if(event->modifiers() & Qt::ControlModifier) { + if (event->modifiers() & Qt::ControlModifier) { g_MarkerA.pos -= 5; } else { g_MarkerA.pos -= 1; } - if((g_MarkerA.pos >= g_GraphStop) || (g_MarkerA.pos <= g_GraphStart)) { + if ((g_MarkerA.pos >= g_GraphStop) || (g_MarkerA.pos <= g_GraphStart)) { uint32_t halfway = PageWidth / 2; - if((g_MarkerA.pos - halfway) > g_GraphTraceLen) { + if ((g_MarkerA.pos - halfway) > g_GraphTraceLen) { g_GraphStart = 0; } else { g_GraphStart = g_MarkerA.pos - halfway; } } - if(g_MarkerA.pos < g_GraphStart) { + if (g_MarkerA.pos < g_GraphStart) { g_MarkerA.pos = g_GraphStart; } RepaintGraphWindow(); break; } - + case Qt::Key_BracketRight: { - if(event->modifiers() & Qt::ControlModifier) { + if (event->modifiers() & Qt::ControlModifier) { g_MarkerA.pos += 5; } else { g_MarkerA.pos += 1; } - if((g_MarkerA.pos >= g_GraphStop) || (g_MarkerA.pos <= g_GraphStart)) { + if ((g_MarkerA.pos >= g_GraphStop) || (g_MarkerA.pos <= g_GraphStart)) { uint32_t halfway = PageWidth / 2; - if((g_MarkerA.pos + halfway) >= g_GraphTraceLen) { + if ((g_MarkerA.pos + halfway) >= g_GraphTraceLen) { g_GraphStart = g_GraphTraceLen - halfway; } else { g_GraphStart = g_MarkerA.pos - halfway; } } - if(g_MarkerA.pos >= g_GraphTraceLen) { + if (g_MarkerA.pos >= g_GraphTraceLen) { g_MarkerA.pos = g_GraphTraceLen; } RepaintGraphWindow(); break; } - + case Qt::Key_BraceLeft: - if(event->modifiers() & Qt::ControlModifier) { + if (event->modifiers() & Qt::ControlModifier) { g_MarkerB.pos -= 5; } else { g_MarkerB.pos -= 1; } - if(g_MarkerB.pos < g_GraphStart) { + if (g_MarkerB.pos < g_GraphStart) { g_MarkerB.pos = g_GraphStart; } - + RepaintGraphWindow(); break; - + case Qt::Key_BraceRight: - if(event->modifiers() & Qt::ControlModifier) { + if (event->modifiers() & Qt::ControlModifier) { g_MarkerB.pos += 5; } else { g_MarkerB.pos += 1; } - if(g_MarkerB.pos >= g_GraphTraceLen) { + if (g_MarkerB.pos >= g_GraphTraceLen) { g_MarkerB.pos = g_GraphTraceLen; } diff --git a/common/hitag2/hitag2_crypto.c b/common/hitag2/hitag2_crypto.c index 8fd596fa8..9e9499426 100644 --- a/common/hitag2/hitag2_crypto.c +++ b/common/hitag2/hitag2_crypto.c @@ -16,10 +16,15 @@ // Hitag2 Crypto //----------------------------------------------------------------------------- #include "hitag2_crypto.h" - +#include #include "util.h" #include "string.h" #include "commonutil.h" +#include "pm3_cmd.h" + +#ifndef ON_DEVICE +#include "ui.h" +#endif /* Following is a modified version of cryptolib.com/ciphers/hitag2/ */ // Software optimized 48-bit Philips/NXP Mifare Hitag2 PCF7936/46/47/52 stream cipher algorithm by I.C. Wiener 2006-2007. @@ -27,39 +32,337 @@ // No warranties or guarantees of any kind. // This code is released into the public domain by its author. + // Single bit Hitag2 functions: #ifndef i4 -#define i4(x,a,b,c,d) ((uint32_t)((((x)>>(a))&1)+(((x)>>(b))&1)*2+(((x)>>(c))&1)*4+(((x)>>(d))&1)*8)) +#define i4(x,a,b,c,d) ((uint32_t)((((x)>>(a))&1)+(((x)>>(b))&1)*2+(((x)>>(c))&1)*4+(((x)>>(d))&1)*8)) #endif static const uint32_t ht2_f4a = 0x2C79; // 0010 1100 0111 1001 static const uint32_t ht2_f4b = 0x6671; // 0110 0110 0111 0001 static const uint32_t ht2_f5c = 0x7907287B; // 0111 1001 0000 0111 0010 1000 0111 1011 -static uint32_t ht2_f20(const uint64_t x) { - uint32_t i5; +static uint32_t ht2_f20(const uint64_t state) { - i5 = ((ht2_f4a >> i4(x, 1, 2, 4, 5)) & 1) * 1 - + ((ht2_f4b >> i4(x, 7, 11, 13, 14)) & 1) * 2 - + ((ht2_f4b >> i4(x, 16, 20, 22, 25)) & 1) * 4 - + ((ht2_f4b >> i4(x, 27, 28, 30, 32)) & 1) * 8 - + ((ht2_f4a >> i4(x, 33, 42, 43, 45)) & 1) * 16; + uint32_t i5 = ((ht2_f4a >> i4(state, 1, 2, 4, 5)) & 1) * 1 + + ((ht2_f4b >> i4(state, 7, 11, 13, 14)) & 1) * 2 + + ((ht2_f4b >> i4(state, 16, 20, 22, 25)) & 1) * 4 + + ((ht2_f4b >> i4(state, 27, 28, 30, 32)) & 1) * 8 + + ((ht2_f4a >> i4(state, 33, 42, 43, 45)) & 1) * 16; return (ht2_f5c >> i5) & 1; } -uint64_t ht2_hitag2_init(const uint64_t key, const uint32_t serial, const uint32_t IV) { - uint32_t i; +// return a single bit from a value +static int ht2_bitn(uint64_t x, int bit) { + const uint64_t bitmask = (uint64_t)(1) << bit; + return (x & bitmask) ? 1 : 0; +} + +// the sub-function R that rollback depends upon +int ht2_fnR(uint64_t state) { + // renumbered bits because my state is 0-47, not 1-48 + return ( + ht2_bitn(state, 1) ^ ht2_bitn(state, 2) ^ ht2_bitn(state, 5) ^ + ht2_bitn(state, 6) ^ ht2_bitn(state, 7) ^ ht2_bitn(state, 15) ^ + ht2_bitn(state, 21) ^ ht2_bitn(state, 22) ^ ht2_bitn(state, 25) ^ + ht2_bitn(state, 29) ^ ht2_bitn(state, 40) ^ ht2_bitn(state, 41) ^ + ht2_bitn(state, 42) ^ ht2_bitn(state, 45) ^ ht2_bitn(state, 46) ^ + ht2_bitn(state, 47) + ); +} + +/* +static void ht2_rollback(hitag_state_t *hstate, unsigned int steps) { + for (int i = 0; i < steps; i++) { + hstate->shiftreg = ((hstate->shiftreg << 1) & 0xffffffffffff) | ht2_fnR(hstate->shiftreg); + } +} +*/ +// the rollback function that lets us go backwards in time +void ht2_rollback(hitag_state_t *hstate, uint32_t steps) { + for (uint32_t i = 0; i < steps; i++) { + hstate->shiftreg = ((hstate->shiftreg << 1) & 0xffffffffffff) | ht2_fnR(hstate->shiftreg); + hstate->lfsr = LFSR_INV(hstate->lfsr); + } +} + +// the three filter sub-functions that feed fnf +#define ht2_fa(x) ht2_bitn(0x2C79, (x)) +#define ht2_fb(x) ht2_bitn(0x6671, (x)) +#define ht2_fc(x) ht2_bitn(0x7907287B, (x)) + +// the filter function that generates a bit of output from the prng state +int ht2_fnf(uint64_t state) { + + uint32_t x1 = (ht2_bitn(state, 2) << 0) | (ht2_bitn(state, 3) << 1) | (ht2_bitn(state, 5) << 2) | (ht2_bitn(state, 6) << 3); + uint32_t x2 = (ht2_bitn(state, 8) << 0) | (ht2_bitn(state, 12) << 1) | (ht2_bitn(state, 14) << 2) | (ht2_bitn(state, 15) << 3); + uint32_t x3 = (ht2_bitn(state, 17) << 0) | (ht2_bitn(state, 21) << 1) | (ht2_bitn(state, 23) << 2) | (ht2_bitn(state, 26) << 3); + uint32_t x4 = (ht2_bitn(state, 28) << 0) | (ht2_bitn(state, 29) << 1) | (ht2_bitn(state, 31) << 2) | (ht2_bitn(state, 33) << 3); + uint32_t x5 = (ht2_bitn(state, 34) << 0) | (ht2_bitn(state, 43) << 1) | (ht2_bitn(state, 44) << 2) | (ht2_bitn(state, 46) << 3); + + uint32_t x6 = (ht2_fa(x1) << 0) | (ht2_fb(x2) << 1) | (ht2_fb(x3) << 2) | (ht2_fb(x4) << 3) | (ht2_fa(x5) << 4); + return ht2_fc(x6); +} + +// builds the lfsr for the prng (quick calcs for hitag2_nstep()) +/* +static void ht2_buildlfsr(hitag_state_t *hstate) { + if (hstate == NULL) { + return; + } + + uint64_t state = hstate->shiftreg; + uint64_t temp = state ^ (state >> 1); + hstate->lfsr = state ^ (state >> 6) ^ (state >> 16) + ^ (state >> 26) ^ (state >> 30) ^ (state >> 41) + ^ (temp >> 2) ^ (temp >> 7) ^ (temp >> 22) + ^ (temp >> 42) ^ (temp >> 46); +} +*/ +#ifndef ON_DEVICE +#include +#endif + +uint64_t ht2_recoverkey(hitag_state_t *hstate, uint32_t uid, uint32_t nRenc) { + +// hstate->shiftreg = (uint64_t)(((hstate->shiftreg << 1) & 0xffffffffffff) | (uint64_t)ht2_fnR(hstate->shiftreg)); +// hstate->shiftreg = (uint64_t)(((hstate->shiftreg << 1) & 0xffffffffffff) | (uint64_t)ht2_fnR(hstate->shiftreg)); + +#ifndef ON_DEVICE + PrintAndLogEx(INFO, "shiftreg.... %" PRIx64, hstate->shiftreg); +#endif + + // key lower 16 bits are lower 16 bits of prng state + uint64_t key = hstate->shiftreg & 0xffff; + uint32_t nRxork = (hstate->shiftreg >> 16) & 0xffffffff; + + // rollback and extract bits b + uint32_t b = 0; + for (uint8_t i = 0; i < 32; i++) { + hstate->shiftreg = ((hstate->shiftreg) << 1) | ((uid >> (31 - i)) & 0x1); + b = (b << 1) | (unsigned int) ht2_fnf(hstate->shiftreg); + } + + uint32_t nR = nRenc ^ b; + uint64_t keyupper = nRxork ^ nR; + key = key | (keyupper << 16); + +#ifndef ON_DEVICE + + + + PrintAndLogEx(INFO, "b..... %08" PRIx32 " %08" PRIx32 " %012" PRIx64, b, nRenc, hstate->shiftreg); + PrintAndLogEx(INFO, "key... %012" PRIx64 " %012" PRIx64 "\n", key, REV64(key)); +#endif + return key; +} + +/* + * Parameters: + * Hitag_State* pstate - output, internal state after initialisation + * uint64_t sharedkey - 48 bit key shared between reader & tag + * uint32_t serialnum - 32 bit tag serial number + * uint32_t iv - 32 bit random IV from reader, part of tag authentication + */ +void ht2_hitag2_init_ex(hitag_state_t *hstate, uint64_t sharedkey, uint32_t serialnum, uint32_t iv) { + // init state, from serial number and lowest 16 bits of shared key + uint64_t state = ((sharedkey & 0xFFFF) << 32) | serialnum; + + // mix the initialisation vector and highest 32 bits of the shared key + iv ^= (uint32_t)(sharedkey >> 16); + + // move 16 bits from (IV xor Shared Key) to top of uint64_t state + // these will be XORed in turn with output of the crypto function + state |= (uint64_t) iv << 48; + iv >>= 16; + + // unrolled loop is faster on PIC32 (MIPS), do 32 times + // shift register, then calc new bit + state >>= 1; + state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46; + state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46; + state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46; + state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46; + state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46; + state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46; + state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46; + state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46; + + state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46; + state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46; + state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46; + state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46; + state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46; + state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46; + state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46; + state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46; + + // highest 16 bits of IV XOR Shared Key + state |= (uint64_t) iv << 47; + + state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46; + state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46; + state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46; + state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46; + state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46; + state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46; + state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46; + state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46; + + state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46; + state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46; + state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46; + state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46; + state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46; + state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46; + state = (state >> 1) ^ (uint64_t) ht2_f20(state) << 46; + state ^= (uint64_t) ht2_f20(state) << 47; + + // LSFR + + hstate->shiftreg = state; + /* naive version for reference, LFSR has 16 taps + pstate->lfsr = state ^ (state >> 2) ^ (state >> 3) ^ (state >> 6) + ^ (state >> 7) ^ (state >> 8) ^ (state >> 16) ^ (state >> 22) + ^ (state >> 23) ^ (state >> 26) ^ (state >> 30) ^ (state >> 41) + ^ (state >> 42) ^ (state >> 43) ^ (state >> 46) ^ (state >> 47); + */ + { + // optimise with one 64-bit intermediate + uint64_t temp = state ^ (state >> 1); + hstate->lfsr = state ^ (state >> 6) ^ (state >> 16) + ^ (state >> 26) ^ (state >> 30) ^ (state >> 41) + ^ (temp >> 2) ^ (temp >> 7) ^ (temp >> 22) + ^ (temp >> 42) ^ (temp >> 46); + } +} + +/* + * Return up to 32 crypto bits. + * Last bit is in least significant bit, earlier bits are shifted left. + * Note that the Hitag transmission protocol is least significant bit, + * so we may want to change this, or add a function, that returns the + * crypto output bits in the other order. + * + * Parameters: + * Hitag_State* pstate - in/out, internal cipher state after initialisation + * uint32_t steps - number of bits requested, (capped at 32) + */ +uint32_t ht2_hitag2_nstep(hitag_state_t *hstate, uint32_t steps) { + uint64_t state = hstate->shiftreg; + uint32_t result = 0; + uint64_t lfsr = hstate->lfsr; + + if (steps == 0) { + return 0; + } + + do { + // update shift registers + if (lfsr & 1) { + state = (state >> 1) | 0x800000000000; + lfsr = (lfsr >> 1) ^ 0xB38083220073; + // accumulate next bit of crypto + result = (result << 1) | ht2_f20(state); + } else { + state >>= 1; + lfsr >>= 1; + result = (result << 1) | ht2_f20(state); + } + } while (--steps); + + hstate->shiftreg = state; + hstate->lfsr = lfsr; + return result; +} + +uint64_t ht2_hitag2_init(const uint64_t key, const uint32_t serial, const uint32_t iv) { + uint64_t x = ((key & 0xFFFF) << 32) + serial; - for (i = 0; i < 32; i++) { + for (uint32_t i = 0; i < 32; i++) { x >>= 1; - x += (uint64_t)(ht2_f20(x) ^ (((IV >> i) ^ (key >> (i + 16))) & 1)) << 47; + x += (uint64_t)(ht2_f20(x) ^ (((iv >> i) ^ (key >> (i + 16))) & 1)) << 47; } return x; } -uint64_t ht2_hitag2_round(uint64_t *state) { +int ht2_try_state(uint64_t s, uint32_t uid, uint32_t aR2, uint32_t nR1, uint32_t nR2, uint64_t *key) { + + hitag_state_t hstate; + hstate.shiftreg = s; + hstate.lfsr = 0; + + hstate.shiftreg = (uint64_t)(((hstate.shiftreg << 1) & 0xffffffffffff) | (uint64_t)ht2_fnR(hstate.shiftreg)); + hstate.shiftreg = (uint64_t)(((hstate.shiftreg << 1) & 0xffffffffffff) | (uint64_t)ht2_fnR(hstate.shiftreg)); + +#ifndef ON_DEVICE + hitag_state_t hs2; + hs2.shiftreg = s; + hs2.lfsr = 0; + ht2_rollback(&hs2, 2); + + PrintAndLogEx(INFO, "hstate shiftreg.... %" PRIx64 " lfsr... %" PRIx64, hstate.shiftreg, hstate.lfsr); + PrintAndLogEx(INFO, "hstate shiftreg.... %" PRIx64 " lfsr... %" PRIx64, hs2.shiftreg, hs2.lfsr); +#endif + + // recover key + uint64_t keyrev = hstate.shiftreg & 0xffff; + uint64_t nR1xk = (hstate.shiftreg >> 16) & 0xffffffff; + +#ifndef ON_DEVICE + PrintAndLogEx(INFO, "keyrev...... %012" PRIx64 " nR1xk... %08" PRIx64, keyrev, nR1xk); +#endif + + uint32_t b = 0; + for (uint8_t i = 0; i < 32; i++) { + hstate.shiftreg = ((hstate.shiftreg) << 1) | ((uid >> (31 - i)) & 0x1); + b = (b << 1) | (unsigned int) ht2_fnf(hstate.shiftreg); + } + +#ifndef ON_DEVICE + PrintAndLogEx(INFO, "b..... %08" PRIx32 " %08" PRIx32 " %012" PRIx64, b, nR1, hstate.shiftreg); +#endif + + keyrev |= (nR1xk ^ nR1 ^ b) << 16; + +#ifndef ON_DEVICE + PrintAndLogEx(INFO, "key... %012" PRIx64 " %012" PRIx64, keyrev, REV64(keyrev)); +#endif + + // test key + ht2_hitag2_init_ex(&hstate, keyrev, uid, nR2); + + if ((aR2 ^ ht2_hitag2_nstep(&hstate, 32)) == 0xFFFFFFFF) { + *key = REV64(keyrev); + return PM3_SUCCESS; + } + return PM3_ESOFT; +} + + +// "MIKRON" = O N M I K R +// Key = 4F 4E 4D 49 4B 52 - Secret 48-bit key +// Serial = 49 43 57 69 - Serial number of the tag, transmitted in clear +// Random = 65 6E 45 72 - Random IV, transmitted in clear +//~28~DC~80~31 = D7 23 7F CE - Authenticator value = inverted first 4 bytes of the keystream + +// The code below must print out "D7 23 7F CE 8C D0 37 A9 57 49 C1 E6 48 00 8A B6". +// The inverse of the first 4 bytes is sent to the tag to authenticate. +// The rest is encrypted by XORing it with the subsequent keystream. + +/* + * Return 8 crypto bits. + * Last bit is in least significant bit, earlier bits are shifted left. + * Note that the Hitag transmission protocol is least significant bit, + * so we may want to change this, or add a function, that returns the + * crypto output bits in the other order. + * + * Parameters: + * uint64_t *state - in/out, internal cipher state after initialisation + */ +uint64_t ht2_hitag2_bit(uint64_t *state) { uint64_t x = *state; x = (x >> 1) + @@ -72,21 +375,25 @@ uint64_t ht2_hitag2_round(uint64_t *state) { return ht2_f20(x); } -// "MIKRON" = O N M I K R -// Key = 4F 4E 4D 49 4B 52 - Secret 48-bit key -// Serial = 49 43 57 69 - Serial number of the tag, transmitted in clear -// Random = 65 6E 45 72 - Random IV, transmitted in clear -//~28~DC~80~31 = D7 23 7F CE - Authenticator value = inverted first 4 bytes of the keystream +// Take a state and create one byte (8bits) of crypto +uint32_t ht2_hitag2_byte(uint64_t *state) { + uint32_t c = 0; + c += (uint32_t) ht2_hitag2_bit(state) << 7; // 7 + c += (uint32_t) ht2_hitag2_bit(state) << 6; // 6 + c += (uint32_t) ht2_hitag2_bit(state) << 5; // 5 + c += (uint32_t) ht2_hitag2_bit(state) << 4; + c += (uint32_t) ht2_hitag2_bit(state) << 3; + c += (uint32_t) ht2_hitag2_bit(state) << 2; + c += (uint32_t) ht2_hitag2_bit(state) << 1; + c += (uint32_t) ht2_hitag2_bit(state) << 0; + return c; +} -// The code below must print out "D7 23 7F CE 8C D0 37 A9 57 49 C1 E6 48 00 8A B6". -// The inverse of the first 4 bytes is sent to the tag to authenticate. -// The rest is encrypted by XORing it with the subsequent keystream. - -uint32_t ht2_hitag2_byte(uint64_t *x) { - uint32_t i, c; - for (i = 0, c = 0; i < 8; i++) { - c += (uint32_t) ht2_hitag2_round(x) << (i ^ 7); - } +uint32_t ht2_hitag2_word(uint64_t *state, uint32_t steps) { + uint32_t c = 0; + do { + c += (uint32_t) ht2_hitag2_bit(state) << (steps - 1); + } while (--steps); return c; } @@ -108,19 +415,23 @@ void ht2_hitag2_cipher_reset(hitag2_t *tag, const uint8_t *iv) { tag->cs = ht2_hitag2_init(REV64(key), REV32(uid), REV32(iv_)); } -int ht2_hitag2_cipher_authenticate(uint64_t *cs, const uint8_t *authenticator_is) { +int ht2_hitag2_cipher_authenticate(uint64_t *state, const uint8_t *authenticator_is) { uint8_t authenticator_should[4]; - authenticator_should[0] = ~ht2_hitag2_byte(cs); - authenticator_should[1] = ~ht2_hitag2_byte(cs); - authenticator_should[2] = ~ht2_hitag2_byte(cs); - authenticator_should[3] = ~ht2_hitag2_byte(cs); + authenticator_should[0] = ~ht2_hitag2_byte(state); + authenticator_should[1] = ~ht2_hitag2_byte(state); + authenticator_should[2] = ~ht2_hitag2_byte(state); + authenticator_should[3] = ~ht2_hitag2_byte(state); return (memcmp(authenticator_should, authenticator_is, 4) == 0); } -int ht2_hitag2_cipher_transcrypt(uint64_t *cs, uint8_t *data, uint16_t bytes, uint16_t bits) { +void ht2_hitag2_cipher_transcrypt(uint64_t *state, uint8_t *data, uint16_t bytes, uint16_t bits) { int i; - for (i = 0; i < bytes; i++) data[i] ^= ht2_hitag2_byte(cs); - for (i = 0; i < bits; i++) data[bytes] ^= ht2_hitag2_round(cs) << (7 - i); - return 0; + for (i = 0; i < bytes; i++) { + data[i] ^= ht2_hitag2_byte(state); + } + + for (i = 0; i < bits; i++) { + data[bytes] ^= ht2_hitag2_bit(state) << (7 - i); + } } diff --git a/common/hitag2/hitag2_crypto.h b/common/hitag2/hitag2_crypto.h index 381417621..1dae77353 100644 --- a/common/hitag2/hitag2_crypto.h +++ b/common/hitag2/hitag2_crypto.h @@ -17,6 +17,12 @@ #define __HITAG2_CRYPTO_H #include "common.h" +#include + +#ifndef LFSR_INV +#define LFSR_INV(state) (((state) << 1) | (__builtin_parityll((state) & ((0xce0044c101cd >> 1) | (1ull << 47))))) +#endif + typedef struct { uint32_t uid; @@ -32,11 +38,27 @@ typedef struct { uint8_t sectors[12][4]; } hitag2_t; -uint64_t ht2_hitag2_init(const uint64_t key, const uint32_t serial, const uint32_t IV); -uint64_t ht2_hitag2_round(uint64_t *state); -uint32_t ht2_hitag2_byte(uint64_t *x); -void ht2_hitag2_cipher_reset(hitag2_t *tag, const uint8_t *iv); -int ht2_hitag2_cipher_authenticate(uint64_t *cs, const uint8_t *authenticator_is); -int ht2_hitag2_cipher_transcrypt(uint64_t *cs, uint8_t *data, uint16_t bytes, uint16_t bits) ; +typedef struct { + uint64_t shiftreg; // naive shift register, required for nonlinear fn input + uint64_t lfsr; // fast lfsr, used to make software faster +} hitag_state_t; +void ht2_hitag2_init_ex(hitag_state_t *hstate, uint64_t sharedkey, uint32_t serialnum, const uint32_t iv); +void ht2_rollback(hitag_state_t *hstate, uint32_t steps); +uint64_t ht2_recoverkey(hitag_state_t *hstate, uint32_t uid, uint32_t nRenc); +uint32_t ht2_hitag2_nstep(hitag_state_t *hstate, uint32_t steps); +uint32_t ht2_hitag_acid(hitag_state_t *hstate, uint32_t steps); + +int ht2_try_state(uint64_t s, uint32_t uid, uint32_t aR2, uint32_t nR1, uint32_t nR2, uint64_t *key); + +uint32_t ht2_hitag2_word(uint64_t *state, uint32_t steps); +uint64_t ht2_hitag2_init(const uint64_t key, const uint32_t serial, const uint32_t iv); +uint64_t ht2_hitag2_bit(uint64_t *state); +uint32_t ht2_hitag2_byte(uint64_t *state); +void ht2_hitag2_cipher_reset(hitag2_t *tag, const uint8_t *iv); +int ht2_hitag2_cipher_authenticate(uint64_t *state, const uint8_t *authenticator_is); +void ht2_hitag2_cipher_transcrypt(uint64_t *state, uint8_t *data, uint16_t bytes, uint16_t bits) ; + +int ht2_fnf(uint64_t state); +int ht2_fnR(uint64_t state); #endif diff --git a/common/parity.h b/common/parity.h index 3694c515a..3985a1e04 100644 --- a/common/parity.h +++ b/common/parity.h @@ -42,10 +42,8 @@ static const uint8_t g_odd_byte_parity[256] = { 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1 }; -//extern const uint8_t OddByteParity[256]; - -#define ODD_PARITY8(x) { g_odd_byte_parity[x] } -#define EVEN_PARITY8(x) { !g_odd_byte_parity[x] } +#define ODD_PARITY8(x) g_odd_byte_parity[x] +#define EVEN_PARITY8(x) !g_odd_byte_parity[x] static inline uint8_t oddparity8(const uint8_t x) { return g_odd_byte_parity[x]; @@ -60,7 +58,7 @@ static inline uint8_t evenparity16(uint16_t x) { x ^= x >> 8; return EVEN_PARITY8(x) ; #else - return (__builtin_parity(x) & 0xFF); + return __builtin_parity(x); #endif } @@ -77,9 +75,9 @@ static inline uint8_t evenparity32(uint32_t x) { #if !defined __GNUC__ x ^= x >> 16; x ^= x >> 8; - return EVEN_PARITY8(x); + return EVEN_PARITY8(x) ; #else - return (__builtin_parity(x) & 0xFF); + return __builtin_parity(x); #endif } diff --git a/doc/commands.json b/doc/commands.json index 1334ad0fe..8dfa18c30 100644 --- a/doc/commands.json +++ b/doc/commands.json @@ -189,7 +189,7 @@ "options": [ "-h, --help This help", "-d ASN1 encoded byte array", - "-t, --test perform selftest" + "-t, --test perform self test" ], "usage": "data asn1 [-ht] [-d ]" }, @@ -221,18 +221,21 @@ ], "usage": "data autocorr [-hg] [-w ]" }, - "data bin2hex": { - "command": "data bin2hex", - "description": "This function converts binary to hexadecimal. It will ignore all characters not 1 or 0 but stop reading on whitespace", + "data biphaserawdecode": { + "command": "data biphaserawdecode", + "description": "Biphase decode binary stream in DemodBuffer Converts 10 or 01 -> 1 and 11 or 00 -> 0 - must have binary sequence in DemodBuffer (run `data rawdemod --ar` before) - invert for Conditional Dephase Encoding (CDP) AKA Differential Manchester", "notes": [ - "data bin2hex -d 0101111001010" + "data biphaserawdecode -> decode biphase bitstream from the DemodBuffer", + "data biphaserawdecode -oi -> decode biphase bitstream from the DemodBuffer, adjust offset, and invert output" ], "offline": true, "options": [ "-h, --help This help", - "-d, --data binary string to convert" + "-o, --offset set to adjust decode start position", + "-i, --inv invert output", + "--err set max errors tolerated (def 20)" ], - "usage": "data bin2hex [-h] -d " + "usage": "data biphaserawdecode [-hoi] [--err ]" }, "data bitsamples": { "command": "data bitsamples", @@ -261,18 +264,6 @@ ], "usage": "data bmap [-h] [-d ] [-m ]" }, - "data clear": { - "command": "data clear", - "description": "This function clears the bigbuff on deviceside and graph window", - "notes": [ - "data clear" - ], - "offline": true, - "options": [ - "-h, --help This help" - ], - "usage": "data clear [-h]" - }, "data convertbitstream": { "command": "data convertbitstream", "description": "Convert GraphBuffer's 0|1 values to 127|-127", @@ -444,32 +435,15 @@ }, "data help": { "command": "data help", - "description": "----------- ------------------------- General------------------------- help This help ----------- ------------------------- Modulation------------------------- biphaserawdecode Biphase decode bin stream in DemodBuffer detectclock Detect ASK, FSK, NRZ, PSK clock rate of wave in GraphBuffer fsktonrz Convert fsk2 to nrz wave for alternate fsk demodulating (for weak fsk) manrawdecode Manchester decode binary stream in DemodBuffer modulation Identify LF signal for clock and modulation rawdemod Demodulate the data in the GraphBuffer and output binary ----------- ------------------------- Graph------------------------- askedgedetect Adjust Graph for manual ASK demod autocorr Autocorrelation over window dirthreshold Max rising higher up-thres/ Min falling lower down-thres decimate Decimate samples envelope Generate square envelope of samples undecimate Un-decimate samples hide Hide graph window hpf Remove DC offset from trace iir Apply IIR buttersworth filter on plot data grid overlay grid on graph window ltrim Trim samples from left of trace mtrim Trim out samples from the specified start to the specified stop norm Normalize max/min to +/-128 plot Show graph window cthreshold Average out all values between rtrim Trim samples from right of trace setgraphmarkers Set blue and orange marker in graph window shiftgraphzero Shift 0 for Graphed wave + or - shift value timescale Set cursor display timescale zerocrossings Count time between zero-crossings convertbitstream Convert GraphBuffer's 0/1 values to 127 / -127 getbitstream Convert GraphBuffer's >=1 values to 1 and <1 to 0 ----------- ------------------------- Operations------------------------- asn1 ASN1 decoder atr ATR lookup bin2hex Converts binary to hexadecimal bmap Convert hex value according a binary template clear Clears bigbuf on deviceside and graph window crypto Encrypt and decrypt data diff Diff of input files hex2bin Converts hexadecimal to binary load Load contents of file into graph window num Converts dec/hex/bin print Print the data in the DemodBuffer save Save signal trace data ( GraphBuffer ) setdebugmode Set Debugging Level on client side xor Xor a input string --------------------------------------------------------------------------------------- data biphaserawdecode available offline: yes Biphase decode binary stream in DemodBuffer Converts 10 or 01 -> 1 and 11 or 00 -> 0 - must have binary sequence in DemodBuffer (run `data rawdemod --ar` before) - invert for Conditional Dephase Encoding (CDP) AKA Differential Manchester", + "description": "help This help ----------- ------------------------- General------------------------- clear Clears various buffers used by the graph window hide Hide the graph window load Load contents of file into graph window num Converts dec/hex/bin plot Show the graph window print Print the data in the DemodBuffer save Save signal trace data setdebugmode Set Debugging Level on client side xor Xor a input string ----------- ------------------------- Modulation------------------------- biphaserawdecode Biphase decode bin stream in DemodBuffer detectclock Detect ASK, FSK, NRZ, PSK clock rate of wave in GraphBuffer fsktonrz Convert fsk2 to nrz wave for alternate fsk demodulating (for weak fsk) manrawdecode Manchester decode binary stream in DemodBuffer modulation Identify LF signal for clock and modulation rawdemod Demodulate the data in the GraphBuffer and output binary ----------- ------------------------- Graph------------------------- askedgedetect Adjust Graph for manual ASK demod autocorr Autocorrelation over window convertbitstream Convert GraphBuffer's 0/1 values to 127 / -127 cthreshold Average out all values between dirthreshold Max rising higher up-thres/ Min falling lower down-thres decimate Decimate samples envelope Generate square envelope of samples grid overlay grid on graph window getbitstream Convert GraphBuffer's >=1 values to 1 and <1 to 0 hpf Remove DC offset from trace iir Apply IIR buttersworth filter on plot data ltrim Trim samples from left of trace mtrim Trim out samples from the specified start to the specified stop norm Normalize max/min to +/-128 rtrim Trim samples from right of trace setgraphmarkers Set the markers in the graph window shiftgraphzero Shift 0 for Graphed wave + or - shift value timescale Set cursor display timescale undecimate Un-decimate samples zerocrossings Count time between zero-crossings ----------- ------------------------- Operations------------------------- asn1 ASN1 decoder atr ATR lookup bmap Convert hex value according a binary template crypto Encrypt and decrypt data diff Diff of input files --------------------------------------------------------------------------------------- data clear available offline: yes This function clears the BigBuf on device side and graph window ( graphbuffer )", "notes": [ - "data biphaserawdecode -> decode biphase bitstream from the DemodBuffer", - "data biphaserawdecode -oi -> decode biphase bitstream from the DemodBuffer, adjust offset, and invert output" + "data clear" ], "offline": true, "options": [ - "-h, --help This help", - "-o, --offset set to adjust decode start position", - "-i, --inv invert output", - "--err set max errors tolerated (def 20)" + "-h, --help This help" ], - "usage": "data biphaserawdecode [-hoi] [--err ]" - }, - "data hex2bin": { - "command": "data hex2bin", - "description": "This function converts hexadecimal to binary. It will ignore all non-hexadecimal characters but stop reading on whitespace", - "notes": [ - "data hex2bin -d 01020304" - ], - "offline": true, - "options": [ - "-h, --help This help", - "-d, --data bytes to convert" - ], - "usage": "data hex2bin [-h] [-d ]" + "usage": "data clear [-h]" }, "data hexsamples": { "command": "data hexsamples", @@ -735,18 +709,22 @@ }, "data setgraphmarkers": { "command": "data setgraphmarkers", - "description": "Set blue and orange marker in graph window", + "description": "Set the locations of the markers in the graph window", "notes": [ - "data setgraphmarkers -> turn off", - "data setgraphmarkers -a 64 -b 50" + "data setgraphmarkers -> reset the markers", + "data setgraphmarkers -a 64 -> set A, reset the rest", + "data setgraphmarkers -d --keep -> set D, keep the rest" ], "offline": true, "options": [ "-h, --help This help", - "-a orange marker", - "-b blue marker" + "--keep keep the current values of the markers", + "-a yellow marker", + "-b pink marker", + "-c orange marker", + "-d blue marker" ], - "usage": "data setgraphmarkers [-h] [-a ] [-b ]" + "usage": "data setgraphmarkers [-h] [--keep] [-a ] [-b ] [-c ] [-d ]" }, "data shiftgraphzero": { "command": "data shiftgraphzero", @@ -1621,14 +1599,16 @@ "command": "hf 15 csetuid", "description": "Set UID for magic Chinese card (only works with such cards)", "notes": [ - "hf 15 csetuid -u E011223344556677" + "hf 15 csetuid -u E011223344556677 -> use gen1 command", + "hf 15 csetuid -u E011223344556677 --v2 -> use gen2 command" ], "offline": false, "options": [ "-h, --help This help", - "-u, --uid UID, 8 hex bytes" + "-u, --uid UID, 8 hex bytes", + "-2, --v2 Use gen2 magic command" ], - "usage": "hf 15 csetuid [-h] -u " + "usage": "hf 15 csetuid [-h2] -u " }, "hf 15 demod": { "command": "hf 15 demod", @@ -3329,7 +3309,7 @@ }, "hf iclass help": { "command": "hf iclass help", - "description": "----------- --------------------- General --------------------- help This help list List iclass history view Display content from tag dump file ----------- --------------------- Recovery -------------------- loclass Use loclass to perform bruteforce reader attack lookup Uses authentication trace to check for key in dictionary file ----------- ---------------------- Utils ---------------------- calcnewkey Calc diversified keys (blocks 3 & 4) to write new keys encode Encode binary wiegand to block 7 encrypt Encrypt given block data decrypt Decrypt given block data or tag dump file managekeys Manage keys to use with iclass commands permutekey Permute function from 'heart of darkness' paper --------------------------------------------------------------------------------------- hf iclass list available offline: yes Alias of `trace list -t iclass -c` with selected protocol data to annotate trace buffer You can load a trace from file (see `trace load -h`) or it be downloaded from device by default It accepts all other arguments of `trace list`. Note that some might not be relevant for this specific protocol", + "description": "help This help list List iclass history view Display content from tag dump file ----------- --------------------- Recovery -------------------- loclass Use loclass to perform bruteforce reader attack lookup Uses authentication trace to check for key in dictionary file ----------- ---------------------- Utils ---------------------- calcnewkey Calc diversified keys (blocks 3 & 4) to write new keys encode Encode binary wiegand to block 7 encrypt Encrypt given block data decrypt Decrypt given block data or tag dump file managekeys Manage keys to use with iclass commands permutekey Permute function from 'heart of darkness' paper --------------------------------------------------------------------------------------- hf iclass list available offline: yes Alias of `trace list -t iclass -c` with selected protocol data to annotate trace buffer You can load a trace from file (see `trace load -h`) or it be downloaded from device by default It accepts all other arguments of `trace list`. Note that some might not be relevant for this specific protocol", "notes": [ "hf iclass list --frame -> show frame delay times", "hf iclass list -1 -> use trace buffer" @@ -3372,14 +3352,14 @@ "options": [ "-h, --help This help", "-f, --file filename with nr/mac data from `hf iclass sim -t 2`", - "--test Perform self-test", - "--long Perform self-test, including long ones" + "--test Perform self test", + "--long Perform self test, including long ones" ], "usage": "hf iclass loclass [-h] [-f ] [--test] [--long]" }, "hf iclass lookup": { "command": "hf iclass lookup", - "description": "Lookup keys takes some sniffed trace data and tries to verify what key was used against a dictionary file", + "description": "This command take sniffed trace data and try to recovery a iCLASS Standard or iCLASS Elite key.", "notes": [ "hf iclass lookup --csn 9655a400f8ff12e0 --epurse f0ffffffffffffff --macs 0000000089cb984b -f iclass_default_keys.dic", "hf iclass lookup --csn 9655a400f8ff12e0 --epurse f0ffffffffffffff --macs 0000000089cb984b -f iclass_default_keys.dic --elite" @@ -3670,7 +3650,7 @@ "-h, --help This help", "-u, --uid uid bytes", "-r read uid from tag instead", - "-t selftest", + "-t self test", "-v, --verbose verbose output", "--dragon figurine type", "--fox figurine type", @@ -8219,11 +8199,12 @@ ], "usage": "lf awid clone [-h] --fmt --fc --cn [--q5] [--em]" }, - "lf awid help": { - "command": "lf awid help", - "description": "help this help demod demodulate an AWID FSK tag from the GraphBuffer --------------------------------------------------------------------------------------- lf awid demod available offline: yes Try to find AWID Prox preamble, if found decode / descramble data", + "lf awid demod": { + "command": "lf awid demod", + "description": "Try to find AWID Prox preamble, if found decode / descramble data", "notes": [ - "lf awid demod" + "lf awid demod", + "lf awid demod --raw" ], "offline": true, "options": [ @@ -8231,6 +8212,25 @@ ], "usage": "lf awid demod [-h]" }, + "lf awid help": { + "command": "lf awid help", + "description": "help this help demod demodulate an AWID FSK tag from the GraphBuffer --------------------------------------------------------------------------------------- lf awid brute available offline: no Enables bruteforce of AWID reader with specified facility-code. This is a attack against reader. if cardnumber is given, it starts with it and goes up / down one step if cardnumber is not given, it starts with 1 and goes up to 65535", + "notes": [ + "lf awid brute --fmt 26 --fc 224", + "lf awid brute --fmt 50 --fc 2001 --delay 2000", + "lf awid brute --fmt 50 --fc 2001 --cn 200 --delay 2000 -v" + ], + "offline": true, + "options": [ + "-h, --help This help", + "--fmt format length 26|50", + "--fc 8|16bit value facility code", + "--cn optional - card number to start with, max 65535", + "--delay optional - delay betweens attempts in ms. Default 1000ms", + "-v, --verbose verbose output" + ], + "usage": "lf awid brute [-hv] --fmt --fc [--cn ] [--delay ]" + }, "lf awid reader": { "command": "lf awid reader", "description": "read a AWID Prox tag", @@ -9426,20 +9426,32 @@ ], "usage": "lf hitag cc [-h] -f " }, + "lf hitag chk": { + "command": "lf hitag chk", + "description": "Run dictionary key or password recovery against Hitag card.", + "notes": [ + "lf hitag chk", + "-> checks for both pwd / crypto keyslf hitag chk --crypto -> use def dictionary", + "lf hitag chk --pwd -f my.dic -> pwd mode, custom dictionary" + ], + "offline": false, + "options": [ + "-h, --help This help", + "-f, --file specify dictionary filename", + "--pwd password mode", + "--crypto crypto mode" + ], + "usage": "lf hitag chk [-h] [-f ] [--pwd] [--crypto]" + }, "lf hitag dump": { "command": "lf hitag dump", - "description": "Read all Hitag 2 card memory and save to file Crypto mode key format: ISK high + ISK low", + "description": "Read all Hitag 2 card memory and save to file Crypto mode key format: ISK high + ISK low, 4F4E4D494B52 (ONMIKR) Password mode, default key 4D494B52 (MIKR)", "notes": [ - "Password mode => use default key 4D494B52 (MIKR)", - "lf hitag dump --pwd", - "Short key = password mode", - "lf hitag dump -k 4D494B52", - "Challenge mode", - "lf hitag dump --nrar 0102030411223344", - "Crypto mode => use default key 4F4E4D494B52 (ONMIKR)", - "lf hitag dump --crypto", - "Long key = crypto mode", - "lf hitag dump -k 4F4E4D494B52" + "lf hitag dump --pwd -> use def pwd", + "lf hitag dump -k 4D494B52 -> pwd mode", + "lf hitag dump --crypto -> use def crypto", + "lf hitag dump -k 4F4E4D494B52 -> crypto mode", + "lf hitag dump --nrar 0102030411223344" ], "offline": false, "options": [ @@ -9485,7 +9497,7 @@ }, "lf hitag help": { "command": "lf hitag help", - "description": "help This help list List Hitag trace history view Display content from tag dump file --------------------------------------------------------------------------------------- lf hitag list available offline: yes Alias of `trace list -t hitag2` with selected protocol data to annotate trace buffer You can load a trace from file (see `trace load -h`) or it be downloaded from device by default It accepts all other arguments of `trace list`. Note that some might not be relevant for this specific protocol", + "description": "help This help list List Hitag trace history selftest Perform self test view Display content from tag dump file lookup Uses authentication trace to check for key in dictionary file --------------------------------------------------------------------------------------- lf hitag list available offline: yes Alias of `trace list -t hitag2` with selected protocol data to annotate trace buffer You can load a trace from file (see `trace load -h`) or it be downloaded from device by default It accepts all other arguments of `trace list`. Note that some might not be relevant for this specific protocol", "notes": [ "lf hitag list --frame -> show frame delay times", "lf hitag list -1 -> use trace buffer" @@ -9516,29 +9528,41 @@ ], "usage": "lf hitag info [-h]" }, + "lf hitag lookup": { + "command": "lf hitag lookup", + "description": "This command take sniffed trace data and try to recovery a Hitag2 crypto key. You can either - verify that NR/AR matches a known crypto key - verify if NR/AR matches a known 6 byte crypto key in a dictionary", + "notes": [ + "lf hitag lookup --uid 11223344 --nr 73AA5A62 --ar EAB8529C -k 010203040506 -> check key", + "lf hitag lookup --uid 11223344 --nr 73AA5A62 --ar EAB8529C -> use def dictionary", + "lf hitag lookup --uid 11223344 --nr 73AA5A62 --ar EAB8529C -f my.dic -> use custom dictionary", + "lf hitag lookup --uid 11223344 --nrar 73AA5A62EAB8529C" + ], + "offline": true, + "options": [ + "-h, --help This help", + "-f, --file specify dictionary filename", + "-k, --key specify known cryptokey as 6 bytes", + "-u, --uid specify UID as 4 hex bytes", + "--nr specify nonce as 4 hex bytes", + "--ar specify answer as 4 hex bytes", + "--nrar specify nonce / answer as 8 hex bytes" + ], + "usage": "lf hitag lookup [-h] [-f ] [-k ] -u [--nr ] [--ar ] [--nrar ]" + }, "lf hitag read": { "command": "lf hitag read", - "description": "Read Hitag memory Crypto mode key format: ISK high + ISK low", + "description": "Read Hitag memory. It support HitagS and Hitag 2 Password mode: - default key 4D494B52 (MIKR) Crypto mode: - key format ISK high + ISK low - default key 4F4E4D494B52 (ONMIKR)", "notes": [ - "Hitag S, plain mode", - "lf hitag read --hts", - "Hitag S, challenge mode", - "lf hitag read --hts --nrar 0102030411223344", - "Hitag S, crypto mode => use default key 4F4E4D494B52 (ONMIKR)", - "lf hitag read --hts --crypto", - "Hitag S, long key = crypto mode", - "lf hitag read --hts -k 4F4E4D494B52", + "lf hitag read --hts -> HitagS, plain mode", + "lf hitag read --hts --nrar 0102030411223344 -> HitagS, challenge mode", + "lf hitag read --hts --crypto -> HitagS, crypto mode, def key", + "lf hitag read --hts -k 4F4E4D494B52 -> HitagS, crypto mode", "", - "Hitag 2, password mode => use default key 4D494B52 (MIKR)", - "lf hitag read --ht2 --pwd", - "Hitag 2, providing a short key = password mode", - "lf hitag read --ht2 -k 4D494B52", - "Hitag 2, challenge mode", - "lf hitag read --ht2 --nrar 0102030411223344", - "Hitag 2, crypto mode => use default key 4F4E4D494B52 (ONMIKR)", - "lf hitag read --ht2 --crypto", - "Hitag 2, providing a long key = crypto mode", - "lf hitag read --ht2 -k 4F4E4D494B52" + "lf hitag read --ht2 --pwd -> Hitag 2, pwd mode, def key", + "lf hitag read --ht2 -k 4D494B52 -> Hitag 2, pwd mode", + "lf hitag read --ht2 --nrar 0102030411223344 -> Hitag 2, challenge mode", + "lf hitag read --ht2 --crypto -> Hitag 2, crypto mode, def key", + "lf hitag read --ht2 -k 4F4E4D494B52 -> Hitag 2, crypto mode" ], "offline": false, "options": [ @@ -9552,6 +9576,18 @@ ], "usage": "lf hitag read [-hs2] [--pwd] [--nrar ] [--crypto] [-k ]" }, + "lf hitag selftest": { + "command": "lf hitag selftest", + "description": "Perform selftest of Hitag crypto engine", + "notes": [ + "lf hitag selftest" + ], + "offline": true, + "options": [ + "-h, --help This help" + ], + "usage": "lf hitag selftest [-h]" + }, "lf hitag sim": { "command": "lf hitag sim", "description": "Simulate Hitag transponder You need to `lf hitag eload` first", @@ -9595,27 +9631,18 @@ }, "lf hitag wrbl": { "command": "lf hitag wrbl", - "description": "Write a page in Hitag memory Crypto mode key format: ISK high + ISK low", + "description": "Write a page in Hitag memory. It support HitagS and Hitag 2 Password mode: - default key 4D494B52 (MIKR) Crypto mode: - key format ISK high + ISK low - default key 4F4E4D494B52 (ONMIKR)", "notes": [ - "Hitag S, plain mode", - "lf hitag wrbl --hts -p 6 -d 01020304", - "Hitag S, challenge mode", - "lf hitag wrbl --hts --nrar 0102030411223344 -p 6 -d 01020304", - "Hitag S, crypto mode => use default key 4F4E4D494B52 (ONMIKR)", - "lf hitag wrbl --hts --crypto -p 6 -d 01020304", - "Hitag S, long key = crypto mode", - "lf hitag wrbl --hts -k 4F4E4D494B52 -p 6 -d 01020304", + "lf hitag wrbl --hts -p 6 -d 01020304 -> HitagS, plain mode", + "lf hitag wrbl --hts -p 6 -d 01020304 --nrar 0102030411223344 -> HitagS, challenge mode", + "lf hitag wrbl --hts -p 6 -d 01020304 --crypto -> HitagS, crypto mode, def key", + "lf hitag wrbl --hts -p 6 -d 01020304 -k 4F4E4D494B52 -> HitagS, crypto mode", "", - "Hitag 2, password mode => use default key 4D494B52 (MIKR)", - "lf hitag wrbl --ht2 --pwd -p 6 -d 01020304", - "Hitag 2, providing a short key = password mode", - "lf hitag wrbl --ht2 -k 4D494B52 -p 6 -d 01020304", - "Hitag 2, challenge mode", - "lf hitag wrbl --ht2 --nrar 0102030411223344 -p 6 -d 01020304", - "Hitag 2, crypto mode => use default key 4F4E4D494B52 (ONMIKR)", - "lf hitag wrbl --ht2 --crypto -p 6 -d 01020304", - "Hitag 2, providing a long key = crypto mode", - "lf hitag wrbl --ht2 -k 4F4E4D494B52 -p 6 -d 01020304" + "lf hitag wrbl --ht2 -p 6 -d 01020304 --pwd -> Hitag 2, pwd mode, def key", + "lf hitag wrbl --ht2 -p 6 -d 01020304 -k 4D494B52 -> Hitag 2, pwd mode", + "lf hitag wrbl --ht2 -p 6 -d 01020304 --nrar 0102030411223344 -> Hitag 2, challenge mode", + "lf hitag wrbl --ht2 -p 6 -d 01020304 --crypto -> Hitag 2, crypto mode, def key", + "lf hitag wrbl --ht2 -p 6 -d 01020304 -k 4F4E4D494B52 -> Hitag 2, crypto mode" ], "offline": false, "options": [ @@ -12595,8 +12622,8 @@ } }, "metadata": { - "commands_extracted": 727, + "commands_extracted": 729, "extracted_by": "PM3Help2JSON v1.00", - "extracted_on": "2024-04-07T09:37:51" + "extracted_on": "2024-04-22T14:35:02" } } diff --git a/doc/commands.md b/doc/commands.md index 778e10a91..d828f70df 100644 --- a/doc/commands.md +++ b/doc/commands.md @@ -94,6 +94,15 @@ Check column "offline" for their availability. |command |offline |description |------- |------- |----------- |`data help `|Y |`This help` +|`data clear `|Y |`Clears various buffers used by the graph window` +|`data hide `|Y |`Hide the graph window` +|`data load `|Y |`Load contents of file into graph window` +|`data num `|Y |`Converts dec/hex/bin` +|`data plot `|Y |`Show the graph window` +|`data print `|Y |`Print the data in the DemodBuffer` +|`data save `|Y |`Save signal trace data` +|`data setdebugmode `|Y |`Set Debugging Level on client side` +|`data xor `|Y |`Xor a input string` |`data biphaserawdecode `|Y |`Biphase decode bin stream in DemodBuffer` |`data detectclock `|Y |`Detect ASK, FSK, NRZ, PSK clock rate of wave in GraphBuffer` |`data fsktonrz `|Y |`Convert fsk2 to nrz wave for alternate fsk demodulating (for weak fsk)` @@ -102,43 +111,32 @@ Check column "offline" for their availability. |`data rawdemod `|Y |`Demodulate the data in the GraphBuffer and output binary` |`data askedgedetect `|Y |`Adjust Graph for manual ASK demod` |`data autocorr `|Y |`Autocorrelation over window` +|`data convertbitstream `|Y |`Convert GraphBuffer's 0/1 values to 127 / -127` +|`data cthreshold `|Y |`Average out all values between` |`data dirthreshold `|Y |`Max rising higher up-thres/ Min falling lower down-thres` |`data decimate `|Y |`Decimate samples` |`data envelope `|Y |`Generate square envelope of samples` -|`data undecimate `|Y |`Un-decimate samples` -|`data hide `|Y |`Hide graph window` +|`data grid `|Y |`overlay grid on graph window` +|`data getbitstream `|Y |`Convert GraphBuffer's >=1 values to 1 and <1 to 0` |`data hpf `|Y |`Remove DC offset from trace` |`data iir `|Y |`Apply IIR buttersworth filter on plot data` -|`data grid `|Y |`overlay grid on graph window` |`data ltrim `|Y |`Trim samples from left of trace` |`data mtrim `|Y |`Trim out samples from the specified start to the specified stop` |`data norm `|Y |`Normalize max/min to +/-128` -|`data plot `|Y |`Show graph window` -|`data cthreshold `|Y |`Average out all values between` |`data rtrim `|Y |`Trim samples from right of trace` -|`data setgraphmarkers `|Y |`Set blue and orange marker in graph window` +|`data setgraphmarkers `|Y |`Set the markers in the graph window` |`data shiftgraphzero `|Y |`Shift 0 for Graphed wave + or - shift value` |`data timescale `|Y |`Set cursor display timescale` +|`data undecimate `|Y |`Un-decimate samples` |`data zerocrossings `|Y |`Count time between zero-crossings` -|`data convertbitstream `|Y |`Convert GraphBuffer's 0/1 values to 127 / -127` -|`data getbitstream `|Y |`Convert GraphBuffer's >=1 values to 1 and <1 to 0` |`data asn1 `|Y |`ASN1 decoder` |`data atr `|Y |`ATR lookup` -|`data bin2hex `|Y |`Converts binary to hexadecimal` |`data bitsamples `|N |`Get raw samples as bitstring` |`data bmap `|Y |`Convert hex value according a binary template` -|`data clear `|Y |`Clears bigbuf on deviceside and graph window` |`data crypto `|Y |`Encrypt and decrypt data` |`data diff `|Y |`Diff of input files` |`data hexsamples `|N |`Dump big buffer as hex bytes` -|`data hex2bin `|Y |`Converts hexadecimal to binary` -|`data load `|Y |`Load contents of file into graph window` -|`data num `|Y |`Converts dec/hex/bin` -|`data print `|Y |`Print the data in the DemodBuffer` |`data samples `|N |`Get raw samples for graph window ( GraphBuffer )` -|`data save `|Y |`Save signal trace data ( GraphBuffer )` -|`data setdebugmode `|Y |`Set Debugging Level on client side` -|`data xor `|Y |`Xor a input string` ### emv @@ -857,9 +855,10 @@ Check column "offline" for their availability. |command |offline |description |------- |------- |----------- |`lf awid help `|Y |`this help` +|`lf awid brute `|N |`bruteforce card number against reader` +|`lf awid clone `|N |`clone AWID tag to T55x7, Q5/T5555 or EM4305/4469` |`lf awid demod `|Y |`demodulate an AWID FSK tag from the GraphBuffer` |`lf awid reader `|N |`attempt to read and extract tag data` -|`lf awid clone `|N |`clone AWID tag to T55x7, Q5/T5555 or EM4305/4469` |`lf awid sim `|N |`simulate AWID tag` |`lf awid brute `|N |`bruteforce card number against reader` |`lf awid watch `|N |`continuously watch for cards. Reader mode` @@ -923,7 +922,7 @@ Check column "offline" for their availability. |`lf em 4x05 help `|Y |`This help` |`lf em 4x05 clonehelp `|N |`Shows the available clone commands` |`lf em 4x05 brute `|N |`Bruteforce password` -|`lf em 4x05 chk `|N |`Check passwords from dictionary` +|`lf em 4x05 chk `|N |`Check passwords` |`lf em 4x05 config `|Y |`Create common configuration words` |`lf em 4x05 demod `|Y |`Demodulate a EM4x05/EM4x69 tag from the GraphBuffer` |`lf em 4x05 dump `|N |`Dump EM4x05/EM4x69 tag` @@ -944,7 +943,7 @@ Check column "offline" for their availability. |------- |------- |----------- |`lf em 4x50 help `|Y |`This help` |`lf em 4x50 brute `|N |`Bruteforce attack to find password` -|`lf em 4x50 chk `|N |`Check passwords from dictionary` +|`lf em 4x50 chk `|N |`Check passwords` |`lf em 4x50 dump `|N |`Dump EM4x50 tag` |`lf em 4x50 info `|N |`Tag information` |`lf em 4x50 login `|N |`Login into EM4x50 tag` @@ -1042,16 +1041,19 @@ Check column "offline" for their availability. |`lf hitag help `|Y |`This help` |`lf hitag list `|Y |`List Hitag trace history` |`lf hitag info `|N |`Hitag 2 tag information` +|`lf hitag selftest `|Y |`Perform self test` |`lf hitag dump `|N |`Dump Hitag 2 tag` |`lf hitag read `|N |`Read Hitag memory` +|`lf hitag sniff `|N |`Eavesdrop Hitag communication` |`lf hitag view `|Y |`Display content from tag dump file` |`lf hitag wrbl `|N |`Write a block (page) in Hitag memory` -|`lf hitag sniff `|N |`Eavesdrop Hitag communication` -|`lf hitag cc `|N |`Hitag S: test all provided challenges` -|`lf hitag ta `|N |`Hitag 2: test all recorded authentications` |`lf hitag eload `|N |`Upload file into emulator memory` |`lf hitag eview `|N |`View emulator memory` |`lf hitag sim `|N |`Simulate Hitag transponder` +|`lf hitag cc `|N |`Hitag S: test all provided challenges` +|`lf hitag chk `|N |`Check keys` +|`lf hitag lookup `|Y |`Uses authentication trace to check for key in dictionary file` +|`lf hitag ta `|N |`Hitag 2: test all recorded authentications` ### lf idteck @@ -1285,7 +1287,7 @@ Check column "offline" for their availability. |`lf t55xx wakeup `|N |`Send AOR wakeup command` |`lf t55xx write `|N |`Write T55xx block data` |`lf t55xx bruteforce `|N |`Simple bruteforce attack to find password` -|`lf t55xx chk `|N |`Check passwords from dictionary/flash` +|`lf t55xx chk `|N |`Check passwords` |`lf t55xx protect `|N |`Password protect tag` |`lf t55xx recoverpw `|N |`Try to recover from bad password write from a cloner` |`lf t55xx sniff `|Y |`Attempt to recover T55xx commands from sample buffer` diff --git a/include/common.h b/include/common.h index a2542ef38..b405b2ac7 100644 --- a/include/common.h +++ b/include/common.h @@ -127,6 +127,17 @@ extern bool g_tearoff_enabled; #endif #endif +// endian change for 48bit +#ifndef BSWAP_48 +#define BSWAP_48(x) \ + (((uint64_t)(x) << 40) & 0x0000ff0000000000ULL) | \ + (((uint64_t)(x) << 24) & 0x000000ff00000000ULL) | \ + (((uint64_t)(x) << 8) & 0x00000000ff000000ULL) | \ + (((uint64_t)(x) >> 8) & 0x000000000ff0000ULL) | \ + (((uint64_t)(x) >> 24) & 0x00000000000ff00ULL) | \ + (((uint64_t)(x) >> 40) & 0x0000000000000ffULL) +#endif + // endian change for 32bit #ifdef __GNUC__ #ifndef BSWAP_32 diff --git a/include/hitag.h b/include/hitag.h index fd0b2ddac..06a8de9cf 100644 --- a/include/hitag.h +++ b/include/hitag.h @@ -39,37 +39,28 @@ typedef enum { RHT2F_UID_ONLY = 26, WHT2F_PASSWORD = 27, HT2_LAST_CMD = WHT2F_PASSWORD, -} hitag_function; - -typedef struct { - uint8_t password[4]; -} PACKED rht2d_password; +} PACKED hitag_function; typedef struct { + hitag_function cmd; + int16_t page; + uint8_t data[4]; uint8_t NrAr[8]; - uint8_t data[4]; -} PACKED rht2d_authenticate; - -typedef struct { uint8_t key[6]; - uint8_t data[4]; -} PACKED rht2d_crypto; + uint8_t pwd[4]; -typedef struct { + // Hitag 1 section. + // will reuse pwd or key field. uint8_t key_no; uint8_t logdata_0[4]; uint8_t logdata_1[4]; uint8_t nonce[4]; - uint8_t key[4]; -} PACKED rht1d_authenticate; - -typedef union { - rht2d_password pwd; - rht1d_authenticate ht1auth; - rht2d_authenticate auth; - rht2d_crypto crypto; -} hitag_data; +} PACKED lf_hitag_data_t; +typedef struct { + int status; + uint8_t data[48]; +} PACKED lf_hitag_crack_response_t; //--------------------------------------------------------- // Hitag S diff --git a/tools/hitag2crack/hitag2_gen_nRaR.py b/tools/hitag2crack/hitag2_gen_nRaR.py index 232add1f3..68256b61e 100755 --- a/tools/hitag2crack/hitag2_gen_nRaR.py +++ b/tools/hitag2crack/hitag2_gen_nRaR.py @@ -67,9 +67,9 @@ def hitag2_init(key, uid, nonce): #print '%012x' % state #print '%012x' % (int("{0:048b}".format(state)[::-1],2)) for i in range(0, 32): - nonce_bit = (f20(state) ^ ((nonce >> (31-i)) & 1)) + nonce_bit = (f20(state) ^ ((nonce >> (31 - i)) & 1)) #print nonce_bit - state = (state >> 1) | (((nonce_bit ^ (key >> (31-i))) & 1) << 47) + state = (state >> 1) | (((nonce_bit ^ (key >> (31 - i))) & 1) << 47) #print '%012x' % state #print '%012x' % (int("{0:048b}".format(state)[::-1],2)) return state @@ -81,6 +81,7 @@ def lfsr_feedback(state): ^ (state >> 26) ^ (state >> 30) ^ (state >> 41) ^ (state >> 42) ^ (state >> 43) ^ (state >> 46) ^ (state >> 47)) & 1) + def lfsr(state): return (state >> 1) + (lfsr_feedback(state) << 47) @@ -93,15 +94,17 @@ def lfsr_feedback_inv(state): ^ (state >> 46)) & 1) def lfsr_inv(state): - return ((state << 1) + (lfsr_feedback_inv(state))) & ((1<<48)-1) + return ((state << 1) + (lfsr_feedback_inv(state))) & ((1 << 48) - 1) def hitag2(state, length=48): c = 0 for i in range(0, length): c = (c << 1) | f20(state) - #print '%012x' % state - #print '%012x' % (int("{0:048b}".format(state)[::-1],2)) + #print ('%012x' % state) state = lfsr(state) + #print ('%012x' % (int("{0:048b}".format(state)[::-1],2))) + #print('%08X %08X' % (c, state)) + #print('final: %08X %08X' % (c, state)) return c if __name__ == "__main__": @@ -111,8 +114,15 @@ if __name__ == "__main__": uid = int(sys.argv[2], 16) n = int(sys.argv[3]) for i in range(n): - nonce = random.randrange(2**32) - state = hitag2_init(key, uid, nonce) - print('%08X %08X' % (nonce, hitag2(state, 32)^0xffffffff)) + nonceA = random.randrange(2**32) + stateA = hitag2_init(key, uid, nonceA) + csA = hitag2(stateA, 32) ^ 0xffffffff + # print('%08X %08X' % (nonceA, csA)) + + nonceB = random.randrange(2**32) + stateB = hitag2_init(key, uid, nonceB) + csB = hitag2(stateB, 32) ^ 0xffffffff + print('./ht2crack5opencl %08X %08X %08X %08X %08X' % (uid, nonceA, csA, nonceB, csB)) + print('lf hitag lookup --uid %08X --nr %08X --ar %08X --key %012X' % (uid, nonceA, csA, key)) else: print("Usage: python %s " % sys.argv[0]) diff --git a/tools/pm3_tests.sh b/tools/pm3_tests.sh index 7b28a3f09..d2ffb74c4 100755 --- a/tools/pm3_tests.sh +++ b/tools/pm3_tests.sh @@ -414,6 +414,7 @@ while true; do if ! CheckExecute "nfc decode test - signature" "$CLIENTBIN -c 'nfc decode -d 03FF010194113870696C65742E65653A656B616172743A3266195F26063132303832325904202020205F28033233335F2701316E1B5A13333038363439303039303030323636343030355304EBF2CE704103000000AC536967010200803A2448FCA7D354A654A81BD021150D1A152D1DF4D7A55D2B771F12F094EAB6E5E10F2617A2F8DAD4FD38AFF8EA39B71C19BD42618CDA86EE7E144636C8E0E7CFC4096E19C3680E09C78A0CDBC05DA2D698E551D5D709717655E56FE3676880B897D2C70DF5F06ECE07C71435255144F8EE41AF110E7B180DA0E6C22FB8FDEF61800025687474703A2F2F70696C65742E65652F6372742F33303836343930302D303030312E637274FE'" "30864900-0001.crt"; then break; fi echo -e "\n${C_BLUE}Testing LF:${C_NC}" + if ! CheckExecute "lf hitag2 test" "$CLIENTBIN -c 'lf hitag selftest'" "Tests \( ok"; then break; fi if ! CheckExecute "lf cotag demod test" "$CLIENTBIN -c 'data load -f traces/lf_cotag_220_8331.pm3; data norm; data cthreshold -u 50 -d -20; data envelope; data raw --ar -c 272; lf cotag demod'" \ "COTAG Found: FC 220, CN: 8331 Raw: FFB841170363FFFE00001E7F00000000"; then break; fi if ! CheckExecute "lf AWID test" "$CLIENTBIN -c 'data load -f traces/lf_AWID-15-259.pm3;lf search -1'" "AWID ID found"; then break; fi