【binder】【android12】【2.servicemanager启动——全源码分析】

系列文章目录

 可跳转到下面链接查看下表所有内容https://blog.csdn.net/handsomethefirst/article/details/138226266?spm=1001.2014.3001.5501文章浏览阅读2次。系列文章大全https://blog.csdn.net/handsomethefirst/article/details/138226266?spm=1001.2014.3001.5501


目录

系列文章目录

1.简介

1.1 流程介绍

1.2 时序图

2.源码分析

2.1 servicemanager的启动

 2.2 servicemanager.rc

 2.3 main.cpp

 2.4 ProcessState::initWithDriver

 2.5 ProcessState::init

 2.6 ProcessState::ProcessState

 2.7 open_driver

 2.8 binder_open

 2.9 获取版本号binder_ioctl

 2.10 设置binder最大线程数binder_ioctl

2.11 binder_mmap

 2.12 binder_update_page_range

 2.13 setThreadPoolMaxThreadCount

 2.14 ServiceManager构造函数

 2.15 ServiceManager::addService

 2.16 getCallingContext

 2.17 IPCThreadState::self

 2.18 IPCThreadState::IPCThreadState

 2.19 Access::canAdd

 2.20 IPCThreadState::setTheContextObject

 2.21 ProcessState::becomeContextManager

2.22  binder_ioctl

 2.23 binder_new_node

 2.24 Looper::prepare

 2.25 Looper::getForThread

 2.26 Looper::initTLSKey

 2.27 Looper::Looper

 2.28 Looper::rebuildEpollLocked

2.29 Looper::setForThread

 2.30 sp setupTo

 2.31 IPCThreadState::setupPolling

 2.32 Parcel::writeInt32

 2.33 IPCThreadState::flushCommands

2.34 IPCThreadState::talkWithDriver

 2.35 binder_ioctl

 2.36 binder_thread_write

 2.37 Looper::addFd

 2.38 ClientCallbackCallback::setupTo

2.39 pollAll

 2.40 pollOnce

 2.41 pollInner


1.简介

经过上一篇,我们已经知道servermanager的框架,那么本篇便从源码的角度分析servermangaer服务的启动流程。

1.1 流程介绍

第一步:首先init进程启动后会读取各个进程的rc启动文件,然后会去启动servermanager服务。

第二步:在servermanager服务的main函数中,首先会打开/dev/binder驱动,并申请一块内存,通过mmap的进行内存映射,将servermanager服务的用户空间映射到驱动中,从而会减少数据的拷贝。

第三步:在servermanager服务的main函数中,创建servicemanager服务的对象,并将ServiceManager对象注册到自身的Map表保存起来。

第四步:becomeContextManager通知驱动成为binder的管理者。

第五步:servermanager服务的主线程进入死循环,调用epoll_wait() 监听/dev/binder是否有数据可读,如有则调用回调执行指令,根据client传入的code,从而调用get()\add()\ 等接口,来查询、注册binder服务。

1.2 时序图

 (为了保证流程的完整性,较为模糊,可放大观看)


2.源码分析

2.1 servicemanager的启动

1.在init.rc中,当init进程启动后,会去启动servicemanager、hwservicemanager、vndservicemanager 三个binder的守护进程。

[/system/core/rootdir/init.rc]
on init...start servicemanager //启动sericemanager服务start hwservicemanagerstart vndservicemanager

 2.2 servicemanager.rc

1.init进程启动后,会从指定路径加载进程的rc文件,然后启动servicemanager服务。

service servicemanager /system/bin/servicemanagerclass core animation //服务的类为core和animationuser system //在启动服务前将用户切换为systemgroup system readproc //在启动前将用户组切换为system和readproccritical //表明这个服务是至关重要的服务,如果它在四分钟内退出超过四次,则设备将重启进入恢复模式onrestart restart apexd //当此服务重启后,重启apexd服务onrestart restart audioserver //当此服务重启后,重启audioserver服务onrestart restart gatekeeperd //当此服务重启后,重启gatekeeperd服务onrestart class_restart main //当此服务重启后,重启所有class为main的服务onrestart class_restart hal //当此服务重启后,重启所有class为 hal的服务onrestart class_restart early_hal //当此服务重启后,重启所有class为early_hal的服务writepid /dev/cpuset/system-background/tasks //写入当前servicemanager进程的pid到/dev/cpuset/system-background/tasks文件中shutdown critical //设置Service进程的关闭行为。在关机期间,当前服务在shutdown超时之前不会被关闭。

 2.3 main.cpp

主要作用为:

1.打开/dev/binder驱动,并完成mmap的内存映射,然后向设置最大线程数。

2.创建servicemanager服务的对象。

3.将ServiceManager对象注册到自身的Map表中。

4.becomeContextManager通知驱动成为binder的管理者。

5.进入死循环,调用epoll_wait() 监听/dev/binder是否有数据可读,如有则调用回调执行指令,根据client传入的code,从而调用get()\add()\ 等接口,来查询、注册binder服务。

int main(int argc, char** argv) {//servicemanager入口,与/dev/binder交互,vndservicemanager也是走这个口,只是init时,会传入/dev/vndbinder值if (argc > 2) {LOG(FATAL) << "usage: " << argv[0] << " [binder driver]";}const char* driver = argc == 2 ? argv[1] : "/dev/binder";//因为没传入值所以driver值是/dev/bindersp<ProcessState> ps = ProcessState::initWithDriver(driver);//传入的值是/dev/binder,创建了ProcessState对象,里面主要是通过mmap内存映射一块地址空间ps->setThreadPoolMaxThreadCount(0);//设置最大线程数为0ps->setCallRestriction(ProcessState::CallRestriction::FATAL_IF_NOT_ONEWAY);sp<ServiceManager> manager = sp<ServiceManager>::make(std::make_unique<Access>());//创建了一个ServiceManager对象if (!manager->addService("manager", manager, false /*allowIsolated*/, IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT).isOk()) {//将自身注册到ServiceManager当中LOG(ERROR) << "Could not self register servicemanager";}IPCThreadState::self()->setTheContextObject(manager);ps->becomeContextManager();//成为管理者sp<Looper> looper = Looper::prepare(false /*allowNonCallbacks*/);BinderCallback::setupTo(looper);ClientCallbackCallback::setupTo(looper, manager);while(true) {//死循环,looper->pollAll(-1);//阻塞在此处,等待监听的fd有消息的到来}// should not be reachedreturn EXIT_FAILURE;
}

 2.4 ProcessState::initWithDriver

sp<ProcessState> ProcessState::initWithDriver(const char* driver)
{return init(driver, true /*requireDefault*/);
}

 2.5 ProcessState::init

1.创建了ProcessState对象。此对象用于打开binder驱动,并完成内存的映射,将用户空间的一块内存映射到内核空间,映射关系建立后,用户对这块内存区域的修改可直接反映到内核空间,反之内核空间对其修改也能反映到用户空间。

sp<ProcessState> ProcessState::init(const char *driver, bool requireDefault)
{[[clang::no_destroy]] static sp<ProcessState> gProcess;[[clang::no_destroy]] static std::mutex gProcessMutex;/**if (driver == nullptr) {//此时不为空,不执行std::lock_guard<std::mutex> l(gProcessMutex);return gProcess;}*/[[clang::no_destroy]] static std::once_flag gProcessOnce;//call_once的flagstd::call_once(gProcessOnce, [&](){//call_once表示这个函数只执行一次if (access(driver, R_OK) == -1) {//access判断/dev/binder文件是否存在ALOGE("Binder driver %s is unavailable. Using /dev/binder instead.", driver);driver = "/dev/binder";}std::lock_guard<std::mutex> l(gProcessMutex);gProcess = sp<ProcessState>::make(driver);//此处使用的是安卓智能指针的构造,内部会调用new ProcessState});if (requireDefault) {//传入的是true,打印logLOG_ALWAYS_FATAL_IF(gProcess->getDriverName() != driver,"ProcessState was already initialized with %s,"" can't initialize with %s.",gProcess->getDriverName().c_str(), driver);}return gProcess;
}

 2.6 ProcessState::ProcessState

