Linux代码阅读准备

Linux内核的代码规模庞大。现在发布的linux-5.6.2版本压缩包有100多M,包含7W多个文件,代码规模100多万行。并且Linux支持的CPU体系众多。每种CPU下面还有不少不同的平台实现。再加上Linux的各种功能模块里面还有大量的可以改变的配置参数。在阅读代码的时候会发现一个功能有多个不同的实现,代码里面有大量的CONFIG_XXX的宏定义。这些定义都与内核的具体的配置有关,需要结合编译时的具体配置才能确定值。在阅读代码时很不方便。

spin_lock() 为例。根据内核编译的时候是否定义了
CONFIG_SMP CONFIG_INLINE_SPIN_LOCK CONFIG_LOCKDEP这些宏。spin_lock()的定义完全不同。

提供一个小程序。用内核编译生成的过程文件,对内核内核源代码进行筛选。并对source insight4工程进行一些配置。使内核代码更方便阅读。

build_kernel_src.py:

#!/usr/bin/python

import sys
import os
import re
import tempfile
from xml.etree.ElementTree import Element,ElementTree

def create_condition_xml(gcc, conf):
    for one in open('./include/generated/autoconf.h'):
        m = re.match('#define (.*) ', one)
        if m == None: continue
        conf.discard(m.group(1))
    root = Element('SourceInsightParseConditions')
    tree = ElementTree(root)
    root.attrib['AppVer']='4.00.0096'
    root.attrib['AppVerMinReader']='4.00.0019'
    child = Element('ParseConditions')
    root.append(child)
    defines = Element('Defines')
    child.append(defines)

    for one in conf: 
        define=Element('define')
        define.attrib['id']=f'{one}'
        define.attrib['value']='0'
        defines.append(define)
    tree.write(f'{gcc}.conditions.xml', encoding='UTF-8', xml_declaration=True)
    return f'{gcc}.conditions.xml'

def parse_conf_xxx(fn, conf):
    try:
        with open(fn, 'r') as fn: text=fn.read()
        for one in re.finditer(r'[ (](CONFIG_[\da-zA-Z_]*)', text):
            text=one.group(1)
            #text=re.sub('[()\s]', '', text)
            conf.add(text)
    except:return

def create_gcc_predefine(res, cpio):
    with open('init/.main.o.cmd', 'r') as fn: cmd = fn.read()
    m = re.match(r'cmd_.*:= (.*?) -D"?KBUILD_MODFILE', cmd)
    cmd = m.group(1)
    cmd = re.sub(' -Wp,.*? ', ' ', cmd)
    for one in re.findall('-include .*? ', cmd):
        fn=one.replace('-include','').strip()
        res.add(fn); print(fn, file=cpio)
    cmd = re.sub('-include .*? ', ' ', cmd)
    tmp = re.match('(.*?) ', cmd).group(0);
    tmp = f'{tmp} -v 2>&1|grep Target'
    tmp += '|awk \'{print $2}\''
    with os.popen(tmp) as fn: gcc = fn.read().strip()
    fn = f'{gcc}.h'
    tmp = tempfile.mkstemp(suffix='.c')
    os.system(f'{cmd} -E -dMM {tmp[1]} >{fn}')
    os.unlink(tmp[1])
    res.add(fn); print(fn, file=cpio)
    return gcc

def process_dotcmd(fn, res, cpio, srcdir, objdir, conf, debug=False):
    if(debug): print(f'{fn}', file=sys.stderr)
    with open(fn, 'r') as fn: text = fn.read()
    #get source first
    m = re.search(r'source_(.*) := (.*)', text)
    if m != None: 
        obj=m.group(1)
        src=m.group(2)
        if not os.path.exists(src):
            obj = os.path.dirname(obj.replace(objdir, srcdir))
            src = os.path.join(obj, os.path.basename(src))
        src = os.path.normpath(src)
        if os.path.isabs(src): src=os.path.relpath(src, objdir)
        if not src in res:
            if debug: print(f'src={src}', file=sys.stderr)
            res.add(src); print(src, file=cpio); parse_conf_xxx(src, conf)
    #get dep files
    m = re.search(r'deps_.* := \\\n(.*)\\\n', text, re.M|re.S)
    if m == None: return
    text = m.group(1)
    text = re.split(r'\n', text);
    for line in text:
        m = re.match(r'.*\s(.*?)[\s)]', line)
        if m == None:continue
        fn = m.group(1)
        if srcdir in fn:
            fn=os.path.relpath(fn, objdir)
        try: 
            fn=os.path.normpath(fn)
            if not os.path.getsize(fn) >0: continue
            if fn in res: continue
            res.add(fn); print(fn, file=cpio); parse_conf_xxx(fn, conf)
            if debug: print(f'dep={fn}', file=sys.stderr)
        except: pass

if __name__ ==  "__main__":
    res = set()
    conf = set()
    if(len(sys.argv)<=2 or (not os.path.isdir(sys.argv[1]))):
        print(f'usage {sys.argv[0]}'+' {dir} {cpiofile}')
        sys.exit()
    if not os.path.islink(f'{sys.argv[1]}/source'):
        print(f'{sys.argv[1]}/source not link to kernel source')
        exit(-1)

    objdir=os.path.realpath(f'{sys.argv[1]}')
    srcdir=os.path.realpath(f'{sys.argv[1]}/source')
    objdir=os.path.normpath(objdir)
    srcdir=os.path.normpath(srcdir)
    cpio=os.path.realpath(sys.argv[2])
    os.chdir(objdir)

    #cmd = f'find {sys.argv[1]}/a -type f -name ".*.cmd"'
    cmd = f'find {sys.argv[1]} -type f -name ".*.cmd"'
    cmd = f'{cmd} -and -not -name "*built-in.*"'
    cmd = f'{cmd} -and -not -name ".*.mod.cmd"'
    cmd = f'{cmd} -and -not -path "./tools/*"'
    cmd = f'{cmd} -and -not -path "./scripts/*"'
    cmd = f'{cmd} -and -not -path "./usr/*"'
    cpio = f'cpio --no-absolute-filenames -o >{cpio} 2>/dev/null'
    cpio = os.popen(cpio, mode='w')

    # save .config first
    print('./.config', file=cpio)
    print('./System.map', file=cpio)
    fn = './include/generated/autoconf.h'
    res.add(fn); print(fn, file=cpio)
    gcc = create_gcc_predefine(res, cpio)
    ll = 0
    for fn in os.popen(cmd):
        fn = fn.strip()
        process_dotcmd(fn, res, cpio, srcdir, objdir, conf)
        print(f'\r{len(res)}+%-*s'%(ll,fn), file=sys.stderr, end='', 
              flush=True)
        ll = len(fn)
    fn = create_condition_xml(gcc, conf)
    print(fn, file=cpio)
    cpio.close()
    print(f'\n{len(res)} files')
    os.unlink(fn) #condition.xml
    os.unlink(f'{gcc}.h') # x86_64-linux-gnu.h


程序生成一个cpio文件。解开之后建立source insight4工程。并通过source insight工程的”Edit Conditon"导入cpio中的xml定义:


image-20200505202845978.png

--->>Edit List...

image-20200505202955261.png

--->>Import...


image-20200505203041518.png

--->>Load...

image-20200505203118336.png
image-20200505200445146.png

好了。这下Linux的代码就更好阅读了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,366评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,521评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,689评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,925评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,942评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,727评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,447评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,349评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,820评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,990评论 3 337
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,127评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,812评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,471评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,017评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,142评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,388评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,066评论 2 355