顯示具有 Android 標籤的文章。 顯示所有文章
顯示具有 Android 標籤的文章。 顯示所有文章

2021年3月17日 星期三

Android APK

 

>安卓手機可以安裝LTE Discovery來觀察TSU可以安裝LTE Discovery來觀察嗎?

尝试下载了一个 LTE Discovery apk

Adb install XXX.apk

 

然后怎么启动? 能给一个 adb shell start am -n Packagename/ActivityName

的命令吗?ActivityName不知道。

2020年1月3日 星期五

Andriod version, API level, and Linux version

Source https://android.stackexchange.com/questions/51651/which-android-runs-which-linux-kernel

Linux version in AOSP

    Android Version    |API Level  |Linux Version in AOSP                    |Header Version
    ----------------------------------------------------------------------------------------
    1.5   Cupcake      |3          |(2.6.27)                                 |
    1.6   Donut        |4          |(2.6.29)                                 |2.6.18
    2.0/1 Eclair       |5-7        |(2.6.29)                                 |2.6.18
    2.2.x Froyo        |8          |(2.6.32)                                 |2.6.18
    2.3.x Gingerbread  |9, 10      |(2.6.35)                                 |2.6.18
    3.x.x Honeycomb    |11-13      |(2.6.36)                                 |2.6.18
    4.0.x Ice Cream San|14, 15     |(3.0.1)                                  |2.6.18
    4.1.x Jelly Bean   |16         |(3.0.31)                                 |2.6.18
    4.2.x Jelly Bean   |17         |(3.4.0)                                  |2.6.18
    4.3   Jelly Bean   |18         |(3.4.39)                                 |2.6.18
    4.4   Kit Kat      |19, 20     |(3.10)                                   |2.6.18
    5.x   Lollipop     |21, 22     |(3.16.1)                                 |3.14.0
    6.0   Marshmallow  |23         |(3.18.10)                                |3.18.10
    7.0   Nougat       |24         | 3.18.48 4.4.0                           |4.4.1
    7.1   Nougat       |25         | ?                                       |4.4.1
    8.0   Oreo         |26         | 3.18.72 4.4.83  4.9.44                  |4.10.0
    8.1   Oreo         |27         | 3.18.70 4.4.88  4.9.56                  |4.10.0
    9.0   Pie          |28         |         4.4.146 4.9.118 4.14.61         |4.15.0
   10.0   Q            |29         |                 4.9.191 4.14.142 4.19.71|5.0.3
Table compiled from:
Note: other “distributions” of Android might run different kernel versions.
Anyone is welcome to correct and expand this table. Please keep formatting.

Why Android OS/kernel version mismatches

OEMs tend to ship their major Android updates with a similar kernel to the one the device was initially released with. This is most likely to avoid hardware and driver incompatibility issues with a newer kernel. For example, a device that has been updated to run Android 8.0 Oreo but originally shipped with 6.0 Marshmallow may still be running Linux 3.18.x instead of Linux 4.10.x.

Vendor Test Suite (VTS) requirements on Linux version

According to a 2017 article on XDA-Developers (shortened):
One aspect that has been up to the OEM is the Linux kernel version but this is changing with Android Oreo.
As long as the OEM was able to pass the certification tests that Google lays out, then they didn’t care what kernel version was used in a new device. This generally wasn’t an issue as most OEMs would use the same version of the kernel for that generation that other OEMs were using, as it is tied heavily to what the hardware drivers support. However, some had been falling through the cracks and this started to cause security issues. This is something that Google has been taking seriously lately so it makes sense that they would want to start mandating this.
Starting this year with smartphones which ship with Android Oreo, Google is requiring that all SoCs productized in 2017 must launch with kernel 4.4 or newer.
Currently existing devices that are upgraded to Android Oreo are only required to run kernel version 3.18 or newer, and will not have to be upgraded to support Project Treble.
According to https://android.googlesource.com/platform/test/vts-testcase/kernel/, there was a requirement on the Linux version, VtsKernelConfigTest or VtsKernelVersionTest, on 8.0, 8.1, and 9.0, but later removed on 10.0. For 8.0 and 8.1, it requires the version to be either 3.18, 4.4, or 4.9. For 9.0, it requires the version to be at least 4.4.107, 4.9.84, or 4.14.42.
More technical and recent information available directly from the AOSP website: https://source.android.com/devices/architecture/kernel/core-kernel-reqs

2018年10月2日 星期二

Android Virtual Screen over ADB

Chrome pluggin:

  • Vysor  https://chrome.google.com/webstore/detail/vysor/gidgenkbbabolejbgbpnhbimgjbffefm/related


Windows EXE:

2018年8月30日 星期四

Android Init Language

The Android Init Language consists of five broad classes of statements:
  1. Actions
  2. Commands
  3. Services
  4. Options
  5. Imports.

All of these are line-oriented, consisting of tokens separated by whitespace.
The c-style backslash escapes may be used to insert whitespace into a token.
Double quotes may also be used to prevent whitespace from breaking text into multiple tokens.
The backslash, when it is the last character on a line, may be used for line-folding.

Lines which start with a # (leading whitespace allowed) are comments.

Actions and Services implicitly declare a new section.
All commands or options belong to the section most recently declared.
Commands or options before the first section are ignored.

Services have unique names.
If a second Service is defined with the same name as an existing one,
it is ignored and an error message is logged.


Init .rc Files
--------------
The init language is used in plain text files that take the .rc file extension.
There are typically multiple of these in multiple locations on the system, described below.