ProcessState::ProcessState(const char *driver): mDriverName(String8(driver))//driver是/dev/binder, mDriverFD(open_driver(driver))//打开binder驱动返回的fd文件描述符, mVMStart(MAP_FAILED)//, mThreadCountLock(PTHREAD_MUTEX_INITIALIZER)//保护线程数量的锁,pthread_mutex_t mThreadCountLock;, mThreadCountDecrement(PTHREAD_COND_INITIALIZER)//条件变量。pthread_cond_t mThreadCountDecrement;, mExecutingThreadsCount(0), mWaitingForThreads(0), mMaxThreads(DEFAULT_MAX_BINDER_THREADS)//最大线程数15, mStarvationStartTimeMs(0), mThreadPoolStarted(false), mThreadPoolSeq(1), mCallRestriction(CallRestriction::NONE)
{if (mDriverFD >= 0) {// mmap binder,内存映射。128k的内存地址,申请128k的内存地址用来接收事务,对应binder驱动的binder_mmap函数。mVMStart = mmap(nullptr, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, 0);/**if (mVMStart == MAP_FAILED) {//如果内存映射失败// *sigh*ALOGE("Using %s failed: unable to mmap transaction memory.\n", mDriverName.c_str());close(mDriverFD);mDriverFD = -1;mDriverName.clear();}*/}
}

 2.7 open_driver

主要作用为:

1.open打开binder驱动,通过系统调用_open,最后会调用到binder_open,陷入内核态。获取fd。

2.通过ioctl,获取binder驱动版本号,用vers保存。然后对比版本号是否一致。

3.通过ioctl设置binder驱动最大线程数。

static int open_driver(const char *driver)
{int fd = open(driver, O_RDWR | O_CLOEXEC);//driver值是/dev/binder,打开binder驱动,陷入内核,此//open对应_open,然后对应binder驱动层的binder_open,binder_open中主要是为/dev/binder这个驱动设备节点,创建//对应的proc对象,然后通过fd返回。这样就可以和驱动进行通信。if (fd >= 0) {//大于0代表打开成功int vers = 0;status_t result = ioctl(fd, BINDER_VERSION, &vers);//获取binder驱动的版本信息,用vers保存/**正常不执行if (result == -1) {//如果获取信息失败,则关闭binder驱动ALOGE("Binder ioctl to obtain version failed: %s", strerror(errno));close(fd);fd = -1;}*//**if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) {//如果获取的版本信息不匹配,则关闭binder驱动ALOGE("Binder driver protocol(%d) does not match user space protocol(%d)! ioctl() return value: %d",vers, BINDER_CURRENT_PROTOCOL_VERSION, result);close(fd);fd = -1;}*/size_t maxThreads = DEFAULT_MAX_BINDER_THREADS;//设置最大线程数15result = ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads);//设置binder驱动最大线程数/**if (result == -1) {ALOGE("Binder ioctl to set max threads failed: %s", strerror(errno));}*/uint32_t enable = DEFAULT_ENABLE_ONEWAY_SPAM_DETECTION;//DEFAULT_ENABLE_ONEWAY_SPAM_DETECTION值是1,表示默认启用更新垃圾检测result = ioctl(fd, BINDER_ENABLE_ONEWAY_SPAM_DETECTION, &enable);//设置到binder驱动中/**if (result == -1) {ALOGD("Binder ioctl to enable oneway spam detection failed: %s", strerror(errno));}*/} /**else {ALOGW("Opening '%s' failed: %s\n", driver, strerror(errno));}*/return fd;
}

 2.8 binder_open

1.为当前sm服务进程分配保存binder_proc的对象。binder_proc结构体保存的是sm服务的进程的信息。

2.对sm服务的binder_proc的对象进行初始化,如初始化todo队列,设置进程优先级等。

3.将sm服务的binder_proc添加到binder_procs队列中,驱动有一个全局的binder_procss的列表,用于存储所有进程的binder_proc对象。

//主要作用:binder驱动为用户进程创建了用户进程自己的binder——proc实体
static int binder_open(struct inode *nodp, struct file *filp)
{struct binder_proc *proc;//proc表示驱动中binder进程proc = kzalloc(sizeof(*proc), GFP_KERNEL);//为binder_proc结构体在分配kernel内存空间if (proc == NULL)return -ENOMEM;//下面是对binder_proc进行初始化,binder_proc用于管理数据的记录体get_task_struct(current);proc->tsk = current;//current代表当前线程。当前线程此时是servicemanager的主线程,当前线程的task保存在binder进程的tskINIT_LIST_HEAD(&proc->todo);//初始化to列表init_waitqueue_head(&proc->wait);//初始化wait列表proc->default_priority = task_nice(current);//当前进程的nice值转化为进程优先级binder_lock(__func__);binder_stats_created(BINDER_STAT_PROC);//BINDER_PROC对象创建+1hlist_add_head(&proc->proc_node, &binder_procs);//将proc_node节点添加到binder_procs为表头的队列proc->pid = current->group_leader->pid;INIT_LIST_HEAD(&proc->delivered_death);filp->private_data = proc;//将 proc 保存到filp中,这样下次可以通过filp找到此procbinder_unlock(__func__);if (binder_debugfs_dir_entry_proc) {char strbuf[11];snprintf(strbuf, sizeof(strbuf), "%u", proc->pid);proc->debugfs_entry = debugfs_create_file(strbuf, S_IRUGO,binder_debugfs_dir_entry_proc, proc, &binder_proc_fops);}return 0;
}
//进程相关的参数
struct binder_proc {struct hlist_node proc_node;//hlist_node表示哈希表中的一个节点。哈希表中的一个节点,用于标记该进程struct rb_root threads;// rb_root表示红黑树。Binder线程池每一个Binder进程都有一个线程池,//由Binder驱动来维护,Binder线程池中所有线程由一个红黑树来组织,RB树以线程ID为关键字  *///上述红黑树的根节点struct rb_root nodes;// 一系列Binder实体对象(binder_node)和Binder引用对象(binder_ref) *///在用户空间:运行在Server端称为Binder本地对象,运行在Client端称为Binder代理对象*///在内核空间:Binder实体对象用来描述Binder本地对象,Binder引用对象来描述Binder代理对象 *///Binder实体对象列表(RB树),关键字 ptrstruct rb_root refs_by_desc;//记录binder引用, 便于快速查找,binder_ref红黑树的根节点(以handle为key),它是Client在Binder驱动中的体现。//Binder引用对象,关键字  descstruct rb_root refs_by_node;//记录binder引用, 便于快速查找,binder_ref红黑树的根节点(以ptr为key),它是Client在Binder驱动中的体现,//Binder引用对象,关键字  nodestruct list_head waiting_threads; int pid;//进程组pidstruct task_struct *tsk;//任务控制模块const struct cred *cred;struct hlist_node deferred_work_node;int deferred_work;bool is_dead;struct list_head todo;//待处理队列,进程每接收到一个通信请求,Binder将其封装成一个工作项,保存在待处理队列to_do中  */struct binder_stats stats;struct list_head delivered_death;int max_threads;// Binder驱动程序最多可以请求进程注册线程的最大数量,//进程可以调用ioctl注册线程到Binder驱动程序中,当线程池中没有足够空闲线程来处理事务时,Binder驱动可以主动要求进程注册更多的线程到Binder线程池中 */// Binder驱动程序最多可以请求进程注册线程的最大数量int requested_threads;int requested_threads_started;int tmp_ref;long default_priority;struct dentry *debugfs_entry;struct binder_alloc alloc;struct binder_context *context;//存储binder_node和binder_context_mgr_uid以及namespinlock_t inner_lock;spinlock_t outer_lock;struct dentry *binderfs_entry;
};

 2.9 获取版本号binder_ioctl

主要作用为:

1.此时用于获取版本号,存在一次拷贝行为。

//获取binder版本号分析
static long binder_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{int ret;struct binder_proc *proc = filp->private_data;struct binder_thread *thread;//binder线程unsigned int size = _IOC_SIZE(cmd);void __user *ubuf = (void __user *)arg;trace_binder_ioctl(cmd, arg);ret = wait_event_interruptible(binder_user_error_wait, binder_stop_on_user_error < 2);//binder_stop_on_user_error值是0,//binder_stop_on_user_error < 2为假时,休眠,故此处不休眠if (ret)goto err_unlocked;binder_lock(__func__);thread = binder_get_thread(proc);//获取当前sm的proc实体对象的binder_threadif (thread == NULL) {ret = -ENOMEM;goto err;}switch (cmd) {case BINDER_VERSION://获取版本号if (size != sizeof(struct binder_version)) {ret = -EINVAL;goto err;}if (put_user(BINDER_CURRENT_PROTOCOL_VERSION, &((struct binder_version *)ubuf)->protocol_version)) {//将驱动程序的BINDER_CURRENT_PROTOCOL_VERSION变量地址,拷贝sizeof(*ptr)的ubuf用户空间地址。//分析,此处是有一次拷贝的。ret = -EINVAL;goto err;}break;default:ret = -EINVAL;goto err;}ret = 0;
err:if (thread)thread->looper &= ~BINDER_LOOPER_STATE_NEED_RETURN;binder_unlock(__func__);wait_event_interruptible(binder_user_error_wait, binder_stop_on_user_error < 2);//不休眠if (ret && ret != -ERESTARTSYS)printk(KERN_INFO "binder: %d:%d ioctl %x %lx returned %d\n", proc->pid, current->pid, cmd, arg, ret);
err_unlocked:trace_binder_ioctl_done(ret);return ret;
}

 2.10 设置binder最大线程数binder_ioctl

//设置binder最大线程数分析
//ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads);maxThreads值为15
static long binder_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{int ret;struct binder_proc *proc = filp->private_data;struct binder_thread *thread;//binder线程unsigned int size = _IOC_SIZE(cmd);void __user *ubuf = (void __user *)arg;//ubuf是15的地址trace_binder_ioctl(cmd, arg);ret = wait_event_interruptible(binder_user_error_wait, binder_stop_on_user_error < 2);//不休眠if (ret)goto err_unlocked;binder_lock(__func__);thread = binder_get_thread(proc);//获取当前sm的proc实体的binder_threadif (thread == NULL) {ret = -ENOMEM;goto err;}switch (cmd) {case BINDER_SET_MAX_THREADS://设置binder最大线程数量if (copy_from_user(&proc->max_threads, ubuf, sizeof(proc->max_threads))) {//拷贝用户空间的地址到内核空间ret = -EINVAL;goto err;}break;ret = 0;
err:if (thread)thread->looper &= ~BINDER_LOOPER_STATE_NEED_RETURN;binder_unlock(__func__);wait_event_interruptible(binder_user_error_wait, binder_stop_on_user_error < 2);if (ret && ret != -ERESTARTSYS)printk(KERN_INFO "binder: %d:%d ioctl %x %lx returned %d\n", proc->pid, current->pid, cmd, arg, ret);
err_unlocked:trace_binder_ioctl_done(ret);return ret;
}

2.11 binder_mmap

主要作用为:

1.get_vm_area分配一个连续的内核虚拟空间,与用户进程虚拟空间大小一致。

2.binder_update_page_range,分配物理页面,同时映射到内核空间和用户进程空间。

即,此时servermanager服务在其内部分配了一块地址映射进入了内核空间。减少了拷贝。

//filp对应fp,vma代表用户地址空间
static int binder_mmap(struct file *filp, struct vm_area_struct *vma)//vma描述了应用程序使用的用户虚拟空间
{int ret;struct vm_struct *area;//内核虚拟空间struct binder_proc *proc = filp->private_data;//取出sm进程对应的binder_proc对象const char *failure_string;struct binder_buffer *buffer;//用于binder传输数据的缓冲区if ((vma->vm_end - vma->vm_start) > SZ_4M)//保证映射内存大小不超过4Mvma->vm_end = vma->vm_start + SZ_4M;if (vma->vm_flags & FORBIDDEN_MMAP_FLAGS) {//判断是否禁止mmapret = -EPERM;failure_string = "bad vm_flags";goto err_bad_arg;}vma->vm_flags = (vma->vm_flags | VM_DONTCOPY) & ~VM_MAYWRITE;mutex_lock(&binder_mmap_lock);if (proc->buffer) {//如果buffer不为空,则代表已经mmap过了ret = -EBUSY;failure_string = "already mapped";goto err_already_mapped;}area = get_vm_area(vma->vm_end - vma->vm_start, VM_IOREMAP);//分配一个连续的内核虚拟空间,与用户进程虚拟空间大小一致if (area == NULL) {ret = -ENOMEM;failure_string = "get_vm_area";goto err_get_vm_area_failed;}proc->buffer = area->addr;//binder_proc对象的buffer指向内核虚拟空间的地址proc->user_buffer_offset = vma->vm_start - (uintptr_t)proc->buffer;//计算偏移量,地址偏移量=用户空间地址-内核空间地址mutex_unlock(&binder_mmap_lock);proc->pages = kzalloc(sizeof(proc->pages[0]) * ((vma->vm_end - vma->vm_start) / PAGE_SIZE), GFP_KERNEL);//分配//分配物理页的指针数组,大小等于用户虚拟内存/4K,此数组用于指示binder申请的物理页的状态if (proc->pages == NULL) {ret = -ENOMEM;failure_string = "alloc page array";goto err_alloc_pages_failed;}proc->buffer_size = vma->vm_end - vma->vm_start;//计算大小vma->vm_ops = &binder_vm_ops;vma->vm_private_data = proc;if (binder_update_page_range(proc, 1, proc->buffer, proc->buffer + PAGE_SIZE, vma)) {//分配物理页面,同时映射到内核空间和进程空间,//目前只分配1个page的物理页ret = -ENOMEM;failure_string = "alloc small buf";goto err_alloc_small_buf_failed;}buffer = proc->buffer;//binder_buffer对象,指向proc的buffer地址,proc的buffer地址又指向内核虚拟空间的地址INIT_LIST_HEAD(&proc->buffers);list_add(&buffer->entry, &proc->buffers);//将内核虚拟空间的地址加入到所属进程的buffer队列buffer->free = 1;binder_insert_free_buffer(proc, buffer);//将空闲的buffer放入proc->free_buffer中proc->free_async_space = proc->buffer_size / 2;barrier();proc->files = get_files_struct(proc->tsk);proc->vma = vma;//binder_proc对象保存了用户空间的地址proc->vma_vm_mm = vma->vm_mm;/*printk(KERN_INFO "binder_mmap: %d %lx-%lx maps %p\n",proc->pid, vma->vm_start, vma->vm_end, proc->buffer);*/return 0;
错误跳转
err_alloc_small_buf_failed:kfree(proc->pages);proc->pages = NULL;
err_alloc_pages_failed:mutex_lock(&binder_mmap_lock);vfree(proc->buffer);proc->buffer = NULL;
err_get_vm_area_failed:
err_already_mapped:mutex_unlock(&binder_mmap_lock);
err_bad_arg:printk(KERN_ERR "binder_mmap: %d %lx-%lx %s failed %d\n",proc->pid, vma->vm_start, vma->vm_end, failure_string, ret);return ret;
}

 2.12 binder_update_page_range

主要作用为:

1.分配物理内存空间。

2.将物理空间映射到内核空间。

3.将物理空间映射到用户进程空间。

当然binder_update_page_range 既可以分配物理页面,也可以释放物理页面。

//binder_update_page_range 主要完成工作:分配物理内存空间,将物理空间映射到内核空间,将物理空间映射到进程空间。
//当然binder_update_page_range 既可以分配物理页面,也可以释放物理页面
static int binder_update_page_range(struct binder_proc *proc, int allocate,void *start, void *end,struct vm_area_struct *vma)//参数说明://proc对应的进程的proc对象//allocate表示是申请还是释放//start,表示内核虚拟空间起始地址//end,内核虚拟空间末尾地址//用户空间地址
{void *page_addr;unsigned long user_page_addr;struct vm_struct tmp_area;struct page **page;struct mm_struct *mm;if (end <= start)return 0;trace_binder_update_page_range(proc, allocate, start, end);if (vma)mm = NULL;elsemm = get_task_mm(proc->tsk);if (mm) {down_write(&mm->mmap_sem);vma = proc->vma;if (vma && mm != proc->vma_vm_mm) {pr_err("binder: %d: vma mm and task mm mismatch\n",proc->pid);vma = NULL;}}if (allocate == 0)goto free_range;if (vma == NULL) {printk(KERN_ERR "binder: %d: binder_alloc_buf failed to ""map pages in userspace, no vma\n", proc->pid);goto err_no_vma;}//前面都在判断参数是否合法//for (page_addr = start; page_addr < end; page_addr += PAGE_SIZE) {int ret;struct page **page_array_ptr;page = &proc->pages[(page_addr - proc->buffer) / PAGE_SIZE];BUG_ON(*page);//分配物理内存*page = alloc_page(GFP_KERNEL | __GFP_HIGHMEM | __GFP_ZERO);if (*page == NULL) {printk(KERN_ERR "binder: %d: binder_alloc_buf failed ""for page at %p\n", proc->pid, page_addr);goto err_alloc_page_failed;}tmp_area.addr = page_addr;//tmp_area是内核地址,此时指向物理地址tmp_area.size = PAGE_SIZE + PAGE_SIZE /* guard page? */;page_array_ptr = page;ret = map_vm_area(&tmp_area, PAGE_KERNEL, &page_array_ptr);//映射物理页地址到内核地址tmp_areaif (ret) {printk(KERN_ERR "binder: %d: binder_alloc_buf failed ""to map page at %p in kernel\n",proc->pid, page_addr);goto err_map_kernel_failed;}user_page_addr =(uintptr_t)page_addr + proc->user_buffer_offset;ret = vm_insert_page(vma, user_page_addr, page[0]);//映射物理页地址到虚拟用户地址空间vmaif (ret) {printk(KERN_ERR "binder: %d: binder_alloc_buf failed ""to map page at %lx in userspace\n",proc->pid, user_page_addr);goto err_vm_insert_page_failed;}/* vm_insert_page does not seem to increment the refcount */}if (mm) {up_write(&mm->mmap_sem);mmput(mm);}return 0;free_range:for (page_addr = end - PAGE_SIZE; page_addr >= start;page_addr -= PAGE_SIZE) {page = &proc->pages[(page_addr - proc->buffer) / PAGE_SIZE];if (vma)zap_page_range(vma, (uintptr_t)page_addr +proc->user_buffer_offset, PAGE_SIZE, NULL);
err_vm_insert_page_failed:unmap_kernel_range((unsigned long)page_addr, PAGE_SIZE);
err_map_kernel_failed:__free_page(*page);*page = NULL;
err_alloc_page_failed:;}
err_no_vma:if (mm) {up_write(&mm->mmap_sem);mmput(mm);}return -ENOMEM;
}

 2.13 setThreadPoolMaxThreadCount

