分析获取当前系统进程列表的代码流程(及ioctl在bionic库中的实现)

分析获取当前系统进程列表的代码流程。
应用层java会调用ActivityManager类的getRunningAppProcesses方法来获取进程列表。


先找ActivityManager的实现,在frameworks/base/core/java/android/app/ActivityManager.java中
定义了ActivityManager类
{
public List<RunningAppProcessInfo> getRunningAppProcesses() {
       try {
           return ActivityManagerNative.getDefault().getRunningAppProcesses();
       } catch (RemoteException e) {
           return null;
       }
   }
}

说明调用的是ActivityManagerNative中的函数getRunningAppProcesses,在frameworks/base/core/java/android/app/ActivityManagerNative.java中,
public abstract class ActivityManagerNative extends Binder implements IActivityManager
{
static public IActivityManager getDefault() {
       return gDefault.get();
   }

   private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() {      //匿名类
       protected IActivityManager create() {
           IBinder b = ServiceManager.getService("activity");      //(1)
           if (false) {
               Log.v("ActivityManager", "default service binder = " + b);
           }
           IActivityManager am = asInterface(b);                   //(2)
           if (false) {
               Log.v("ActivityManager", "default service = " + am);
           }
           return am;
       }
   };

   static public IActivityManager asInterface(IBinder obj)            (2)
   {
       if (obj == null)
       {
           return null;
       }
       IActivityManager in = (IActivityManager)obj.queryLocalInterface(descriptor);
       if (in != null)
       {
           return in;
       }
       return new ActivityManagerProxy(obj);
   }

}

ActivityManagerNative.getDefault()返回的是gDefault.get();
而gDefault是Singleton的IActivityManager对象;gDefault.get()调用的是Singleton中的get方法。

在frameworks/base/include/utils/Singleton.java中
public abstract class Singleton<T> {
   private T mInstance;

   protected abstract T create();

   public final T get() {
       synchronized (this) {
           if (mInstance == null) {
               mInstance = create();
           }
           return mInstance;
       }
   }
}


(1)对IBinder b = ServiceManager.getService("activity");进行分析:
public final class ServiceManager {
   private static final String TAG = "ServiceManager";

   private static IServiceManager sServiceManager;
   private static HashMap<String, IBinder> sCache = new HashMap<String, IBinder>();

   /**
    * Returns a reference to a service with the given name.
    *
    * @param name the name of the service to get
    * @return a reference to the service, or <code>null</code> if the service doesn't exist
    */
   public static IBinder getService(String name) {                       (1)
       try {
           IBinder service = sCache.get(name);
           if (service != null) {
               return service;
           } else {
               return getIServiceManager().getService(name);
           }
       } catch (RemoteException e) {
           Log.e(TAG, "error in getService", e);
       }
       return null;
   }
}
getService函数应该是获取“activity”服务的binder接口。

ServiceManager类有一个静态成员函数getIServiceManager,它的作用就是用来获取Service ManagerJava远程接口(BinderProxy),而这个函数又是通过ServiceManagerNative来获取Service ManagerJava远程接口的。

getIServiceManager().getService(name)相当于获得了"activity"的服务接口。


(2)对IActivityManager am = asInterface(b);进行分析:
am是ActivityManagerProxy对象。


从上,ActivityManagerNative.getDefault().getRunningAppProcesses();实际执行的是ActivityManagerProxy.getRunningAppProcesses();


IActivityManager的实现,在frameworks/base/core/java/android/app/IActivityManager.java中
public interface IActivityManager extends IInterface
{
}

class ActivityManagerProxy implements IActivityManager
{
private IBinder mRemote;
public ActivityManagerProxy(IBinder remote)
   {
       mRemote = remote;
   }

public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses()
           throws RemoteException {
       Parcel data = Parcel.obtain();
       Parcel reply = Parcel.obtain();
       data.writeInterfaceToken(IActivityManager.descriptor);
       mRemote.transact(GET_RUNNING_APP_PROCESSES_TRANSACTION, data, reply, 0);
       reply.readException();
       ArrayList<ActivityManager.RunningAppProcessInfo> list
       = reply.createTypedArrayList(ActivityManager.RunningAppProcessInfo.CREATOR);
       data.recycle();
       reply.recycle();
       return list;
   }
}


注意mRemote.transact(GET_RUNNING_APP_PROCESSES_TRANSACTION, data, reply, 0);现在关键就是mRemote.transact是怎么实现的了。
mRemote是创建IActivityManager对象时传进来的参数b,也就是 IBinder b = ServiceManager.getService("activity");

