uboot 添加自定义命令

时间:2025-05-13 17:37:14
ref : https://www.cnblogs.com/FREMONT/p/9824226.html

1、添加命令
1.1在common目录下,新建一个cmd_xx.c,
需要添加的命令格式为:
int do_hello(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
并在文件中使用 U_BOOT_CMD 宏进行有关说明
U_BOOT_CMD(name, maxargs, repeatable, command, "usage","help")
宏参数有6个:
第一个参数:添加的命令的名字
第二个参数:添加的命令最多有几个参数(注意,假如你设置的参数个数是3,而实际的参数个数是4,那么执行命令会输出帮助信息的)
第三个参数:是否重复(1重复,0不重复)(即按下Enter键的时候,自动执行上次的命令)
第四个参数:执行函数,即运行了命令具体做啥会在这个函数中体现出来
第五个参数:帮助信息(short)
第六个参数:帮助信息(long)
以下是最精简的命令示例:
#include <command.h>
#include <common.h>
int do_hello(cmd_tbl_t *cmdtp,int flag,int argc,char *argv)
{
    printf("my test \n");
    return 0;
}
U_BOOT_CMD(
hello,1,0,do_hello,"usage:test\n","help:test\n"
);
1.2 修改 common/Makefile 
    在Makfile中添加一行:
       COBJS-y += cmd_hello.o 
2、uboot命令解析
  uboot的命令基本都是基于宏U_BOOT_CMD实现的,所以解析下该宏:
  通过搜索,我们找到U_BOOT_CMD该宏的定义:
  #define U_BOOT_CMD(name,maxargs,rep,cmd,usage,help) \
  cmd_tbl_t   __u_boot_cmd_##name Struct_Section = {#name, maxargs, rep, cmd, usage, help}
  1.#define Struct_Section  __attribute__ ((unused,section (".u_boot_cmd"))) 
  由定义可知该命令在链接的时候链接的地址或者说该命令存放的位置是u_boot_cmd section
  2.typedef struct cmd_tbl_s        cmd_tbl_t  struct cmd_tbl_s {
          char   *name;          /* Command Name    */ 
          int   maxargs;        /* maximum number of arguments  */
          int   repeatable;     /* autorepeat allowed?          */
                         /* Implementation function      */
          int   (*cmd)(struct cmd_tbl_s *, int, int, char *[]);
    char  *usage;         /* Usage message        (short) */
    char  *help
}