// File: /workspace/github_c_makefile_star2_O1/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 0x71c13(%rip), %r12     # 0xc9fa8
movq 0x7e0(%r12), %r14
xorl %edi, %edi
callq 0x5929b
movq $0x0, 0x810(%r12)
movq 0x38(%rbx), %rax
movq 0x10(%rax), %rsi
leaq 0x8(%rsp), %rdx
movq %rbx, %rdi
xorl %ecx, %ecx
callq 0x31082
testl %eax, %eax
jne 0x58781
movslq 0x30(%rbx), %rax
addq $-0x3, %rax
cmpq %rax, 0x8(%rsp)
jle 0x583f2
leaq 0x4598c(%rip), %rsi     # 0x9dd71
movq %rbx, %rdi
callq 0x2d9d7
jmp 0x58781
movw $0x5f66, 0x10(%rsp)     # imm = 0x5F66
testl %ebp, %ebp
je 0x58435
movq 0x38(%rbx), %rax
movq 0x8(%rax), %rax
movq 0x8(%rax), %rax
xorl %ecx, %ecx
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
cmpq $0x28, %rcx
jne 0x5840b
movb $0x0, 0x3a(%rsp)
jmp 0x5844f
leaq 0x12(%rsp), %rdi
movq 0x38(%rbx), %rax
movq 0x8(%rax), %rax
movq 0x8(%rax), %rsi
movslq -0x8(%rsi), %rdx
callq 0x574a4
leaq 0x4594f(%rip), %rdx     # 0x9dda5
movq %r14, %rdi
movl $0xffffd8ee, %esi       # imm = 0xFFFFD8EE
callq 0x6698e
leaq 0x10(%rsp), %rdx
movq %r14, %rdi
movl $0xffffd8ee, %esi       # imm = 0xFFFFD8EE
callq 0x6698e
movq %r14, %rdi
movl $0xffffffff, %esi       # imm = 0xFFFFFFFF
callq 0x662f0
testl %eax, %eax
je 0x58625
movq 0x38(%rbx), %rdx
addq $0x18, %rdx
movl 0x8(%rsp), %ecx
leaq 0x45931(%rip), %rsi     # 0x9ddce
movq %r14, %rdi
callq 0x58171
movq 0x38(%rbx), %rax
movq 0x8(%rsp), %rsi
leaq (%rax,%rsi,8), %rdx
addq $0x18, %rdx
movl 0x30(%rbx), %ecx
subl %esi, %ecx
addl $-0x3, %ecx
leaq 0x4590e(%rip), %rsi     # 0x9ddd3
movq %r14, %rdi
callq 0x58171
movq 0x7e8(%r12), %rdi
movq 0x8(%rbx), %rax
movl 0x30(%rax), %esi
callq 0x3192d
movq %rbx, 0x7f0(%r12)
callq 0x232a3
movq %rax, 0x808(%r12)
movl $0x0, 0x81c(%r12)
cmpq $0x0, 0x800(%r12)
setle %al
cmpq $0x0, 0x650(%r12)
setne %r13b
orb %al, %r13b
jne 0x58539
leaq -0xe70(%rip), %rsi      # 0x576b7
movq %r14, %rdi
movl $0x8, %edx
movl $0x186a0, %ecx          # imm = 0x186A0
callq 0x672b0
movq %r14, %rdi
xorl %esi, %esi
movl $0x1, %edx
movl $0xfffffffe, %ecx       # imm = 0xFFFFFFFE
callq 0x66dd8
movl %eax, %r15d
testb %r13b, %r13b
jne 0x58568
leaq -0xea5(%rip), %rsi      # 0x576b7
movq %r14, %rdi
xorl %edx, %edx
xorl %ecx, %ecx
callq 0x672b0
cmpl $0x0, 0x818(%r12)
je 0x5859a
movl $0x0, 0x818(%r12)
movq 0x28(%r12), %rdi
movl (%rbx), %esi
leaq -0x2b66f(%rip), %rcx    # 0x2cf1e
movl $0x1, %edx
movq %rbx, %r8
callq 0x209d7
movq $0x0, 0x7f0(%r12)
movq 0x7e8(%r12), %rax
movq 0x8(%rax), %rax
movl 0x30(%rax), %esi
movq %rbx, %rdi
callq 0x3192d
movq 0x8621c(%rip), %rax     # 0xde7e0
incq %rax
movq %rax, 0x86212(%rip)     # 0xde7e0
cmpq $0x32, %rax
jne 0x585f1
movq %r14, %rdi
movl $0x5, %esi
movl $0x32, %edx
callq 0x66f85
movq $0x0, 0x861ef(%rip) # 0xde7e0
testl %r15d, %r15d
je 0x58662
movq %r14, %rdi
movl $0xffffffff, %esi       # imm = 0xFFFFFFFF
xorl %edx, %edx
callq 0x6652e
leaq 0x457cc(%rip), %rsi     # 0x9ddd8
leaq 0x10(%rsp), %rdx
movq %rbx, %rdi
movq %rax, %rcx
xorl %eax, %eax
callq 0x2d9fe
movl $0xfffffffd, %esi       # imm = 0xFFFFFFFD
jmp 0x58672
movq %r14, %rdi
movl $0xfffffffe, %esi       # imm = 0xFFFFFFFE
callq 0x660a2
testl %ebp, %ebp
je 0x58716
movq %r14, %rdi
movl $0xfffffffe, %esi       # imm = 0xFFFFFFFE
callq 0x660a2
leaq 0x721b2(%rip), %rax     # 0xca800
movq 0x98(%rax), %rsi
movq %rbx, %rdi
callq 0x2d6f0
jmp 0x58781
movq %rbx, %rdi
movq %r14, %rsi
callq 0x57e90
movl $0xfffffffe, %esi       # imm = 0xFFFFFFFE
movq %r14, %rdi
callq 0x660a2
testl %ebp, %ebp
je 0x58781
movq 0x38(%rbx), %rax
movq 0x8(%rax), %rax
movq 0x8(%rax), %rdi
callq 0x3576b
testl %eax, %eax
jne 0x58781
movq 0x7f8(%r12), %rdi
movq 0x38(%rbx), %rax
movq 0x8(%rax), %rax
movq 0x8(%rax), %rsi
callq 0x22813
movq %rax, %r14
movq 0x38(%rbx), %rax
movq 0x8(%rax), %rax
movq 0x8(%rax), %rdi
callq 0x356b2
testq %r14, %r14
je 0x58790
leaq 0x45736(%rip), %rdi     # 0x9de0e
movl $0x4, %esi
callq 0x303b7
movq %rax, %rdi
callq 0x308dc
movq %rbx, %rdi
xorl %esi, %esi
movq %rax, %rdx
callq 0x2f6dd
movq %rbx, %rdi
movl $0x1, %esi
movq %r14, %rdx
callq 0x2f6dd
movq %rbx, %rdi
movl $0x3, %esi
callq 0x25b1c
jmp 0x58781
movq 0x38(%rbx), %rax
movq 0x8(%rax), %rcx
leaq 0x10(%rsp), %rdx
movq %rbx, %rdi
movq %r14, %rsi
callq 0x581e4
cmpl $-0x1, %eax
je 0x58774
leaq 0x10(%rsp), %rdx
movq %r14, %rdi
movl $0xffffd8ee, %esi       # imm = 0xFFFFD8EE
callq 0x6698e
movq %r14, %rdi
movl $0xffffffff, %esi       # imm = 0xFFFFFFFF
callq 0x662f0
testl %eax, %eax
jne 0x5848a
leaq 0x4565a(%rip), %rdi     # 0x9ddbb
leaq 0x455fd(%rip), %rsi     # 0x9dd65
movl $0x4bf, %edx            # imm = 0x4BF
callq 0x4d037
jmp 0x587ae
movq %r14, %rdi
movl $0xfffffffe, %esi       # imm = 0xFFFFFFFE
callq 0x660a2
addq $0x48, %rsp
popq %rbx
popq %r12
popq %r13
popq %r14
popq %r15
popq %rbp
retq
leaq 0x45668(%rip), %rdx     # 0x9ddff
leaq 0x455c7(%rip), %rcx     # 0x9dd65
movq %rbx, %rdi
xorl %esi, %esi
movl $0x54a, %r8d            # imm = 0x54A
callq 0x4d872
movl $0x1, %edi
callq 0x1f3b0