这里的mRemote实际上是一个BinderProxy对象,它的transact成员函数是一个JNI方法,实现在frameworks/base/core/jni/android_util_Binder.cpp文件中的android_os_BinderProxy_transact函数中。

所以 mRemote.transact实际是BinderProxy.transact();而BinderProxy.transact是native方法,跳到JNI中去执行。后面就是数据IPCThreadState::self()->transact()了。

final class BinderProxy implements IBinder
{
   public native boolean pingBinder();
   public native boolean isBinderAlive();

   public IInterface queryLocalInterface(String descriptor) {
       return null;
   }

   public native String getInterfaceDescriptor() throws RemoteException;
   public native boolean transact(int code, Parcel data, Parcel reply,
           int flags) throws RemoteException;
}



这里的transact成员函数又是一个JNI方法,它定义在frameworks/base/core/jni/android_util_Binder.cpp文件中:

view plain

1.     static jboolean android_os_BinderProxy_transact(JNIEnv* env, jobject obj,  

2.                             jint code, jobject dataObj,  

3.                             jobject replyObj, jint flags)  

4.     {  

5.         ......  

6.      

7.         Parcel* data = parcelForJavaObject(env, dataObj);  

8.         if (data == NULL) {  

9.             return JNI_FALSE;  

10.      }  

11.      Parcel* reply = parcelForJavaObject(env, replyObj);  

12.      if (reply == NULL && replyObj != NULL) {  

13.          return JNI_FALSE;  

14.      }  

15.    

16.      IBinder* target = (IBinder*)  

17.          env->GetIntField(obj, gBinderProxyOffsets.mObject);  

18.      if (target == NULL) {  

19.          jniThrowException(env, "java/lang/IllegalStateException", "Binder has been finalized!");  

20.          return JNI_FALSE;  

21.      }  

22.    

23.      ......  

24.    

25.      status_t err = target->transact(code, *data, reply, flags);  

26.    

27.      ......  

28.    

29.      if (err == NO_ERROR) {  

30.          return JNI_TRUE;  

31.      } elseif (err == UNKNOWN_TRANSACTION) {  

32.          return JNI_FALSE;  

33.      }  

34.    

35.      signalExceptionForError(env, obj, err);  

36.      return JNI_FALSE;  

37.  }  


在JNI层中,创建了一个BpBinder对象,它的句柄值为0,它的地址保存在gBinderProxyOffsets.mObject中,因此,这里通过下面语句得到这个BpBinder对象的IBinder接口:

view plain

1.     IBinder* target = (IBinder*)  

       env->GetIntField(obj, gBinderProxyOffsets.mObject);



最后,通过BpBinder::transact函数进入到Binder驱动程序,然后Binder驱动程序唤醒Service Manager响应这个ADD_SERVICE_TRANSACTION请求:

view plain

1.     status_t err = target->transact(code, *data, reply, flags);  


后续

最后在framework/base/libs/binder/IPCThreadState.cpp中,传输数据的是IPCThreadState::self()->transact;
status_t IPCThreadState::transact(int32_t handle,
                                 uint32_t code, const Parcel& data,
                                 Parcel* reply, uint32_t flags)
{
   status_t err = data.errorCheck();

   flags |= TF_ACCEPT_FDS;

   IF_LOG_TRANSACTIONS() {
       TextOutput::Bundle _b(alog);
       alog << "BC_TRANSACTION thr " << (void*)pthread_self() << " / hand "
           << handle << " / code " << TypeCode(code) << ": "
           << indent << data << dedent << endl;
   }

   if (err == NO_ERROR) {
       LOG_ONEWAY(">>>> SEND from pid %d uid %d %s", getpid(), getuid(),
           (flags & TF_ONE_WAY) == 0 ? "READ REPLY" : "ONE WAY");
       err = writeTransactionData(BC_TRANSACTION, flags, handle, code, data, NULL);
   }

   if (err != NO_ERROR) {
       if (reply) reply->setError(err);
       return (mLastError = err);
   }

   if ((flags & TF_ONE_WAY) == 0) {
       #if 0
       if (code == 4) { // relayout
           LOGI(">>>>>> CALLING transaction 4");
       } else {
           LOGI(">>>>>> CALLING transaction %d", code);
       }
       #endif
       if (reply) {
           err = waitForResponse(reply);
       } else {
           Parcel fakeReply;
           err = waitForResponse(&fakeReply);
       }
       #if 0
       if (code == 4) { // relayout
           LOGI("<<<<<< RETURNING transaction 4");
       } else {
           LOGI("<<<<<< RETURNING transaction %d", code);
       }
       #endif

       IF_LOG_TRANSACTIONS() {
           TextOutput::Bundle _b(alog);
           alog << "BR_REPLY thr " << (void*)pthread_self() << " / hand "
               << handle << ": ";
           if (reply) alog << indent << *reply << dedent << endl;
           else alog << "(none requested)" << endl;
       }
   } else {
       err = waitForResponse(NULL, NULL);
   }

   return err;
}

