extcmd.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /* extcmd.c - support extended command */
  2. /*
  3. * GRUB -- GRand Unified Bootloader
  4. * Copyright (C) 2009 Free Software Foundation, Inc.
  5. *
  6. * GRUB is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * GRUB is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with GRUB. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #include <grub/mm.h>
  20. #include <grub/list.h>
  21. #include <grub/misc.h>
  22. #include <grub/extcmd.h>
  23. GRUB_EXPORT(grub_reg_ecmd);
  24. GRUB_EXPORT(grub_unregister_extcmd);
  25. static grub_err_t
  26. grub_extcmd_dispatcher (struct grub_command *cmd,
  27. int argc, char **args)
  28. {
  29. int new_argc;
  30. char **new_args;
  31. struct grub_arg_option *parser;
  32. struct grub_arg_list *state;
  33. int maxargs = 0;
  34. grub_err_t ret;
  35. grub_extcmd_t ext;
  36. ext = cmd->data;
  37. parser = (struct grub_arg_option *) ext->options;
  38. while (parser && (parser++)->doc)
  39. maxargs++;
  40. /* Set up the option state. */
  41. state = grub_zalloc (sizeof (struct grub_arg_list) * maxargs);
  42. if (grub_arg_parse (ext, argc, args, state, &new_args, &new_argc))
  43. {
  44. ext->state = state;
  45. ret = (ext->func) (ext, new_argc, new_args);
  46. grub_free (new_args);
  47. }
  48. else
  49. ret = grub_errno;
  50. grub_free (state);
  51. return ret;
  52. }
  53. grub_extcmd_t
  54. grub_reg_ecmd (const char *name, grub_extcmd_func_t func,
  55. unsigned flags, const char *summary,
  56. const char *description,
  57. const struct grub_arg_option *parser)
  58. {
  59. grub_extcmd_t ext;
  60. grub_command_t cmd;
  61. ext = (grub_extcmd_t) grub_malloc (sizeof (*ext));
  62. if (! ext)
  63. return 0;
  64. cmd = grub_reg_cmd (name, grub_extcmd_dispatcher,
  65. summary, description, 1);
  66. if (! cmd)
  67. {
  68. grub_free (ext);
  69. return 0;
  70. }
  71. cmd->flags = (flags | GRUB_COMMAND_FLAG_EXTCMD);
  72. cmd->data = ext;
  73. ext->cmd = cmd;
  74. ext->func = func;
  75. ext->options = parser;
  76. ext->data = 0;
  77. return ext;
  78. }
  79. void
  80. grub_unregister_extcmd (grub_extcmd_t ext)
  81. {
  82. grub_unregister_command (ext->cmd);
  83. grub_free (ext);
  84. }