1.设置最大线程数。

status_t ProcessState::setThreadPoolMaxThreadCount(size_t maxThreads) {//传入的是0LOG_ALWAYS_FATAL_IF(mThreadPoolStarted && maxThreads < mMaxThreads,"Binder threadpool cannot be shrunk after starting");status_t result = NO_ERROR;if (ioctl(mDriverFD, BINDER_SET_MAX_THREADS, &maxThreads) != -1) {//设置最大线程数为0mMaxThreads = maxThreads;} else {result = -errno;ALOGE("Binder ioctl to set max threads failed: %s", strerror(-result));}return result;
}

 2.14 ServiceManager构造函数

ServiceManager::ServiceManager(std::unique_ptr<Access>&& access) : mAccess(std::move(access)) {
}
//负责权限控制
Access::Access() {union selinux_callback cb;//selinux相关cb.func_audit = auditCallback;selinux_set_callback(SELINUX_CB_AUDIT, cb);cb.func_log = kIsVendor ? selinux_vendor_log_callback : selinux_log_callback;selinux_set_callback(SELINUX_CB_LOG, cb);CHECK(selinux_status_open(true /*fallback*/) >= 0);CHECK(getcon(&mThisProcessContext) == 0);
}

 2.15 ServiceManager::addService

主要作用为:

1.将自身ServiceManager对象添加到一个map中保存。此map的key是服务的name,Value则是封装了对应的binder对象的service类。