/init.rc is the primary .rc file and is loaded by the init executable at the beginning of its execution.
It is responsible for the initial set up of the system.

Devices that mount /system, /vendor through the first stage mount mechanism
load all of the files contained within the
/{system,vendor,odm}/etc/init/ directories immediately after loading
the primary /init.rc.  This is explained in more details in the
Imports section of this file.

Legacy devices without the first stage mount mechanism do the following:
1. /init.rc imports /init.${ro.hardware}.rc which is the primary
   vendor supplied .rc file.
2. During the mount\_all command, the init executable loads all of the
   files contained within the /{system,vendor,odm}/etc/init/ directories.
   These directories are intended for all Actions and Services used after
   file system mounting.

One may specify paths in the mount\_all command line to have it import
.rc files at the specified paths instead of the default ones listed above.
This is primarily for supporting factory mode and other non-standard boot
modes.  The three default paths should be used for the normal boot process.

The intention of these directories is:

   1. /system/etc/init/ is for core system items such as
      SurfaceFlinger, MediaService, and logcatd.
   2. /vendor/etc/init/ is for SoC vendor items such as actions or
      daemons needed for core SoC functionality.
   3. /odm/etc/init/ is for device manufacturer items such as
      actions or daemons needed for motion sensor or other peripheral
      functionality.

All services whose binaries reside on the system, vendor, or odm
partitions should have their service entries placed into a
corresponding init .rc file, located in the /etc/init/
directory of the partition where they reside.  There is a build
system macro, LOCAL\_INIT\_RC, that handles this for developers.  Each
init .rc file should additionally contain any actions associated with
its service.

An example is the logcatd.rc and Android.mk files located in the
system/core/logcat directory.  The LOCAL\_INIT\_RC macro in the
Android.mk file places logcatd.rc in /system/etc/init/ during the
build process.  Init loads logcatd.rc during the mount\_all command and
allows the service to be run and the action to be queued when
appropriate.

This break up of init .rc files according to their daemon is preferred
to the previously used monolithic init .rc files.  This approach
ensures that the only service entries that init reads and the only
actions that init performs correspond to services whose binaries are in
fact present on the file system, which was not the case with the
monolithic init .rc files.  This additionally will aid in merge
conflict resolution when multiple services are added to the system, as
each one will go into a separate file.

There are two options "early" and "late" in mount\_all command
which can be set after optional paths. With "--early" set, the
init executable will skip mounting entries with "latemount" flag
and triggering fs encryption state event. With "--late" set,
init executable will only mount entries with "latemount" flag but skip
importing rc files. By default, no option is set, and mount\_all will
process all entries in the given fstab.

Actions
-------
Actions are named sequences of commands.  Actions have a trigger which
is used to determine when the action is executed.  When an event
occurs which matches an action's trigger, that action is added to
the tail of a to-be-executed queue (unless it is already on the
queue).

Each action in the queue is dequeued in sequence and each command in
that action is executed in sequence.  Init handles other activities
(device creation/destruction, property setting, process restarting)
"between" the execution of the commands in activities.

Actions take the form of:

    on [&& ]*
       
       
       

Actions are added to the queue and executed based on the order that
the file that contains them was parsed (see the Imports section), then
sequentially within an individual file.

For example if a file contains:

    on boot
       setprop a 1
       setprop b 2

    on boot && property:true=true
       setprop c 1
       setprop d 2

    on boot
       setprop e 1
       setprop f 2

Then when the `boot` trigger occurs and assuming the property `true`
equals `true`, then the order of the commands executed will be:

    setprop a 1
    setprop b 2
    setprop c 1
    setprop d 2
    setprop e 1
    setprop f 2


Services
--------
Services are programs which init launches and (optionally) restarts
when they exit.  Services take the form of:

    service [ ]*
       
       
       ...


Options
-------
Options are modifiers to services.  They affect how and when init
runs the service.

`console []`
> This service needs a console. The optional second parameter chooses a
  specific console instead of the default. The default "/dev/console" can
  be changed by setting the "androidboot.console" kernel parameter. In
  all cases the leading "/dev/" should be omitted, so "/dev/tty0" would be
  specified as just "console tty0".

`critical`
> This is a device-critical service. If it exits more than four times in
  four minutes, the device will reboot into recovery mode.

`disabled`
> This service will not automatically start with its class.
  It must be explicitly started by name.

`setenv `
> Set the environment variable _name_ to _value_ in the launched process.

`socket [ [ [ ] ] ]`
> Create a unix domain socket named /dev/socket/_name_ and pass its fd to the
  launched process.  _type_ must be "dgram", "stream" or "seqpacket".  User and
  group default to 0.  'seclabel' is the SELinux security context for the
  socket.  It defaults to the service security context, as specified by
  seclabel or computed based on the service executable file security context.
  For native executables see libcutils android\_get\_control\_socket().

`file `
> Open a file path and pass its fd to the launched process. _type_ must be
  "r", "w" or "rw".  For native executables see libcutils
  android\_get\_control\_file().

`user `
> Change to 'username' before exec'ing this service.
  Currently defaults to root.  (??? probably should default to nobody)
  As of Android M, processes should use this option even if they
  require Linux capabilities.  Previously, to acquire Linux
  capabilities, a process would need to run as root, request the
  capabilities, then drop to its desired uid.  There is a new
  mechanism through fs\_config that allows device manufacturers to add
  Linux capabilities to specific binaries on a file system that should
  be used instead. This mechanism is described on
  .  When
  using this new mechanism, processes can use the user option to
  select their desired uid without ever running as root.
  As of Android O, processes can also request capabilities directly in their .rc
  files. See the "capabilities" option below.

