// File: /workspace/github_c_makefile_star2_O2/nilyang[P]redis-tdd-annotation/src/scripting.c
// Function: evalGenericCommand
void evalGenericCommand(redisClient *c, int evalsha) {
    lua_State *lua = server.lua;
    char funcname[43];
    long long numkeys;
    int delhook = 0, err;

    /* We want the same PRNG sequence at every call so that our PRNG is
     * not affected by external state. 
     *
     * 在每次执行 EVAL 时重置随机 seed ，从而保证可以生成相同的随机序列。
     */
    redisSrand48(0);

    /* We set this flag to zero to remember that so far no random command
     * was called. This way we can allow the user to call commands like
     * SRANDMEMBER or RANDOMKEY from Lua scripts as far as no write command
     * is called (otherwise the replication and AOF would end with non
     * deterministic sequences).
     *
     * 两个变量：
     *
     *  - lua_random_dirty 记录脚本是否执行了随机命令
     *
     *  - lua_write_dirty 记录脚本是否进行了写入命令
     *
     * Thanks to this flag we'll raise an error every time a write command
     * is called after a random command was used. 
     *
     * 通过这两个变量，程序可以在脚本试图在执行随机命令之后执行写入时报错。
     */
    server.lua_random_dirty = 0;
    server.lua_write_dirty = 0;

    /* Get the number of arguments that are keys */
    // 获取输入键的数量
    if (getLongLongFromObjectOrReply(c,c->argv[2],&numkeys,NULL) != REDIS_OK)
        return;

    // 对键的正确性做一个快速检查
    if (numkeys > (c->argc - 3)) {
        addReplyError(c,"Number of keys can't be greater than number of args");
        return;
    }

    /* We obtain the script SHA1, then check if this function is already
     * defined into the Lua state 
     *
     * 组合出函数的名字，例如 f_282297a0228f48cd3fc6a55de6316f31422f5d17
     */
    funcname[0] = 'f';
    funcname[1] = '_';
    if (!evalsha) {
        /* Hash the code if this is an EVAL call */
        // 如果执行的是 EVAL 命令，那么计算脚本的 SHA1 校验和
        sha1hex(funcname+2,c->argv[1]->ptr,sdslen(c->argv[1]->ptr));
    } else {
        /* We already have the SHA if it is a EVALSHA */
        // 如果执行的是 EVALSHA 命令，直接使用传入的 SHA1 值
        int j;
        char *sha = c->argv[1]->ptr;

        /* Convert to lowercase. We don't use tolower since the function
         * managed to always show up in the profiler output consuming
         * a non trivial amount of time. */
        for (j = 0; j < 40; j++)
            funcname[j+2] = (sha[j] >= 'A' && sha[j] <= 'Z') ?
                sha[j]+('a'-'A') : sha[j];
        funcname[42] = '\0';
    }

    /* Push the pcall error handler function on the stack. */
    lua_getglobal(lua, "__redis__err__handler");

    /* Try to lookup the Lua function */
    // 根据函数名，在 Lua 环境中检查函数是否已经定义
    lua_getglobal(lua, funcname);

    if (lua_isnil(lua,-1)) {

        // 没找到脚本相应的脚本函数

        lua_pop(lua,1); /* remove the nil from the stack */
        /* Function not defined... let's define it if we have the
         * body of the function. If this is an EVALSHA call we can just
         * return an error. */

        // 脚本函数不存在，需要根据所执行的命令来做判断。。。

        // 如果执行的是 EVALSHA ，返回脚本未找到错误
        if (evalsha) {
            lua_pop(lua,1); /* remove the error handler from the stack. */
            addReply(c, shared.noscripterr);
            return;
        }

        // 如果执行的是 EVAL ，那么创建新函数，然后将代码添加到脚本字典中
        if (luaCreateFunction(c,lua,funcname,c->argv[1]) == REDIS_ERR) {
            lua_pop(lua,1); /* remove the error handler from the stack. */
            /* The error is sent to the client by luaCreateFunction()
             * itself when it returns REDIS_ERR. */
            return;
        }
        /* Now the following is guaranteed to return non nil */
        lua_getglobal(lua, funcname);
        redisAssert(!lua_isnil(lua,-1));
    }

    /* Populate the argv and keys table accordingly to the arguments that
     * EVAL received. 
     *
     * 将用户传入的键数组和参数数组设为 Lua 环境中的 KEYS 全局变量和 ARGV 全局变量
     */
    luaSetGlobalArray(lua,"KEYS",c->argv+3,numkeys);
    luaSetGlobalArray(lua,"ARGV",c->argv+3+numkeys,c->argc-3-numkeys);

    /* Select the right DB in the context of the Lua client */
    // 为 Lua 所属的伪客户端设置数据库
    selectDb(server.lua_client,c->db->id);
    
    /* Set a hook in order to be able to stop the script execution if it
     * is running for too much time.
     *
     * 设置一个钩子，用于在脚本运行时间过长时，停止脚本并等待用户的 SCRIPT 命令
     *
     * We set the hook only if the time limit is enabled as the hook will
     * make the Lua script execution slower. 
     *
     * 只有时间限制功能被开启时才使用钩子，因为它会拖慢脚本的运行速度。
     */
    // 调用客户端
    server.lua_caller = c;
    // 脚本开始时间
    server.lua_time_start = mstime();
    // 是否杀死脚本
    server.lua_kill = 0;
    // 只在开启了时间限制功能的时候，才使用钩子
    if (server.lua_time_limit > 0 && server.masterhost == NULL) {
        lua_sethook(lua,luaMaskCountHook,LUA_MASKCOUNT,100000);
        delhook = 1;
    }

    /* At this point whether this script was never seen before or if it was
     * already defined, we can call it. We have zero arguments and expect
     * a single return value. */
    // 执行脚本对应的 Lua 函数
    err = lua_pcall(lua,0,1,-2);

    /* Perform some cleanup that we need to do both on error and success. 
     *
     * 执行一些无论执行是否成功都要执行的清理工作
     */
    // 关闭超时钩子
    if (delhook) lua_sethook(lua,luaMaskCountHook,0,0); /* Disable hook */
    // 脚本执行已超时
    if (server.lua_timedout) {
            // 清除超时 FLAG
        server.lua_timedout = 0;
        /* Restore the readable handler that was unregistered when the
         * script timeout was detected. 
         *
         * 将超时钩子里删除的读事件重新加上，
         * 使得服务器可以继续接受当前客户端发来的命令请求
         */
        aeCreateFileEvent(server.el,c->fd,AE_READABLE,
                          readQueryFromClient,c);
    }

    // 清空调用者
    server.lua_caller = NULL;

    // 因为客户端的当前数据库在脚本执行之后可能已经改变
    // 所以这里需要更新客户端
    selectDb(c,server.lua_client->db->id); /* set DB ID from Lua client */

    /* Call the Lua garbage collector from time to time to avoid a
     * full cycle performed by Lua, which adds too latency.
     *
     * The call is performed every LUA_GC_CYCLE_PERIOD executed commands
     * (and for LUA_GC_CYCLE_PERIOD collection steps) because calling it
     * for every command uses too much CPU. */
    #define LUA_GC_CYCLE_PERIOD 50
    {
        static long gc_count = 0;

        gc_count++;
        if (gc_count == LUA_GC_CYCLE_PERIOD) {
            lua_gc(lua,LUA_GCSTEP,LUA_GC_CYCLE_PERIOD);
            gc_count = 0;
        }
    }

    // 检查脚本运行是否出错
    if (err) {
        // 出错
        addReplyErrorFormat(c,"Error running script (call to %s): %s\n",
            funcname, lua_tostring(lua,-1));
        lua_pop(lua,2); /* Consume the Lua reply and remove error handler. */
    } else {
        /* On success convert the Lua return value into Redis protocol, and
         * send it to * the client.
         * 执行成功，将结果转换回 Redis 回复，并返回给客户端 */
        luaReplyToRedisReply(c,lua); /* Convert and consume the reply. */
        lua_pop(lua,1); /* Remove the error handler. */
    }

    /* EVALSHA should be propagated to Slave and AOF file as full EVAL, unless
     * we are sure that the script was already in the context of all the
     * attached slaves *and* the current AOF file if enabled.
     *
     * 除非程序确认脚本已经存在于所有 slave 和 AOF 文件的上下文中，
     * 否则在传播脚本到 slave 和 AOF 文件时，
     * 必须将 EVALSHA 当作 EVAL 来传播。
     *
     * To do so we use a cache of SHA1s of scripts that we already propagated
     * as full EVAL, that's called the Replication Script Cache.
     *
     * 为此，服务器使用一个字典来作为已传播脚本的缓存，
     * 这个缓存称之为 Replication Script Cache ，
     * 缓存字典的键为 SHA1 ，值为 NULL （一个集合）。
     *
     * For repliation, everytime a new slave attaches to the master, we need to
     * flush our cache of scripts that can be replicated as EVALSHA, while
     * for AOF we need to do so every time we rewrite the AOF file. 
     *
     * 每次有一个新的 slave 连上主服务器时，
     * 或者每次进行 AOF 重写时，程序清空缓存字典
     */
    if (evalsha) {
        // replicationScriptCacheExists 如果返回 1 
        // 那么表示所有 slave 和 AOF 文件中都知道这个脚本
        // 如果返回 0 ，那么表示这个脚本未被传播到所有 slave 和 AOF 文件中
        if (!replicationScriptCacheExists(c->argv[1]->ptr)) {
            /* This script is not in our script cache, replicate it as
             * EVAL, then add it into the script cache, as from now on
             * slaves and AOF know about it. */
            // 将这个脚本加入脚本缓存，并且将以 EVAL 命令的方式传播它
            // 从现在开始， slaves 和 AOF 文件都知道它

            // 取出脚本 body
            robj *script = dictFetchValue(server.lua_scripts,c->argv[1]->ptr);

            // 将脚本的 SHA1 值加入到缓存
            replicationScriptCacheAdd(c->argv[1]->ptr);
            redisAssertWithInfo(c,NULL,script != NULL);
            // 将 EVALSHA 命令改写为 EVAL
            rewriteClientCommandArgument(c,0,
                resetRefCount(createStringObject("EVAL",4)));
            rewriteClientCommandArgument(c,1,script);
            forceCommandPropagation(c,REDIS_PROPAGATE_REPL|REDIS_PROPAGATE_AOF);
        }
    }
}