//ServiceManager继承自BnServiceManager
"manager", manager, false /*allowIsolated*/, IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT).isOk()
Status ServiceManager::addService(const std::string& name, const sp<IBinder>& binder, bool allowIsolated, int32_t dumpPriority) {//传入的参数//name是manager//binder是ServiceManager类对象,ServiceManager继承自BnServiceManager//allowIsolated是falseauto ctx = mAccess->getCallingContext();/**// app不能添加到service中if (multiuser_get_app_id(ctx.uid) >= AID_APP) {return Status::fromExceptionCode(Status::EX_SECURITY);}if (!mAccess->canAdd(ctx, name)) {//检查se权限return Status::fromExceptionCode(Status::EX_SECURITY);}if (binder == nullptr) {return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);}if (!isValidServiceName(name)) {LOG(ERROR) << "Invalid service name: " << name;return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);}*/#ifndef VENDORSERVICEMANAGERif (!meetsDeclarationRequirements(binder, name)) {// already loggedreturn Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);}
#endif  // !VENDORSERVICEMANAGER//检查是否有死亡链接if (binder->remoteBinder() != nullptr &&binder->linkToDeath(sp<ServiceManager>::fromExisting(this)) != OK) {LOG(ERROR) << "Could not linkToDeath when adding " << name;return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);}// 覆盖旧服务(如果存在)//mNameToService是一个ServiceMap,using ServiceMap = std::map<std::string, Service>;//    struct Service {//   sp<IBinder> binder; // not null//    bool allowIsolated;//    int32_t dumpPriority;//    bool hasClients = false; // notifications sent on true -> false.//    bool guaranteeClient = false; // forces the client check to true//    pid_t debugPid = 0; // the process in which this service runs// the number of clients of the service, including servicemanager itself//    ssize_t getNodeStrongRefCount();//};mNameToService[name] = Service {//保存此service,name是manager.binder = binder,//此时是ServiceManager,对象。.allowIsolated = allowIsolated.dumpPriority = dumpPriority,.debugPid = ctx.debugPid,};auto it = mNameToRegistrationCallback.find(name);//mNameToRegistrationCallback是一个ServiceCallbackMap//using ServiceCallbackMap = std::map<std::string, std::vector<sp<IServiceCallback>>>;/**if (it != mNameToRegistrationCallback.end()) {for (const sp<IServiceCallback>& cb : it->second) {mNameToService[name].guaranteeClient = true;// permission checked in registerForNotificationscb->onRegistration(name, binder);}}*/return Status::ok();
}

 然后我们再看一下其类的结构图。

 2.16 getCallingContext

Access::CallingContext Access::getCallingContext() {IPCThreadState* ipc = IPCThreadState::self();//创建了IPCThreadState对象const char* callingSid = ipc->getCallingSid();//获取了sidpid_t callingPid = ipc->getCallingPid();//获取了pidreturn CallingContext {.debugPid = callingPid,.uid = ipc->getCallingUid(),.sid = callingSid ? std::string(callingSid) : getPidcon(callingPid),};//返回了一个保存sid,uid的结构体
}

 2.17 IPCThreadState::self

IPCThreadState* IPCThreadState::self()
{/**不执行if (gHaveTLS.load(std::memory_order_acquire)) {//定义时是false。static std::atomic<bool> gHaveTLS(false);
restart:const pthread_key_t k = gTLS;IPCThreadState* st = (IPCThreadState*)pthread_getspecific(k);if (st) return st;return new IPCThreadState;}// Racey, heuristic test for simultaneous shutdown.if (gShutdown.load(std::memory_order_relaxed)) {//定义是false。static std::atomic<bool> gShutdown = false;ALOGW("Calling IPCThreadState::self() during shutdown is dangerous, expect a crash.\n");return nullptr;}*/pthread_mutex_lock(&gTLSMutex);if (!gHaveTLS.load(std::memory_order_relaxed)) {int key_create_value = pthread_key_create(&gTLS, threadDestructor);//分配用于表示进程中线程特定数据的键,键对进程中的所有线程来说是全局的.//pthread_key_create第一个参数为指向一个键值的指针,第二个参数指明了一个destructor函数,//如果这个参数不为空,那么当每个线程结束时,系统将调用这个函数来释放绑定在这个键上的内存块。//key_create_value成功返回0,其他是失败/**if (key_create_value != 0) {pthread_mutex_unlock(&gTLSMutex);ALOGW("IPCThreadState::self() unable to create TLS key, expect a crash: %s\n",strerror(key_create_value));return nullptr;}*/gHaveTLS.store(true, std::memory_order_release);//将gHaveTLS值设置为true。static std::atomic<bool> gHaveTLS(false);}pthread_mutex_unlock(&gTLSMutex);goto restart;
}

 2.18 IPCThreadState::IPCThreadState

IPCThreadState::IPCThreadState(): mProcess(ProcessState::self()),//保存当前的ProcessState对象mServingStackPointer(nullptr),mWorkSource(kUnsetWorkSource),mPropagateWorkSource(false),mIsLooper(false),mIsFlushing(false),mStrictModePolicy(0),mLastTransactionBinderFlags(0),mCallRestriction(mProcess->mCallRestriction) {pthread_setspecific(gTLS, this);//将自己即IPCThreadState对象存储到gTLS中。clearCaller();mIn.setDataCapacity(256);//设置输入缓存区大小mOut.setDataCapacity(256);//设置输出缓存区大小
}

 2.19 Access::canAdd

主要作用为:

1.检查是否有向servermanager添加的服务权限。


bool Access::canAdd(const CallingContext& ctx, const std::string& name) {return actionAllowedFromLookup(ctx, name, "add");
}bool Access::actionAllowedFromLookup(const CallingContext& sctx, const std::string& name, const char *perm) {char *tctx = nullptr;if (selabel_lookup(getSehandle(), &tctx, name.c_str(), SELABEL_CTX_ANDROID_SERVICE) != 0) {LOG(ERROR) << "SELinux: No match for " << name << " in service_contexts.\n";return false;}bool allowed = actionAllowed(sctx, tctx, perm, name);freecon(tctx);return allowed;
}

 2.20 IPCThreadState::setTheContextObject

主要作用为:

1.设置当前线程的上下文对象。

void IPCThreadState::setTheContextObject(const sp<BBinder>& obj)
{the_context_object = obj;//设置当前ipc线程的上下文对象,BBbinder,obj是ServiceManager类对象。
}

 2.21 ProcessState::becomeContextManager

主要作用是:

1.告诉驱动注册成为binder的管理者。

bool ProcessState::becomeContextManager()
{AutoMutex _l(mLock);flat_binder_object obj {.flags = FLAT_BINDER_FLAG_TXN_SECURITY_CTX,//表示请求安全上下文。FLAT_BINDER_FLAG_TXN_SECURITY_CTX};int result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR_EXT, &obj);//通知驱动,将ServiecManager设置成为安全的上下文// fallback to original methodif (result != 0) {android_errorWriteLog(0x534e4554, "121035042");int unused = 0;//如果安全上下文设置失败,继续使用原有的BINDER_SET_CONTEXT_MGR来设置为管理者result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR, &unused);}if (result == -1) {ALOGE("Binder ioctl to become context manager failed: %s\n", strerror(errno));}return result == 0;
}

2.22  binder_ioctl

主要作用为:

1.取出SM进程对应的porc对象。

2.设置binder的context管理者,也就是servicemanager称为守护进程。

3.在驱动中创建一个驱动中的binder实体对象,并赋值给binder_context_mgr_node。

//设置成为binder管理者
//ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR_EXT, &obj);//通知驱动,将ServiecManager设置成为安全的上下文
static long binder_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{int ret;struct binder_proc *proc = filp->private_data;struct binder_thread *thread;//binder线程unsigned int size = _IOC_SIZE(cmd);void __user *ubuf = (void __user *)arg;trace_binder_ioctl(cmd, arg);ret = wait_event_interruptible(binder_user_error_wait, binder_stop_on_user_error < 2);//条件成立,不休眠,返回值是0if (ret)goto err_unlocked;binder_lock(__func__);thread = binder_get_thread(proc);//获取binder_threadif (thread == NULL) {ret = -ENOMEM;goto err;}switch (cmd) {case BINDER_SET_CONTEXT_MGR://设置binder的context管理者,也就是servicemanager称为守护进程if (binder_context_mgr_node != NULL) {//如果不为空,代表已经设置过了printk(KERN_ERR "binder: BINDER_SET_CONTEXT_MGR already set\n");ret = -EBUSY;goto err;}ret = security_binder_set_context_mgr(proc->tsk);if (ret < 0)goto err;if (binder_context_mgr_uid != -1) {//binder_context_mgr_uid不为-1,代表已经有进程注册过管理者了if (binder_context_mgr_uid != current->cred->euid) {//如果和当前进程id不等,则错误printk(KERN_ERR "binder: BINDER_SET_""CONTEXT_MGR bad uid %d != %d\n",current->cred->euid,binder_context_mgr_uid);ret = -EPERM;goto err;}} else//未被注册过binder_context_mgr_uid = current->cred->euid;//则设置为当前进程的用户idbinder_context_mgr_node = binder_new_node(proc, NULL, NULL);//创建一个binder对象,并赋值给binder_context_mgr_nodeif (binder_context_mgr_node == NULL) {ret = -ENOMEM;goto err;}binder_context_mgr_node->local_weak_refs++;binder_context_mgr_node->local_strong_refs++;binder_context_mgr_node->has_strong_ref = 1;binder_context_mgr_node->has_weak_ref = 1;break;}ret = 0;
err:if (thread)thread->looper &= ~BINDER_LOOPER_STATE_NEED_RETURN;binder_unlock(__func__);wait_event_interruptible(binder_user_error_wait, binder_stop_on_user_error < 2);if (ret && ret != -ERESTARTSYS)printk(KERN_INFO "binder: %d:%d ioctl %x %lx returned %d\n", proc->pid, current->pid, cmd, arg, ret);
err_unlocked:trace_binder_ioctl_done(ret);return ret;
}

 2.23 binder_new_node

1.创建驱动中对应的sm的binder实体对象,并用红黑树保存,此时sm的binder对象作为红黑树的第一个节点。

static struct binder_node *binder_new_node(struct binder_proc *proc,void __user *ptr,void __user *cookie)
{struct rb_node **p = &proc->nodes.rb_node;//该进程(SM进程)的nodes会用红黑树保存一系列的binder实体对象(binder_node)和binder引用对象(binder_ref)。struct rb_node *parent = NULL;struct binder_node *node;//binder_node代表是binder实体while (*p) {//proc->nodes.rb_node,代表如果当前进程的红黑树节点不为空,则将当前节点插入红黑树的指定位置。那么我们知道sm刚启动肯定是空的,parent = *p;node = rb_entry(parent, struct binder_node, rb_node);//返回该节点对应的数据类型if (ptr < node->ptr)p = &(*p)->rb_left;else if (ptr > node->ptr)p = &(*p)->rb_right;elsereturn NULL;}node = kzalloc(sizeof(*node), GFP_KERNEL);//为binder实体(SM的驱动的binder实体)对象分配内核空间if (node == NULL)return NULL;binder_stats_created(BINDER_STAT_NODE);rb_link_node(&node->rb_node, parent, p);rb_insert_color(&node->rb_node, &proc->nodes);//将当前binder对象插入红黑树node->debug_id = ++binder_last_id;node->proc = proc;//binder实体的节点中保存此binder实体对应的进程proc对象,即sm的驱动中的binder实体保存sm进程的proc对象。node->ptr = ptr;//此处是nullnode->cookie = cookie;//此处是nullnode->work.type = BINDER_WORK_NODE;INIT_LIST_HEAD(&node->work.entry);//创建该binder实体对象的work头节点INIT_LIST_HEAD(&node->async_todo);//创建该binder实体对象todo头节点binder_debug(BINDER_DEBUG_INTERNAL_REFS,"binder: %d:%d node %d u%p c%p created\n",proc->pid, current->pid, node->debug_id,node->ptr, node->cookie);return node;
}

 2.24 Looper::prepare

此处便涉及到looper的机制了。为了完全透彻的理解,本人也将looper进行了剖析。

主要作用为:

1.创建一个looper对象。

sp<Looper> Looper::prepare(int opts) {//opt是falsebool allowNonCallbacks = opts & PREPARE_ALLOW_NON_CALLBACKS;//表示是否有回调,此时是falsesp<Looper> looper = Looper::getForThread();if (looper == nullptr) {looper = new Looper(allowNonCallbacks);//创建Looper,allowNonCallbacks是falseLooper::setForThread(looper);//将新的looper设置给gTLSKey}if (looper->getAllowNonCallbacks() != allowNonCallbacks) {ALOGW("Looper already prepared for this thread with a different value for the ""LOOPER_PREPARE_ALLOW_NON_CALLBACKS option.");}return looper;//返回一个looper对象
}

 2.25 Looper::getForThread

sp<Looper> Looper::getForThread() {int result = pthread_once(& gTLSOnce, initTLSKey);//pthread_once保证initTLSKey函数在此进程只执行一次//static pthread_once_t gTLSOnce = PTHREAD_ONCE_INIT;LOG_ALWAYS_FATAL_IF(result != 0, "pthread_once failed");return (Looper*)pthread_getspecific(gTLSKey);
}

 2.26 Looper::initTLSKey

void Looper::initTLSKey() {int error = pthread_key_create(&gTLSKey, threadDestructor);分配用于表示进程中线程特定数据的键,键对进程中的所有线程来说是全局的.//pthread_key_create第一个参数为指向一个键值的指针,第二个参数指明了一个destructor函数,//如果这个参数不为空,那么当每个线程结束时,系统将调用这个函数来释放绑定在这个键上的内存块。//key_create_value成功返回0,其他是失败LOG_ALWAYS_FATAL_IF(error != 0, "Could not allocate TLS key: %s", strerror(error));
}

 2.27 Looper::Looper

Looper::Looper(bool allowNonCallbacks): mAllowNonCallbacks(allowNonCallbacks),mSendingMessage(false),mPolling(false),mEpollRebuildRequired(false),mNextRequestSeq(0),mResponseIndex(0),mNextMessageUptime(LLONG_MAX) {mWakeEventFd.reset(eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC));//重置唤醒事件fd,mWakeEventFd文件描述符为0LOG_ALWAYS_FATAL_IF(mWakeEventFd.get() < 0, "Could not make wake event fd: %s", strerror(errno));AutoMutex _l(mLock);rebuildEpollLocked();
}

 2.28 Looper::rebuildEpollLocked

