【问题标题】:How to extract python builtin function code [duplicate]如何提取python内置函数代码[重复]
【发布时间】:2015-01-28 14:20:54
【问题描述】:

据我所知,python 内置函数是从 C 源代码编译而来并内置到解释器中的。有什么方法可以找出功能代码的位置以便在反汇编程序中查看它?

补充: 对于这样的函数 id() 返回一个地址,不是吗?但是当我在调试器中查看它时,它包含的内容与 asm 代码相去甚远。

加法2: 我没有源代码,因为解释器是定制的。

【问题讨论】:

    标签: python built-in python-internals


    【解决方案1】:

    所有内置函数都在__builtin__ 模块中定义,由Python/bltinmodule.c source file 定义。

    要查找特定的内置函数,请查看module initialisation functionmodule methods table,然后使用 grep 查找附加函数定义的 Python 源代码。 __builtin__ 中的大多数函数都定义在同一个文件中。

    例如,dir() function 在方法表中为:

    {"dir",             builtin_dir,        METH_VARARGS, dir_doc},
    

    builtin_dir 定义为in the same file,委托给PyObject_Dir()

    static PyObject *
    builtin_dir(PyObject *self, PyObject *args)
    {
        PyObject *arg = NULL;
    
        if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
            return NULL;
        return PyObject_Dir(arg);
    }
    

    在 Python 源代码中快速 grep 会导致 Objects/object.c,其中 PyObject_Dir() 是通过几个辅助函数实现的:

    /* Implementation of dir() -- if obj is NULL, returns the names in the current
       (local) scope.  Otherwise, performs introspection of the object: returns a
       sorted list of attribute names (supposedly) accessible from the object
    */
    PyObject *
    PyObject_Dir(PyObject *obj)
    {
        PyObject * result;
    
        if (obj == NULL)
            /* no object -- introspect the locals */
            result = _dir_locals();
        else
            /* object -- introspect the object */
            result = _dir_object(obj);
    
        assert(result == NULL || PyList_Check(result));
    
        if (result != NULL && PyList_Sort(result) != 0) {
            /* sorting the list failed */
            Py_DECREF(result);
            result = NULL;
        }
    
        return result;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-04-30
      • 1970-01-01
      • 2021-06-12
      • 2020-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-05
      相关资源
      最近更新 更多