Android中的进程名和线程名_android 获取processname " proc " + pid + " cmdline


#### 1.1 Command Line


该函数的第一个参数是可执行文件的路径名,后面的参数则共同构成command line。内核在处理这些command line参数时,会将它们顺次连接地存放在栈底,每个参数中间通过’\0’进行分隔。这些参数在程序启动后会传递给main方法,也即我们经常看到的argv[]。按照约定俗成的规定(非强制),第一个参数(argv[0]指向的字符串)是文件名,当然如果你喜欢,也可以传入任何其他字符串。


比如下面的输入,最终产生的command line就是"banana`\0`-l`\0`",`\0`对应的ASCII码为0x00。



execl(“/bin/ls”, “banana”, “-l”, NULL);


由于command line中各个字符串通过’\0’进行分隔,因此如果简单地通过printf进行输出,我们将只会看到argv[0]指向的字符串。如果想要完整地获取command line中的所有内容,通常需要一些特殊处理。如下是Android提供的两种获取方式,`get_command_line`将获取其中所有的字符串,而`get_process_name`只会获取argv[0]指向的字符串,对纯native进程而言,它通常是可执行文件的名称,也可以理解为进程名。不过对于Android应用而言,它却有别的含义。此处按下不表,后文再述。


**[/system/core/debuggerd/util.cpp]**



std::vectorstd::string get_command_line(pid_t pid) {
std::vectorstd::string result;

std::string cmdline;
android::base::ReadFileToString(android::base::StringPrintf(“/proc/%d/cmdline”, pid), &cmdline);

auto it = cmdline.cbegin();
while (it != cmdline.cend()) {
// string::iterator is a wrapped type, not a raw char*.
auto terminator = std::find(it, cmdline.cend(), ‘\0’);
result.emplace_back(it, terminator);
it = std::find_if(terminator, cmdline.cend(), [](char c) { return c != ‘\0’; });
}
if (result.empty()) {
result.emplace_back(“”);
}

return result;
}

std::string get_process_name(pid_t pid) {
std::string result = “”;
android::base::ReadFileToString(android::base::StringPrintf(“/proc/%d/cmdline”, pid), &result);
// We only want the name, not the whole command line, so truncate at the first NUL.
return result.c_str();
}


上文提到,command line会顺次连接地存放在栈底,也即用户空间。当我们在adb shell中执行`cat /proc/[pid]/cmdline`指令时,本质上是访问一个特殊的文件节点(该文件节点只可读)。这个访问动作最后会触发内核空间的一个函数,如下。


**[/kernel/common/fs/proc/base.c]**



REG(“cmdline”, S_IRUGO, proc_pid_cmdline_ops),


**[/kernel//common/fs/proc/base.c]**



static const struct file_operations proc_pid_cmdline_ops = {
.read = proc_pid_cmdline_read,
.llseek = generic_file_llseek,
};


`proc_pid_cmdline_read`函数会通过`access_remote_vm`来访问[pid]进程的地址空间,进而获得它存放在用户空间的command line数据,并将其拷贝到输出的buffer中。因此,command line数据并不存在于内核地址空间。


#### 1.2 Command Name


每一个调度实体都有自己的名字,也即task\_struct中的"comm"字段。Comm本意为command name,并非上述的command line,这里要注意区分。


**[/kernel/common/include/linux/sched.h]**



/* Task command name length: /
#define TASK_COMM_LEN 16

struct task_struct {

/

  • executable name, excluding path.
    • normally initialized setup_new_exec()
    • access it with [gs]et_task_comm()
    • lock it with task_lock()
      */
      char comm[TASK_COMM_LEN];

      }

comm字符串存储的到底是什么?只有源码最清楚。当我们调用exec执行可执行文件时,它在kernel层会调用`load_elf_binary`,其中便会设置`task_strcut.comm`字段。


**[/kernel/common/fs/exec.c]**



__set_task_comm(me, kbasename(bprm->filename), true);


**[/kernel/common/include/linux/string.h]**