Looper本质是通过epoll机制来实现的功能。

主要作用为:

1.此处先创建epoll。

2.将唤醒事件的fd添加到epoll_ctl下监听,如果唤醒事件的fd下有数据,则返回eventItem

void Looper::rebuildEpollLocked() {/**if (mEpollFd >= 0) {//如果有老的epoll,则关闭老的epoll单例
#if DEBUG_CALLBACKSALOGD("%p ~ rebuildEpollLocked - rebuilding epoll set", this);
#endifmEpollFd.reset();}*/mEpollFd.reset(epoll_create1(EPOLL_CLOEXEC));//创建一个epooll对象赋值给mEpollFd,EPOLL_CLOEXEC代表进程被替换时会关闭打开的文件描述符struct epoll_event eventItem;//epoll_event结构体memset(& eventItem, 0, sizeof(epoll_event));eventItem.events = EPOLLIN;//代表是可读事件eventItem.data.fd = mWakeEventFd.get();//保存mWakeEventFd的fdint result = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, mWakeEventFd.get(), &eventItem);//将唤醒事件的fd添加到epoll_ctl下监听,如果唤醒事件的fd下有数据,则返回eventItemLOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake event fd to epoll instance: %s",strerror(errno));/**刚开始没有for (size_t i = 0; i < mRequests.size(); i++) {const Request& request = mRequests.valueAt(i);struct epoll_event eventItem;request.initEventItem(&eventItem);int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, request.fd, &eventItem);if (epollResult < 0) {ALOGE("Error adding epoll events for fd %d while rebuilding epoll set: %s",request.fd, strerror(errno));}}*/
}

2.29 Looper::setForThread

1.将新的looper设置给gTLSKey,这个gTLSKey对于进程中的所有线程都是全局的,共享的。

void Looper::setForThread(const sp<Looper>& looper) {sp<Looper> old = getForThread(); // also has side-effect of initializing TLSif (looper != nullptr) {looper->incStrong((void*)threadDestructor);//}pthread_setspecific(gTLSKey, looper.get());//将新的looper设置给gTLSKey,这个gTLSKey对于进程中的所有线程都是全局的。if (old != nullptr) {old->decStrong((void*)threadDestructor);}
}

 2.30 sp<BinderCallback> setupTo

主要作用为:

1.创建了BinderCallback对象。

2.和binder驱动通信,告诉bingder驱动要进入消息循环了。

3.将/dev/binder驱动的fd,添加到epoll中,用于监听是否有来自驱动的消息。

static sp<BinderCallback> setupTo(const sp<Looper>& looper) {sp<BinderCallback> cb = sp<BinderCallback>::make();//创建了BinderCallback对象int binder_fd = -1;IPCThreadState::self()->setupPolling(&binder_fd);//告诉binder驱动要进入消息循环了。设置binder_fd为/dev/binder的fdint ret = looper->addFd(binder_fd,Looper::POLL_CALLBACK,Looper::EVENT_INPUT,cb,nullptr /*data*/);//将/dev/binder驱动的fd,添加到epoll中,用于监听是否有来自驱动的消息。return cb;
}

 2.31 IPCThreadState::setupPolling

主要作用为:

1.向binder驱动发送消息是通过mout的Parcel类对象来进行通信的。所以此处的作用是通过填充和binder驱动通信的结构体,从而向binder驱动发送命令协议BC_ENTER_LOOPER,告诉binder驱动"本线程要进入循环状态了。

2.填充完mout结构体后,向驱动发送命令。

status_t IPCThreadState::setupPolling(int* fd)
{if (mProcess->mDriverFD < 0) {return -EBADF;}mOut.writeInt32(BC_ENTER_LOOPER);//mOut是一个Parcel类对象,向设备注册派生的looper线程,//向binder驱动发送命令协议BC_ENTER_LOOPER,告诉binder驱动"本线程要进入循环状态了"flushCommands();//向驱动发送命令*fd = mProcess->mDriverFD;//设置fd为/dev/binder的fdreturn 0;
}

 2.32 Parcel::writeInt32