// Assembly:
pushq %rbp
pushq %r15
pushq %r14
pushq %r13
pushq %r12
pushq %rbx
subq $0x48, %rsp
movl %esi, %ebp
movq %rdi, %rbx
leaq 0x737cb(%rip), %r13     # 0xc6fa8
movq 0x7e0(%r13), %r14
xorl %edi, %edi
callq 0x545d3
andq $0x0, 0x810(%r13)
movq 0x38(%rbx), %rax
movq 0x10(%rax), %rsi
movq %rsp, %rdx
movq %rbx, %rdi
xorl %ecx, %ecx
callq 0x2f617
testl %eax, %eax
jne 0x53b8f
movslq 0x30(%rbx), %rax
addq $-0x3, %rax
cmpq %rax, (%rsp)
jle 0x53832
leaq 0x4054c(%rip), %rsi     # 0x93d71
movq %rbx, %rdi
callq 0x2c2da
jmp 0x53b8f
movw $0x5f66, 0x10(%rsp)     # imm = 0x5F66
testl %ebp, %ebp
je 0x53877
movq 0x38(%rbx), %rax
movq 0x8(%rax), %rax
movq 0x8(%rax), %rax
xorl %ecx, %ecx
cmpq $0x28, %rcx
je 0x53870
movzbl (%rax,%rcx), %edx
leal -0x41(%rdx), %esi
leal 0x20(%rdx), %edi
cmpb $0x1a, %sil
movzbl %dil, %esi
cmovael %edx, %esi
movb %sil, 0x12(%rsp,%rcx)
incq %rcx
jmp 0x5384b
movb $0x0, 0x3a(%rsp)
jmp 0x53891
leaq 0x12(%rsp), %rdi
movq 0x38(%rbx), %rax
movq 0x8(%rax), %rax
movq 0x8(%rax), %rsi
movslq -0x8(%rsi), %rdx
callq 0x529ed
leaq 0x4050d(%rip), %rdx     # 0x93da5
movq %r14, %rdi
movl $0xffffd8ee, %esi       # imm = 0xFFFFD8EE
callq 0x60fee
leaq 0x10(%rsp), %rdx
movq %r14, %rdi
movl $0xffffd8ee, %esi       # imm = 0xFFFFD8EE
callq 0x60fee
pushq $-0x1
popq %rsi
movq %r14, %rdi
callq 0x60984
testl %eax, %eax
je 0x53a44
movq 0x38(%rbx), %rdx
addq $0x18, %rdx
movl (%rsp), %ecx
leaq 0x404f2(%rip), %rsi     # 0x93dce
movq %r14, %rdi
callq 0x535ce
movq 0x38(%rbx), %rax
movq (%rsp), %rsi
leaq (%rax,%rsi,8), %rdx
addq $0x18, %rdx
movl 0x30(%rbx), %ecx
subl %esi, %ecx
addl $-0x3, %ecx
leaq 0x404d0(%rip), %rsi     # 0x93dd3
movq %r14, %rdi
callq 0x535ce
movq 0x7e8(%r13), %rdi
movq 0x8(%rbx), %rax
movl 0x30(%rax), %esi
callq 0x2fdf0
movq %rbx, 0x7f0(%r13)
callq 0x22843
movq %rax, 0x808(%r13)
andl $0x0, 0x81c(%r13)
cmpq $0x0, 0x800(%r13)
setle %al
cmpq $0x0, 0x650(%r13)
setne %r12b
orb %al, %r12b
jne 0x5396c
leaq -0xd6e(%rip), %rsi      # 0x52bee
pushq $0x8
popq %rdx
movq %r14, %rdi
movl $0x186a0, %ecx          # imm = 0x186A0
callq 0x61914
pushq $0x1
popq %rdx
pushq $-0x2
popq %r15
movq %r14, %rdi
xorl %esi, %esi
movl %r15d, %ecx
callq 0x61434
movl %eax, 0xc(%rsp)
testb %r12b, %r12b
jne 0x5399c
leaq -0xda2(%rip), %rsi      # 0x52bee
movq %r14, %rdi
xorl %edx, %edx
xorl %ecx, %ecx
callq 0x61914
cmpl $0x0, 0x818(%r13)
je 0x539c6
andl $0x0, 0x818(%r13)
movq 0x28(%r13), %rdi
movl (%rbx), %esi
leaq -0x2801b(%rip), %rcx    # 0x2b9a0
pushq $0x1
popq %rdx
movq %rbx, %r8
callq 0x2030c
andq $0x0, 0x7f0(%r13)
movq 0x7e8(%r13), %rax
movq 0x8(%rax), %rax
movl 0x30(%rax), %esi
movq %rbx, %rdi
callq 0x2fdf0
movq 0x87df5(%rip), %rax     # 0xdb7e0
incq %rax
movq %rax, 0x87deb(%rip)     # 0xdb7e0
cmpq $0x32, %rax
jne 0x53a11
pushq $0x5
popq %rsi
pushq $0x32
popq %rdx
movq %r14, %rdi
callq 0x615e5
andq $0x0, 0x87dcf(%rip)     # 0xdb7e0
cmpl $0x0, 0xc(%rsp)
je 0x53a7d
pushq $-0x1
popq %rsi
movq %r14, %rdi
xorl %edx, %edx
callq 0x60bad
leaq 0x403ac(%rip), %rsi     # 0x93dd8
leaq 0x10(%rsp), %rdx
movq %rbx, %rdi
movq %rax, %rcx
xorl %eax, %eax
callq 0x2c301
pushq $-0x3
popq %r15
jmp 0x53a88
pushq $-0x2
popq %rsi
movq %r14, %rdi
callq 0x60744
testl %ebp, %ebp
je 0x53b28
pushq $-0x2
popq %rsi
movq %r14, %rdi
callq 0x60744
leaq 0x73d97(%rip), %rax     # 0xc7800
movq 0x98(%rax), %rsi
movq %rbx, %rdi
callq 0x2c10d
jmp 0x53b8f
movq %rbx, %rdi
movq %r14, %rsi
callq 0x5334f
movq %r14, %rdi
movl %r15d, %esi
callq 0x60744
testl %ebp, %ebp
je 0x53b8f
movq 0x38(%rbx), %rax
movq 0x8(%rax), %rax
movq 0x8(%rax), %rdi
callq 0x338ea
testl %eax, %eax
jne 0x53b8f
movq 0x7f8(%r13), %rdi
movq 0x38(%rbx), %rax
movq 0x8(%rax), %rax
movq 0x8(%rax), %rsi
callq 0x21e57
movq %rax, %r14
movq 0x38(%rbx), %rax
movq 0x8(%rax), %rax
movq 0x8(%rax), %rdi
callq 0x33833
testq %r14, %r14
je 0x53b9e
leaq 0x4031e(%rip), %rdi     # 0x93e0e
pushq $0x4
popq %rsi
callq 0x2ea81
movq %rax, %rdi
callq 0x2eebe
movq %rbx, %rdi
xorl %esi, %esi
movq %rax, %rdx
callq 0x2de87
pushq $0x1
popq %rsi
movq %rbx, %rdi
movq %r14, %rdx
callq 0x2de87
pushq $0x3
popq %rsi
movq %rbx, %rdi
callq 0x24c79
jmp 0x53b8f
movq 0x38(%rbx), %rax
movq 0x8(%rax), %rcx
leaq 0x10(%rsp), %rdx
movq %rbx, %rdi
movq %r14, %rsi
callq 0x53644
cmpl $-0x1, %eax
je 0x53b84
leaq 0x10(%rsp), %rdx
movq %r14, %rdi
movl $0xffffd8ee, %esi       # imm = 0xFFFFD8EE
callq 0x60fee
pushq $-0x1
popq %rsi
movq %r14, %rdi
callq 0x60984
testl %eax, %eax
jne 0x538ca
leaq 0x4024a(%rip), %rdi     # 0x93dbb
leaq 0x401ed(%rip), %rsi     # 0x93d65
movl $0x4bf, %edx            # imm = 0x4BF
callq 0x4906b
jmp 0x53bbc
pushq $-0x2
popq %rsi
movq %r14, %rdi
callq 0x60744
addq $0x48, %rsp
popq %rbx
popq %r12
popq %r13
popq %r14
popq %r15
popq %rbp
retq
leaq 0x4025a(%rip), %rdx     # 0x93dff
leaq 0x401b9(%rip), %rcx     # 0x93d65
movq %rbx, %rdi
xorl %esi, %esi
movl $0x54a, %r8d            # imm = 0x54A
callq 0x4980c
pushq $0x1
popq %rdi
callq 0x1f3b0