/**

  • kbasename - return the last part of a pathname.
  • @path: path to extract the filename from.
    */
    static inline const char *kbasename(const char *path) {
    const char *tail = strrchr(path, ‘/’);
    return tail ? tail + 1 : path;
    }

Exec传入的第一个参数虽说是文件名,但它是带有路径的文件名,譬如`/system/bin/surfaceflinger`,而存入comm字段的名称则是剥离路径的文件名,也即`surfaceflinger`。另外需要注意的是,comm长度为16,任何过长的文件名都会被截断。因此,comm最初始的含义为可执行文件的名称,不过随着系统的发展,它的含义早已超出当初的设定。


### 2. Ps视角下的进程名和线程名


Ps最初是Linux shell中的一个指令,用于展示进程相关的一些信息。不过Android采用的是toybox里的实现,和原生ps在使用方法上有些许差异。源码位于`/external/toybox/toys/posix/ps.c`。



> 
> Toybox combines the most common Linux command line utilities together into a single BSD-licensed executable that’s simple, small, fast, reasonably standards-compliant, and powerful enough to turn Android into a development environment. See the links on the left for details.
> 
> 
> 


#### 2.1 Ps -A显示的进程名


`ps -A`和`ps -e`执行的是同一个动作,都是显示所有进程。



-A All
-e Synonym for -A


下面是`ps -A`的一个示例输出。



ps -A

USER PID PPID VSZ RSS WCHAN ADDR S NAME
root 1 0 13001184 14608 do_epoll_+ 0 S init
root 2 0 0 0 kthreadd 0 S [kthreadd]
root 3 2 0 0 rescuer_t+ 0 I [rcu_gp]

logd 278 1 13036024 7516 do_sys+ 0 S logd
lmkd 279 1 13060480 7372 do_epoll
+ 0 S lmkd
system 1383 1 13504456 60264 do_epoll_+ 0 S surfaceflinger

u0_a150 5280 1105 16943368 103628 do_freeze+ 0 S com.android.mms
u0_a190 5334 1105 16966004 134128 do_freeze+ 0 S com.android.permissioncontroller
u0_a37 5352 1105 16778080 100784 do_freeze+ 0 S com.android.providers.calendar


注意最后一列:NAME,它的含义如下所示:Process name。可是看完上面的输出,会发现有几个奇怪的点。


1. 为什么有的进程名是可执行文件的名称,有的却是应用的包名?
2. 为什么有的进程名会用方括号括住?


下面我们翻译翻译,什么TM的是TM的进程名。


**[/external/toybox/toys/posix/ps.c]**



// String fields (-1 is procpid->str, rest are str+offset[1-slot])
{“TTY”, “Controlling terminal”, -8, -2},
{“WCHAN”, “Wait location in kernel”, -6, -3},
{“LABEL”, “Security label”, -30, -4},
{“COMM”, “EXE filename (/proc/PID/exe)”, -27, -5},
{“NAME”, “Process name (PID’s argv[0])”, -27, -7},
{“COMMAND”, “EXE path (/proc/PID/exe)”, -27, -5},
{“CMDLINE”, “Command line (argv[])”, -27, -6},
{“ARGS”, “CMDLINE minus initial path”, -27, -6},
{“CMD”, “Thread name (/proc/TID/stat:2)”, -15, -1},


Process name按照上述的注释,可以理解为argv[0]指向的字符串。这个数据从`/proc/[pid]/cmdline`文件节点读出,但需要经过一些特殊的处理。


**[/external/toybox/toys/posix/ps.c]**



struct {
char *name; // Path under /proc/$PID directory
long long bits; // Only fetch extra data if an -o field is displaying it
} fetch[] = {
// sources for procpid->offset[] data
{“fd/”, _PS_TTY}, {“wchan”, _PS_WCHAN}, {“attr/current”, _PS_LABEL},
{“exe”, _PS_COMMAND|_PS_COMM}, {“cmdline”, _PS_CMDLINE|_PS_ARGS|_PS_NAME},
{“”, _PS_NAME}
};


