]> cloudbase.mooo.com Git - z180-stamp.git/blob - avr/env.c
Find subcommands without prefix
[z180-stamp.git] / avr / env.c
1 /*
2 * (C) Copyright 2014 Leo C. <erbl259-lmu@yahoo.de>
3 *
4 * SPDX-License-Identifier: GPL-2.0
5 */
6
7 #include "env.h"
8 #include <avr/eeprom.h>
9
10 #include "config.h"
11 #include "debug.h"
12 #include "xmalloc.h"
13 #include "crc.h"
14 #include "getopt-min.h"
15
16
17 #define ENV_SIZE (CONFIG_ENV_SIZE - sizeof(uint16_t) -1)
18 #define ACTIVE_FLAG 1
19 #define OBSOLETE_FLAG 0
20
21 #define ENVLIST_DELETE (1<<0)
22
23
24 /*
25 * Default Environment
26 */
27
28 #define DELIM "\0"
29
30 const FLASH char default_env[] = {
31 ENV_BAUDRATE "=" "115200" DELIM
32 ENV_BOOTDELAY "=" "3" DELIM
33 ENV_BOOTCMD "=" "pin ${pins}; loadcpm3; go ${startaddress}" DELIM
34 ENV_CPM3_SYSFILE "=" CONFIG_CPM3_SYSFILE DELIM
35 ENV_PINALIAS "=" "0:PG5,1:PG4,2:PB4,3:PB5,4:PB6,5:PB7,"
36 "6:PG3,7:PG2,8:PG1,9:PG0,10:PE7" DELIM
37 ENV_STARTADDRESS "=" "0" DELIM
38 "pins" "=" "2,8 low 9 high 3 2" DELIM
39 DELIM
40 };
41
42
43 /* EEPROM storage */
44 typedef struct environment_s {
45 uint16_t crc; /* CRC16 over data bytes */
46 uint8_t flags; /* active/obsolete flags */
47 char data[ENV_SIZE]; /* Environment data */
48 } env_t;
49
50
51 /* */
52 typedef struct env_item_s {
53 char * envvar;
54 } env_item_t;
55
56
57 static uint8_t env_valid;
58 static env_item_t env_list[CONFIG_ENVVAR_MAX];
59 static int entrycount;
60
61
62 static
63 char env_get_char(uint16_t index)
64 {
65 unsigned int off = CONFIG_ENV_OFFSET;
66 char ret;
67
68 switch (env_valid) {
69 case 2:
70 off += CONFIG_ENV_SIZE;
71 case 1:
72 ret = (char) eeprom_read_byte((const uint8_t *)off + index +
73 offsetof(env_t, data));
74 break;
75
76 default:
77 ret = default_env[index];
78 }
79
80 return ret;
81 }
82
83
84 static const FLASH char *comp_key;
85
86 static
87 int comp_env_items(const void *m1, const void *m2)
88 {
89 env_item_t *ep1 = (env_item_t *) m1;
90 env_item_t *ep2 = (env_item_t *) m2;
91
92 if (ep1 == NULL)
93 return - strcmp_P(ep2->envvar, comp_key);
94 else
95 return strcmp(ep1->envvar, ep2->envvar);
96 }
97
98
99 env_item_t *envlist_search(const MEMX char *name)
100 {
101 #ifdef __MEMX
102 if (__builtin_avr_flash_segment(name) != -1) {
103 comp_key = name;
104 return bsearch(0, env_list, entrycount,
105 sizeof(env_item_t), comp_env_items);
106 } else {
107
108 env_item_t e;
109 e.envvar = (char *) name;
110
111 return bsearch(&e, env_list, entrycount,
112 sizeof(env_item_t), comp_env_items);
113 }
114 #else
115 env_item_t e;
116 e.envvar = (char *) name;
117
118 return bsearch(&e, env_list, entrycount,
119 sizeof(env_item_t), comp_env_items);
120 #endif /* __MEMX */
121 }
122
123
124 static
125 env_item_t *envlist_enter(env_item_t *e)
126 {
127 const size_t size = sizeof(env_item_t);
128 env_item_t *ep;
129
130 ep = bsearch(e, env_list, entrycount,
131 size, comp_env_items);
132
133 if (ep == NULL) {
134 if (entrycount < CONFIG_ENVVAR_MAX) {
135
136 env_list[entrycount++] = *e;
137 qsort(env_list, entrycount, size, comp_env_items);
138 ep = bsearch(e, env_list, entrycount,
139 size, comp_env_items);
140 }
141 } else {
142 free(ep->envvar);
143 ep->envvar = e->envvar;
144 }
145
146 return ep;
147 }
148
149
150 static
151 int env_item_delete(env_item_t *ep)
152 {
153 if (entrycount == 0)
154 return -1;
155
156 free(ep->envvar);
157
158 entrycount--;
159 size_t size = sizeof(env_item_t);
160 memmove(ep, ep + 1, (env_list - ep)*size + entrycount*size);
161
162 return 0;
163 }
164
165 static
166 int envlist_delete(const MEMX char *name)
167 {
168 env_item_t *ep = envlist_search(name);
169
170 if (ep != NULL)
171 return env_item_delete(ep);
172
173 return 1;
174 }
175
176
177
178 static
179 int envlist_import(uint8_t flags)
180 {
181 uint16_t index;
182
183 int len;
184 env_item_t e;
185 char *np, c;
186 uint_fast8_t ef;
187
188 if ((flags & ENVLIST_DELETE) != 0)
189 while (entrycount != 0)
190 env_item_delete(&env_list[entrycount-1]);
191
192 for (index = 0; env_get_char(index) != '\0'; ) {
193 for (len = 0; env_get_char(index + len) != '\0'; ++len) {
194 if ((index + len) >= ENV_SIZE)
195 return -1;
196 }
197
198 np = (char *) xmalloc(len+1);
199 if (np == NULL) {
200 printf_P(PSTR("## Can't malloc %d bytes\n"), len+1);
201 return 1;
202 }
203 e.envvar = np;
204 ef = 0;
205 while ((c = env_get_char(index++)) != '\0') {
206 if (!ef && (c == '=')) {
207 *np = '\0';
208 ef = 1;
209 } else
210 *np = c;
211 np++;
212 }
213 *np = '\0';
214 envlist_enter(&e);
215 }
216
217
218 return 0;
219 }
220
221
222 static
223 uint16_t env_crc(uint16_t data_offset)
224 {
225 uint16_t crc;
226 uint16_t i;
227 char c, c0;
228
229 crc = 0xffff;
230 c = 0xff;
231 for (i = 0; !(c == 0 && c0 == 0) && i < ENV_SIZE; i++)
232 {
233 c0 = c;
234 c = eeprom_read_byte((const uint8_t *) data_offset + i);
235 crc = crc16(crc, c);
236 }
237 return crc ;
238 }
239
240
241 /**
242 * return valid env
243 */
244 static
245 int env_check_valid(void)
246 {
247 const uint16_t offset[2] = {CONFIG_ENV_OFFSET,
248 CONFIG_ENV_OFFSET + CONFIG_ENV_SIZE};
249 uint_fast8_t flags[2], crc_ok[2];
250 int rc;
251
252 /* read FLAGS */
253 flags[0] = eeprom_read_byte ((uint8_t *) offset[0] +
254 offsetof(env_t, flags));
255 flags[1] = eeprom_read_byte ((uint8_t *) offset[1] +
256 offsetof(env_t, flags));
257
258 /* check CRC */
259 crc_ok[0] = (
260 eeprom_read_word((uint16_t *) offset[0] +
261 offsetof(env_t, crc))
262 == env_crc(offset[0] + offsetof(env_t, data))
263 );
264 crc_ok[1] = (
265 eeprom_read_word((uint16_t *) offset[1] +
266 offsetof(env_t, crc))
267 == env_crc(offset[1] + offsetof(env_t, data))
268 );
269
270 if (!crc_ok[0] && !crc_ok[1]) {
271 rc = 0;
272
273 } else if (crc_ok[0] && !crc_ok[1]) {
274 rc = 1;
275 } else if (!crc_ok[0] && crc_ok[1]) {
276 rc = 2;
277 } else {
278 /* both ok - check serial */
279 #if 1
280 if (flags[1] == ACTIVE_FLAG && flags[0] != ACTIVE_FLAG)
281 rc = 2;
282 else if (flags[1] == OBSOLETE_FLAG && flags[0] == 0xFF)
283 rc = 2;
284 else
285 rc = 1;
286 #else
287 if (flags[0] == ACTIVE_FLAG && flags[1] == OBSOLETE_FLAG)
288 rc = 1;
289 else if (flags[0] == OBSOLETE_FLAG && flags[1] == ACTIVE_FLAG)
290 rc = 2;
291 else if (flags[0] == 0xFF && flags[1] == 0)
292 rc = 2;
293 else if (flags[1] == 0xFF && flags[0] == 0)
294 rc = 1;
295 else /* flags are equal - almost impossible */
296 rc = 1;
297 #endif
298 }
299
300 return rc;
301 }
302
303
304 int env_init(void)
305 {
306 env_valid = env_check_valid();
307 if (env_valid == 0) {
308 printf_P(PSTR("*** Warning - bad CRC, "
309 "using default environment\n\n"));
310 }
311
312 envlist_import(ENVLIST_DELETE);
313 return 0;
314 }
315
316
317 char *getenv_str(const MEMX char *name)
318 {
319 env_item_t *ep;
320 char *ret = NULL;
321
322 ep = envlist_search(name);
323 if (ep != NULL)
324 ret = ep->envvar + strlen(ep->envvar) +1;
325 return ret;
326 }
327
328 static
329 int env_item_save(env_item_t *ep, uint16_t offset, int space_left)
330 {
331 int nlen, vlen;
332 char *var = ep->envvar;
333
334 nlen = strlen(var);
335 if (nlen == 0)
336 return 0;
337 vlen = strlen(var + nlen + 1);
338 if (vlen == 0)
339 return 0;
340 if (nlen + vlen + 2 > space_left)
341 return 0;
342
343 eeprom_update_block(var, (uint8_t *) offset, nlen);
344 offset += nlen;
345 eeprom_update_byte((uint8_t *) offset++, '=');
346 eeprom_update_block(var + nlen +1, (uint8_t *) offset, vlen+1);
347
348 return nlen + vlen + 2;
349 }
350
351
352 static
353 int saveenv(void)
354 {
355 unsigned int off = CONFIG_ENV_OFFSET + CONFIG_ENV_SIZE;
356 unsigned int off_red = CONFIG_ENV_OFFSET;
357 unsigned int pos;
358 int len, left;
359 uint16_t crc;
360 int rc = 0;
361
362 if (env_valid == 2) {
363 off = CONFIG_ENV_OFFSET;
364 off_red = CONFIG_ENV_OFFSET + CONFIG_ENV_SIZE;
365 }
366
367 eeprom_update_byte((uint8_t *) off + offsetof(env_t, flags), 0xff);
368
369 pos = off + offsetof(env_t, data);
370 left = ENV_SIZE - 1;
371 for (int i = 0 ; i < entrycount; i++) {
372 len = env_item_save(&env_list[i], pos, left);
373 if (len == 0) {
374 return 1;
375 }
376 pos += len;
377 left -= len;
378 }
379 /* terminate list */
380 eeprom_update_byte((uint8_t *) pos, 0);
381 crc = env_crc(off + offsetof(env_t, data));
382 eeprom_update_word((uint16_t *) off + offsetof(env_t, crc), crc);
383 eeprom_update_byte((uint8_t *) off + offsetof(env_t, flags),
384 ACTIVE_FLAG);
385
386 if (rc == 0) {
387 eeprom_update_byte((uint8_t *) off_red + offsetof(env_t, flags),
388 OBSOLETE_FLAG);
389 env_valid = (env_valid == 2) ? 1 : 2;
390 }
391
392 return rc;
393 }
394
395
396 static
397 int env_item_print(env_item_t *ep, bool mode)
398 {
399 int len;
400 char *ev = ep->envvar;
401
402 if (mode) {
403 len = printf_P(PSTR("setenv %s "), ev) - 7;
404 len += printf_P(PSTR("'%s'\n"), ev + len) - 2;
405 } else {
406 len = printf_P(PSTR("%s="), ev);
407 len += printf_P(PSTR("%s\n"), ev + len);
408 }
409 return len;
410 }
411
412
413 /*
414 * Command interface: print one or all environment variables
415 *
416 * Returns -1 in case of error, or length of printed string
417 */
418 static
419 int env_print(const MEMX char *name, bool mode)
420 {
421 int len = -1;
422
423 if (name) { /* print a single name */
424
425 env_item_t *ep = envlist_search(name);
426 if (ep != NULL)
427 len = env_item_print(ep, mode);
428
429 } else { /* print whole list */
430 len = 0;
431 for (int i = 0 ; i < entrycount; i++) {
432 len += env_item_print(&env_list[i], mode);
433 }
434 }
435 return len;
436 }
437
438
439 /**
440 * Set or delete environment variable
441 *
442 * Set a new environment variable,
443 * or replace or delete an existing one.
444 *
445 * @param flag (not used)
446 * @param argc
447 * @param argv[1] Environment variable to set or delete
448 * if no more args
449 * @param argv[2] ... Value to set it to
450 *
451 * @return 0 if ok, 1 on error
452 */
453 static
454 command_ret_t _do_env_set(uint_fast8_t flag, int argc, char * const argv[])
455 {
456 int i, len;
457 char *name, *value, *valp, *p;
458 env_item_t e, *ep;
459
460 (void) flag;
461
462 name = argv[1];
463 value = argv[2];
464
465 if (strchr(name, '=')) {
466 printf_P(PSTR("## Error: illegal character '='"
467 "in variable name \"%s\"\n"), name);
468 return CMD_RET_FAILURE;
469 }
470 len = strlen(name);
471 if (len > CONFIG_SYS_ENV_NAMELEN) {
472 printf_P(PSTR("## Error: Variable name \"%s\" too long. "
473 "(max %d characters)\n"), name, CONFIG_SYS_ENV_NAMELEN);
474 return CMD_RET_FAILURE;
475 }
476 /*
477 env_id++;
478 */
479 /* Delete only ? */
480 if (argc < 3 || argv[2] == NULL) {
481 int rc = envlist_delete(name);
482 return rc ? CMD_RET_FAILURE : CMD_RET_SUCCESS;
483 }
484
485 /*
486 * Insert / replace new value
487 */
488 for (i = 2, len += 1; i < argc; ++i)
489 len += strlen(argv[i]) + 1;
490
491 value = xmalloc(len);
492 if (value == NULL) {
493 printf_P(PSTR("## Can't malloc %d bytes\n"), len);
494 return CMD_RET_FAILURE;
495 }
496 strcpy(value, name);
497 valp = value + strlen(name) + 1;
498 for (i = 2, p = valp; i < argc; ++i) {
499 char *v = argv[i];
500
501 while ((*p++ = *v++) != '\0')
502 ;
503 *(p - 1) = ' ';
504 }
505 if (p != valp)
506 *--p = '\0';
507
508 e.envvar = value;
509 ep = envlist_enter(&e);
510 if (!ep) {
511 printf_P(PSTR("## Error inserting \"%s\" variable.\n"),
512 name);
513 return CMD_RET_FAILURE;
514 }
515
516 return CMD_RET_SUCCESS;
517 }
518
519 /**
520 * Set an environment variable
521 *
522 * @param varname Environment variable to set
523 * @param varvalue Value to set it to
524 * @return 0 if ok, 1 on error
525 */
526 static
527 int setenv(const MEMX char *varname, const char *varvalue)
528 {
529 int rc;
530
531 #ifdef __MEMX
532 char *tmpname = NULL;
533 if (__builtin_avr_flash_segment(varname) != -1) {
534 tmpname = malloc(strlen_P(varname)+1);
535 if (tmpname == NULL) {
536 printf_P(PSTR("setenv: Out of Memory!\n"));
537 return 1;
538 }
539 strcpy_P(tmpname, varname);
540 } else
541 tmpname = (char *) varname;
542 #endif
543
544 const char * const argv[3] = { NULL, tmpname, varvalue };
545 int argc = 3;
546
547 if (varvalue == NULL || varvalue[0] == '\0')
548 --argc;
549
550 rc = (int) _do_env_set(0, argc, (char * const *)argv);
551
552 #ifdef __MEMX
553 free(tmpname);
554 #endif
555 return rc;
556 }
557
558 /**
559 * Set an environment variable to an integer value
560 *
561 * @param name Environment variable to set
562 * @param value Value to set it to
563 * @param radix Base
564 * @return 0 if ok, 1 on error
565 */
566 static
567 int setenv_intval(const MEMX char *name, unsigned long value, int radix)
568 {
569 char buf[11];
570
571 ultoa(value, buf, radix);
572
573 return setenv(name, buf);
574 }
575
576 /**
577 * Set an environment variable to a decimal integer value
578 *
579 * @param name Environment variable to set
580 * @param value Value to set it to
581 * @return 0 if ok, 1 on error
582 */
583 int setenv_ulong(const MEMX char *name, unsigned long value)
584 {
585 return setenv_intval(name, value, 10);
586 }
587
588
589 /**
590 * Set an environment variable to a value in hex
591 *
592 * @param name Environment variable to set
593 * @param value Value to set it to
594 * @return 0 if ok, 1 on error
595 */
596 int setenv_hex(const MEMX char *name, unsigned long value)
597 {
598 return setenv_intval(name, value, 16);
599 }
600
601
602 /**
603 * Decode the integer value of an environment variable and return it.
604 *
605 * @param name Name of environemnt variable
606 * @param base Number base to use (normally 10, or 16 for hex)
607 * @param default_val Default value to return if the variable is not
608 * found
609 * @return the decoded value, or default_val if not found
610 */
611 unsigned long getenv_ulong(const MEMX char *name, int base, unsigned long default_val)
612 {
613 unsigned long value;
614 char *vp, *endp;
615
616 env_item_t *ep = envlist_search(name);
617
618 if (ep != NULL ) {
619 vp = ep->envvar + strlen(ep->envvar) +1;
620 value = strtoul(vp, &endp, base);
621 if (endp != vp)
622 return value;
623 }
624
625 return default_val;
626 }
627
628
629 /*
630 * Read an environment variable as a boolean
631 */
632 bool getenv_yesno(const MEMX char *name)
633 {
634 char *s = getenv_str(name);
635
636 if (s == NULL)
637 return false;
638
639 return strchr_P(PSTR("1yYtT"), *s) != NULL;
640
641 /*
642 return *s == '1' || *s == 'y' || *s == 'Y' || *s == 't' || *s == 'T' ?
643 1 : 0;
644 */
645 }
646
647 command_ret_t do_env_print(cmd_tbl_t *cmdtp, uint_fast8_t flag, int argc, char * const argv[])
648 {
649 (void) cmdtp; (void) flag;
650
651 bool mode = 0;
652 command_ret_t rc = CMD_RET_SUCCESS;
653
654 /* reset getopt() */
655 optind = 0;
656
657 int opt;
658 while ((opt = getopt(argc, argv, PSTR("s"))) != -1) {
659 switch (opt) {
660 case 's':
661 mode = 1;
662 break;
663 default: /* '?' */
664 return CMD_RET_USAGE;
665 }
666 }
667
668 if (optind == argc) {
669 /* print all env vars */
670 int size = env_print(NULL, mode);
671 if (size < 0)
672 return CMD_RET_FAILURE;
673 if (mode == 0)
674 printf_P(PSTR("\nEnvironment size: %d/%d bytes\n"),
675 size, ENV_SIZE);
676 return CMD_RET_SUCCESS;
677 }
678
679 /* print selected env vars */
680 while (optind < argc) {
681 int rc = env_print(argv[optind], mode);
682 if (rc < 0) {
683 printf_P(PSTR("## Error: \"%s\" not defined\n"), argv[optind]);
684 rc = CMD_RET_FAILURE;
685 }
686 optind++;
687 }
688
689 return rc;
690 }
691
692
693 command_ret_t do_env_set(cmd_tbl_t *cmdtp, uint_fast8_t flag, int argc, char * const argv[])
694 {
695 (void) cmdtp;
696
697 if (argc < 2)
698 return CMD_RET_USAGE;
699
700 return _do_env_set(flag, argc, argv);
701 }
702
703
704 command_ret_t do_env_default(cmd_tbl_t *cmdtp, uint_fast8_t flag,
705 int argc, char * const argv[])
706 {
707 (void) cmdtp; (void) flag; (void) argc; (void) argv;
708
709 uint8_t tmp = env_valid;
710 env_valid = 0;
711
712 /* Reset the whole environment */
713 printf_P(PSTR("## Resetting to default environment\n"));
714 envlist_import(ENVLIST_DELETE);
715
716 env_valid = tmp;
717
718 return CMD_RET_SUCCESS;
719 }
720
721
722 command_ret_t do_env_save(cmd_tbl_t *cmdtp, uint_fast8_t flag, int argc, char * const argv[])
723 {
724 (void) cmdtp; (void) flag; (void) argc; (void) argv;
725
726 printf_P(PSTR("Saving Environment ...\n"));
727 return saveenv() ? CMD_RET_FAILURE : CMD_RET_SUCCESS;
728 }
729
730
731 #if defined(CONFIG_AUTO_COMPLETE)
732 int env_complete(char *var, int maxv, char *cmdv[], int bufsz, char *buf)
733 {
734 ENTRY *match;
735 int found, idx;
736
737 idx = 0;
738 found = 0;
739 cmdv[0] = NULL;
740
741 while ((idx = hmatch_r(var, idx, &match, &env_htab))) {
742 int vallen = strlen(match->key) + 1;
743
744 if (found >= maxv - 2 || bufsz < vallen)
745 break;
746
747 cmdv[found++] = buf;
748 memcpy(buf, match->key, vallen);
749 buf += vallen;
750 bufsz -= vallen;
751 }
752
753 qsort(cmdv, found, sizeof(cmdv[0]), strcmp_compar);
754
755 if (idx)
756 cmdv[found++] = "...";
757
758 cmdv[found] = NULL;
759 return found;
760 }
761 #endif