`group [ \* ]`
> Change to 'groupname' before exec'ing this service.  Additional
  groupnames beyond the (required) first one are used to set the
  supplemental groups of the process (via setgroups()).
  Currently defaults to root.  (??? probably should default to nobody)

`capabilities [ \* ]`
> Set capabilities when exec'ing this service. 'capability' should be a Linux
  capability without the "CAP\_" prefix, like "NET\_ADMIN" or "SETPCAP". See
  http://man7.org/linux/man-pages/man7/capabilities.7.html for a list of Linux
  capabilities.

`seclabel `
> Change to 'seclabel' before exec'ing this service.
  Primarily for use by services run from the rootfs, e.g. ueventd, adbd.
  Services on the system partition can instead use policy-defined transitions
  based on their file security context.
  If not specified and no transition is defined in policy, defaults to the init context.

`oneshot`
> Do not restart the service when it exits.

`class [ \* ]`
> Specify class names for the service.  All services in a
  named class may be started or stopped together.  A service
  is in the class "default" if one is not specified via the
  class option. Additional classnames beyond the (required) first
  one are used to group services.
`animation class`
> 'animation' class should include all services necessary for both
  boot animation and shutdown animation. As these services can be
  launched very early during bootup and can run until the last stage
  of shutdown, access to /data partition is not guaranteed. These
  services can check files under /data but it should not keep files opened
  and should work when /data is not available.

`onrestart`
> Execute a Command (see below) when service restarts.

`writepid [ \* ]`
> Write the child's pid to the given files when it forks. Meant for
  cgroup/cpuset usage. If no files under /dev/cpuset/ are specified, but the
  system property 'ro.cpuset.default' is set to a non-empty cpuset name (e.g.
  '/foreground'), then the pid is written to file /dev/cpuset/_cpuset\_name_/tasks.

`priority `
> Scheduling priority of the service process. This value has to be in range
  -20 to 19. Default priority is 0. Priority is set via setpriority().

`namespace `
> Enter a new PID or mount namespace when forking the service.

`oom_score_adjust `
> Sets the child's /proc/self/oom\_score\_adj to the specified value,
  which must range from -1000 to 1000.

`memcg.swappiness `
> Sets the child's memory.swappiness to the specified value (only if memcg is mounted),
  which must be equal or greater than 0.

`memcg.soft_limit_in_bytes `
> Sets the child's memory.soft_limit_in_bytes to the specified value (only if memcg is mounted),
  which must be equal or greater than 0.

`memcg.limit_in_bytes `
> Sets the child's memory.limit_in_bytes to the specified value (only if memcg is mounted),
  which must be equal or greater than 0.

`shutdown `
> Set shutdown behavior of the service process. When this is not specified,
  the service is killed during shutdown process by using SIGTERM and SIGKILL.
  The service with shutdown_behavior of "critical" is not killed during shutdown
  until shutdown times out. When shutdown times out, even services tagged with
  "shutdown critical" will be killed. When the service tagged with "shutdown critical"
  is not running when shut down starts, it will be started.


Triggers
--------
Triggers are strings which can be used to match certain kinds of
events and used to cause an action to occur.

Triggers are subdivided into event triggers and property triggers.

Event triggers are strings triggered by the 'trigger' command or by
the QueueEventTrigger() function within the init executable.  These
take the form of a simple string such as 'boot' or 'late-init'.

Property triggers are strings triggered when a named property changes
value to a given new value or when a named property changes value to
any new value.  These take the form of 'property:=' and
'property:=\*' respectively.  Property triggers are additionally
evaluated and triggered accordingly during the initial boot phase of
init.

An Action can have multiple property triggers but may only have one
event trigger.

For example:
`on boot && property:a=b` defines an action that is only executed when
the 'boot' event trigger happens and the property a equals b.

`on property:a=b && property:c=d` defines an action that is executed
at three times:

   1. During initial boot if property a=b and property c=d.
   2. Any time that property a transitions to value b, while property c already equals d.
   3. Any time that property c transitions to value d, while property a already equals b.


Commands
--------

`bootchart [start|stop]`
> Start/stop bootcharting. These are present in the default init.rc files,
  but bootcharting is only active if the file /data/bootchart/enabled exists;
  otherwise bootchart start/stop are no-ops.

`chmod `
> Change file access permissions.

`chown `
> Change file owner and group.

`class_start `
> Start all services of the specified class if they are
  not already running.  See the start entry for more information on
  starting services.

`class_stop `
> Stop and disable all services of the specified class if they are
  currently running.

`class_reset `
> Stop all services of the specified class if they are
  currently running, without disabling them. They can be restarted
  later using `class_start`.

`class_restart `
> Restarts all services of the specified class.

`copy `
> Copies a file. Similar to write, but useful for binary/large
  amounts of data.
  Regarding to the src file, copying from symbolic link file and world-writable
  or group-writable files are not allowed.
  Regarding to the dst file, the default mode created is 0600 if it does not
  exist. And it will be truncated if dst file is a normal regular file and
  already exists.

`domainname `
> Set the domain name.