从cmdline文件节点读出来的原始信息包含所有参数,它们中间由’\0’进行分隔。Ps进程拿到这些数据后将会进行如下处理:


(假设我们拿到的原始信息是:“/system/bin/top`\0`-d`\0`4`\0`”)


1. 将所有的’\0’用空格代替,处理后的字符串可以显示在`CMDLINE`列。(处理后变为:“/system/bin/top -d 4”)
2. 将之前代替的第一个’\0’前的字符串作为argv[0],并将argv[0]字符串最后一个’/'前的信息去除,只保留基本的文件名(英文又称basename),处理后的字符串可以显示在`NAME`列。(处理后变为:“top”)
3. 将argv[0]中的路径信息去除,但是保留后续的参数信息,处理后的字符串可以显示在`ARGS`列。(处理后变为:“top -d 4”)


因此我们可以知道,cmdline文件节点读出的信息最终被用在了三个地方,有点一鱼三吃的感觉。


最终显示在`ps -A`中的进程名,是argv[0]字符串的basename,通常是可执行文件的名称。而Android应用之所以显示为包名,是因为进程启动过程中改写了argv[0]的值,这个放到后面再说。


那为什么有些进程名用方括号括起来了呢?


答案是这些进程没有cmdline(内核进程和一些特殊的用户进程)。当cmdline文件节点读不到任何信息时,ps会将该进程的`task_struct.comm`值取出,并用方括号括住来替代显示。对这些进程而言,`CMDLINE`、`NAME`和`ARGS`列显示的都是同一个字符串。所以看到这样的进程名时,我们大概率可以推测这是一个内核进程。


#### 2.2 Top显示的进程名


[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8E8osACv-1655301109515)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/aaf4408653354c7fb4480df4bbcad375~tplv-k3u1fbpfcp-zoom-in-crop-mark:1956:0:0:0.image?)]


