Search code examples
androidandroid-source

How does the Android system create the /storage/self/primary directory?


I noticed that the android directories are organized by symbolic links as below:

lrwxrwxrwx 1 root root 21 1970-01-01 08:00 /sdcard -> /storage/self/primary 
lrwxrwxrwx 1 root root 19 1972-12-17 02:19 /storage/self/primary -> /mnt/user/0/primary
lrwxrwxrwx 1 root root 19 2020-02-21 10:31 /mnt/user/0/primary -> /storage/emulated/0 

I had searched some android documents, and found:

/sdcard -> /storage/self/primary is created by the command in system/core/rootdir/init.rc:

symlink /storage/self/primary /sdcard

/storage/self/and/mnt/user/0/ are mounted in system/vold/VolumeManager.cpp:

            std::string storageSource;
            if (mode == "default") {
                storageSource = "/mnt/runtime/default";
            } else if (mode == "read") {
                storageSource = "/mnt/runtime/read";
            } else if (mode == "write") {
                storageSource = "/mnt/runtime/write";
            } else if (mode == "full") {
                storageSource = "/mnt/runtime/full";
            } else {
                // Sane default of no storage visible
                _exit(0);
            }
            if (TEMP_FAILURE_RETRY(
                    mount(storageSource.c_str(), "/storage", NULL, MS_BIND | MS_REC, NULL)) == -1) {
                PLOG(ERROR) << "Failed to mount " << storageSource << " for " << de->d_name;
                _exit(1);
            }
            if (TEMP_FAILURE_RETRY(mount(NULL, "/storage", NULL, MS_REC | MS_SLAVE, NULL)) == -1) {
                PLOG(ERROR) << "Failed to set MS_SLAVE to /storage for " << de->d_name;
                _exit(1);
            }

            // Mount user-specific symlink helper into place
            userid_t user_id = multiuser_get_user_id(uid);
            std::string userSource(StringPrintf("/mnt/user/%d", user_id));
            if (TEMP_FAILURE_RETRY(
                    mount(userSource.c_str(), "/storage/self", NULL, MS_BIND, NULL)) == -1) {
                PLOG(ERROR) << "Failed to mount " << userSource << " for " << de->d_name;
                _exit(1);
            }

However, I didn't find when and where the Android system creates a primary directory in /storage/self or /mnt/user/0/self. Could you please help me solve the problem? Thank you very much!


Solution

  • maybe you can refer to the function "linkPrimary" in VolumeManager.cpp. It will create the linker /mnt/user/0/primary -> /storage/emulated/0