`enable `
> Turns a disabled service into an enabled one as if the service did not
  specify disabled.
  If the service is supposed to be running, it will be started now.
  Typically used when the bootloader sets a variable that indicates a specific
  service should be started when needed. E.g.

    on property:ro.boot.myfancyhardware=1
        enable my_fancy_service_for_my_fancy_hardware

`exec [ [ [ \* ] ] ] -- [ \* ]`
> Fork and execute command with the given arguments. The command starts
  after "--" so that an optional security context, user, and supplementary
  groups can be provided. No other commands will be run until this one
  finishes. _seclabel_ can be a - to denote default. Properties are expanded
  within _argument_.
  Init halts executing commands until the forked process exits.

`exec_start `
> Start a given service and halt the processing of additional init commands
  until it returns.  The command functions similarly to the `exec` command,
  but uses an existing service definition in place of the exec argument vector.

`export `
> Set the environment variable _name_ equal to _value_ in the
  global environment (which will be inherited by all processes
  started after this command is executed)

`hostname `
> Set the host name.

`ifup `
> Bring the network interface _interface_ online.

`insmod [-f] []`
> Install the module at _path_ with the specified options.
  -f: force installation of the module even if the version of the running kernel
  and the version of the kernel for which the module was compiled do not match.

`load_all_props`
> Loads properties from /system, /vendor, et cetera.
  This is included in the default init.rc.

`load_persist_props`
> Loads persistent properties when /data has been decrypted.
  This is included in the default init.rc.

`loglevel `
> Sets the kernel log level to level. Properties are expanded within _level_.

`mkdir [mode] [owner] [group]`
> Create a directory at _path_, optionally with the given mode, owner, and
  group. If not provided, the directory is created with permissions 755 and
  owned by the root user and root group. If provided, the mode, owner and group
  will be updated if the directory exists already.

`mount_all [ ]\* [--
> Calls fs\_mgr\_mount\_all on the given fs\_mgr-format fstab and imports .rc files
  at the specified paths (e.g., on the partitions just mounted) with optional
  options "early" and "late".
  Refer to the section of "Init .rc Files" for detail.

`mount