Top显示的进程名为`ARGS`(具体含义见#2.1)。严格来说,它不能叫做”进程名“,而应该叫”参数列表“。这里我们以top进程示例(第二行),可以看到`ARGS`为"top -d 4",它包含了后续的参数信息。


#### 2.3 Ps -T -p显示的线程名



ps -T -p 5280

USER PID TID PPID VSZ RSS WCHAN ADDR S CMD
u0_a150 5280 5280 1105 16943368 103628 do_freeze+ 0 S com.android.mms
u0_a150 5280 5281 1105 16943368 103628 do_freeze+ 0 S Runtime worker
u0_a150 5280 5282 1105 16943368 103628 do_freeze+ 0 S Runtime worker
u0_a150 5280 5283 1105 16943368 103628 do_freeze+ 0 S Runtime worker
u0_a150 5280 5284 1105 16943368 103628 do_freeze+ 0 S Runtime worker
u0_a150 5280 5285 1105 16943368 103628 do_freeze+ 0 S Signal Catcher
u0_a150 5280 5286 1105 16943368 103628 do_freeze+ 0 S perfetto_hprof_
u0_a150 5280 5287 1105 16943368 103628 do_freeze+ 0 S ADB-JDWP Connec
u0_a150 5280 5288 1105 16943368 103628 do_freeze+ 0 S Jit thread pool
u0_a150 5280 5289 1105 16943368 103628 do_freeze+ 0 S HeapTaskDaemon
u0_a150 5280 5290 1105 16943368 103628 do_freeze+ 0 S ReferenceQueueD
u0_a150 5280 5291 1105 16943368 103628 do_freeze+ 0 S FinalizerDaemon
u0_a150 5280 5292 1105 16943368 103628 do_freeze+ 0 S FinalizerWatchd
u0_a150 5280 5293 1105 16943368 103628 do_freeze+ 0 S Binder:5280_1
u0_a150 5280 5294 1105 16943368 103628 do_freeze+ 0 S Binder:5280_2
u0_a150 5280 5295 1105 16943368 103628 do_freeze+ 0 S Binder:5280_3
u0_a150 5280 5303 1105 16943368 103628 do_freeze+ 0 S k worker thread
u0_a150 5280 5307 1105 16943368 103628 do_freeze+ 0 S Binder:5280_4
u0_a150 5280 5310 1105 16943368 103628 do_freeze+ 0 S queued-work-loo
u0_a150 5280 5312 1105 16943368 103628 do_freeze+ 0 S ent.InfoHandler
u0_a150 5280 5313 1105 16943368 103628 do_freeze+ 0 S nt.EventHandler
u0_a150 5280 6312 1105 16943368 103628 do_freeze+ 0 S android.bg


Ps -T -p将会显示特定进程下的所有线程 。这里的显示名为`CMD`,该信息通过访问`/proc/TID/stat:2`节点信息获取,它本质上就是`task_struct.comm`字段,有16位长度的限制。



(2) comm %s
The filename of the executable, in parentheses.
Strings longer than TASK_COMM_LEN (16) characters
(including the terminating null byte) are silently
truncated. This is visible whether or not the
executable is swapped out.


如果仔细观察上述的`CMD`信息,你会发现一个奇怪的现象:有些截断是保留名称的后半段(譬如"nt.EventHandler"),而有些截断是保留名称的前半段(譬如"ReferenceQueueD")。这个具体的原因我们保留到Android应用那一节再阐述。


### 3. Pthread视角下的线程名


Native层的线程创建一般采用pthread,不论是libcxx里的std::thread还是Java层的Thread,其底层都是pthread。所以想要准确地理解应用中的线程名,pthread这一关必须得过。


对于pthread而言,它的线程名就是`task_struct.comm`字段。


当我们通过`pthread_create()`创建线程时,有一点值得注意:该函数的内部并没有设置线程名,因此clone动作会将调用线程的comm字段复制给新的线程。也就是说,新线程默认的线程名和调用线程一致。这也是为什么我们会在`surfaceflinger`进程内看到多个同名线程的原因。


改变线程名称可以采用`pthread_setname_np`函数,其最终会修改位于内核空间的`task_struct.comm`字段。这里依然有个地方需要注意,即传入的名称长度不能超过16,否则设置无效。


**[/bionic/libc/bionic/pthread\_setname\_np.cpp]**



int pthread_setname_np(pthread_t t, const char* thread_name) {
ErrnoRestorer errno_restorer;

size_t thread_name_len = strlen(thread_name);
if (thread_name_len >= MAX_TASK_COMM_LEN) return ERANGE;


### 4. Android视角下的进程名和线程名


#### 4.1 Zygote的进程名和线程名


`以下讨论均为64位zygote进程`


Init进程根据`init.zygote64.rc`文件来启动64位的zygote进程,其本质也是fork完之后执行exec调用,传入的参数如下,总长度为78(包含结尾的’\0’)。【现有机器上很多根据init.zygote64\_32.rc文件来启动64位zygote进程,这是参数总长度为99,包含结尾的’\0’。】



/system/bin/app_process64 -Xzygote /system/bin --zygote --start-system-server


**[/frameworks/base/cmds/app\_process/app\_main.cpp]**



#if defined(LP64)
static const char ABI_LIST_PROPERTY[] = “ro.product.cpu.abilist64”;
static const char ZYGOTE_NICE_NAME[] = “zygote64”;
#else

int main(int argc, char* const argv[]) {

AppRuntime runtime(argv[0], computeArgBlockSize(argc, argv));

while (i < argc) {
const char* arg = argv[i++];
if (strcmp(arg, “–zygote”) == 0) {
zygote = true;
niceName = ZYGOTE_NICE_NAME;

if (!niceName.isEmpty()) {
runtime.setArgv0(niceName.string(), true /* setProcName */);
}


Exec执行之后,zygote的进程名和主线程名均会被设置为app\_process64,也即可执行文件的名称。不过main函数内部会对它们进行修改,通过`setArgv0`函数。


**[/frameworks/base/core/jni/AndroidRuntime.cpp]**



void AndroidRuntime::setArgv0(const char* argv0, bool setProcName) {
// Set the kernel’s task name, for as much of the name as we can fit.
// The kernel’s TASK_COMM_LEN minus one for the terminating NUL == 15.
if (setProcName) {
int len = strlen(argv0);
if (len < 15) {
pthread_setname_np(pthread_self(), argv0);
} else {
pthread_setname_np(pthread_self(), argv0 + len - 15);
}
}

// Directly change the memory pointed to by argv[0].
memset(mArgBlockStart, 0, mArgBlockLength);
strlcpy(mArgBlockStart, argv0, mArgBlockLength);

// Let bionic know that we just did that, because __progname points
// into argv[0] (https://issuetracker.google.com/152893281).
setprogname(mArgBlockStart);

}


`SetArgv0`函数会做三件事:


1. 修改zygote主线程的名称为"zygote64",也即修改`task_struct.comm`字段。
2. 修改位于栈底的command line,将原有数据全部清空,更改为"zygote64"。这时候访问`/proc/[zygote's pid]/cmdline`文件节点,获取到的只有"zygote64"。这样不论我们使用cmdline完整的字符串,还是argv[0]指向的字符串,抑或是argv[0]剥离路径后的basename,都将得到"zygote64"。因此,我们有理由说,此时的进程名已经被改为了"zygote64"。
3. 令`__progname`指向command line的开头,该字段主要在libc中使用。


执行完`setArgv0`后,zygote进程的进程名和主线程名都更改为了"zygote64"。可是,事情到这里就结束了么?并不会!


随后zygote还会启动虚拟机,在虚拟机启动的尾声执行如下函数。


**[/art/runtime/thread.cc]**



void Thread::FinishStartup() {
Runtime* runtime = Runtime::Current();
CHECK(runtime->IsStarted());

// Finish attaching the main thread.
ScopedObjectAccess soa(Thread::Current());
soa.Self()->CreatePeer(“main”, false, runtime->GetMainThreadGroup());


`CreatePeer`内部会调用`SetThreadName`再次修改线程的名称。


**[/art/runtime/thread.cc]**



void Thread::SetThreadName(const char* name) {
tlsPtr_.name->assign(name);
:🎨:SetThreadName(name);
Dbg::DdmSendThreadNotification(this, CHUNK_TYPE(“THNM”));
}


这里线程名将拥有两层含义,因为启动虚拟机之后的主线程将不仅仅是一个pthread线程,还是一个ART线程。


1. 第一层含义:`task_struct.comm`字段,也即pthread的线程名,该名称存放于内核地址空间。
2. 第二层含义:每个ART线程都会对应一个art::Thread对象,其内部有一个字段:`tlsPtr_.name`。该名称存放于用户地址空间。


回到`SetThreadName`函数,它会分别修改两层含义的线程名。首先将`tlsPtr_.name`字段改为"main",接着通过`::art::SetThreadName`将`task_struct.comm`字段更改为"main"。


**[/art/libartbase/base/utils.cc]**



void SetThreadName(const char* thread_name) {
bool hasAt = false;
bool hasDot = false;
const char* s = thread_name;
while (*s) {
if (*s == ‘.’) {
hasDot = true;
} else if (*s == ‘@’) {
hasAt = true;
}
s++;
}
int len = s - thread_name;
if (len < 15 || hasAt || !hasDot) {
s = thread_name;
} else {
s = thread_name + len - 15;
}
#if defined(linux) || defined(_WIN32)
// pthread_setname_np fails rather than truncating long strings.
char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded in the kernel.
strncpy(buf, s, sizeof(buf)-1);
buf[sizeof(buf)-1] = ‘\0’;
errno = pthread_setname_np(pthread_self(), buf);
if (errno != 0) {
PLOG(WARNING) << “Unable to set the name of current thread to '” << buf << “'”;
}
#else // APPLE
pthread_setname_np(thread_name);
#endif
}


`::art::SetThreadName`对传入的名称有些特殊处理,处理规则如下。


1. 如果传入的名称含有’@‘符号,或者**不**含’.'符号,则在截断时保留前半部分。
2. 否则字符串在截断时保留后半部分。


了解规则并不重要,理解规则背后的思考才重要。这里说下我对于这个规则的理解:16字符的长度限制是内核空间为了控制task\_struct结构体大小不得不做的牺牲,对于长度超过16的名称,Google设计的目标是保留其中最有信息量的部分。通过’.‘符号来分割的名称,前半部分的信息含量一般较低。我们以包名举例,前半部分一般为"com"、"org"之类的名称,而最后才是每个包名最独特的地方,也是信息量最大的部分。而’@'符号后面跟的一般是版本信息,它对于我们了解线程的身份并不重要,因为系统中很少有多个版本同时存在。


回到之前`ps -T -p`显示过的线程名,5290线程保留了前半部分,5312线程保留了后半部分。配合刚刚介绍的规则,我想你可以更加深入地理解。



u0_a150 5280 5290 1105 16943368 103628 do_freeze+ 0 S ReferenceQueueD
u0_a150 5280 5291 1105 16943368 103628 do_freeze+ 0 S FinalizerDaemon
u0_a150 5280 5292 1105 16943368 103628 do_freeze+ 0 S FinalizerWatchd
u0_a150 5280 5310 1105 16943368 103628 do_freeze+ 0 S queued-work-loo
u0_a150 5280 5312 1105 16943368 103628 do_freeze+ 0 S ent.InfoHandler


继续回到zygote进程。当虚拟机启动完毕后,zygote的主线程名更改为"main",不论是pthread的视角(`task_struct.comm`),还是ART线程的视角(`tlsPtr_.name`)。


#### 4.2 Android应用的进程名和线程名


Android应用进程由zygote fork而出,而且这个fork动作发生在zygote的主线程。当fork完毕后,应用进程(目前只有一个线程)主线程的`task_struct.comm`和zygote主线程一致,且它的`tlsPtr_.name`也和zygote主线程一致,均为"main"。


应用进程主线程会接着调用`SpecializeCommon`函数,其中会再次修改线程名。nice\_name也即应用在manifest中声明的进程名,默认情况下它和包名是一致的,除非我们设置了"android:process"。


**[/frameworks/base/core/jni/com\_android\_internal\_os\_Zygote.cpp]**



// Make it easier to debug audit logs by setting the main thread’s name to the
// nice name rather than “app_process”.
if (nice_name.has_value()) {
SetThreadName(nice_name.value());
} else if (is_system_server) {
SetThreadName(“system_server”);
}


不过需要注意的是,这个`SetThreadName`只会修改`task_struct.comm`,而不会修改`tlsPtr_.name`。因此如果我们将这个线程看作pthread,那么它的名称就是包名;可是如果我们将它看作ART thread,那么它的名称就是"main"。


**[/frameworks/base/core/jni/com\_android\_internal\_os\_Zygote.cpp]**



void SetThreadName(const std::string& thread_name) {
bool hasAt = false;
bool hasDot = false;

for (const char str_el : thread_name) {
if (str_el == ‘.’) {
hasDot = true;
} else if (str_el == ‘@’) {
hasAt = true;
}
}

const char* name_start_ptr = thread_name.c_str();
if (thread_name.length() >= MAX_NAME_LENGTH && !hasAt && hasDot) {
name_start_ptr += thread_name.length() - MAX_NAME_LENGTH;
}

// pthread_setname_np fails rather than truncating long strings.
char buf[16]; // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
strlcpy(buf, name_start_ptr, sizeof(buf) - 1);
errno = pthread_setname_np(pthread_self(), buf);
if (errno != 0) {
ALOGW(“Unable to set the name of current thread to ‘%s’: %s”, buf, strerror(errno));
}
// Update base::logging default tag.
android::base::SetDefaultTag(buf);
}


待`SpecializeCommon`执行完毕后,主线程会调用`setArgv0`来修改进程名,将command line由"zygote64"改为应用包名。


至此,应用进程的command line和主线程的`task_struct.comm`均设置为包名,而主线程的`tlsPtr_.name`依旧为"main"。


#### 4.3 Java中新线程的名称


我们在Java中创建的线程,它本质上是ART线程,而Java层的Thread对象更像是个傀儡,其核心的运作和数据都在Native层的art::Thread对象中。当我们在Java层new一个Thread对象时,与之对应的art::Thread并没有创建。只有当我们调用Thread.start()时,art::Thread才会创建。


art::Thread创建并启动成功后,新线程会将自己的名称改为创建Thread时传入的名称。如果我们在创建时并未指定名称,则系统会按照"Thread"+"序号"的方式自动命名,这一点和pthread不同。


**[/libcore/ojluni/src/main/java/java/lang/Thread.java]**



public Thread(ThreadGroup group, Runnable target) {
init(group, target, “Thread-” + nextThreadNum(), 0);
}


不过即便线程启动完毕,我们也可以在后续过程中通过Thread.setName来修改线程名。


与主线程不同,这些线程在修改名称时会同时修改`task_struct.comm`和`tlsPtr_.name`。


#### 4.4 Trace文件和Tombstone文件中的进程名和线程名


对大多数开发者而言,他们接触到进程名和线程名的地方主要是trace文件和tombstone文件。


**[Trace文件示例]**



----- pid 9000 at 2022-03-17 05:00:52.489353500+0000 -----
Cmd line: com.hangl.helloworldhelloworldhelloworldhelloworldhelloworldhelloworldhellowo

DALVIK THREADS (16):
“Signal Catcher” daemon prio=10 tid=5 Runnable

“main” prio=5 tid=1 Native

“ReferenceQueueDaemon” daemon prio=5 tid=12 Waiting


"Cmd line"后的字符串是通过访问`/proc/self/cmdline`文件节点获取到的。只不过将原始字符串去除了尾部多余的’\0’,且将分隔的’\0’替换为了空格。根据前文可知,待`SpecializeCommon`执行完毕后,应用主线程会调用`setArgv0`来修改进程名,将command line由"zygote64"改为应用包名。


**[/art/runtime/signal\_catcher.cc]**



static void DumpCmdLine(std::ostream& os) {
#if defined(linux)
// Show the original command line, and the current command line too if it’s changed.
// On Android, /proc/self/cmdline will have been rewritten to something like “system_server”.
// Note: The string “Cmd line:” is chosen to match the format used by debuggerd.
std::string current_cmd_line;
if (android::base::ReadFileToString(“/proc/self/cmdline”, &current_cmd_line)) {
current_cmd_line.resize(current_cmd_line.find_last_not_of(‘\0’) + 1); // trim trailing '\0’s
std::replace(current_cmd_line.begin(), current_cmd_line.end(), ‘\0’, ’ ');

os << "Cmd line: " << current_cmd_line << "\n";
const char* stashed_cmd_line = GetCmdLine();
if (stashed_cmd_line != nullptr && current_cmd_line != stashed_cmd_line
        && strcmp(stashed_cmd_line, "<unset>") != 0) {
  os << "Original command line: " << stashed_cmd_line << "\n";
}

}
#else
os << "Cmd line: " << GetCmdLine() << “\n”;
#endif
}


继续延申下,其实这里显示的"Cmd line"也是有长度限制的。它的最大长度为`init.zygote64.rc`启动zygote时传入的参数长度,现阶段为78(包括结尾’\0’)。不知道你们注意到上述的示例trace文件没有,我声明的包名是超过最大长度的,"Cmd line"只保留了前77个字符,加上结尾的’\0’正好78。对比如下。(如果你的机器上用的是`init.zygote64_32.rc`,那么将会保留98个字符。)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值