status_t Parcel::writeInt32(int32_t val)
{return writeAligned(val);
}template<class T>
status_t Parcel::writeAligned(T val) {static_assert(PAD_SIZE_UNSAFE(sizeof(T)) == sizeof(T));if ((mDataPos+sizeof(val)) <= mDataCapacity) {//如果已经有的mDataPos位置加上数据的大小小于容量
restart_write:*reinterpret_cast<T*>(mData+mDataPos) = val;//则将数据设置进去return finishWrite(sizeof(val));}status_t err = growData(sizeof(val));if (err == NO_ERROR) goto restart_write;return err;
}

 2.33 IPCThreadState::flushCommands

1.此时执行的是BC_ENTER_LOOPER,告诉binder驱动本线程要进入循环状态了。

void IPCThreadState::flushCommands()
{if (mProcess->mDriverFD < 0)return;talkWithDriver(false);//刷新可能会导致执行写后refcount递减,进而可能导致BC_RELEASE/BC_DECREFS在mOut中排队。所以,如果需要的话,再次冲洗。if (mOut.dataSize() > 0) {talkWithDriver(false);}if (mOut.dataSize() > 0) {ALOGW("mOut.dataSize() > 0 after flushCommands()");}
}

2.34 IPCThreadState::talkWithDriver

1.此时执行的是BC_ENTER_LOOPER,告诉binder驱动本线程要进入循环状态了。

status_t IPCThreadState::talkWithDriver(bool doReceive)
{if (mProcess->mDriverFD < 0) {return -EBADF;}binder_write_read bwr;//struct binder_write_read {//binder_size_t		write_size;//要写入的字节数,write_buffer的总字节数//binder_size_t		write_consumed;//驱动程序占用的字节数,write_buffer已消费的字节数//binder_uintptr_t	write_buffer;//写缓冲数据的指针//binder_size_t		read_size;//要读的字节数,read_buffer的总字节数//binder_size_t		read_consumed;//驱动程序占用的字节数,read_buffer已消费的字节数//binder_uintptr_t	read_buffer;//读缓存数据的指针//};// Is the read buffer empty?const bool needRead = mIn.dataPosition() >= mIn.dataSize();//min是驱动发送给serviceManager的消息,查看needRead是否有来自驱动的消息//当我们正在从min中读取数据,或者调用方打算读取下一条数据(doReceive为true时),我们不会写入任何内容。//此时doReceive是false,且无数据可读,所以我们是会写入数据的const size_t outAvail = (!doReceive || needRead) ? mOut.dataSize() : 0;bwr.write_size = outAvail;bwr.write_buffer = (uintptr_t)mOut.data();/**if (doReceive && needRead) {//当我们正在读的时候。bwr.read_size = mIn.dataCapacity();bwr.read_buffer = (uintptr_t)mIn.data();}*/else {//当不读的时候,设置读的大小和buffer为0bwr.read_size = 0;bwr.read_buffer = 0;}/**log不看IF_LOG_COMMANDS() {TextOutput::Bundle _b(alog);if (outAvail != 0) {alog << "Sending commands to driver: " << indent;const void* cmds = (const void*)bwr.write_buffer;const void* end = ((const uint8_t*)cmds)+bwr.write_size;alog << HexDump(cmds, bwr.write_size) << endl;while (cmds < end) cmds = printCommand(alog, cmds);alog << dedent;}alog << "Size of receive buffer: " << bwr.read_size<< ", needRead: " << needRead << ", doReceive: " << doReceive << endl;}*/// 如果读缓冲区和写缓冲区都为0,代表无事可做,立即返回,此时write_size中有数据。/**if ((bwr.write_size == 0) && (bwr.read_size == 0)) return NO_ERROR;*/bwr.write_consumed = 0;bwr.read_consumed = 0;status_t err;do {
#if defined(__ANDROID__)if (ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr) >= 0)//向binder驱动不断的读写err = NO_ERROR;elseerr = -errno;
#elseerr = INVALID_OPERATION;
#endif/**if (mProcess->mDriverFD < 0) {err = -EBADF;}*/} while (err == -EINTR);if (err >= NO_ERROR) {//代表读取成功if (bwr.write_consumed > 0) {if (bwr.write_consumed < mOut.dataSize())//如果驱动消费的数据大小小于mout的大小,则说明驱动没有消费mout数据LOG_ALWAYS_FATAL("Driver did not consume write buffer. ""err: %s consumed: %zu of %zu",statusToString(err).c_str(),(size_t)bwr.write_consumed,mOut.dataSize());else {//代表mout被正确消费mOut.setDataSize(0);//重置数据大小为0processPostWriteDerefs();//主要是将写的引用计数减少1,释放}}if (bwr.read_consumed > 0) {//如果驱动读的数据大小大于0mIn.setDataSize(bwr.read_consumed);//设置mIn的大小mIn.setDataPosition(0);//设置min数据起始位置}return NO_ERROR;}return err;
}

 2.35 binder_ioctl

1.驱动层,陷入内核态。

2.驱动将数据从用户空间拷贝到内核空间。然后解析数据。

3.执行BC_ENTER_LOOPER,告诉binder驱动本线程要进入循环状态了。

//ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr),此时mout数据是BC_ENTER_LOOPER分析
static long binder_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{int ret;struct binder_proc *proc = filp->private_data;//取出此fd(/dev/binder驱动)的proc对象,一个驱动节点对应一个proc对象struct binder_thread *thread;//binder线程unsigned int size = _IOC_SIZE(cmd);void __user *ubuf = (void __user *)arg;//是bwrtrace_binder_ioctl(cmd, arg);ret = wait_event_interruptible(binder_user_error_wait, binder_stop_on_user_error < 2);//不休眠if (ret)goto err_unlocked;binder_lock(__func__);thread = binder_get_thread(proc);//获取当前线程binder_threadif (thread == NULL) {ret = -ENOMEM;goto err;}switch (cmd) {case BINDER_WRITE_READ: {struct binder_write_read bwr;if (size != sizeof(struct binder_write_read)) {//查看大小是否正确ret = -EINVAL;goto err;}if (copy_from_user(&bwr, ubuf, sizeof(bwr))) {//从用户空间复制数据到内核空间//第一个参数to是内核空间的数据目标地址指针,//第二个参数from是用户空间的数据源地址指针,//第三个参数n是数据的长度。ret = -EFAULT;goto err;}if (bwr.write_size > 0) {//当写缓存有数据的时候,执行写操作ret = binder_thread_write(proc, thread, (void __user *)bwr.write_buffer, bwr.write_size, &bwr.write_consumed);//参数分析://proc代表sm对象的proc//thread为此sm进程的binder线程//bwr.write_buffer,内核数据的起始地址//write_size,数据大小//write_consumed,驱动程序已消费的数据大小trace_binder_write_done(ret);if (ret < 0) {//如果写失败,再将bwr的值写回给ubufbwr.read_consumed = 0;if (copy_to_user(ubuf, &bwr, sizeof(bwr)))//第一个参数是用户空间的指针,//第二个参数是内核空间指针,//n表示从内核空间向用户空间拷贝数据的字节数ret = -EFAULT;goto err;}}/**if (bwr.read_size > 0) {//当读缓存有数据的时候,执行读操作,此时读缓存无数据ret = binder_thread_read(proc, thread, (void __user *)bwr.read_buffer, bwr.read_size, &bwr.read_consumed, filp->f_flags & O_NONBLOCK);trace_binder_read_done(ret);if (!list_empty(&proc->todo))wake_up_interruptible(&proc->wait);if (ret < 0) {if (copy_to_user(ubuf, &bwr, sizeof(bwr)))ret = -EFAULT;goto err;}}*/if (copy_to_user(ubuf, &bwr, sizeof(bwr))) {//将此内核空间数据,拷贝到ubuf中,此时是写的消费的大小write_consumed变成了4字节。//第一个参数是用户空间的指针,//第二个参数是内核空间指针,//n表示从内核空间向用户空间拷贝数据的字节数ret = -EFAULT;goto err;}break;}ret = 0;
err:if (thread)thread->looper &= ~BINDER_LOOPER_STATE_NEED_RETURN;binder_unlock(__func__);wait_event_interruptible(binder_user_error_wait, binder_stop_on_user_error < 2);if (ret && ret != -ERESTARTSYS)printk(KERN_INFO "binder: %d:%d ioctl %x %lx returned %d\n", proc->pid, current->pid, cmd, arg, ret);
err_unlocked:trace_binder_ioctl_done(ret);return ret;
}

 2.36 binder_thread_write

1.取出消息是BC_ENTER_LOOPER,驱动层则设置当前线程BINDER_LOOPER_STATE_ENTERED。

int binder_thread_write(struct binder_proc *proc, struct binder_thread *thread,void __user *buffer, int size, signed long *consumed)//参数分析://proc代表sm对象的proc//thread为此sm进程的binder线程//bwr.write_buffer,内核数据的起始地址,数据是BC_ENTER_LOOPER//write_size,4字节,数据大小//consumed=0,驱动程序已消费的数据大小
{uint32_t cmd;void __user *ptr = buffer + *consumed;//首地址+0,即是写buffer首地址。void __user *end = buffer + size;//buffer的尾地址。while (ptr < end && thread->return_error == BR_OK) {if (get_user(cmd, (uint32_t __user *)ptr))//从写buffer中获取命令给cmd,即此时是BC_ENTER_LOOPERreturn -EFAULT;ptr += sizeof(uint32_t);//让buffer的地址跳过BC_ENTER_LOOPER,因为buffer中可能还有其他数据。此时是没数据了trace_binder_command(cmd);if (_IOC_NR(cmd) < ARRAY_SIZE(binder_stats.bc)) {//记录信息binder_stats.bc[_IOC_NR(cmd)]++;proc->stats.bc[_IOC_NR(cmd)]++;thread->stats.bc[_IOC_NR(cmd)]++;}switch (cmd) {case BC_ENTER_LOOPER:/**if (thread->looper & BINDER_LOOPER_STATE_REGISTERED) {//如果此looper已经注册过,则错误thread->looper |= BINDER_LOOPER_STATE_INVALID;binder_user_error("binder: %d:%d ERROR:"" BC_ENTER_LOOPER called after ""BC_REGISTER_LOOPER\n",proc->pid, thread->pid);}*/thread->looper |= BINDER_LOOPER_STATE_ENTERED;//设置为此binder线程已经注册过了。break;}*consumed = ptr - buffer;//已消费的字节大小,此时为4字节}return 0;
}

 2.37 Looper::addFd

1.将/dev/binder的fd添加到epoll中进行监听,是否有可读事件。

int Looper::addFd(int fd, int ident, int events, Looper_callbackFunc callback, void* data) {//此时传入的参数是//fd是/dev/binder的fd//ident是POLL_CALLBACK //代表Looper_pollOnce()和Looper_polAll()的会执行了一个或多个回调。//events是EVENT_INPUT ///dev/binder文件描述符中存在可读事件,然后会执行回调函数。//callback是BinderCallback//data是nullptrreturn addFd(fd, ident, events, callback ? new SimpleLooperCallback(callback) : nullptr, data);
}
SimpleLooperCallback::SimpleLooperCallback(Looper_callbackFunc callback) :mCallback(callback) {
}
int Looper::addFd(int fd, int ident, int events, const sp<LooperCallback>& callback, void* data) {/**if (!callback.get()) {if (! mAllowNonCallbacks) {ALOGE("Invalid attempt to set NULL callback but not allowed for this looper.");return -1;}if (ident < 0) {ALOGE("Invalid attempt to set NULL callback with ident < 0.");return -1;}}*/else {ident = POLL_CALLBACK;}{ // acquire lockAutoMutex _l(mLock);Request request;request.fd = fd;//此时fd是/dev/binder的fdrequest.ident = ident;//ident是POLL_CALLBACK,代表Looper_pollOnce()和Looper_polAll()的会执行了一个或多个回调request.events = events;//events是EVENT_INPUT 代表dev/binder文件描述符中存在可读事件,然后会执行回调函数。request.seq = mNextRequestSeq++;//seq值是0,mNextRequestSeq值变成1request.callback = callback;//BinderCallbackrequest.data = data;//data是空/**if (mNextRequestSeq == -1) mNextRequestSeq = 0;*/ // reserve sequence number -1struct epoll_event eventItem;request.initEventItem(&eventItem);//初始化epoll_event,用于监听此fd是否有可读事件,如果有,则执行回调函数ssize_t requestIndex = mRequests.indexOfKey(fd);//此时此/dev/binder的fd应该不存在if (requestIndex < 0) {int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, fd, &eventItem);//将/dev/binder的fd,加入epoll,监听此设备节点下是否有可读事件/**if (epollResult < 0) {ALOGE("Error adding epoll events for fd %d: %s", fd, strerror(errno));return -1;}*/mRequests.add(fd, request);//添加到容器中。} /**else {int epollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_MOD, fd, &eventItem);if (epollResult < 0) {if (errno == ENOENT) {// Tolerate ENOENT because it means that an older file descriptor was// closed before its callback was unregistered and meanwhile a new// file descriptor with the same number has been created and is now// being registered for the first time.  This error may occur naturally// when a callback has the side-effect of closing the file descriptor// before returning and unregistering itself.  Callback sequence number// checks further ensure that the race is benign.//// Unfortunately due to kernel limitations we need to rebuild the epoll// set from scratch because it may contain an old file handle that we are// now unable to remove since its file descriptor is no longer valid.// No such problem would have occurred if we were using the poll system// call instead, but that approach carries others disadvantages.
#if DEBUG_CALLBACKSALOGD("%p ~ addFd - EPOLL_CTL_MOD failed due to file descriptor ""being recycled, falling back on EPOLL_CTL_ADD: %s",this, strerror(errno));
#endifepollResult = epoll_ctl(mEpollFd.get(), EPOLL_CTL_ADD, fd, &eventItem);if (epollResult < 0) {ALOGE("Error modifying or adding epoll events for fd %d: %s",fd, strerror(errno));return -1;}scheduleEpollRebuildLocked();} else {ALOGE("Error modifying epoll events for fd %d: %s", fd, strerror(errno));return -1;}}mRequests.replaceValueAt(requestIndex, request);}*/} // release lockreturn 1;
}

 1.初始化eventItem结构体。此结构体当dev/hwbinder节点下有数据可读时,会返回eventItem结构体的消息。

void Looper::Request::initEventItem(struct epoll_event* eventItem) const {int epollEvents = 0;if (events & EVENT_INPUT) epollEvents |= EPOLLIN;//如果是监听可读事件,则设置为可读if (events & EVENT_OUTPUT) epollEvents |= EPOLLOUT;//如果是监听可写事件,则设置为可写memset(eventItem, 0, sizeof(epoll_event)); // zero out unused members of data field unioneventItem->events = epollEvents;eventItem->data.fd = fd;//是dev/binder驱动的fd。代表监听此fd是否有可读事件,如果有,则执行回调函数
}

 2.38 ClientCallbackCallback::setupTo

1.主要是通过一个定时器,做定时的处理,避免超时.

static sp<ClientCallbackCallback> setupTo(const sp<Looper>& looper, const sp<ServiceManager>& manager) {sp<ClientCallbackCallback> cb = sp<ClientCallbackCallback>::make(manager);int fdTimer = timerfd_create(CLOCK_MONOTONIC, 0 /*flags*/);//timerfd_create() 创建一个新的计时器对象,并返回引用该计时器的文件描述符//CLOCK_MONOTONIC代表。一个不可设置的单调递增时钟,它从过去的某个未指定点测量时间,系统启动后不会改变,且CLOCK_MONOTONIC 时钟不测量系统挂起时的时间。LOG_ALWAYS_FATAL_IF(fdTimer < 0, "Failed to timerfd_create: fd: %d err: %d", fdTimer, errno);itimerspec timespec {//此处表示计时器启动后,将会在5S后报告一次,然后每隔5S报告一次;.it_interval = {.tv_sec = 5,.tv_nsec = 0,},.it_value = {.tv_sec = 5,.tv_nsec = 0,},};int timeRes = timerfd_settime(fdTimer, 0 /*flags*/, &timespec, nullptr);//此函数用于设置新的超时时间,并开始计时。//参数flags为1代表设置的是绝对时间;为0代表相对时间。//timespec需要设置的时间LOG_ALWAYS_FATAL_IF(timeRes < 0, "Failed to timerfd_settime: res: %d err: %d", timeRes, errno);int addRes = looper->addFd(fdTimer,Looper::POLL_CALLBACK,Looper::EVENT_INPUT,cb,nullptr);//将计时器添加到epoll中,并传递cb,此时是每隔5秒执行一次LOG_ALWAYS_FATAL_IF(addRes != 1, "Failed to add client callback FD to Looper");return cb;
}

2.39 pollAll

1.让当前线程阻塞,等待监听的fd(驱动)有消息的到来。

inline int pollAll(int timeoutMillis) {//timeoutMillis值是-1return pollAll(timeoutMillis, nullptr, nullptr, nullptr);
}int Looper::pollAll(int timeoutMillis, int* outFd, int* outEvents, void** outData) {if (timeoutMillis <= 0) {int result;do {result = pollOnce(timeoutMillis, outFd, outEvents, outData);} while (result == POLL_CALLBACK);return result;} /**此时不执行else {nsecs_t endTime = systemTime(SYSTEM_TIME_MONOTONIC)+ milliseconds_to_nanoseconds(timeoutMillis);for (;;) {int result = pollOnce(timeoutMillis, outFd, outEvents, outData);if (result != POLL_CALLBACK) {return result;}nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);timeoutMillis = toMillisecondTimeoutDelay(now, endTime);if (timeoutMillis == 0) {return POLL_TIMEOUT;}}}*/
}

 2.40 pollOnce

1.刚开始,无消息时,会阻塞在这里,等待有消息的到来。

int Looper::pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData) {int result = 0;for (;;) {/**while (mResponseIndex < mResponses.size()) {//此时mResponseIndex=0,mResponses.size也等于0const Response& response = mResponses.itemAt(mResponseIndex++);int ident = response.request.ident;if (ident >= 0) {int fd = response.request.fd;int events = response.events;void* data = response.request.data;
#if DEBUG_POLL_AND_WAKEALOGD("%p ~ pollOnce - returning signalled identifier %d: ""fd=%d, events=0x%x, data=%p",this, ident, fd, events, data);
#endifif (outFd != nullptr) *outFd = fd;if (outEvents != nullptr) *outEvents = events;if (outData != nullptr) *outData = data;return ident;}}*//**if (result != 0) {
#if DEBUG_POLL_AND_WAKEALOGD("%p ~ pollOnce - returning result %d", this, result);
#endifif (outFd != nullptr) *outFd = 0;if (outEvents != nullptr) *outEvents = 0;if (outData != nullptr) *outData = nullptr;return result;}*/result = pollInner(timeoutMillis);//阻塞在此处}
}

 2.41 pollInner

1.阻塞在此处 ,等待监听的fd中有消息。主要是监听binder驱动是否有可读消息。

int Looper::pollInner(int timeoutMillis) {/**if (timeoutMillis != 0 && mNextMessageUptime != LLONG_MAX) {nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);int messageTimeoutMillis = toMillisecondTimeoutDelay(now, mNextMessageUptime);if (messageTimeoutMillis >= 0&& (timeoutMillis < 0 || messageTimeoutMillis < timeoutMillis)) {timeoutMillis = messageTimeoutMillis;}}*/// Poll.int result = POLL_WAKE;mResponses.clear();mResponseIndex = 0;// We are about to idle.mPolling = true;struct epoll_event eventItems[EPOLL_MAX_EVENTS];int eventCount = epoll_wait(mEpollFd.get(), eventItems, EPOLL_MAX_EVENTS, timeoutMillis);//阻塞在此处//等待监听的fd中有消息。主要是监听binder驱动是否有可读消息。/**// No longer idling.mPolling = false;// Acquire lock.mLock.lock();// Rebuild epoll set if needed.if (mEpollRebuildRequired) {mEpollRebuildRequired = false;rebuildEpollLocked();goto Done;}// Check for poll error.if (eventCount < 0) {if (errno == EINTR) {goto Done;}ALOGW("Poll failed with an unexpected error: %s", strerror(errno));result = POLL_ERROR;goto Done;}// Check for poll timeout.if (eventCount == 0) {
#if DEBUG_POLL_AND_WAKEALOGD("%p ~ pollOnce - timeout", this);
#endifresult = POLL_TIMEOUT;goto Done;}// Handle all events.
#if DEBUG_POLL_AND_WAKEALOGD("%p ~ pollOnce - handling events from %d fds", this, eventCount);
#endiffor (int i = 0; i < eventCount; i++) {int fd = eventItems[i].data.fd;uint32_t epollEvents = eventItems[i].events;if (fd == mWakeEventFd.get()) {if (epollEvents & EPOLLIN) {awoken();} else {ALOGW("Ignoring unexpected epoll events 0x%x on wake event fd.", epollEvents);}} else {ssize_t requestIndex = mRequests.indexOfKey(fd);if (requestIndex >= 0) {int events = 0;if (epollEvents & EPOLLIN) events |= EVENT_INPUT;if (epollEvents & EPOLLOUT) events |= EVENT_OUTPUT;if (epollEvents & EPOLLERR) events |= EVENT_ERROR;if (epollEvents & EPOLLHUP) events |= EVENT_HANGUP;pushResponse(events, mRequests.valueAt(requestIndex));} else {ALOGW("Ignoring unexpected epoll events 0x%x on fd %d that is ""no longer registered.", epollEvents, fd);}}}
Done: ;// Invoke pending message callbacks.mNextMessageUptime = LLONG_MAX;while (mMessageEnvelopes.size() != 0) {nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(0);if (messageEnvelope.uptime <= now) {// Remove the envelope from the list.// We keep a strong reference to the handler until the call to handleMessage// finishes.  Then we drop it so that the handler can be deleted *before*// we reacquire our lock.{ // obtain handlersp<MessageHandler> handler = messageEnvelope.handler;Message message = messageEnvelope.message;mMessageEnvelopes.removeAt(0);mSendingMessage = true;mLock.unlock();#if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKSALOGD("%p ~ pollOnce - sending message: handler=%p, what=%d",this, handler.get(), message.what);
#endifhandler->handleMessage(message);} // release handlermLock.lock();mSendingMessage = false;result = POLL_CALLBACK;} else {// The last message left at the head of the queue determines the next wakeup time.mNextMessageUptime = messageEnvelope.uptime;break;}}// Release lock.mLock.unlock();// Invoke all response callbacks.for (size_t i = 0; i < mResponses.size(); i++) {Response& response = mResponses.editItemAt(i);if (response.request.ident == POLL_CALLBACK) {int fd = response.request.fd;int events = response.events;void* data = response.request.data;
#if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKSALOGD("%p ~ pollOnce - invoking fd event callback %p: fd=%d, events=0x%x, data=%p",this, response.request.callback.get(), fd, events, data);
#endif// Invoke the callback.  Note that the file descriptor may be closed by// the callback (and potentially even reused) before the function returns so// we need to be a little careful when removing the file descriptor afterwards.int callbackResult = response.request.callback->handleEvent(fd, events, data);if (callbackResult == 0) {removeFd(fd, response.request.seq);}// Clear the callback reference in the response structure promptly because we// will not clear the response vector itself until the next poll.response.request.callback.clear();result = POLL_CALLBACK;}}return result;
*/
}

 至此,serviceManager的启动流程,我们就讲解完毕了。


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/877944.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

入门Java编程的知识点—>面向对象(day07)

重点掌握什么是面向对象&#xff1f;重点掌握面向对象封装的意义&#xff1f;重点掌握类的封装,创建对象,访问对象&#xff1f; 面向对象 OO&#xff1a;&#xff08;Object Oriented&#xff09;面向对象 面向对象是一种编程思想,遵循面向对象设计原则可以写出高质量代码, …

sheng的学习笔记-AI-生成式方法

AI目录&#xff1a;sheng的学习笔记-AI目录-CSDN博客 需要额外的知识对应连接&#xff1a; EM&#xff1a;sheng的学习笔记-AI-EM算法-CSDN博客 贝叶斯&#xff1a; sheng的学习笔记-AI-贝叶斯&#xff08;Bayesian&#xff09;分类-CSDN博客 高斯混合模型&#xff1a;shen…

C#中的WebClient与XPath:实现精准高效的Screen Scraping

在现代互联网中&#xff0c;Screen Scraping&#xff08;屏幕抓取&#xff09;已成为从网页中提取信息的重要技术。对于C#开发者来说&#xff0c;WebClient和XPath是实现高效抓取的重要工具。本文将概述如何使用C#中的WebClient类结合XPath技术&#xff0c;实现精准高效的Scree…

流媒体服务器如何让WebRTC支持H.265,同时又能支持Web js硬解码、软解码(MSE硬解、WASM软解)

为了这一整套的解决方案&#xff0c;调研研发整整花费了差不多半年多的时间&#xff0c;需达成的目标&#xff1a; 流媒体服务器端不需要将H.265转码成H.264&#xff0c;就能让Chrome解码播放H.265&#xff1b; 注意&#xff1a;现在很多市面上的软硬件通过转码H.265成H.264的…

融合创新趋势:Web3时代的跨界融合

随着互联网技术的飞速发展&#xff0c;Web3时代的到来正引领着一场深刻的技术与社会变革。Web3&#xff0c;作为下一代互联网技术的代表&#xff0c;不仅仅是一种技术创新&#xff0c;更是一种跨界融合的趋势。通过去中心化、智能合约和区块链技术的应用&#xff0c;Web3正在重…

django学习入门系列番外篇《request》

文章目录 1 Response功能介绍2 HttpResponse2.1 HttpResponse对象介绍content_typeContent-Type是什么&#xff1f;Content-Type的格式 Content-DispositionContent-Disposition的作用Content-Disposition的使用语句 例子 2.2 HttpResponse常用用法 3 JsonResponse3.1 JsonResp…

2054. 骑马修栅栏

代码 #include<bits/stdc.h> using namespace std; int mp[505][505]; queue<int> ans; int du[505]; int n0,m,u,v;void dfs(int i) {for(int j1;j<n;j){if(mp[i][j]>1){mp[i][j]--;mp[j][i]--;dfs(j);}}ans.push(i); } int main() {cin>>m;for(int …

WordPress简约响应式个人博客Kratos主题

Kratos主题基于Bootstrap和Font Awesome的WordPress一个干净&#xff0c;简单且响应迅速的博客主题&#xff0c;Vtrois创建和维护&#xff0c;主题设计简约友好&#xff0c;并且支持响应式&#xff0c;自适应访问&#xff0c;简seo单大方的主页构造&#xff0c;使得博客能在臃肿…

8.20T3 无损加密(线性代数转LGV+状压dp+高维前缀和)

http://cplusoj.com/d/senior/p/NODSX2301C 对于式子&#xff1a; 这个神秘的线性代数形式比较难处理&#xff0c;但我们可以考虑其组合意义。行列式现存的可用组合意义之一就是LGV&#xff08;矩阵式不太可用&#xff09; 先把原先的矩阵转化为一个有向图。现在我们要构造一…

ArcGIS如何将投影坐标系转回为地理坐标系

有时候两个数据&#xff0c;一个为投影坐标系&#xff0c;另一个为地理坐标系时&#xff0c;在GIS软件中位置无法叠加到一起&#xff0c;这需要将两个或多个数据的坐标系统一&#xff0c;可以直接将地理坐标系的数据进行投影&#xff0c;或将投影坐标系转为地理坐标系。下面介绍…

自养号测评技术:如何挑选适合的IP环境方案

市面上的IP服务及常见问题 当前市场上常见的IP服务包括911、Luminati、Google Fi、TM流量卡、Socks专线等。这些服务在为用户提供网络代理或VPN服务时&#xff0c;常会遇到以下主要问题&#xff1a; 1. 高负载与重复率高&#xff1a;由于使用人数众多&#xff0c;导致网络拥堵…

移动端爬虫学习记录

免责声明 本文旨在探讨移动端爬虫技术的应用和挑战&#xff0c;仅供教育和研究用途。请确保在合法合规的框架内使用爬虫技术&#xff0c;遵循相关法律法规和网站的使用条款。作者不对因使用本文内容而产生的任何法律或安全问题承担责任。 1、初识移动端爬虫 学习移动端爬虫的原…

docker映射了端口,宿主机不生效

1、问题产生原因 docker run -d --name my-redis -p 6379:6379 -v /usr/redis.conf:/usr/local/etc/redis/redis.conf team-redis:3.2 redis-server /usr/local/etc/redis/redis.conf 这容器跑起来了&#xff0c;端口6379没用。搞的我一直怀疑哪里出错了&#xff0c;查看配置…

Kakfa的核心概念-Replica副本(kafka创建topic并指定分区和副本的两种方式)

Kakfa的核心概念-Replica副本&#xff08;kafka创建topic并指定分区和副本的两种方式&#xff09; 1、kafka命令行脚本创建topic并指定分区和副本2、springboot集成kafka创建topic并指定分区和副本2.1、springboot集成kafka2.1.1、springboot集成kafka创建topic并指定5个分区和…

VScode 连接远程服务器

1、 2、 3、免密登录 1、本地生成密钥 ssh-keygen2、生成的密钥默认在 C:\Users\***\.ssh\ 中3、将私钥 C:\Users\***\.ssh\id_rsa 添加到上面的配置文件中的 IdentityFile 项内4、将公钥 C:\Users\***\.ssh\id_rsa\id_rsa.pub 拷贝到远程 ~/.ssh/authorized_keys 中 4、远程…

【精选】基于django柚子校园影院(咨询+解答+辅导)

博主介绍&#xff1a; ✌我是阿龙&#xff0c;一名专注于Java技术领域的程序员&#xff0c;全网拥有10W粉丝。作为CSDN特邀作者、博客专家、新星计划导师&#xff0c;我在计算机毕业设计开发方面积累了丰富的经验。同时&#xff0c;我也是掘金、华为云、阿里云、InfoQ等平台…

Golang | Leetcode Golang题解之第371题两整数之和

题目&#xff1a; 题解&#xff1a; func getSum(a, b int) int {for b ! 0 {carry : uint(a&b) << 1a ^ bb int(carry)}return a }

「Python数据分析」Pandas进阶,利用concat()函数连接数据(一)

在我们迈向中高级出局数据分析的过程中&#xff0c;数据的合并和连接&#xff0c;是一个非常重要的技能。 现实中&#xff0c;分散在各种数据库&#xff0c;各种数据表格&#xff0c;各种数据存储设备当中的&#xff0c;各式各样的数据&#xff0c;是我们进行数据分析的基础&a…

SmartGit-Git版本控制系统的图形化客户端

SmartGit&#xff1a; SmartGit是一款免费的、专业的Git版本控制系统的图形化客户端。它适用于Windows、Mac和Linux等多种操作系统&#xff0c;提供了直观的用户界面和丰富的功能。支持创建、克隆、推送、拉取、合并和管理Git仓库&#xff0c;以及强大的分支管理功能。还提供了…

(免费领源码)python#Django#msyql学生个性化培养的教学资源平台的设计与实现19385-计算机毕业设计项目选题推荐

摘 要 信息化社会内需要与之针对性的信息获取途径&#xff0c;但是途径的扩展基本上为人们所努力的方向&#xff0c;由于站在的角度存在偏差&#xff0c;人们经常能够获得不同类型信息&#xff0c;这也是技术最为难以攻克的课题。针对学生个性化培养的教学资源平台等问题&#…