而transact实际是调用talkWithDriver来发送数据的:
status_t IPCThreadState::talkWithDriver(bool doReceive)
{
   LOG_ASSERT(mProcess->mDriverFD >= 0, "Binder driver is not opened");

   binder_write_read bwr;

   // Is the read buffer empty?
   const bool needRead = mIn.dataPosition() >= mIn.dataSize();

   // We don't want to write anything if we are still reading
   // from data left in the input buffer and the caller
   // has requested to read the next data.
   const size_t outAvail = (!doReceive || needRead) ? mOut.dataSize() : 0;

   bwr.write_size = outAvail;
   bwr.write_buffer = (long unsigned int)mOut.data();

   // This is what we'll read.
   if (doReceive && needRead) {
       bwr.read_size = mIn.dataCapacity();
       bwr.read_buffer = (long unsigned int)mIn.data();
   } else {
       bwr.read_size = 0;
   }

   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;
   }

   // Return immediately if there is nothing to do.
   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_LOG_COMMANDS() {
           alog << "About to read/write, write size = " << mOut.dataSize() << endl;
       }
#if defined(HAVE_ANDROID_OS)
       if (ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr) >= 0)
           err = NO_ERROR;
       else
           err = -errno;
#else
       err = INVALID_OPERATION;
#endif
       IF_LOG_COMMANDS() {
           alog << "Finished read/write, write size = " << mOut.dataSize() << endl;
       }
   } while (err == -EINTR);

   IF_LOG_COMMANDS() {
       alog << "Our err: " << (void*)err << ", write consumed: "
           << bwr.write_consumed << " (of " << mOut.dataSize()
  << "), read consumed: " << bwr.read_consumed << endl;
   }

   if (err >= NO_ERROR) {
       if (bwr.write_consumed > 0) {
           if (bwr.write_consumed < (ssize_t)mOut.dataSize())
               mOut.remove(0, bwr.write_consumed);
           else
               mOut.setDataSize(0);
       }
       if (bwr.read_consumed > 0) {
           mIn.setDataSize(bwr.read_consumed);
           mIn.setDataPosition(0);
       }
       IF_LOG_COMMANDS() {
           TextOutput::Bundle _b(alog);
           alog << "Remaining data size: " << mOut.dataSize() << endl;
           alog << "Received commands from driver: " << indent;
           const void* cmds = mIn.data();
           const void* end = mIn.data() + mIn.dataSize();
           alog << HexDump(cmds, mIn.dataSize()) << endl;
           while (cmds < end) cmds = printReturnCommand(alog, cmds);
           alog << dedent;
       }
       return NO_ERROR;
   }

   return err;
}

talkWithDriver又是调用ioctl来通信的。
根据framework/base/libs/binder/Android.mk, IPCThreadState.cpp编译成了libbinder.so
在IPCThreadState.cpp中包含了头文件sys/ioctl.h

./bionic/libc/include/sys/ioctl.h

在./bionic/libc/bionic/ioctl.c中。这里的C文件是编译成libc_common.a
#include <stdarg.h>

extern int __ioctl(int, int, void *);

int ioctl(int fd, int request, ...)
{
   va_list ap;
   void * arg;

   va_start(ap, request);
   arg = va_arg(ap, void *);
   va_end(ap);

   return __ioctl(fd, request, arg);
}

__ioctl是汇编代码,在./bionic/libc/arch-arm/syscalls/__ioctl.S中
ENTRY(__ioctl)
   .save   {r4, r7}
   stmfd   sp!, {r4, r7}
   ldr     r7, =__NR_ioctl
   swi     #0
   ldmfd   sp!, {r4, r7}
   movs    r0, r0
   bxpl    lr
   b       __set_syscall_errno
END(__ioctl)


你可能感兴趣的:(Bionic,ioctl)