uboot_env_params.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*
  2. * Copyright (C) 2023 Alibaba Group Holding Limited
  3. */
  4. #include <stdio.h>
  5. #include <string.h>
  6. #include <stdlib.h>
  7. #include <prd_utils_kv.h>
  8. #include <prd_utils_internal.h>
  9. #include "uboot_env_params.h"
  10. static char g_result[PRD_UTILS_VAL_MAX_LENGTH] = "";
  11. static int execmd_fetch_result_string(const char *cmd, char *result)
  12. {
  13. char buffer[PRD_UTILS_VAL_MAX_LENGTH];
  14. FILE *pipe = popen(cmd, "r");
  15. if (pipe == NULL)
  16. {
  17. return -1;
  18. }
  19. while(!feof(pipe))
  20. {
  21. if(fgets(buffer, PRD_UTILS_VAL_MAX_LENGTH, pipe))
  22. {
  23. strcat(result, buffer);
  24. if(strlen(result) >= PRD_UTILS_VAL_MAX_LENGTH)
  25. break;
  26. }
  27. }
  28. pclose(pipe);
  29. return 0;
  30. }
  31. int light_uboot_get_env(const char *key, char **value)
  32. {
  33. char cmd[128 + PRD_UTILS_KEY_MAX_LENGTH] ="";
  34. memset(g_result, 0, sizeof(g_result));
  35. snprintf(cmd, sizeof(cmd),
  36. "fw_printenv | grep '%s=' | awk -F '=' '{print $2}' | tr -d '\n' '\r'", key);
  37. if (execmd_fetch_result_string(cmd, g_result) == 0)
  38. {
  39. *value = g_result;
  40. if (strlen(*value) == 0)
  41. {
  42. //PRD_UTILS_LOG("light_uboot_get_env() failed, return enmpty value\n");
  43. return PRD_UTILS_RESULT_KV_NOT_EXIST;
  44. }
  45. return PRD_UTILS_RESULT_OK;
  46. }
  47. else
  48. {
  49. *value = NULL;
  50. //PRD_UTILS_LOG("light_uboot_get_env() failed\n");
  51. return PRD_UTILS_RESULT_KV_IO_FAILED;
  52. }
  53. }
  54. int light_uboot_set_env(const char *key, char *value)
  55. {
  56. char cmd[128 + PRD_UTILS_KEY_MAX_LENGTH + PRD_UTILS_VAL_MAX_LENGTH] ="";
  57. snprintf(cmd, sizeof(cmd), "fw_setenv %s '%s'", key, value);
  58. if (system(cmd) != 0)
  59. {
  60. PRD_UTILS_LOG("execute cmd='%s' failed\n", cmd);
  61. return PRD_UTILS_RESULT_KV_IO_FAILED;
  62. }
  63. return PRD_UTILS_RESULT_OK;
  64. }
  65. int light_uboot_clean_env(const char *key)
  66. {
  67. char cmd[128 + PRD_UTILS_KEY_MAX_LENGTH] = "";
  68. snprintf(cmd, sizeof(cmd), "fw_setenv %s", key);
  69. if (system(cmd) != 0)
  70. {
  71. PRD_UTILS_LOG("execute cmd='%s' failed\n", cmd);
  72. return PRD_UTILS_RESULT_KV_IO_FAILED;
  73. }
  74. return PRD_UTILS_RESULT_OK;
  75. }