[ \* ] []`
> Attempt to mount the named device at the directory _dir_
  _flag_s include "ro", "rw", "remount", "noatime", ...
  _options_ include "barrier=1", "noauto\_da\_alloc", "discard", ... as
  a comma separated string, eg: barrier=1,noauto\_da\_alloc

`restart `
> Stops and restarts a running service, does nothing if the service is currently
  restarting, otherwise, it just starts the service.

`restorecon [ \* ]`
> Restore the file named by _path_ to the security context specified
  in the file\_contexts configuration.
  Not required for directories created by the init.rc as these are
  automatically labeled correctly by init.

`restorecon_recursive [ \* ]`
> Recursively restore the directory tree named by _path_ to the
  security contexts specified in the file\_contexts configuration.

`rm `
> Calls unlink(2) on the given path. You might want to
  use "exec -- rm ..." instead (provided the system partition is
  already mounted).

`rmdir `
> Calls rmdir(2) on the given path.

`setprop `
> Set system property _name_ to _value_. Properties are expanded
  within _value_.

`setrlimit `
> Set the rlimit for a resource.

`start `
> Start a service running if it is not already running.
  Note that this is _not_ synchronous, and even if it were, there is
  no guarantee that the operating system's scheduler will execute the
  service sufficiently to guarantee anything about the service's status.

> This creates an important consequence that if the service offers
  functionality to other services, such as providing a
  communication channel, simply starting this service before those
  services is _not_ sufficient to guarantee that the channel has
  been set up before those services ask for it.  There must be a
  separate mechanism to make any such guarantees.

`stop `
> Stop a service from running if it is currently running.

`swapon_all `
> Calls fs\_mgr\_swapon\_all on the given fstab file.

`symlink `
> Create a symbolic link at _path_ with the value _target_

`sysclktz `
> Set the system clock base (0 if system clock ticks in GMT)

`trigger `
> Trigger an event.  Used to queue an action from another
  action.

`umount `
> Unmount the filesystem mounted at that path.

`verity_load_state`
> Internal implementation detail used to load dm-verity state.

`verity_update_state `
> Internal implementation detail used to update dm-verity state and
  set the partition._mount-point_.verified properties used by adb remount
  because fs\_mgr can't set them directly itself.

`wait [ ]`
> Poll for the existence of the given file and return when found,
  or the timeout has been reached. If timeout is not specified it
  currently defaults to five seconds.

`wait_for_prop `
> Wait for system property _name_ to be _value_. Properties are expanded
  within _value_. If property _name_ is already set to _value_, continue
  immediately.

`write `
> Open the file at _path_ and write a string to it with write(2).
  If the file does not exist, it will be created. If it does exist,
  it will be truncated. Properties are expanded within _content_.


Imports
-------
`import `
> Parse an init config file, extending the current configuration.
  If _path_ is a directory, each file in the directory is parsed as
  a config file. It is not recursive, nested directories will
  not be parsed.

The import keyword is not a command, but rather its own section,
meaning that it does not happen as part of an Action, but rather,
imports are handled as a file is being parsed and follow the below logic.

There are only three times where the init executable imports .rc files:

   1. When it imports /init.rc or the script indicated by the property
      `ro.boot.init_rc` during initial boot.
   2. When it imports /{system,vendor,odm}/etc/init/ for first stage mount
      devices immediately after importing /init.rc.
   3. When it imports /{system,vendor,odm}/etc/init/ or .rc files at specified
      paths during mount_all.

The order that files are imported is a bit complex for legacy reasons
and to keep backwards compatibility.  It is not strictly guaranteed.

The only correct way to guarantee that a command has been run before a
different command is to either 1) place it in an Action with an
earlier executed trigger, or 2) place it in an Action with the same
trigger within the same file at an earlier line.

Nonetheless, the defacto order for first stage mount devices is:
1. /init.rc is parsed then recursively each of its imports are
   parsed.
2. The contents of /system/etc/init/ are alphabetized and parsed
   sequentially, with imports happening recursively after each file is
   parsed.
3. Step 2 is repeated for /vendor/etc/init then /odm/etc/init

The below pseudocode may explain this more clearly:

    fn Import(file)
      Parse(file)
      for (import : file.imports)
        Import(import)

    Import(/init.rc)
    Directories = [/system/etc/init, /vendor/etc/init, /odm/etc/init]
    for (directory : Directories)
      files =
      for (file : files)
        Import(file)


Properties
----------
Init provides information about the services that it is responsible
for via the below properties.

`init.svc.`
> State of a named service ("stopped", "stopping", "running", "restarting")


Boot timing
-----------
Init records some boot timing information in system properties.

`ro.boottime.init`
> Time after boot in ns (via the CLOCK\_BOOTTIME clock) at which the first
  stage of init started.

`ro.boottime.init.selinux`
> How long it took the first stage to initialize SELinux.

`ro.boottime.init.cold_boot_wait`
> How long init waited for ueventd's coldboot phase to end.

`ro.boottime.`
> Time after boot in ns (via the CLOCK\_BOOTTIME clock) that the service was
  first started.


Bootcharting
------------
This version of init contains code to perform "bootcharting": generating log
files that can be later processed by the tools provided by .

On the emulator, use the -bootchart _timeout_ option to boot with bootcharting
activated for _timeout_ seconds.

On a device:

    adb shell 'touch /data/bootchart/enabled'

Don't forget to delete this file when you're done collecting data!

The log files are written to /data/bootchart/. A script is provided to
retrieve them and create a bootchart.tgz file that can be used with the
bootchart command-line utility:

    sudo apt-get install pybootchartgui
    # grab-bootchart.sh uses $ANDROID_SERIAL.
    $ANDROID_BUILD_TOP/system/core/init/grab-bootchart.sh

One thing to watch for is that the bootchart will show init as if it started
running at 0s. You'll have to look at dmesg to work out when the kernel
actually started init.


Comparing two bootcharts
------------------------
A handy script named compare-bootcharts.py can be used to compare the
start/end time of selected processes. The aforementioned grab-bootchart.sh
will leave a bootchart tarball named bootchart.tgz at /tmp/android-bootchart.
If two such barballs are preserved on the host machine under different
directories, the script can list the timestamps differences. For example:

Usage: system/core/init/compare-bootcharts.py _base-bootchart-dir_ _exp-bootchart-dir_

    process: baseline experiment (delta) - Unit is ms (a jiffy is 10 ms on the system)
    ------------------------------------
    /init: 50 40 (-10)
    /system/bin/surfaceflinger: 4320 4470 (+150)
    /system/bin/bootanimation: 6980 6990 (+10)
    zygote64: 10410 10640 (+230)
    zygote: 10410 10640 (+230)
    system_server: 15350 15150 (-200)
    bootanimation ends at: 33790 31230 (-2560)


Systrace
--------
Systrace () can be
used for obtaining performance analysis reports during boot
time on userdebug or eng builds.

Here is an example of trace events of "wm" and "am" categories:

    $ANDROID_BUILD_TOP/external/chromium-trace/systrace.py \
          wm am --boot

This command will cause the device to reboot. After the device is rebooted and
the boot sequence has finished, the trace report is obtained from the device
and written as trace.html on the host by hitting Ctrl+C.

Limitation: recording trace events is started after persistent properties are loaded, so
the trace events that are emitted before that are not recorded. Several
services such as vold, surfaceflinger, and servicemanager are affected by this
limitation since they are started before persistent properties are loaded.
Zygote initialization and the processes that are forked from the zygote are not
affected.


Debugging init
--------------
By default, programs executed by init will drop stdout and stderr into
/dev/null. To help with debugging, you can execute your program via the
Android program logwrapper. This will redirect stdout/stderr into the
Android logging system (accessed via logcat).

For example
service akmd /system/bin/logwrapper /sbin/akmd

For quicker turnaround when working on init itself, use:

    mm -j &&
    m ramdisk-nodeps &&
    m bootimage-nodeps &&
    adb reboot bootloader &&
    fastboot boot $ANDROID_PRODUCT_OUT/boot.img

Alternatively, use the emulator:

    emulator -partition-size 1024 \
        -verbose -show-kernel -no-window

2018年8月24日 星期五

Android Property - setProp配合代碼, 大大加快測試

https://www.jianshu.com/p/1a2123d940c8

1. 前言


最近, 在Android 開發中遇到一個問題, 有個app 需要每次燒寫(比如略修改一些代碼, 就要重新編譯, 再燒錄到Android 手機裡)。
這樣, 對於測試一些代碼的改動就不是很方便了, 比如我要修改Android 底層C++ 代碼中的兩個變量, 這兩個都可以取整數值。
其中一個是echo_delay, 另一個是filter_length。
我要測試出這兩個數值的最佳組合,需要測試很多次,也就是要修改、編譯、燒寫、啟動很多次,這工作量那是相當大呀。

2. 解決


有沒有什麼辦法可以大大減輕工作量呢?必須有!
自己找了一下:
在Android 開發中,你可以用USB 線連接Android 設備和電腦,進入adb 模式(用adb shell),然後用各種命令來操作你的手機。
Android 系統有不少屬性,例如:
ro.product.model
是對應設備的型號。如果我在Samsung 的S5 手機上,它的值是
SM-G900F
這些系統屬性是在/system/build.prop 這個文件中,需要你有Root 權限才能修改。
我們可以用cat 命令來打印出/system/build.prop 這個文件的內容:
cat /system/build.prop
屬性很多,我們只截屏了開頭的一部分。
可以看到屬性中有很多是以ro 開頭的,例如:
ro.product.model
ro.build.id
ro.product.board
等等。
ro 表示Read Only,是英語「只讀」的意思,表示只能讀取,不能修改。
當然了,這些ro開頭的屬性也不是不能修改,你可以通過一些方式來修改。修改的後果自負。
你可以自行Google搜索,或者參考這篇StackOverFlow的文章,或者這篇文章,不過不在本課討論之列。
adb 的眾多命令中有一個命令叫做setprop,是set property(設置屬性)的簡寫,用於為系統設置屬性的值,就是類似鍵值對的概念。
setprop 命令還可以用於設置自定義的屬性。你可以隨便取什麼名字的屬性,例如hostname,可以用如下方法來設置它的值:
setprop 属性名称 属性的值
既然有setprop 命令,Android 也提供了getprop 命令,用於顯示屬性的值。
使用方法如下:
getprop 属性名称
用setprop 設置了設備的屬性之後,在Android 的代碼中就可以獲取到屬性的值。
例如我們來修改系統的一個屬性值,名叫media.enable-commonsource(這個屬性值不是以ro 開頭,不是只讀,可以修改),它的默認值是true。我們可以用
setprop media.enable-commonsource false
把它的值改為false。然後用getprop 來查看它新的值:
getprop media.enable-commonsource
可以看到,media.enable-commonsource 已經被我們從true 改成了false。
用這個原理,我們只要用setprop 命令修改我們的兩個變量的取值,就立即生效了。很方便吧!
首先你可以在Java 代碼中寫一個你自己的readProp 函數,用於根據屬性的名稱來獲取屬性的值,可以類似如下:
private int readProp(String prop) {
        try {
            Process process = Runtime.getRuntime().exec("getprop " + prop);
            InputStreamReader ir = new InputStreamReader(process.getInputStream());
            BufferedReader input = new BufferedReader(ir);
            return Integer.parseInt(input.readLine());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
在你的代碼中調用
int delay = readProp("delay");
int filter = readProp("filter");

Log.i(TAG, "Echo_delay = " + delay + ", filter_length = " + filter);
然後把代碼編譯,燒寫到Android 設備中,再用setprop 命令開始測試。
例如設置echo delay:
setprop delay 250
可以用getprop 命令看看設置的值是否正確:
getprop delay
設置另一個值filter length:
setprop filter 100
getprop filter
我們在Logcat 裡打印出來的值也可以驗證我們的設置:
這樣, 你就只要一次燒寫, 之後這兩個值完全可以通過命令行來實時修改, 豈不快哉~


作者:程序员联盟
链接:https://www.jianshu.com/p/1a2123d940c8
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

2018年8月12日 星期日

Android Property

相關文章
https://stackoverflow.com/questions/23758994/change-the-model-in-build-prop
https://www.techgainer.com/change-fake-android-device-model-number-and-brand-name/


====================================================================
出處 https://blog.csdn.net/Dylan_Sen/article/details/78757466

本文將從下面三方面簡單分析總結android property:
1. Property的使用方式
2. Property文件的加載
3. Property的存儲

1. Property的使用方式

在工作中經常通過下面三種方式使用property:
1.1 code裡面使用SystemProperties.java和properties.cpp
SystemProperties.java為Jave層提供了下面的方法:
 public static String get(String key){...}
 public static String get(String key, String def){...}
 public static int getInt(String key, int def){...}
 public static long getLong(String key, long def){...}
 public static boolean getBoolean(String key, boolean def){...}
 public static void set(String key, String val){...}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
system/core/libcutils/properties.cpp給Native層提供了下面的API:
int property_set(const char *key, const char *value) {...}
int property_get(const char *key, char *value, const char *default_value) {...}
int8_t property_get_bool(const char *key, int8_t default_value) {...}
static intmax_t property_get_imax(const char *key, intmax_t lower_bound, intmax_t upper_bound,
                                  intmax_t default_value) {...}
int64_t property_get_int64(const char *key, int64_t default_value) {...}
int32_t property_get_int32(const char *key, int32_t default_value){...}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
1.2 adb命令
adb的方式為我們調式提供了方便。
[格式] 
adb shell getprop [proptery_name] 
adb shell setprop propterty_name value 
[例子] 
adb shell getprop ro.build.type 
adb shell setprop persist.log.tag.ImsManager V
1.3 通過文件設置默認property;將property放在文件中,init進程去加載文件。
前兩種方式可以讀取所有的property;但是在寫方面,對於ro.* property這種write-once的property是不能覆蓋的。

2. Property文件的加載

Property的初始化,以及相關propety文件的加載都在Init進程中完成。所以這部分內容從init進程的main函數開始。按照main函數中的code順序,主要內容如下:
  • Property area初始化
  • 加載default property文件
  • 創建property service
  • 加載解析rc文件
  • 執行rc文件中的action; system property, persistent property和override property文件會在這個過程中相繼被加載。
main函數會調用proprerty_service.cpp中的property_init()函數來初始化property area。
void property_init() {
    if (__system_property_area_init()) {
        LOG(ERROR) << "Failed to initialize property area";
        exit(1);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
property_init函數調用了System_properties.cpp中的__system_property_area_init()函數。後者又先後調用了initialize_properties()和map_system_property_area函數。
initialize_properties()函數:
initialize_properties會嘗試加載”/property_contexts”,如果失敗會嘗試加載/system和/vendor下對應的文件,看來從Android O開始/property_contexts文件已經不再使用,取而代之的是/plat_property_contexts。“/property_contexts”等文件為property prefix分配了security context,用來控制set權限。
property_contexts內容如下:
...
sys.usb.config          u:object_r:system_radio_prop:s0
ril.                    u:object_r:radio_prop:s0
ro.ril.                 u:object_r:radio_prop:s0
gsm.                    u:object_r:radio_prop:s0
...
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
static bool initialize_properties() {
  // If we do find /property_contexts, then this is being
  // run as part of the OTA updater on older release that had
  // /property_contexts - b/34370523
  if (initialize_properties_from_file("/property_contexts")) {//加载"/property_contexts"
    return true;
  }

  // Use property_contexts from /system & /vendor, fall back to those from /
  if (access("/system/etc/selinux/plat_property_contexts", R_OK) != -1) {
   //如果可以访问/system/etc/selinux/plat_property_contexts,就去加载解析文件。
    if (!initialize_properties_from_file("/system/etc/selinux/plat_property_contexts")) {
      return false;//这里如果解析失败就直接返回了,不再加载其他路径下的文件。
    }
    // Don't check for failure here, so we always have a sane list of properties.
    // E.g. In case of recovery, the vendor partition will not have mounted and we
    // still need the system / platform properties to function.
    //这里去加载/vendor/etc/selinux/nonplat_property_contexts, 但是不care结果。
    initialize_properties_from_file("/vendor/etc/selinux/nonplat_property_contexts");
  } else {
    //如果/system没有配置property_contexts文件,那么加载//plat_property_contexts
    if (!initialize_properties_from_file("/plat_property_contexts")) {
      return false;
    }
    initialize_properties_from_file("/nonplat_property_contexts");
  }

  return true;
}

/*initialize_properties_from_file负责解析property_contexts文件中的内容,
*将property前缀存在prefixes指向的链表中,将context存在contexts指向的链表中。
*/
static bool initialize_properties_from_file(const char* filename) {
  FILE* file = fopen(filename, "re");
  if (!file) {
    return false;
  }

  char* buffer = nullptr;
  size_t line_len;
  char* prop_prefix = nullptr;
  char* context = nullptr;

  while (getline(&buffer, &line_len, file) > 0) {
    int items = read_spec_entries(buffer, 2, &prop_prefix, &context);
    if (items <= 0) {
      continue;
    }
    if (items == 1) {
      free(prop_prefix);
      continue;
    }
    /*
     * init uses ctl.* properties as an IPC mechanism and does not write them
     * to a property file, therefore we do not need to create property files
     * to store them.
     */
    if (!strncmp(prop_prefix, "ctl.", 4)) {
      free(prop_prefix);
      free(context);
      continue;
    }

    auto old_context =
        list_find(contexts, [context](context_node* l) { return !strcmp(l->context(), context); });
    if (old_context) {
      list_add_after_len(&prefixes, prop_prefix, old_context);
    } else {
      list_add(&contexts, context, nullptr);
      list_add_after_len(&prefixes, prop_prefix, contexts);
    }
    free(prop_prefix);
    free(context);
  }

  free(buffer);
  fclose(file);

  return true;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
map_system_property_area函數:
在看map_system_property_area(…)函數之前,我們先看下__system_property_area_init()函數。
int __system_property_area_init() {
  free_and_unmap_contexts();
  //property_filename所指的路径为/dev/__properties__; #define PROP_FILENAME "/dev/__properties__"
  mkdir(property_filename, S_IRWXU | S_IXGRP | S_IXOTH);
  if (!initialize_properties()) {
    return -1;
  }
  bool open_failed = false;
  bool fsetxattr_failed = false;

  /*从property_contexts中解析的context全在contexts指向的链表中,下面这段代码就是遍历链表,
  *open函数将每个context_node节点对应的文件都打开,并映射到一块share memory中。
  *并在这块memory上构造一个prop_area指针存在context_node节点中。
  */
  list_foreach(contexts, [&fsetxattr_failed, &open_failed](context_node* l) {
    if (!l->open(true, &fsetxattr_failed)) {
      open_failed = true;
    }
  });
  if (open_failed || !map_system_property_area(true, &fsetxattr_failed)) {
    free_and_unmap_contexts();
    return -1;
  }
  initialized = true;
  return fsetxattr_failed ? -2 : 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
下面看看map_system_property_area函數:
打開/dev/ properties /properties_serial文件,並映射到共享內存,將地址保存在system_property_area中。
static bool map_system_property_area(bool access_rw, bool* fsetxattr_failed) {
  char filename[PROP_FILENAME_MAX];
  //经过下面的格式化之后filename指向的文件为/dev/__properties__/properties_serial
  int len =
      __libc_format_buffer(filename, sizeof(filename), "%s/properties_serial", property_filename);
  if (len < 0 || len > PROP_FILENAME_MAX) {
    __system_property_area__ = nullptr;
    return false;
  }

  if (access_rw) {
   /*map_prop_area_rw函数会打开filename,映射一块共享内存,然后将地址返回。
   *地址将保存在 __system_property_area__中, 这个是一个全局变量,property
   *相关的操作还会用到这个变量。
   */
    __system_property_area__ =
        map_prop_area_rw(filename, "u:object_r:properties_serial:s0", fsetxattr_failed);
  } else {
    __system_property_area__ = map_prop_area(filename);
  }
  return __system_property_area__;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
到這裡property area初始化就完成了。
在講property文件的加載之前,有必要先講下rc文件相關的知識點。rc文件被加載解析之後,所有的action會被放到ActionManager的actions_ (vector類型)容器裡;而action對應的commend對放到對應action的commands_ (vector類型)容器裡。ActionManager負責根據trigger來執行action。
command對像在被創建的時候,會根據關鍵字在KeywordMap類型的指針function_map_中查找對應的function; function_map_的賦值是在main函數中,使用的是BuiltinFunctionMap對象,BuiltinFunctionMap是繼承自KeywordMap。最終是在BuiltinFunctionMap內Map類型的變量builtin_functions中查找。
下面是buildin_functions中的部分內容:
        {"load_persist_props",      {0,     0,    do_load_persist_props}},
        {"load_system_props",       {0,     0,    do_load_system_props}},
        {"loglevel",                {1,     1,    do_loglevel}},
  • 1
  • 2
  • 3
下面是init.rc中的相關內容:
on post-fs
    # Load properties from
    #     /system/build.prop,
    #     /odm/build.prop,
    #     /vendor/build.prop and
    #     /factory/factory.prop
    load_system_props

    ...

on load_persist_props_action
    load_persist_props
    start logd
    start logd-reinit

    ...

    on property:vold.decrypt=trigger_load_persist_props
    load_persist_props
    start logd
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
當load_persist_props和load_system_props 命令執行的時候do_load_persist_props和do_load_system_props 函數會分別執行。
//下面是system property
static int do_load_system_props(const std::vector<std::string>& args) {
    load_system_props();
    return 0;
}

void load_system_props() {
    load_properties_from_file("/system/build.prop", NULL);
    load_properties_from_file("/odm/build.prop", NULL);
    load_properties_from_file("/vendor/build.prop", NULL);
    load_properties_from_file("/factory/factory.prop", "ro.*");
    load_recovery_id_prop();
}

//下面是persist properties
static int do_load_persist_props(const std::vector<std::string>& args) {
    load_persist_props();
    return 0;
}
void load_persist_props(void) {
    load_override_properties();
    /* Read persistent properties after all default values have been loaded. */
    load_persistent_properties();
    property_set("ro.persistent_properties.ready", "true");
}

static void load_override_properties() {
    if (ALLOW_LOCAL_PROP_OVERRIDE) {
        load_properties_from_file("/data/local.prop", NULL);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
在執行rc文件內的action之前,main函數會調用property_load_boot_defaults()函數加載默認property; 調用start_property_service()函數來創建了一個名字為property_service的Unix domain Socket(PROP_SERVICE_NAME:property_service)來處理set prop請求。
void property_load_boot_defaults() {
    if (!load_properties_from_file("/system/etc/prop.default", NULL)) {
        // Try recovery path
        if (!load_properties_from_file("/prop.default", NULL)) {
            // Try legacy path
            load_properties_from_file("/default.prop", NULL);
        }
    }
    load_properties_from_file("/odm/default.prop", NULL);
    load_properties_from_file("/vendor/default.prop", NULL);

    update_sys_usb_config();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
下面總結了可能會被加載的property文件或property(按照code順序):
文件/屬性註釋
/system/etc/prop.default
/prop.default
/default.prop
/odm/default.prop
/vendor/default.prop
/system/build.prop
/odm/build.prop
/vendor/build.prop
/factory/factory.prop只加載ro.*
ro.recovery_id
/data/local.prop
/數據/屬性這個路徑下只加載persist開頭的property
/system/build.prop, /vendor/build.prop(PRODUCT_PROPERTY_OVERRIDES包含在內),/default.prop等生成規則都在代碼build/core/Makefile中有定義,當然如果不懂make 語法和函數,是不可能看的很明白。

3. Property的存儲

Property的存儲,工作中用不到,所以不想深究,根據System_properties.cpp中的註釋知道使用的是混合樹結構(hybrid trie),查找速度快,也省空間(分割了前綴,可以共用)。
Property是只能由init進程(單線程)更新,由property service完成。為了避免對線程讀的問題,在節點上使用了atomic_uint_least32_t。
/*
 * Properties are stored in a hybrid trie/binary tree structure.
 * Each property's name is delimited at '.' characters, and the tokens are put
 * into a trie structure.  Siblings at each level of the trie are stored in a
 * binary tree.  For instance, "ro.secure"="1" could be stored as follows:
 *
 * +-----+   children    +----+   children    +--------+
 * |     |-------------->| ro |-------------->| secure |
 * +-----+               +----+               +--------+
 *                       /    \                /   |
 *                 left /      \ right   left /    |  prop   +===========+
 *                     v        v            v     +-------->| ro.secure |
 *                  +-----+   +-----+     +-----+            +-----------+
 *                  | net |   | sys |     | com |            |     1     |
 *                  +-----+   +-----+     +-----+            +===========+
 */