94cd7e74df7f1ab884b83abc196c663c8991133d
[fw/openocd] / src / jtag / drivers / jtag_usb_common.c
1 /*
2  * SPDX-License-Identifier: GPL-2.0+
3  * Copyright (c) 2018 Pengutronix, Oleksij Rempel <kernel@pengutronix.de>
4  */
5
6 #include <helper/log.h>
7 #include <string.h>
8
9 #include "jtag_usb_common.h"
10
11 static char *jtag_usb_location;
12 /*
13  * 1 char: bus
14  * 2 * 7 chars: max 7 ports
15  * 1 char: test for overflow
16  * ------
17  * 16 chars
18  */
19 #define JTAG_USB_MAX_LOCATION_LENGTH    16
20
21 void jtag_usb_set_location(const char *location)
22 {
23         if (strnlen(location, JTAG_USB_MAX_LOCATION_LENGTH) ==
24             JTAG_USB_MAX_LOCATION_LENGTH)
25                 LOG_WARNING("usb location string is too long!!\n");
26
27         free(jtag_usb_location);
28
29         jtag_usb_location = strndup(location, JTAG_USB_MAX_LOCATION_LENGTH);
30 }
31
32 const char *jtag_usb_get_location(void)
33 {
34         return jtag_usb_location;
35 }
36
37 bool jtag_usb_location_equal(uint8_t dev_bus, uint8_t *port_path,
38                              size_t path_len)
39 {
40         size_t path_step, string_length;
41         char *ptr, *loc;
42         bool equal = false;
43
44         /* strtok need non const char */
45         loc = strndup(jtag_usb_get_location(), JTAG_USB_MAX_LOCATION_LENGTH);
46         string_length = strnlen(loc, JTAG_USB_MAX_LOCATION_LENGTH);
47
48         ptr = strtok(loc, "-");
49         if (!ptr) {
50                 LOG_WARNING("no '-' in usb path\n");
51                 goto done;
52         }
53
54         string_length -= strnlen(ptr, string_length);
55         /* check bus mismatch */
56         if (atoi(ptr) != dev_bus)
57                 goto done;
58
59         path_step = 0;
60         while (path_step < path_len) {
61                 ptr = strtok(NULL, ".");
62
63                 /* no more tokens in path */
64                 if (!ptr)
65                         break;
66
67                 /* path mismatch at some step */
68                 if (path_step < path_len && atoi(ptr) != port_path[path_step])
69                         break;
70
71                 path_step++;
72                 string_length -= strnlen(ptr, string_length) + 1;
73         };
74
75         /* walked the full path, all elements match */
76         if (path_step == path_len && !string_length)
77                 equal = true;
78
79 done:
80         free(loc);
81         return equal;
82 }