lm4tools-0.1.3/000077500000000000000000000000001325171702700132755ustar00rootroot00000000000000lm4tools-0.1.3/Makefile000066400000000000000000000002051325171702700147320ustar00rootroot00000000000000all: @${MAKE} -C lmicdiusb all @${MAKE} -C lm4flash all install: all @${MAKE} -C lmicdiusb install @${MAKE} -C lm4flash install lm4tools-0.1.3/README.md000066400000000000000000000040641325171702700145600ustar00rootroot00000000000000lm4tools ======== Some tools which enable multi-platform development on the TI Stellaris Launchpad boards. The Stellaris Launchpad is a low cost development board created by Texas Instruments that comes with an ARM Cortex-M4F processor. You can get one here: [Get a Stellaris Launchpad](http://www.ti.com/ww/en/launchpad/stellaris_head.html?DCMP=stellaris-launchpad&HQS=stellaris-launchpad-b) __Included tools__ * lm4flash Command-line firmware flashing tool using libusb-1.0 to communicate with the Stellaris Launchpad ICDI. Works on all Linux, Mac OS X, Windows, and BSD systems. GPLv2+ license. See lm4flash/COPYING for details. * lmicdiusb TCP/USB bridge created by TI, letting GDB communicate with the Stellaris Launchpad ICDI. Works on all Linux, Mac OS X, and BSD systems. Currently not on Windows, due to the use of poll() which does not work for USB on Windows. BSD-style license. See lmicdiusb/license.txt for details. __Setting up a development environment__ First you'll need a cross compiler able to compile for ARM Cortex-Mx aka arm-none-eabi-. Some which are know to work: * [summon-arm-toolchain by Piotr Esden-Tempski](https://github.com/esden/summon-arm-toolchain) * [arm-eabi-toolchain by James Snyder](https://github.com/jsnyder/arm-eabi-toolchain) * [Sourcery Codebench Lite](http://www.mentor.com/embedded-software/sourcery-tools/sourcery-codebench/editions/lite-edition/request?id=e023fac2-e611-476b-a702-90eabb2aeca8&downloadlite=scblite2012&fmpath=/embedded-software/sourcery-tools/sourcery-codebench/editions/lite-edition/form) More info can be found here [eLinux toolchains](http://elinux.org/Toolchains). Grab StellarisWare from Texas Instruments: [Stellaris LM4F120 LaunchPad Evaluation Board Software](http://www.ti.com/tool/sw-ek-lm4f120xl). You need to get SW-EK-LM4F120XL. Inside StellarisWare directory you'll find many examples in the directory *boards/ek-lm4f120xl*. Try building project0 by going to that directory and running *make*. To flash your Stellaris board from *boards/ek-lm4f120xl/project0*, run: $ lm4flash gcc/project0.bin Nice hacking! lm4tools-0.1.3/lm4flash/000077500000000000000000000000001325171702700150075ustar00rootroot00000000000000lm4tools-0.1.3/lm4flash/.gitignore000066400000000000000000000000401325171702700167710ustar00rootroot00000000000000*.o *.obj lm4flash lm4flash.exe lm4tools-0.1.3/lm4flash/COPYING000066400000000000000000000355651325171702700160600ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS lm4tools-0.1.3/lm4flash/Makefile000066400000000000000000000010011325171702700164370ustar00rootroot00000000000000EXE := lm4flash CC ?= gcc CFLAGS += -Wall ifeq ($(shell uname),FreeBSD) LDFLAGS += -lusb else CFLAGS += $(shell pkg-config --cflags libusb-1.0) LDFLAGS += $(shell pkg-config --libs libusb-1.0) endif all: $(EXE) release: CFLAGS += -O2 release: $(EXE) debug: CFLAGS += -g -DDEBUG debug: $(EXE) $(EXE): $(EXE).c $(CC) $(CFLAGS) $^ $(LDFLAGS) -o $@ install: $(EXE) ifndef PREFIX $(error PREFIX is not set) endif mkdir -p $(PREFIX)/bin install $^ $(PREFIX)/bin/ clean: rm -f *.o $(EXE) .PHONY: all clean lm4tools-0.1.3/lm4flash/lm4flash.c000066400000000000000000000501611325171702700166700ustar00rootroot00000000000000/* lm4flash - TI Stellaris Launchpad ICDI flasher * Copyright (C) 2012-2018 Fabio Utzig * Copyright (C) 2012 Peter Stuge * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include #include #include #include #include #include #include #include #include //#define DEBUG 1 #define ICDI_VID 0x1cbe #define ICDI_PID 0x00fd // FlashPatch Control Register: see ARM Av7mRM C1.11.3 static const uint32_t FP_CTRL = 0xe0002000; // Debug Halting Control and Status Register: see ARM Av7mRM C1.6.2 static const uint32_t DHCSR = 0xe000edf0; // Device Identification: see Stellaris LM4F120H5QR Microcontroller Section 5.5 static const uint32_t DID0 = 0x400fe000; static const uint32_t DID1 = 0x400fe004; // Device Identification: see Stellaris LM4F120H5QR Microcontroller Section 5.5 static const uint32_t DC0 = 0x400fe008; // Run-Mode Clock Configuration: Stellaris LM4F120H5QR Microcontroller Section 5.5 static const uint32_t RCC = 0x400fe060; // Non-Volatile Memory Information: Stellaris LM4F120H5QR Microcontroller Section 5.6 static const uint32_t NVMSTAT = 0x400fe1a0; // Rom Control: see Stellaris LM4F120H5QR Microcontroller Page 531 static const uint32_t ROMCTL = 0x400fe0f0; // Flash Memory Address: see Stellaris LM4F120H5QR Microcontroller Page 497 static const uint32_t FMA = 0x400fd000; static const uint8_t INTERFACE_NR = 0x02; static const uint8_t ENDPOINT_IN = 0x83; static const uint8_t ENDPOINT_OUT = 0x02; #define START "$" #define END "#" #ifdef WIN32 #define snprintf _snprintf #define SNPRINTF_OFFSET 1 #else #define SNPRINTF_OFFSET 0 #endif #define START_LEN strlen(START) #define END_LEN (strlen(END) + 2) #define FLASH_BLOCK_SIZE 512 #define FLASH_ERASE_SIZE 1024 /* Prefix + potentially every flash byte escaped */ #define BUF_SIZE 64 + 2*FLASH_BLOCK_SIZE static uint8_t flash_block[FLASH_BLOCK_SIZE]; static union { char c[BUF_SIZE]; uint8_t u8[BUF_SIZE]; uint32_t u32[BUF_SIZE / 4]; } buf; void show_version(void) { printf("%s", "LM4Flash version 0.1.3 - Flasher for Stellaris Launchpad ICDI boards\n" "Copyright (C) 2012-2018 Fabio Utzig \n" "Copyright (C) 2012 Peter Stuge \n" "This is free software; see the source for copying conditions. There is NO\n" "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR " "PURPOSE.\n" ); } static uint32_t le32_to_cpu(const uint32_t x) { union { uint8_t b8[4]; uint32_t b32; } _tmp; _tmp.b8[3] = x >> 24; _tmp.b8[2] = x >> 16; _tmp.b8[1] = x >> 8; _tmp.b8[0] = x & 0xff; return _tmp.b32; } static int do_verify = 0; static int erase_used = 0; static uint32_t start_addr = 0; #define cpu_to_le32 le32_to_cpu #ifdef DEBUG static void pretty_print_buf(uint8_t *b, int size) { #define PP_LINESIZE 80 #define PP_NUM_P_LINE 16 #define PP_HEX_COL 7 #define PP_ASC_COL 56 int i, pos; char linebuf[PP_LINESIZE]; memset(linebuf, ' ', sizeof linebuf); linebuf[PP_ASC_COL + PP_NUM_P_LINE] = 0; for (i = 0; i < size; i++) { if (((i % PP_NUM_P_LINE) == 0)) { if (i) { printf("%s\n", linebuf); memset(linebuf, ' ', sizeof linebuf); linebuf[PP_ASC_COL + PP_NUM_P_LINE] = 0; } sprintf(linebuf, "%04x : ", i); linebuf[PP_ASC_COL] = ' '; linebuf[PP_HEX_COL] = ' '; } pos = PP_HEX_COL + ((i % PP_NUM_P_LINE) * 3); sprintf(linebuf + pos, "%02x", b[i]); linebuf[pos + 2] = ' '; linebuf[(i % PP_NUM_P_LINE) + PP_ASC_COL] = isprint(b[i]) ? b[i] : '.'; } printf("%s\n", linebuf); } #endif static int send_command(libusb_device_handle *handle, int size) { int transferred = 0; int retval; #ifdef DEBUG printf(">>> sending %d bytes\n", size); pretty_print_buf(buf.u8, size); #endif retval = libusb_bulk_transfer(handle, ENDPOINT_OUT, buf.u8, size, &transferred, 0); if (retval != 0 || size != transferred) { printf("Error transmitting data %d\n", retval); } return retval; } static int wait_response(libusb_device_handle *handle, int *has_ack, int *size) { int retval; int transferred = 0; *has_ack = 0; *size = 0; do { retval = libusb_bulk_transfer(handle, ENDPOINT_IN, &buf.u8[*size], BUF_SIZE - *size, &transferred, 0); if (retval != 0) { printf("Error receiving data %d\n", retval); return retval; } if (transferred >= 1 && buf.c[0] == '+') *has_ack = 1; *size += transferred; } while ((*size < 3) || (buf.c[*size - 3] != '#')); #ifdef DEBUG printf("<<< received %d bytes\n", *size); pretty_print_buf(buf.u8, *size); #endif return retval; } static int checksum_and_send(libusb_device_handle *handle, size_t idx, int *xfer) { size_t i; uint8_t sum = 0; int retval, transferred; int has_ack; if (idx + SNPRINTF_OFFSET + END_LEN > BUF_SIZE) return LIBUSB_ERROR_NO_MEM; for (i = 1; i < idx; i++) sum += buf.u8[i]; idx += sprintf(buf.c + idx, END "%02x", sum); retval = send_command(handle, idx); if (retval) return retval; retval = wait_response(handle, &has_ack, &transferred); if (retval) return retval; if (!has_ack) return LIBUSB_ERROR_OTHER; if (xfer) *xfer = transferred; /* FIXME: validate transferred here? */ return retval; } static int send_u8_hex(libusb_device_handle *handle, const char *prefix, const char *bytes, size_t num_bytes) { size_t i, idx; /* Make sure that everything fits! * START + prefix + hex bytes + END + hex checksum + '\0' */ if (START_LEN + (prefix ? strlen(prefix) : 0) + (2 * num_bytes) + END_LEN + 1 > BUF_SIZE) return LIBUSB_ERROR_NO_MEM; idx = sprintf(buf.c, START "%s", prefix); for (i = 0; bytes && i < num_bytes; i++) idx += sprintf(buf.c + idx, "%02x", bytes[i]); return checksum_and_send(handle, idx, NULL); } static int send_u8_binary(libusb_device_handle *handle, const char *prefix, const char *bytes, size_t num_bytes) { size_t idx; /* Make sure that everything fits! * START + prefix + bytes + END + hex checksum + '\0' */ if (START_LEN + (prefix ? strlen(prefix) : 0) + num_bytes + END_LEN + 1 > BUF_SIZE) return LIBUSB_ERROR_NO_MEM; idx = sprintf(buf.c, START "%s", prefix); memcpy(buf.c + idx, bytes, num_bytes); idx += num_bytes; return checksum_and_send(handle, idx, NULL); } static int send_u32(libusb_device_handle *handle, const char *prefix, const uint32_t val, const char *suffix) { size_t idx = snprintf(buf.c, BUF_SIZE, START "%s%08x%s", prefix ? prefix : "", val, suffix ? suffix : ""); return checksum_and_send(handle, idx, NULL); } static int send_u32_u32(libusb_device_handle *handle, const char *prefix, const uint32_t val1, const char *infix, const uint32_t val2, const char *suffix) { size_t idx = snprintf(buf.c, BUF_SIZE, START "%s%08x%s%08x%s", prefix ? prefix : "", val1, infix ? infix : "", val2, suffix ? suffix : ""); return checksum_and_send(handle, idx, NULL); } static int send_mem_write(libusb_device_handle *handle, const uint32_t addr, const uint32_t val) { return send_u32_u32(handle, "X", addr, ",4:", val, NULL); } static int send_mem_read(libusb_device_handle *handle, const uint32_t addr, uint32_t *val) { int retval = send_u32(handle, "x", addr, ",4"); if (retval) return retval; if (val) { uint32_t u = 0; u |= buf.u8[8] << 24; u |= buf.u8[7] << 16; u |= buf.u8[6] << 8; u |= buf.u8[5]; *val = le32_to_cpu(u); } return 0; } static int send_flash_erase(libusb_device_handle *handle, const uint32_t start, const uint32_t end) { return send_u32_u32(handle, "vFlashErase:", start, ",", end, NULL); } static int send_flash_write(libusb_device_handle *handle, const uint32_t addr, const uint8_t *bytes, size_t len) { size_t i; char prefix[] = "vFlashWrite:12345678:"; char by, rawbuf[1024], *buf = rawbuf; sprintf(strchr(prefix, ':') + 1, "%08x:", addr); for (i = 0; i < len; i++) switch (by = bytes[i]) { case '#': case '$': case '}': *buf++ = '}'; by ^= 0x20; /* fall through */ default: if (buf >= rawbuf + sizeof(rawbuf)) return LIBUSB_ERROR_NO_MEM; *buf++ = by; break; } i = buf - rawbuf; return send_u8_binary(handle, prefix, rawbuf, i) ? -1 : i; } static int decode_buffer(char *inbuf, int insize, char *outbuf, int outsize) { int i; char by, *bp = outbuf; for (i = 0; i < insize; i++) { switch (by = inbuf[i]) { case '}': by = inbuf[++i] ^ 0x20; /* fall through */ default: if (bp >= outbuf + outsize) return LIBUSB_ERROR_NO_MEM; *bp++ = by; break; } } return 0; } static int send_flash_verify(libusb_device_handle *handle, const uint32_t addr, const uint8_t *bytes, size_t len) { size_t i, j; char rawbuf[1024]; int retval, transferred; size_t idx = snprintf(buf.c, BUF_SIZE, START "x%x,%x", addr, (uint32_t)len); retval = checksum_and_send(handle, idx, &transferred); if (retval) return retval; decode_buffer(buf.c, transferred, rawbuf, sizeof rawbuf); if (strncmp(rawbuf, "+$OK:", 5) != 0) return LIBUSB_ERROR_OTHER; for (i = 0, j = strlen("+$OK:"); i < len; i++, j++) { if (bytes[i] != (uint8_t)rawbuf[j]) { return LIBUSB_ERROR_OTHER; } } return 0; } static int print_icdi_version(libusb_device_handle *handle) { int retval = 0; char rawbuf[32]; size_t i, idx; int transferred = 0; const char *cmd = "version"; idx = sprintf(buf.c, START "qRcmd,"); for (i = 0; i < strlen(cmd); i++) idx += sprintf(buf.c + idx, "%02x", cmd[i]); retval = checksum_and_send(handle, idx, &transferred); if (retval) return retval; decode_buffer(buf.c, transferred, rawbuf, sizeof rawbuf); if (strncmp(rawbuf, "+$", 2) != 0) return LIBUSB_ERROR_OTHER; printf("ICDI version: "); for (i = strlen("+$"); rawbuf[i] != '#'; i += 2) { char r = rawbuf[i]; char c = (r <= '9') ? (r - '0') << 4 : (r - 'a' + 10) << 4; r = rawbuf[i+1]; c |= (r <= '9') ? r - '0' : r - 'a' + 10; printf("%c", c); } return 0; } #define SEND_COMMAND(cmd) do { \ int r = send_u8_hex(handle, "qRcmd,", (cmd), sizeof((cmd)) - 1); \ if (r) \ return r; \ } while (0) #define SEND_STRING(str) do { \ int r = send_u8_hex(handle, (str), NULL, 0); \ if (r) \ return r; \ } while (0) #define MEM_WRITE(address, value) do { \ int r = send_mem_write(handle, (address), (value)); \ if (r) \ return r; \ } while (0) #define MEM_READ(address, value) do { \ int r = send_mem_read(handle, (address), (value)); \ if (r) \ return r; \ } while (0) #define FLASH_ERASE(start, end) do { \ int r = send_flash_erase(handle, (start), (end)); \ if (r) \ return r; \ } while (0) #define FLASH_WRITE(address, data, length) do { \ int r = send_flash_write(handle, (address), (data), (length)); \ if (r < (length)) \ return LIBUSB_ERROR_OTHER; \ } while (0) /* * This flow is of commands is based on an USB capture of * traffic between LM Flash Programmer and the Stellaris Launchpad * when doing a firmware write */ static int write_firmware(libusb_device_handle *handle, FILE *f) { uint32_t val = 0; uint32_t addr; size_t rdbytes; int retval = 0; uint32_t size; print_icdi_version(handle); SEND_COMMAND("debug clock \0"); SEND_STRING("qSupported"); SEND_STRING("?"); MEM_WRITE(FP_CTRL, 0x3000000); MEM_READ(DID0, &val); MEM_READ(DID1, &val); SEND_STRING("?"); MEM_READ(DHCSR, &val); SEND_COMMAND("debug sreset"); MEM_READ(DHCSR, &val); MEM_READ(ROMCTL, &val); MEM_WRITE(ROMCTL, 0x0); MEM_READ(DHCSR, &val); MEM_READ(RCC, &val); MEM_READ(DID0, &val); MEM_READ(DID1, &val); MEM_READ(DC0, &val); MEM_READ(DID0, &val); MEM_READ(NVMSTAT, &val); MEM_WRITE(FMA, 0x0); MEM_READ(DHCSR, &val); if (erase_used) { fseek(f, 0, SEEK_END); size = ftell(f); for (addr = start_addr; addr < (start_addr + size); addr += FLASH_ERASE_SIZE) FLASH_ERASE(addr, FLASH_ERASE_SIZE); fseek(f, 0, SEEK_SET); } else { FLASH_ERASE(0, 0); } SEND_COMMAND("debug creset"); MEM_READ(DHCSR, &val); MEM_WRITE(DHCSR, 0x0); MEM_READ(ROMCTL, &val); MEM_WRITE(ROMCTL, 0x0); MEM_READ(DHCSR, &val); for (addr = start_addr; !feof(f); addr += sizeof(flash_block)) { rdbytes = fread(flash_block, 1, sizeof(flash_block), f); if (rdbytes < sizeof(flash_block) && !feof(f)) { perror("fread"); return LIBUSB_ERROR_OTHER; } /* * Avoid writing a buffer with zero-sized content which can * happen when the input file has a size multiple of flash_block */ if (rdbytes) FLASH_WRITE(addr, flash_block, rdbytes); } if (do_verify) { fseek(f, 0, SEEK_SET); for (addr = start_addr; !feof(f); addr += sizeof(flash_block)) { rdbytes = fread(flash_block, 1, sizeof(flash_block), f); if (rdbytes < sizeof(flash_block) && !feof(f)) { perror("fread"); return LIBUSB_ERROR_OTHER; } /* On error don't return immediately... finish resetting the board */ retval = send_flash_verify(handle, addr, flash_block, rdbytes); if (retval) { printf("Error verifying flash\n"); break; } } } SEND_COMMAND("set vectorcatch 0"); SEND_COMMAND("debug disable"); /* reset board */ MEM_WRITE(FP_CTRL, 0x3000000); SEND_COMMAND("debug hreset"); SEND_COMMAND("set vectorcatch 0"); SEND_COMMAND("debug disable"); return retval; } enum flasher_error { FLASHER_SUCCESS, FLASHER_ERR_LIBUSB_FAILURE, FLASHER_ERR_NO_DEVICES, FLASHER_ERR_MULTIPLE_DEVICES, }; static enum flasher_error flasher_find_matching_device( libusb_context *ctx, libusb_device **matching_device_out, enum libusb_error *libusb_error_out, int vendor_id, int product_id, const char *serial) { struct libusb_device_descriptor device_descriptor; #ifndef __APPLE__ char descriptor_buffer[256]; #endif libusb_device **device_list = NULL; libusb_device *matching_device = NULL; #ifndef __APPLE__ libusb_device_handle *handle; #endif enum flasher_error flasher_error; enum libusb_error libusb_error; int retval; int device_count; int device_index; /* Enumerate all USB devices */ retval = libusb_get_device_list(ctx, &device_list); if (retval < 0) { libusb_error = retval; flasher_error = FLASHER_ERR_LIBUSB_FAILURE; fprintf(stderr, "Unable to get enumerate USB devices: %s\n", libusb_error_name(libusb_error)); goto out; } else { device_count = retval; flasher_error = FLASHER_SUCCESS; libusb_error = LIBUSB_SUCCESS; } /* Assume no devices were found */ flasher_error = FLASHER_ERR_NO_DEVICES; /* Walk the list of devices and try to match some */ for (device_index = 0; device_index < device_count; ++device_index) { retval = libusb_get_device_descriptor( device_list[device_index], &device_descriptor); if (retval < 0) { fprintf(stderr, "Unable to get device descritor: %s\n", libusb_error_name(retval)); libusb_error = retval; flasher_error = FLASHER_ERR_LIBUSB_FAILURE; goto out; } /* Skip devices that have incorrect vendor and product IDs */ if (device_descriptor.idVendor != vendor_id || device_descriptor.idProduct != product_id) { continue; } #ifndef __APPLE__ /* Open each device so that we can read the serial number */ retval = libusb_open(device_list[device_index], &handle); if (retval < 0) { fprintf(stderr, "Unable to open USB device: %s\n", libusb_error_name(retval)); continue; } /* Read the serial number */ retval = libusb_get_string_descriptor_ascii( handle, device_descriptor.iSerialNumber, (unsigned char *)descriptor_buffer, sizeof descriptor_buffer); /* Close the handle as we won't need it below */ libusb_close(handle); if (retval < 0) { fprintf(stderr, "Unable to get device serial number: %s\n", libusb_error_name(retval)); continue; } printf("Found ICDI device with serial: %s\n", descriptor_buffer); /* Skip devices with serial that does not match */ if (serial != NULL && strcmp(serial, descriptor_buffer) != 0) continue; #endif if (matching_device == NULL) { flasher_error = FLASHER_SUCCESS; matching_device = device_list[device_index]; } else { /* If there's a device found already then abort */ flasher_error = FLASHER_ERR_MULTIPLE_DEVICES; /* Don't try returning arbitrary "first" device */ matching_device = NULL; goto out; } } out: /* Ref the matching device as we'll be returning it */ if (matching_device != NULL && matching_device_out != NULL) { libusb_ref_device(matching_device); *matching_device_out = matching_device; } /* Release the device list */ if (device_list != NULL) libusb_free_device_list(device_list, 1); /* Store libusb error if requested */ if (libusb_error_out != NULL) *libusb_error_out = libusb_error; /* Return the flasher error code */ return flasher_error; } static void flasher_usage() { printf("Usage: lm4flash [options] \n"); printf("\t-V\n"); printf("\t\tPrint version information\n"); printf("\t-h\n"); printf("\t\tPrint usage information\n"); printf("\t-v\n"); printf("\t\tEnables verification after write\n"); printf("\t-E\n"); printf("\t\tOnly erase blocks where binary file will be written\n"); printf("\t-S address\n"); printf("\t\tWrite binary at the given address (in hexadecimal)\n"); printf("\t-s SERIAL\n"); printf("\t\tFlash device with the following serial\n"); } static int flasher_flash(const char *serial, const char *rom_name) { libusb_context *ctx = NULL; libusb_device *device = NULL; libusb_device_handle *handle = NULL; int retval; FILE *f = NULL; retval = libusb_init(&ctx); if (retval != 0) { fprintf(stderr, "Error initializing libusb: %s\n", libusb_error_name(retval)); goto done; } switch (retval = flasher_find_matching_device( ctx, &device, &retval, ICDI_VID, ICDI_PID, serial)) { case FLASHER_SUCCESS: break; case FLASHER_ERR_LIBUSB_FAILURE: fprintf(stderr, "Error while matching ICDI devices: %s\n", libusb_error_name(retval)); goto done; case FLASHER_ERR_NO_DEVICES: fprintf(stderr, "Unable to find any ICDI devices\n"); goto done; case FLASHER_ERR_MULTIPLE_DEVICES: if (serial == NULL) fprintf(stderr, "Found multiple ICDI devices\n"); else fprintf(stderr, "Found ICDI serial number collision!\n"); goto done; } retval = libusb_open(device, &handle); if (retval != 0) { fprintf(stderr, "Error opening selected device: %s\n", libusb_error_name(retval)); goto done; } retval = libusb_claim_interface(handle, INTERFACE_NR); if (retval != 0) { fprintf(stderr, "Error claiming interface: %s\n", libusb_error_name(retval)); goto done; } f = fopen(rom_name, "rb"); if (!f) { perror("fopen"); retval = 1; goto done; } retval = write_firmware(handle, f); done: if (f) fclose(f); if (handle) libusb_close(handle); if (device) libusb_unref_device(device); if (ctx) libusb_exit(ctx); return retval; } int main(int argc, char *argv[]) { const char *serial = NULL; const char *rom_name = NULL; int opt; while ((opt = getopt(argc, argv, "VES:hvs:")) != -1) { switch (opt) { case 'V': show_version(); return 0; case 'h': flasher_usage(); return 0; case 'E': erase_used = 1; break; case 'S': start_addr = strtol(optarg, NULL, 16); /* force erasing only the used blocks */ erase_used = 1; break; case 'v': do_verify = 1; break; case 's': serial = optarg; break; default: flasher_usage(); return EXIT_FAILURE; } } if (optind >= argc) { flasher_usage(); return EXIT_FAILURE; } else rom_name = argv[optind]; if (start_addr && (start_addr % FLASH_ERASE_SIZE)) { printf("Address given to -S must be 0x%x aligned\n", FLASH_ERASE_SIZE); return EXIT_FAILURE; } return flasher_flash(serial, rom_name); } lm4tools-0.1.3/lmicdiusb/000077500000000000000000000000001325171702700152505ustar00rootroot00000000000000lm4tools-0.1.3/lmicdiusb/.gitignore000066400000000000000000000000341325171702700172350ustar00rootroot00000000000000*.o *.obj lmicdi lmicdi.exe lm4tools-0.1.3/lmicdiusb/Makefile000066400000000000000000000053601325171702700167140ustar00rootroot00000000000000#//***************************************************************************** #// #// Makefile - to build lmicdiusb utility #// #// Copyright (c) 2011-2012 Texas Instruments Incorporated. #// All rights reserved. #// #// Software License Agreement #// #// Redistribution and use in source and binary forms, with or without #// modification, are permitted provided that the following conditions #// are met: #// #// Redistributions of source code must retain the above copyright #// notice, this list of conditions and the following disclaimer. #// #// Redistributions in binary form must reproduce the above copyright #// notice, this list of conditions and the following disclaimer in the #// documentation and/or other materials provided with the #// distribution. #// #// Neither the name of Texas Instruments Incorporated nor the names of #// its contributors may be used to endorse or promote products derived #// from this software without specific prior written permission. #// #// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS #// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT #// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR #// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT #// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, #// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT #// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, #// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY #// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT #// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE #// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE #// #//***************************************************************************** ifeq ($(shell uname),Darwin) LIBUSB_CFLAGS := -I/usr/local/include/libusb-1.0 LIBUSB_LIBDIR := /usr/local/lib LIBUSB_LIBS := -lusb-1.0 LDFLAGS += -framework AppKit -framework Carbon -framework IOKit endif ifeq ($(shell uname),FreeBSD) LIBUSB_CFLAGS := LIBUSB_LIBDIR := /usr/lib LIBUSB_LIBS := -lusb endif ifeq ($(shell uname),Linux) LIBUSB_CFLAGS ?= $(shell pkg-config --cflags libusb-1.0) LIBUSB_LIBDIR ?= $(shell pkg-config --variable=libdir libusb-1.0) LIBUSB_LIBS ?= $(shell pkg-config --libs-only-l libusb-1.0) endif VPATH += $(LIBUSB_LIBDIR) LDFLAGS += -L$(LIBUSB_LIBDIR) -g CFLAGS += -Wall -g $(LIBUSB_CFLAGS) all: lmicdi lmicdi: lmicdi.o socket.o gdb.o $(LIBUSB_LIBS) lmicdi.o socket.o: lmicdi.h install: lmicdi ifndef PREFIX $(error PREFIX is not set) endif mkdir -p $(PREFIX)/bin install $^ $(PREFIX)/bin/ .PHONY: all clean clean: rm -rf lmicdi lmicdi.o socket.o gdb.o lm4tools-0.1.3/lmicdiusb/README000066400000000000000000000003641325171702700161330ustar00rootroot00000000000000This project demonstrates how to connect a TCP socket to the USB Bulk device on an LMICDI part. Once the socket and bulk xfer enpoints are connected, one can connect to the socket with an arm-gdb client. GDB to port 7777 It's that easy... lm4tools-0.1.3/lmicdiusb/commands.txt000066400000000000000000000033701325171702700176150ustar00rootroot00000000000000// This is the list of commands supported by the in circuit debugger on the // Stellaris LM4F120 LaunchPad. //Start Rcmd's *debug **mode - do nothing **disable - disable DAP **speed - argument < 5 **trace - do nothing **unlock - Perform Debug mass erase (factory reset) **sreset - System Reset **creset - core reset only **hreset - hardware pin reset *set **resettype - do nothing **vectorcatch - set or clear vector catch bit in the DAP accepts 1 or 0 **stepirq - set or clear the step irq bit in the DAP **xtal - set xtal value for Sandstorm, Fury and DustDevil, NOP for other classes *version - get version number of the firmware *dfu-update - jump to DFU bootloader. *mfg **setu0 - set user 0 register, used for serial #'s and MAC's. **setu1 - set user 1 register, used for serial #'s and MAC's. **getu0 - get user 0 register, used for serial #'s and MAC's. **getu1 - get user 1 register, used for serial #'s and MAC's. //END Rcmd's //Start regular commands *! -> extend mode *? -> halt core *A -> nothing *c -> start the core (continue) *C -> start the core (continue) *D -> Detach *F -> break *g -> send complete registers set *G -> nothing *H -> sends back empty response *i -> nothing *I -> nothing *m -> read memory *M -> write memory *p -> read register *P -> write register *q -> same as 'Q' *R -> reset and continue *s -> read state of DHCS? *S -> identical to s *t -> nothing *T -> nothing *x -> read memory binary *X -> write memory binary *z -> remove breakpoint *Z -> Add breakpoint *v **FlashErase **FlashWrite **FlashDone **Cont? -> send empty respsonse *Q -> query packets, ** supported -> gets info about the target and what it supports? ** Xfer -> send back the memory map ** Rcmd -> call GDBInterpretCommand which processes Rcmd's listed above. lm4tools-0.1.3/lmicdiusb/gdb.c000066400000000000000000000156501325171702700161570ustar00rootroot00000000000000//***************************************************************************** // // gdb.c - all the functions related to getting GDB protocol in and out of // libusb // // Copyright (c) 2011-2012 Texas Instruments Incorporated. // All rights reserved. // // Software License Agreement // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the // distribution. // // Neither the name of Texas Instruments Incorporated nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE // //***************************************************************************** #include "lmicdi.h" //**************************************************************************** // // calculates the checksum across the last GDB payload. Returns 0 if the // checksum is correct. 1 otherwise. // //**************************************************************************** static int gdb_validate() { // // TODO: Take payload and calculate checksum... // return 0; } static int hexchartoi(char c) { if ((c >= '0') && (c <= '9')) { return '0' - c; } if ((c >= 'a') && (c <= 'f')) { return 'a' - c + 10; } if ((c >= 'a') && (c <= 'f')) { return 'A' - c + 10; } return 0; } //**************************************************************************** // // handle 'len' bytes of 'pBuf' and advance the gdb state machine // accordingly. Handle packets in the format of ....$#nn // // When a complete packet has been received, call pFn passing the GDB // context structure and a boolean flag indicating whether or not the // checksum was valid. // //**************************************************************************** void gdb_statemachine(GDBCTX *pGdbCtx, unsigned char *pBuf, unsigned int len, void(*pFn)(GDBCTX*, int)) { while (len--) { switch(pGdbCtx->gdb_state) { case GDB_IDLE: TRACE(0, "GDB_IDLE: '%c'\n", *pBuf); if (*pBuf == '$') { pGdbCtx->gdb_state = GDB_PAYLOAD; } if (*pBuf == '+') { pGdbCtx->iAckCount++; } if (*pBuf == '-') { pGdbCtx->iNakCount++; } pGdbCtx->pResp[pGdbCtx->iRd++] = *pBuf; if (*pBuf == 0x03) { /* GDB Ctrl-C */ if (pFn) { pFn(pGdbCtx, 1); pGdbCtx->iRd = 0; } } pBuf++; break; case GDB_PAYLOAD: TRACE(0, "GDB_PAYLOAD: '%c' 0x%02x\n", isprint(*pBuf) ? *pBuf : '.', *pBuf); pGdbCtx->pResp[pGdbCtx->iRd++] = *pBuf; if (*pBuf == '#') { pGdbCtx->gdb_state = GDB_CSUM1; } pBuf++; break; case GDB_CSUM1: TRACE(0, "GDB_CSUM1: '%c'\n", *pBuf); pGdbCtx->csum = hexchartoi(*pBuf) << 4; pGdbCtx->gdb_state = GDB_CSUM2; pGdbCtx->pResp[pGdbCtx->iRd++] = *pBuf; pBuf++; break; case GDB_CSUM2: TRACE(0, "GDB_CSUM2: '%c'\n", *pBuf); pGdbCtx->csum |= hexchartoi(*pBuf); pGdbCtx->pResp[pGdbCtx->iRd++] = *pBuf; if (pFn) { if (gdb_validate(pGdbCtx->pResp, pGdbCtx->csum) == 0) { pFn(pGdbCtx, 1); } else { pFn(pGdbCtx, 0); } } pGdbCtx->iRd = 0; pGdbCtx->gdb_state = GDB_IDLE; pBuf++; break; } } } // // Grab the payload from the GDB context and call pass it over to the socket // handling code. // static void gdb_packet_from_usb(GDBCTX *pGdbCtx, int bCsumValid) { pGdbCtx->pResp[pGdbCtx->iRd] = 0; usbRxResp(pGdbCtx->pResp, pGdbCtx->iRd); } //**************************************************************************** // // This is the USB callback that gets called whenever our background read // operation RX'es anything from the USB devices (ie. the GDB server) // //**************************************************************************** void LIBUSB_CALL usb_callback(struct libusb_transfer *pTrans) { int rc; TRACE(1, "%s: enter\n", __FUNCTION__); // // Here we want to "digest" the received packet. Then, hopefully, // we can resubmit this same pTrans structure for the next receive // switch(pTrans->status) { case LIBUSB_TRANSFER_COMPLETED: // // Process whatever data we've RX'ed by invoking the GDB state // machine. When a complete GDB packet has been RX'ed the state // machine will call gdb_packet_from_usb. // gdb_statemachine(pTrans->user_data, pTrans->buffer, pTrans->actual_length, gdb_packet_from_usb); // // Requeue the async RX operation so that we catch the next packet // from the USB device // rc = libusb_submit_transfer(pTrans); if (rc != 0) { TRACE(ALWAYS, "%s: submit_transfer: rc = 0x%08x\n", __FUNCTION__, rc); } break; default: TRACE(ALWAYS, "%s: status = 0x%08x\n", __FUNCTION__, pTrans->status); break; } } lm4tools-0.1.3/lmicdiusb/license.txt000066400000000000000000000030401325171702700174300ustar00rootroot00000000000000Copyright (c) 2011-2012 Texas Instruments Incorporated. All rights reserved. Software License Agreement Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the original copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the original copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of Texas Instruments Incorporated nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. lm4tools-0.1.3/lmicdiusb/lmicdi.c000066400000000000000000000263701325171702700166650ustar00rootroot00000000000000//***************************************************************************** // // lmicdi.c - // // Copyright (c) 2011-2012 Texas Instruments Incorporated. // All rights reserved. // // Software License Agreement // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the // distribution. // // Neither the name of Texas Instruments Incorporated nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE // //***************************************************************************** #include "lmicdi.h" #include #include struct libusb_context *pCtx; #ifndef TRACE_LEVEL #define TRACE_LEVEL 2 #endif unsigned int gTraceLvl = TRACE_LEVEL; const struct libusb_endpoint_descriptor *pdEndpIn, *pdEndpOut; libusb_device_handle *phDev; unsigned char pResp[MSGSIZE]; void _dump_dev_strings(libusb_device_handle *phDev, struct libusb_device_descriptor *pdDev, const char *pIndent) { unsigned char pStr[256]; int rc; memset(pStr, 0, sizeof(pStr)); rc = libusb_get_string_descriptor_ascii(phDev, pdDev->iManufacturer, pStr, sizeof(pStr)); TRACE(2, "%sMFG'r string (index %d, len = %d) = '%s'\n", pIndent, pdDev->iManufacturer, rc, pStr); rc = libusb_get_string_descriptor_ascii(phDev, pdDev->iProduct, pStr, sizeof(pStr)); TRACE(2, "%sProduct string (index %d, len = %d) = '%s'\n", pIndent, pdDev->iProduct, rc, pStr); rc = libusb_get_string_descriptor_ascii(phDev, pdDev->iSerialNumber, pStr, sizeof(pStr)); TRACE(2, "%sProduct serial number (index %d, len = %d) = '%s'\n", pIndent, pdDev->iSerialNumber, rc, pStr); } void _dump_cfg_strings(libusb_device_handle *phDev, struct libusb_config_descriptor *pdCfg, const char *pIndent) { unsigned char pStr[256]; int rc; memset(pStr, 0, sizeof(pStr)); rc = libusb_get_string_descriptor_ascii(phDev, pdCfg->iConfiguration, pStr, sizeof(pStr)); TRACE(1, "%sConfig name (index %d, len = %d) = '%s'\n", pIndent, pdCfg->iConfiguration, rc, pStr); } void _dump_if_strings(libusb_device_handle *phDev, const struct libusb_interface_descriptor *pdIf, const char *pIndent) { unsigned char pStr[256]; int rc; memset(pStr, 0, sizeof(pStr)); rc = libusb_get_string_descriptor_ascii(phDev, pdIf->iInterface, pStr, sizeof(pStr)); TRACE(1, "%sInterface name (index %d, len = %d) = '%s'\n", pIndent, pdIf->iInterface, rc, pStr); } // // This is the GDB context for GDB responses from the USB target // unsigned char pUsbResp[MSGSIZE]; GDBCTX gdbUsbCtx = { GDB_IDLE, // gdb_state pUsbResp, // pResp 0, // iRd 0, // csum 0, // iAckCount 0 // iNakCount }; // // This is the transfer structure that maintains the USB read in // the background. // struct libusb_transfer *pTrans; //***************************************************************************** // //! Initializes the sample API. //! //! This function prepares the sample API for use by the application. //! //! \return None. // //***************************************************************************** int main(int argc, char *argv[]) { int rc; unsigned int iDev, iCfg, iIf, iAlt, iEndp; ssize_t nDevs; libusb_device **pDevices; libusb_device *pDev; struct libusb_config_descriptor *pdCfg; struct libusb_device_descriptor dDev; rc = libusb_init(&pCtx); ASSERT(rc == 0); // libusb_set_debug(pCtx, 5); nDevs = libusb_get_device_list(pCtx, &pDevices); TRACE(0, "nDevs = %d\n", (int)nDevs); ASSERT(nDevs >= 0); pDev = NULL; for (iDev = 0; iDev < nDevs; iDev++) { TRACE(0, "Considering device %d\n", iDev); // // Get the device descriptor so we know how many configurations there are // rc = libusb_get_device_descriptor(pDevices[iDev], &dDev); ASSERT(rc == 0); if ((dDev.idVendor == LMICDI_VID) && (dDev.idProduct == LMICDI_PID)) { pDev = pDevices[iDev]; TRACE(1, "Found device with matching VID and PID. pDev = %p\n", pDev); break; } } if (NULL == pDev) { fprintf(stderr, "No ICDI device with USB VID:PID %04x:%04x found!\n", LMICDI_VID, LMICDI_PID); return EXIT_FAILURE; } rc = libusb_open(pDev, &phDev); if (rc != 0) { TRACE(ALWAYS, "Failed to open device. rc = %d\n", rc); libusb_free_device_list(pDevices, 1); goto out; } // // NOTE: If/When we get here dDev should still be valid // // For each configuration... // for each interface... // for each alternate config for the interface... // for each endpoint... // for (iCfg = 0; iCfg < dDev.bNumConfigurations; iCfg++) { TRACE(1, D0 "iCfg = %d\n", iCfg); rc = libusb_get_config_descriptor(pDev, iCfg, &pdCfg); ASSERT(rc == 0); // // It seems as though we need to detach the kernel before we can read // strings for ourselves. // #if 0 for (iIf = 0; iIf < pdCfg->bNumInterfaces; iIf++) { rc = libusb_kernel_driver_active(phDev, iIf); TRACE(1, D1 "kernel_driver_active(if%d) = %d\n", iIf, rc); if (rc) { TRACE(1, D1 "Attempting to detach..."); rc = libusb_detach_kernel_driver(phDev, iIf); if (rc) { TRACE(1, " failed (%d)\n", rc); } else { bKernel[iIf] = 1; TRACE(1, " OK\n"); } } } #endif // // if the MFGr string is coming back as 0 then the device is wedged. // if (dDev.iManufacturer == 0) exit(EXIT_FAILURE); // // TODO: Figure out why some string indexes are coming back as 0 // // _dump_cfg_strings(phDev, pdCfg, D0); // _dump_dev_strings(phDev, &dDev, D0); for (iIf = 0; iIf < pdCfg->bNumInterfaces; iIf++) { const struct libusb_interface *pIf = &pdCfg->interface[iIf]; TRACE(1, D1 "iIf = %d\n", iIf); for (iAlt = 0; iAlt < pIf->num_altsetting; iAlt++) { const struct libusb_interface_descriptor *pdIf = &pIf->altsetting[iAlt]; TRACE(1, D2 "iAlt = %d\n", iAlt); _dump_if_strings(phDev, pdIf, D2); // // The "correct" thing to do would be to identify the // interface based on its name and string index but, at // the moment, the iInterface is coming back as 0. // Instead, we'll grab the interface that uses the // VENDOR_SPECIFIC class // if (pdIf->bInterfaceClass != LIBUSB_CLASS_VENDOR_SPEC) { continue; } // // The interface we're interested in should have two endpoints // if (pdIf->bNumEndpoints != 2) { continue; } rc = libusb_claim_interface(phDev, iIf); ASSERT(rc == 0); for (iEndp = 0; iEndp < pdIf->bNumEndpoints; iEndp++) { const struct libusb_endpoint_descriptor *pdEndp = &pdIf->endpoint[iEndp]; TRACE(1, D3 "iEndp = %d\n", iEndp); if ((pdEndp->bmAttributes & 0x3) != LIBUSB_TRANSFER_TYPE_BULK) { continue; } if ((pdEndp->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_IN) { TRACE(1, D3 "Found ENDPOINT_IN\n"); pdEndpIn = pdEndp; continue; } if ((pdEndp->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT) { TRACE(1, D3 "Found ENDPOINT_OUT\n"); pdEndpOut = pdEndp; continue; } // // We should never get here. An endpoint has to be either // in or out // TRACE(ALWAYS, "%s[%d]: Unexpected error\n", __FILE__, __LINE__); ASSERT(0); } goto found; } } } found: libusb_free_device_list(pDevices, 1); // // EXPERIMENT: Can we kick of an async receive and then do a // synchronous transmit? ANSWER: YES! // pTrans = libusb_alloc_transfer(0); ASSERT(pTrans != NULL); // // Set up a pending receive... // libusb_fill_bulk_transfer(pTrans, phDev, pdEndpIn->bEndpointAddress, pResp, sizeof(pResp), usb_callback, &gdbUsbCtx, 0); // // And wait for a RX operation to complete... // rc = libusb_submit_transfer(pTrans); if (rc != 0) { TRACE(ALWAYS, "%s: ERROR: submit_transfer rc = %d\n", __FUNCTION__, rc); } SocketIO(PORT, phDev); TRACE(1, "%s: libusb_release_interface\n", __FUNCTION__); libusb_release_interface(phDev, iIf); TRACE(1, "%s: libusb_close(phDev)\n", __FUNCTION__); libusb_close(phDev); out: TRACE(1, "%s: libusb_exit\n", __FUNCTION__); libusb_exit(pCtx); return(EXIT_SUCCESS); } lm4tools-0.1.3/lmicdiusb/lmicdi.h000066400000000000000000000105661325171702700166720ustar00rootroot00000000000000//***************************************************************************** // // lmicdi.h - // // Copyright (c) 2011-2012 Texas Instruments Incorporated. // All rights reserved. // // Software License Agreement // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the // distribution. // // Neither the name of Texas Instruments Incorporated nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE // //***************************************************************************** #include #include #include #include #include #include #include #include /* LIBUSB_CALL was introduced in libusb-1.0.9, which also fixes many bugs. * It's strongly recommended to not use any older version, but to be more * compatible let's include the LIBUSB_CALL definition here too. */ #ifndef LIBUSB_CALL #if defined(_WIN32) || defined(__CYGWIN__) #define LIBUSB_CALL WINAPI #else #define LIBUSB_CALL #endif #endif /* LIBUSB_CALL */ //***************************************************************************** // // MACROS // //***************************************************************************** // // Behavior related // #define PORT 7777 #define MSGSIZE 8192 // // Debug related // #define ASSERT assert #define LMICDI_VID 0x1cbe #define LMICDI_PID 0x00fd #define TRACE(LVL, ...) do { if ((LVL) >= gTraceLvl) { \ fprintf(stderr, __VA_ARGS__);} \ } while(0) #define ALWAYS -1 #define D0 "" #define D1 "\t" #define D2 "\t\t" #define D3 "\t\t\t" #define D4 "\t\t\t\t" //***************************************************************************** // // DATA TYPES // //***************************************************************************** typedef enum { GDB_IDLE, GDB_PAYLOAD, GDB_CSUM1, GDB_CSUM2 } GDB_STATE; typedef struct _GDBCTX { GDB_STATE gdb_state; unsigned char *pResp; unsigned int iRd; unsigned char csum; unsigned int iAckCount; unsigned int iNakCount; } GDBCTX; //***************************************************************************** // // GLOBALS // //***************************************************************************** extern struct libusb_context *pCtx; extern unsigned int gTraceLvl; extern const struct libusb_endpoint_descriptor *pdEndpIn, *pdEndpOut; extern libusb_device_handle *phDev; //***************************************************************************** // // FUNCTION PROTOTYPES // //***************************************************************************** extern int SocketIO(int iPort, libusb_device_handle *phDev); void LIBUSB_CALL usb_callback (struct libusb_transfer *pTrans); void gdb_send_ack(const char cAck); void usbRxResp(unsigned char *pResp, unsigned int len); void gdb_statemachine(GDBCTX *pGdbCtx, unsigned char *pBuf, unsigned int len, void(*pFn)(GDBCTX*, int)); lm4tools-0.1.3/lmicdiusb/socket.c000066400000000000000000000270151325171702700167110ustar00rootroot00000000000000//***************************************************************************** // // socket.c - // // Copyright (c) 2011-2012 Texas Instruments Incorporated. // All rights reserved. // // Software License Agreement // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the // distribution. // // Neither the name of Texas Instruments Incorporated nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE // //***************************************************************************** #include "lmicdi.h" #include #include #include #include static unsigned char pGdbReq[MSGSIZE]; // // This GDB context is for tracking the state of packets // which come over a TCP socket. That is to say, GDB // requests from the client. static GDBCTX gdbCliCtx = { GDB_IDLE, pGdbReq, 0, 0, 0, 0 }; static int sdAccept; // static unsigned char endpOut; static struct libusb_transfer *pTransReq; //***************************************************************************** // //! This is the callback for handling the transfer completion of the GDB ack //! //! \param pTrans is pointer to the usb transaction structure in which we //! transmitted the [N]ACK packet. //! //! \return None // //***************************************************************************** static void usb_req_callback(struct libusb_transfer *pTrans) { if (pTrans->status != LIBUSB_TRANSFER_COMPLETED) { TRACE(ALWAYS, "%s: Unable to send request (status = %d)\n", __FUNCTION__, pTrans->status); } else { TRACE(1, "%s: GDB REQ sent successfully\n", __FUNCTION__); } } // // After we receive a complete packet from a TCP socket we send it // off asynchronously. // static void usbTxReq(GDBCTX *pGdbCtx, int ack) { int rc; static char bInited = 0; if (!bInited) { // // Set up an async transfer to ack gdb responses... // pTransReq = libusb_alloc_transfer(0); ASSERT(pTransReq != NULL); pTransReq->dev_handle = phDev; pTransReq->flags = 0; pTransReq->endpoint = pdEndpOut->bEndpointAddress; pTransReq->type = LIBUSB_TRANSFER_TYPE_BULK; pTransReq->timeout = 1000; pTransReq->callback = usb_req_callback; pTransReq->num_iso_packets = 0; bInited = 1; } // // NOTE: There is a possible race condition here because USB may not // consume this buffer before we start writing to it. BUT // since the GDB protocol is inherently syncrhonous, I think // we avoid that scenario. // pGdbCtx->pResp[pGdbCtx->iRd] = 0; pTransReq->buffer = pGdbCtx->pResp; pTransReq->length = pGdbCtx->iRd; TRACE(0, "%s: '%s'\n", __FUNCTION__, pGdbCtx->pResp); rc = libusb_submit_transfer(pTransReq); // // TODO: handle the case where we don't send the whole packet... // if (rc != 0) { TRACE(ALWAYS, "%s: ERROR rc = %d\n", __FUNCTION__, rc); } TRACE(1, "%s: ...done\n", __FUNCTION__); } // // Whenever we receive a packet from USB (ie. the server) // send it over the TCP socket. // void usbRxResp(unsigned char *pResp, unsigned int len) { pResp[len] = 0; TRACE(1, "%s: '%s'\n", __FUNCTION__, pResp); send(sdAccept, pResp, len, 0); } // // Wait for a connection on iPort and return the // static int Listen(unsigned int iPort) { unsigned int addrlen; struct sockaddr_in sin; struct sockaddr_in pin; int so_reuseaddr = 1; int sdListen; // // Open an internet socket // if ((sdListen = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); return(-1); } // Attempt to set SO_REUSEADDR to avoid "address already in use" errors setsockopt(sdListen, SOL_SOCKET, SO_REUSEADDR, &so_reuseaddr, sizeof(so_reuseaddr)); // // Set up to listen on all interfaces/addresses and port iPort // memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = INADDR_ANY; sin.sin_port = htons(iPort); // // Bind out file descriptor to the port/address // TRACE(1, "bind to port %d\n", iPort); if (bind(sdListen, (struct sockaddr *) &sin, sizeof(sin)) == -1) { perror("bind"); return(-1); } // // Put the file descriptor in a state where it can listen for an // incoming connection // TRACE(1, "listen\n"); if (listen(sdListen, 1) == -1) { perror("listen"); return(-1); } // // Accept() will block until someone connects. In return it gives // us a new file descriptor back. // TRACE(1, "accept...\n"); addrlen = sizeof(pin); if ((sdAccept = accept(sdListen, (struct sockaddr *) &pin, &addrlen)) == -1) { perror("accept"); return(-1); } // // Close the file descriptor that we used for listening // close(sdListen); return sdAccept; } static int doGdb(int sdAccept, struct pollfd *pPollFds, int iFds) { static unsigned char pMsg[MSGSIZE]; ssize_t rx; int rc, iTimeoutms, i; struct timeval tv; rc = 0; while(1) { // // A bit of paranoia coding. Clear out the old buffer before rx'ing // the next packet // memset(pMsg, 0, sizeof(pMsg)); // // Figure out how long the timeout on our next poll will be. // rc = libusb_get_next_timeout(pCtx, &tv); if (rc == 0) { // // no timeouts are pending from usb. Force to 1ms. // iTimeoutms = 10; } else { unsigned long long usecs; if ((tv.tv_sec == 0) && (tv.tv_usec == 0)) { // // we were told we had a timeout with a 0 tv // that means something is already pending... // rc = libusb_handle_events(pCtx); ASSERT(rc == 0); } else { // // Convert the Secs + uSecs in the TV to millisecs. // usecs = tv.tv_sec * 1000000 + tv.tv_usec; iTimeoutms = usecs/1000; } } // // Here's the magic! Wait for something interesting to happen! // rc = poll(pPollFds, iFds, iTimeoutms); // // If we woke up because of a timeout, just go back to sleep... // (or if we have some other maintenance to do, here is the place // to do it) // if (rc == 0) continue; // // handle any errors // if (rc == -1) { TRACE(ALWAYS, "%s: poll() returned error\n", __FUNCTION__); break; } // // If we get here then one or more FD's need servicing... // for (i = 0; i < iFds; i++) { // // if revents is 0 then we don't care about this file descriptor // if (pPollFds[i].revents == 0) { // change to trace level 1 TRACE(1,"%s: Fd[%d].revents = 0\n", __FUNCTION__, i); continue; } // // Was it our TCP socket the kicked poll() out of its block? // if (pPollFds[i].fd == sdAccept) { TRACE(1,"%s: socketFd.revents = 0x%08x\n", __FUNCTION__, pPollFds[i].revents); // // Grab the packet payload... // rx = recv(sdAccept, pMsg, MSGSIZE, 0); if (rx < 0) { TRACE(ALWAYS, "%s: ERROR: recv() returned %d\n", __FUNCTION__, (int)rx); perror("recv() failed"); } else { TRACE(1, "%s: recv returned %d\n", __FUNCTION__, (int)rx); if (rx == 0) { // // if we RX 0 bytes it usually means that the other // side closed the connection // rc = 0; break; } gdb_statemachine(&gdbCliCtx, pMsg, rx, usbTxReq); } } // // If we get here it's because poll() kicked out, not because // of TCP activity, but because of USB activity. // else { TRACE(1, "%s: USB activity. Calling handle_events()\n", __FUNCTION__); rc = libusb_handle_events(pCtx); ASSERT(rc == 0); } } // (for all file descriptors) } // (while 1) // // We either encountered an error or the other side closed the connection. // Close our file handle and go back to listening for a new connection. // close(sdAccept); return rc; } int SocketIO(int iPort, libusb_device_handle *phDev) { int iCount, iFds; const struct libusb_pollfd **ppUsbFds; const struct libusb_pollfd **ppTmpFd; struct pollfd *pPollFds; ppTmpFd = ppUsbFds = libusb_get_pollfds(pCtx); // // find out how many USB FD's we have to poll // iCount = 0; while (*ppTmpFd++) { iCount++; } // // allocate iCount + 1 pollfd's to account for the socket // that we'll open below // pPollFds = calloc(iCount + 1, sizeof(struct pollfd)); ASSERT(pPollFds != NULL); for (iFds = 0; iFds < iCount; iFds++) { pPollFds[iFds].fd = (*(ppUsbFds[iFds])).fd; pPollFds[iFds].events = (*(ppUsbFds[iFds])).events; } while (1) { sdAccept = Listen(iPort); if (sdAccept > 0) { // // Set our socket as the last filedescriptor to poll // pPollFds[iFds].fd = sdAccept; pPollFds[iFds].events = POLLIN | POLLPRI | POLLRDNORM; // | POLLRDHUP; iFds++; // // Do the bridging between the socket and the usb bulk device // doGdb(sdAccept, pPollFds, iFds); } } return(0); }