use ref_name as release name
[mfgtools.git] / uuu / uuu.cpp
blob8018b33832d1b9dbee15585bd70956383ec36586
1 /*
2 * Copyright 2018 NXP.
4 * Redistribution and use in source and binary forms, with or without modification,
5 * are permitted provided that the following conditions are met:
7 * Redistributions of source code must retain the above copyright notice, this
8 * list of conditions and the following disclaimer.
10 * Redistributions in binary form must reproduce the above copyright notice, this
11 * list of conditions and the following disclaimer in the documentation and/or
12 * other materials provided with the distribution.
14 * Neither the name of the NXP Semiconductor nor the names of its
15 * contributors may be used to endorse or promote products derived from this
16 * software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
22 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 * POSSIBILITY OF SUCH DAMAGE.
32 #include <iostream>
33 #include <stdio.h>
34 #include <thread>
35 #include <atomic>
36 #include <iomanip>
37 #include <map>
38 #include <mutex>
39 #include <vector>
40 #include <sstream>
41 #include <fstream>
42 #include <stdarg.h>
43 #include <time.h>
44 #include <string.h>
45 #include <signal.h>
46 #include "buildincmd.h"
47 #include <string>
48 #include <streambuf>
50 #include "../libuuu/libuuu.h"
52 const char * g_vt_yellow = "\x1B[93m";
53 const char * g_vt_default = "\x1B[0m";
54 const char * g_vt_green = "\x1B[92m";
55 const char * g_vt_red = "\x1B[91m";
56 const char * g_vt_kcyn = "\x1B[36m";
57 const char * g_vt_boldwhite = "\x1B[97m";
59 void clean_vt_color() noexcept
61 g_vt_yellow = "";
62 g_vt_default = g_vt_yellow;
63 g_vt_green = g_vt_yellow;
64 g_vt_red = g_vt_yellow;
65 g_vt_kcyn = g_vt_yellow;
66 g_vt_boldwhite = g_vt_yellow;
69 using namespace std;
71 int get_console_width();
72 void print_oneline(string str);
73 int auto_complete(int argc, char**argv);
74 void print_autocomplete_help();
76 char g_sample_cmd_list[] = {
77 #include "uuu.clst"
80 vector<string> g_usb_path_filter;
82 int g_verbose = 0;
83 static bool g_start_usb_transfer;
85 class AutoCursor
87 public:
88 ~AutoCursor()
90 printf("\x1b[?25h\n\n\n");
94 void ctrl_c_handle(int)
96 do {
97 AutoCursor a;
98 } while(0);
100 exit(1);
103 class string_ex : public std::string
105 public:
106 int format(const char *fmt, ...)
108 va_list args;
109 va_start(args, fmt);
110 size_t len = std::vsnprintf(NULL, 0, fmt, args);
111 va_end(args);
113 this->resize(len);
115 va_start(args, fmt);
116 std::vsnprintf((char*)c_str(), len + 1, fmt, args);
117 va_end(args);
119 return 0;
123 #ifdef _WIN32
124 #include <conio.h>
125 #else
126 #include <termios.h>
127 #include <unistd.h>
128 #endif
130 int ask_passwd(char* prompt, char user[MAX_USER_LEN], char passwd[MAX_USER_LEN])
132 cout << endl << prompt << " Required Login"<<endl;
133 cout << "Username:";
134 cin.getline(user, 128);
135 cout << "Password:";
136 int i = 0;
138 #ifdef _WIN32
139 while ((passwd[i] = _getch()) != '\r') {
140 if (passwd[i] == '\b') {
141 if (i != 0) {
142 cout << "\b \b";
143 i--;
146 else {
147 cout << '*';
148 i++;
151 #else
152 struct termios old, tty;
153 tcgetattr(STDIN_FILENO, &tty);
154 old = tty;
155 tty.c_lflag &= ~ECHO;
156 tcsetattr(STDIN_FILENO, TCSANOW, &tty);
158 string pd;
159 getline(cin, pd);
161 tcsetattr(STDIN_FILENO, TCSANOW, &old);
162 if(pd.size() > MAX_USER_LEN -1)
163 return -1;
164 memcpy(passwd, pd.data(), pd.size());
165 i=pd.size();
167 #endif
168 passwd[i] = 0;
169 cout << endl;
170 return 0;
173 void print_help(bool detail = false)
175 const char help[] =
176 "uuu [-d -m -v -V] <" "bootloader|cmdlists|cmd" ">\n\n"
177 " bootloader download bootloader to board by usb\n"
178 " cmdlist run all commands in cmdlist file\n"
179 " If it is path, search uuu.auto in dir\n"
180 " If it is zip, search uuu.auto in zip\n"
181 " cmd Run one command, use -H see detail\n"
182 " example: SDPS: boot -f flash.bin\n"
183 " -d Daemon mode, wait for forever.\n"
184 " -v -V verbose mode, -V enable libusb error\\warning info\n"
185 " -dry Dry run mode, check if script or cmd correct \n"
186 " -m USBPATH Only monitor these paths.\n"
187 " -m 1:2 -m 1:3\n\n"
188 " -t Timeout second for wait known usb device appeared\n"
189 " -T Timeout second for wait next known usb device appeared at stage switch\n"
190 " -e set environment variable key=value\n"
191 " -pp usb polling period in milliseconds\n"
192 " -dm disable small memory\n"
193 "uuu -s Enter shell mode. uuu.inputlog record all input commands\n"
194 " you can use \"uuu uuu.inputlog\" next time to run all commands\n\n"
195 "uuu -udev linux: show udev rule to avoid sudo each time \n"
196 "uuu -lsusb List connected know devices\n"
197 "uuu -IgSerNum Set windows registry to ignore USB serial number for known uuu devices\n"
198 "uuu -h show general help\n"
199 "uuu -H show general help and detailed help for commands\n\n";
200 printf("%s", help);
201 printf("uuu [-d -m -v] -b[run] ");
202 g_BuildScripts.ShowCmds();
203 printf(" arg...\n");
204 printf("\tRun Built-in scripts\n");
205 g_BuildScripts.ShowAll();
206 printf("\nuuu -bshow ");
207 g_BuildScripts.ShowCmds();
208 printf("\n");
209 printf("\tShow built-in script\n");
210 printf("\n");
212 print_autocomplete_help();
214 if (detail == false)
215 return;
217 size_t start = 0, pos = 0;
218 string str= g_sample_cmd_list;
220 bool bprint = false;
221 while ((pos = str.find('\n',pos)) != str.npos)
223 string s = str.substr(start, pos - start);
224 if (s.substr(0, 6) == "# ----")
225 bprint = true;
227 if (bprint)
229 if (s[0] == '#')
231 printf("%s\n", &(s[1]));
234 pos += 1;
235 start = pos;
238 void print_version()
240 printf("uuu (Universal Update Utility) for nxp imx chips -- %s\n\n", uuu_get_version_string());
243 int print_cfg(const char *pro, const char * chip, const char * /*compatible*/, uint16_t vid, uint16_t pid, uint16_t bcdmin, uint16_t bcdmax, void * /*p*/)
245 const char *ext;
246 if (strlen(chip) >= 7)
247 ext = "";
248 else
249 ext = "\t";
251 if (bcdmin == 0 && bcdmax == 0xFFFF)
252 printf("\t%s\t %s\t%s 0x%04x\t 0x%04x\n", pro, chip, ext, vid, pid);
253 else
254 printf("\t%s\t %s\t%s 0x%04x\t 0x%04x\t [0x%04x..0x%04x]\n", pro, chip, ext, vid, pid, bcdmin, bcdmax);
255 return 0;
258 int print_udev_rule(const char * /*pro*/, const char * /*chip*/, const char * /*compatible*/,
259 uint16_t vid, uint16_t pid, uint16_t /*bcdmin*/, uint16_t /*bcdmax*/, void * /*p*/)
261 printf("SUBSYSTEM==\"usb\", ATTRS{idVendor}==\"%04x\", ATTRS{idProduct}==\"%04x\", TAG+=\"uaccess\"\n",
262 vid, pid);
263 return 0;
266 int polling_usb(std::atomic<int>& bexit);
268 int g_overall_status;
269 int g_overall_okay;
270 int g_overall_failure;
271 char g_wait[] = "|/-\\";
272 int g_wait_index;
275 string build_process_bar(size_t width, size_t pos, size_t total)
277 string str;
278 str.resize(width, ' ');
279 str[0] = '[';
280 str[width - 1] = ']';
282 if (total == 0)
284 if (pos == 0)
285 return str;
287 string_ex loc;
288 size_t s = pos / (1024 * 1024);
289 loc.format("%dM", s);
290 str.replace(1, loc.size(), loc);
291 return str;
294 size_t i;
296 if (pos > total)
297 pos = total;
299 for (i = 1; i < (width-2) * pos / total; i++)
301 str[i] = '=';
304 if (i > 1)
305 str[i] = '>';
307 if (pos == total)
308 str[str.size() - 2] = '=';
310 string_ex per;
311 per.format("%d%%", pos * 100 / total);
313 size_t start = (width - per.size()) / 2;
314 str.replace(start, per.size(), per);
315 str.insert(start, g_vt_yellow);
316 str.insert(start + per.size() + strlen(g_vt_yellow), g_vt_default);
317 return str;
320 void print_auto_scroll(string str, size_t len, size_t start)
322 if (str.size() <= len)
324 str.resize(len, ' ');
325 cout << str;
326 return;
329 if(str.size())
330 start = start % str.size();
331 else
332 start = 0;
334 string s = str.substr(start, len);
335 s.resize(len, ' ');
336 cout << s;
338 class ShowNotify
340 public:
341 string m_cmd;
342 string m_dev;
343 size_t m_trans_pos = 0;
344 int m_status = 0;
345 size_t m_cmd_total = 0;
346 size_t m_cmd_index = 0;
347 string m_last_err;
348 int m_done = 0;
349 size_t m_start_pos = 0;
350 size_t m_trans_size = 0;
351 clock_t m_start_time;
352 uint64_t m_cmd_start_time;
353 uint64_t m_cmd_end_time;
354 bool m_IsEmptyLine = false;
356 ShowNotify() : m_start_time{clock()} {}
358 bool update(uuu_notify nt)
360 if (nt.type == uuu_notify::NOTIFY_DEV_ATTACH)
362 m_dev = nt.str;
363 m_done = 0;
364 m_status = 0;
366 if (nt.type == uuu_notify::NOTIFY_CMD_START)
368 m_start_pos = 0;
369 m_cmd = nt.str;
370 m_cmd_start_time = nt.timestamp;
372 if (nt.type == uuu_notify::NOTIFY_DECOMPRESS_START)
374 m_start_pos = 0;
375 m_cmd = nt.str;
376 m_cmd_start_time = nt.timestamp;
377 m_dev = "Prep";
379 if (nt.type == uuu_notify::NOTIFY_DOWNLOAD_START)
381 m_start_pos = 0;
382 m_cmd = nt.str;
383 m_cmd_start_time = nt.timestamp;
384 m_dev = "Prep";
386 if (nt.type == uuu_notify::NOTIFY_DOWNLOAD_END)
388 m_IsEmptyLine = true;
390 if (nt.type == uuu_notify::NOTIFY_TRANS_SIZE || nt.type == uuu_notify::NOTIFY_DECOMPRESS_SIZE)
392 m_trans_size = nt.total;
393 return false;
395 if (nt.type == uuu_notify::NOTIFY_CMD_TOTAL)
397 m_cmd_total = nt.total;
398 return false;
400 if (nt.type == uuu_notify::NOTIFY_CMD_INDEX)
402 m_cmd_index = nt.index;
403 return false;
405 if (nt.type == uuu_notify::NOTIFY_DONE)
407 if (m_status)
408 g_overall_failure++;
409 else
410 g_overall_okay++;
412 m_done = 1;
414 if (nt.type == uuu_notify::NOTIFY_CMD_END)
416 m_cmd_end_time = nt.timestamp;
417 if(nt.status)
419 g_overall_status = nt.status;
420 m_last_err = uuu_get_last_err_string();
422 m_status |= nt.status;
423 if (m_status)
424 g_overall_failure++;
426 if (nt.type == uuu_notify::NOTIFY_TRANS_POS || nt.type == uuu_notify::NOTIFY_DECOMPRESS_POS)
428 if (m_trans_size == 0) {
430 m_trans_pos = nt.index;
431 return true;
434 if ((nt.index - m_trans_pos) < (m_trans_size / 100)
435 && nt.index != m_trans_size)
436 return false;
438 m_trans_pos = nt.index;
441 return true;
443 void print_verbose(uuu_notify*nt)
445 if (this->m_dev == "Prep" && g_start_usb_transfer)
446 return;
448 if (nt->type == uuu_notify::NOTIFY_DEV_ATTACH)
450 cout << "New USB Device Attached at " << nt->str << endl;
452 if (nt->type == uuu_notify::NOTIFY_CMD_START)
454 cout << m_dev << ">" << "Start Cmd:" << nt->str << endl;
456 if (nt->type == uuu_notify::NOTIFY_CMD_END)
458 double diff = m_cmd_end_time - m_cmd_start_time;
459 diff /= 1000;
460 if (nt->status)
462 cout << m_dev << ">" << g_vt_red <<"Fail " << uuu_get_last_err_string() << "("<< std::setprecision(4) << diff << "s)" << g_vt_default << endl;
464 else
466 cout << m_dev << ">" << g_vt_green << "Okay ("<< std::setprecision(4) << diff << "s)" << g_vt_default << endl;
470 if (nt->type == uuu_notify::NOTIFY_TRANS_POS || nt->type == uuu_notify::NOTIFY_DECOMPRESS_POS)
472 if (m_trans_size)
473 cout << g_vt_yellow << "\r" << m_trans_pos * 100 / m_trans_size <<"%" << g_vt_default;
474 else
475 cout << "\r" << m_trans_pos;
477 cout.flush();
480 if (nt->type == uuu_notify::NOTIFY_CMD_INFO)
481 cout << nt->str;
483 if (nt->type == uuu_notify::NOTIFY_WAIT_FOR)
484 cout << "\r" << nt->str << " "<< g_wait[((g_wait_index++) & 0x3)];
486 if (nt->type == uuu_notify::NOTIFY_DECOMPRESS_START)
487 cout << "Decompress file:" << nt->str << endl;
489 if (nt->type == uuu_notify::NOTIFY_DOWNLOAD_START)
490 cout << "Download file:" << nt->str << endl;
493 void print(int verbose = 0, uuu_notify*nt=NULL)
495 verbose ? print_verbose(nt) : print_simple();
497 string get_print_dev_string()
499 string str;
500 str = m_dev;
501 str.resize(8, ' ');
503 string_ex s;
504 s.format("%2d/%2d", m_cmd_index+1, m_cmd_total);
506 str += s;
507 return str;
509 void print_simple()
511 int width = get_console_width();
512 int info, bar;
513 info = 14;
514 bar = 40;
516 if (m_IsEmptyLine)
518 string str(width, ' ');
519 cout << str;
520 return;
522 if (width <= bar + info + 3)
524 string_ex str;
526 str += get_print_dev_string();
528 str += g_wait[(g_wait_index++) & 0x3];
530 print_oneline(str);
531 return ;
533 else
535 string_ex str;
536 str += get_print_dev_string();
538 str.resize(info, ' ');
539 cout << str;
541 if (m_done || m_status)
543 string str;
544 str.resize(bar, ' ');
545 str[0] = '[';
546 str[str.size() - 1] = ']';
547 string err;
548 if (m_status)
550 err = uuu_get_last_err_string();
551 err.resize(bar - 2, ' ');
552 str.replace(1, err.size(), err);
553 str.insert(1, g_vt_red);
554 str.insert(1 + strlen(g_vt_red) + err.size(), g_vt_default);
556 else
558 str.replace(1, 4, "Done");
559 str.insert(1, g_vt_green);
560 str.insert(1 + strlen(g_vt_green) + strlen("Done"), g_vt_default);
562 cout << str;
563 } else {
564 cout << build_process_bar(bar, m_trans_pos, m_trans_size);
566 cout << " ";
567 print_auto_scroll(m_cmd, width - bar - info-1, m_start_pos);
569 if (clock() - m_start_time > CLOCKS_PER_SEC / 4)
571 m_start_pos++;
572 m_start_time = clock();
574 cout << endl;
576 return;
581 static map<string, ShowNotify> g_map_path_nt;
582 mutex g_callback_mutex;
584 void print_oneline(string str)
586 size_t w = get_console_width();
587 if (w <= 3)
588 return;
590 if (str.size() >= w)
592 str.resize(w - 1);
593 str[str.size() - 1] = '.';
594 str[str.size() - 2] = '.';
595 str[str.size() - 3] = '.';
597 else
599 str.resize(w, ' ');
601 cout << str << endl;
605 ShowNotify Summary(map<uint64_t, ShowNotify> *np)
607 ShowNotify sn;
608 for (auto it = np->begin(); it != np->end(); it++)
610 if (it->second.m_dev == "Prep")
612 sn.m_trans_size += it->second.m_trans_size;
613 sn.m_trans_pos += it->second.m_trans_pos;
615 else
617 if (it->second.m_trans_pos || it->second.m_cmd_index)
618 g_start_usb_transfer = true; // Hidden HTTP download when USB start transfer
622 if(g_start_usb_transfer)
623 sn.m_IsEmptyLine = true; // Hidden HTTP download when USB start transfer
625 sn.m_dev = "Prep";
626 sn.m_cmd = "Http Download\\Uncompress";
627 return sn;
630 int progress(uuu_notify nt, void *p)
632 map<uint64_t, ShowNotify> *np = (map<uint64_t, ShowNotify>*)p;
633 map<string, ShowNotify>::iterator it;
635 std::lock_guard<std::mutex> lock(g_callback_mutex);
637 if ((*np)[nt.id].update(nt))
639 if (!(*np)[nt.id].m_dev.empty())
640 if ((*np)[nt.id].m_dev != "Prep")
641 g_map_path_nt[(*np)[nt.id].m_dev] = (*np)[nt.id];
643 if (g_verbose)
645 if((*np)[nt.id].m_dev == "Prep")
646 Summary(np).print(g_verbose, &nt);
647 else
648 (*np)[nt.id].print(g_verbose, &nt);
650 else
652 string_ex str;
653 str.format("\rSuccess %d Failure %d ", g_overall_okay, g_overall_failure);
655 if (g_map_path_nt.empty())
656 str += "Wait for Known USB Device Appear...";
658 if (!g_usb_path_filter.empty())
660 str += " at path ";
661 for (size_t i = 0; i < g_usb_path_filter.size(); i++)
662 str += g_usb_path_filter[i] + " ";
665 print_oneline(str);
666 print_oneline("");
667 if ((*np)[nt.id].m_dev == "Prep" && !g_start_usb_transfer)
669 Summary(np).print();
670 }else
671 print_oneline("");
673 for (it = g_map_path_nt.begin(); it != g_map_path_nt.end(); it++)
674 it->second.print();
676 for (size_t i = 0; i < g_map_path_nt.size() + 3; i++)
677 cout << "\x1B[1F";
681 //(*np)[nt.id] = g_map_path_nt[(*np)[nt.id].m_dev];
684 if (nt.type == uuu_notify::NOTIFY_THREAD_EXIT)
686 if(np->find(nt.id) != np->end())
687 np->erase(nt.id);
689 return 0;
691 #ifdef _MSC_VER
693 #define DEFINE_CONSOLEV2_PROPERTIES
694 #include <windows.h>
695 #include <stdlib.h>
696 #include <stdio.h>
698 bool enable_vt_mode()
700 // Set output mode to handle virtual terminal sequences
701 HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
702 if (hOut == INVALID_HANDLE_VALUE)
704 clean_vt_color();
705 return false;
708 DWORD dwMode = 0;
709 if (!GetConsoleMode(hOut, &dwMode))
711 clean_vt_color();
712 return false;
715 dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
716 if (!SetConsoleMode(hOut, dwMode))
718 clean_vt_color();
719 return false;
721 return true;
724 int get_console_width()
726 CONSOLE_SCREEN_BUFFER_INFO sbInfo;
727 GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &sbInfo);
728 return sbInfo.dwSize.X;
730 #else
731 #include <sys/ioctl.h>
732 bool enable_vt_mode() { return true; }
733 int get_console_width()
735 struct winsize w;
736 ioctl(0, TIOCGWINSZ, &w);
737 return w.ws_col;
739 #endif
740 void print_usb_filter()
742 if (!g_usb_path_filter.empty())
744 cout << " at path ";
745 for (size_t i = 0; i < g_usb_path_filter.size(); i++)
746 cout << g_usb_path_filter[i] << " ";
750 int runshell(int shell)
752 int uboot_cmd = 0;
753 string prompt = "U>";
755 if (shell)
757 cout << "Please input command: " << endl;
758 string cmd;
759 ofstream log("uuu.inputlog", ofstream::binary);
760 log << "uuu_version "
761 << ((uuu_get_version() & 0xFF000000) >> 24)
762 << "."
763 << ((uuu_get_version() & 0xFFF000) >> 12)
764 << "."
765 << ((uuu_get_version() & 0xFFF))
766 << endl;
767 while (1)
769 cout << prompt;
770 getline(cin, cmd);
772 if (cmd == "uboot")
774 uboot_cmd = 1;
775 prompt = "=>";
776 cout << "Enter into u-boot cmd mode" << endl;
777 cout << "Okay" << endl;
779 else if (cmd == "exit" && uboot_cmd == 1)
781 uboot_cmd = 0;
782 prompt = "U>";
783 cout << "Exit u-boot cmd mode" << endl;
784 cout << "Okay" << endl;
785 }else if (cmd == "help" || cmd == "?")
787 print_help();
789 else if (cmd == "q" || cmd == "quit")
791 return 0;
793 else
795 log << cmd << endl;
796 log.flush();
798 if (uboot_cmd)
799 cmd = "fb: ucmd " + cmd;
801 int ret = uuu_run_cmd(cmd.c_str(), 0);
802 if (ret)
803 cout << uuu_get_last_err_string() << endl;
804 else
805 cout << "Okay" << endl;
808 return 0;
811 return -1;
814 void print_udev()
816 uuu_for_each_cfg(print_udev_rule, NULL);
817 fprintf(stderr, "\n1: put above udev run into /etc/udev/rules.d/70-uuu.rules\n");
818 fprintf(stderr, "\tsudo sh -c \"uuu -udev >> /etc/udev/rules.d/70-uuu.rules\"\n");
819 fprintf(stderr, "2: update udev rule\n");
820 fprintf(stderr, "\tsudo udevadm control --reload\n");
823 int print_usb_device(const char *path, const char *chip, const char *pro, uint16_t vid, uint16_t pid, uint16_t bcd, void * /*p*/)
825 printf("\t%s\t %s\t %s\t 0x%04X\t0x%04X\t 0x%04X\n", path, chip, pro, vid, pid, bcd);
826 return 0;
829 void print_lsusb()
831 cout << "Connected Known USB Devices\n";
832 printf("\tPath\t Chip\t Pro\t Vid\t Pid\t BcdVersion\n");
833 printf("\t==================================================\n");
835 uuu_for_each_devices(print_usb_device, NULL);
838 #ifdef WIN32
840 int ignore_serial_number(const char *pro, const char *chip, const char */*comp*/, uint16_t vid, uint16_t pid, uint16_t /*bcdlow*/, uint16_t /*bcdhigh*/, void */*p*/)
842 printf("\t %s\t %s\t 0x%04X\t0x%04X\n", chip, pro, vid, pid);
844 char sub[128];
845 snprintf(sub, 128, "IgnoreHWSerNum%04x%04x", vid, pid);
846 const BYTE value = 1;
848 LSTATUS ret = RegSetKeyValueA(HKEY_LOCAL_MACHINE,
849 "SYSTEM\\CurrentControlSet\\Control\\UsbFlags",
850 sub, REG_BINARY, &value, 1);
851 if(ret == ERROR_SUCCESS)
852 return 0;
854 printf("Set key failure, try run as administrator permission\n");
855 return -1;
857 #endif
859 int set_ignore_serial_number()
861 #ifndef WIN32
862 printf("Only windows system need set ignore serial number registry");
863 return -1;
864 #else
865 printf("Set window registry to ignore usb hardware serial number for known uuu device:\n");
866 return uuu_for_each_cfg(ignore_serial_number, NULL);
867 #endif
870 int main(int argc, char **argv)
872 if (auto_complete(argc, argv) == 0)
873 return 0;
875 if (argc >= 2)
877 string s = argv[1];
878 if(s == "-udev")
880 print_udev();
881 return 0;
883 if (s == "-bshow")
885 if (2 == argc || g_BuildScripts.find(argv[2]) == g_BuildScripts.end())
887 fprintf(stderr, "Error, must be have script name: ");
888 g_BuildScripts.ShowCmds(stderr);
889 fprintf(stderr,"\n");
890 return -1;
892 else
894 string str = g_BuildScripts[argv[2]].m_text;
895 while (str.size() > 0 && (str[0] == '\n' || str[0] == ' '))
896 str = str.erase(0,1);
898 printf("%s", str.c_str());
899 return 0;
904 AutoCursor a;
906 print_version();
908 if (!enable_vt_mode())
910 cout << "Your console don't support VT mode, fail back to verbose mode" << endl;
911 g_verbose = 1;
914 if (argc == 1)
916 print_help();
917 return 0;
920 int deamon = 0;
921 int shell = 0;
922 string filename;
923 string cmd;
924 int ret;
925 int dryrun = 0;
927 string cmd_script;
929 for (int i = 1; i < argc; i++)
931 string s = argv[i];
932 if (!s.empty() && s[0] == '-')
934 if (s == "-d")
936 deamon = 1;
937 uuu_set_small_mem(0);
940 else if (s == "-dm")
942 uuu_set_small_mem(0);
944 else if (s == "-s")
946 shell = 1;
947 g_verbose = 1;
949 else if (s == "-v")
951 g_verbose = 1;
953 else if (s == "-V")
955 g_verbose = 1;
956 uuu_set_debug_level(2);
957 }else if (s == "-dry")
959 dryrun = 1;
960 g_verbose = 1;
962 else if (s == "-h")
964 print_help(false);
965 return 0;
967 else if (s == "-H")
969 print_help(true);
970 return 0;
972 else if (s == "-m")
974 i++;
975 uuu_add_usbpath_filter(argv[i]);
976 g_usb_path_filter.push_back(argv[i]);
978 else if (s == "-t")
980 i++;
981 uuu_set_wait_timeout(atoll(argv[i]));
983 else if (s == "-T")
985 i++;
986 uuu_set_wait_next_timeout(atoll(argv[i]));
988 else if (s == "-pp")
990 i++;
991 uuu_set_poll_period(atoll(argv[i]));
993 else if (s == "-lsusb")
995 print_lsusb();
996 return 0;
998 else if (s == "-IgSerNum")
1000 return set_ignore_serial_number();
1002 else if (s == "-e")
1004 #ifndef WIN32
1005 #define _putenv putenv
1006 #endif
1007 i++;
1008 if (_putenv(argv[i]))
1010 printf("error, failed to set '%s', environment parameter must have the form key=value\n", argv[i]);
1011 return -1;
1014 else if (s == "-b" || s == "-brun")
1016 if (i + 1 == argc)
1018 printf("error, must be have script name: ");
1019 g_BuildScripts.ShowCmds();
1020 printf("\n");
1021 return -1;
1024 vector<string> args;
1025 for (int j = i + 2; j < argc; j++)
1027 string s = argv[j];
1028 if (s.find(' ') != string::npos)
1030 s.insert(s.begin(), '"');
1031 s.insert(s.end(), '"');
1033 args.push_back(s);
1036 // if script name is not build-in, try to look for a file
1037 if (g_BuildScripts.find(argv[i + 1]) == g_BuildScripts.end()) {
1038 const string tmpCmdFileName{argv[i + 1]};
1040 std::ifstream t(tmpCmdFileName);
1041 std::string fileContents((std::istreambuf_iterator<char>(t)),
1042 std::istreambuf_iterator<char>());
1044 if (fileContents.empty()) {
1045 printf("%s is not built-in script or fail load external script file", tmpCmdFileName.c_str());
1046 return -1;
1049 BuiltInScriptRawData tmpCmd{
1050 tmpCmdFileName.c_str(),
1051 fileContents.c_str(),
1052 "Script loaded from file"
1055 g_BuildScripts.emplace(tmpCmdFileName, &tmpCmd);
1057 cmd_script = g_BuildScripts[tmpCmdFileName].replace_script_args(args);
1059 else {
1060 cmd_script = g_BuildScripts[argv[i + 1]].replace_script_args(args);
1062 break;
1064 else
1066 cout << "Unknown option: " << s.c_str();
1067 return -1;
1069 }else if (!s.empty() && s[s.size() - 1] == ':')
1071 for (int j = i; j < argc; j++)
1073 s = argv[j];
1074 if (s.find(' ') != string::npos && s[s.size() - 1] != ':')
1076 s.insert(s.begin(), '"');
1077 s.insert(s.end(), '"');
1079 cmd.append(s);
1080 if(j != (argc -1)) /* Don't add space at last arg */
1081 cmd.append(" ");
1083 break;
1085 else
1087 filename = s;
1088 break;
1092 signal(SIGINT, ctrl_c_handle);
1094 uuu_set_askpasswd(ask_passwd);
1096 if (deamon && shell)
1098 printf("Error: -d -s Can't apply at the same time\n");
1099 return -1;
1102 if (deamon && dryrun)
1104 printf("Error: -d -dry Can't apply at the same time\n");
1105 return -1;
1108 if (shell && dryrun)
1110 printf("Error: -dry -s Can't apply at the same time\n");
1111 return -1;
1114 if (g_verbose)
1116 printf("%sBuild in config:%s\n", g_vt_boldwhite, g_vt_default);
1117 printf("\tPctl\t Chip\t\t Vid\t Pid\t BcdVersion\n");
1118 printf("\t==================================================\n");
1119 uuu_for_each_cfg(print_cfg, NULL);
1121 if (!cmd_script.empty())
1122 printf("\n%sRun built-in script:%s\n %s\n\n", g_vt_boldwhite, g_vt_default, cmd_script.c_str());
1124 if (!shell)
1125 cout << "Wait for Known USB Device Appear...";
1127 print_usb_filter();
1129 printf("\n");
1131 else {
1132 cout << "Wait for Known USB Device Appear...";
1133 print_usb_filter();
1134 cout << "\r";
1135 cout << "\x1b[?25l";
1136 cout.flush();
1139 map<uint64_t, ShowNotify> nt_session;
1141 uuu_register_notify_callback(progress, &nt_session);
1144 if (!cmd.empty())
1146 ret = uuu_run_cmd(cmd.c_str(), dryrun);
1148 for (size_t i = 0; i < g_map_path_nt.size()+3; i++)
1149 printf("\n");
1150 if(ret)
1151 printf("\nError: %s\n", uuu_get_last_err_string());
1152 else
1153 printf("Okay\n");
1155 runshell(shell);
1156 return ret;
1159 if (!cmd_script.empty())
1160 ret = uuu_run_cmd_script(cmd_script.c_str(), dryrun);
1161 else
1162 ret = uuu_auto_detect_file(filename.c_str());
1164 if (ret)
1166 ret = runshell(shell);
1167 if(ret)
1168 cout << g_vt_red << "\nError: " << g_vt_default << uuu_get_last_err_string();
1169 return ret;
1172 if (uuu_wait_uuu_finish(deamon, dryrun))
1174 cout << g_vt_red << "\nError: " << g_vt_default << uuu_get_last_err_string();
1175 return -1;
1178 runshell(shell);
1180 /*Wait for the other thread exit, after send out CMD_DONE*/
1181 std::this_thread::sleep_for(std::chrono::milliseconds(100));
1182 if(!g_verbose)
1183 printf("\n\n\n");
1184 return g_overall_status;