How to Create ROM

Published on May 2016 | Categories: Documents | Downloads: 84 | Comments: 0 | Views: 766
of 86
Download PDF   Embed   Report

Describe how to create a ROM

Comments

Content


Adding features to your kernel
Adding features to your kernel
The kernel is probably one of the most important parts of the Android system, the whole system
relies on the kernel, the performance, stability, smoothness, etc.
Considering the kernel as the most important part, you want it to be optimized, making your
system run smooth and performing above standards, also the battery life may not suffer when
gaining these improvements. In this tutorial I will explain how to add C! "overnors, how to
add I#$ %chedulers and a global sight on how to add $verclocking support for your kernel.

Chapters:
1. Github
2. Governors
3. I/O !hedulers
". Over!lo!king

Chapter 1. Github
I will not explain how to use "ithub in general, also I&m not trying to advertise for "ithub. I 'ust
want to say that you really (need) to use "ithub in order to get a clear overview of the changes
you made.
*elieve me, without a commit system and thousands of changes in your source, you will
definitely forget what you actually did to the source.
"ithub helps you keeping track of the changes you made. +asily done by commits added by the
developer.
If you want to build a ,custom- kernel form source and you want to customize it, you #ust use
Github$ .ot 'ust for the overview of changes but also to make sure you don&t violate the "/
law0
%ince the android kernels are open source and protected by the "/ law, you need to share your
source with the world. ,same thing counts for manufacturers0-
+nough about "ithub, let&s start with customizing.

Chapter 2. Governors
1hat is a governor, why is it important to have custom governors and how to add governors to
your kernel2 These 3 4uestions are very important to know.
1hat is a governor5 A governor is actually nothing more then a behavior profile for your C!,
the governor will tell the C! exactly what to do in what situation. The term 6governor& has
nothing to do with it&s function, imagine it was called C! residents0 sounds strange but it&s as
normal as using the word "overnor.
1hy is it important to have custom governors5 The default governors added to kernels are
(ondemand, powersave, performance, conservative) and optionally (userspace), all these
governors are pretty basic and not optimized for usage#battery whatsoever. a list of default
governors with a small description5
7 ondemand, the overall default C! governor worldwide. *asically 'ust ramps up your C!
speed to max fre4 when 'ust pushing the screen once, then lowering it back to the minimal cpu
fre4 ,somewhat smart, but not optimized at all-.
7 performance 'ust stays at the max C! fre4 all the time ,horrible for your battery-.
7 powersave stays at the min C! fre4 all the time ,resulting over the top lag-.
7 conservative is somewhat ad'usted to use less power, but that&s also very notable in
performance.
7 userspace is a governor that needs to be completely configured manually, the default setting is
the same as powersave, it will stay at your min C! fre4 when not configured. ,this governor is
rarely used-
*ecause the stock C! "overnors are 'ust plain boring and do not improve your device
whatsoever, you want to add custom C! "overnors, making your device smoother, more stable
and less battery consuming.
%o& to add a C'( Governor5
The C! governor itself is 'ust 8 C file, which is located in kernel9source#drivers#cpufre4#, for
example5 cpufre49smartass:.c. ;ou are responsible yourself for find the governor ,look in an
existing kernel repo for your device-
*ut in order to successfully call and compile this file into your kernel you will have to make the
following changes5
8. Copy your governor file ,cpufre49govname.c- and browse to kernel9source#drivers#cpufre4,
now paste it.
:. and open )!onfig ,this is the interface of the config menu layout- when adding a kernel, you
want it to show up in your config. ;ou can do that by adding the choice of governor.
8
:
3
<
config C!9=>+?9"$@9"[email protected]+B+>+
tristate CDgov9name9lowercaseD cpufre4 governorC
depends on C!9=>+?
help
E governorD 7 a custom governor0
for example, for smartass@:.
8
:
3
<
E
config C!9=>+?9"$@9%AA>TA%%:
tristate CDsmartass@:D cpufre4 governorC
depends on C!9=>+?
help
Dsmartass@:D 7 a CsmartC optimized governor0

next to adding the choice, you also must declare the possibility that the governor gets chosen as
default governor.
8
:
3
<
E
config C!9=>+?9F+=A!/T9"$@9"[email protected]+B+>+
bool Cgov9name9lowercaseC
select C!9=>+?9"$@9"[email protected]+B+>+
help
!se the C!=re4 governor DgovnameD as default.
for example, for smartass@:.
8
:
3
<
E
config C!9=>+?9F+=A!/T9"$@9%AA>TA%%:
bool Csmartass:C
select C!9=>+?9"$@9%AA>TA%%:
help
!se the C!=re4 governor Dsmartass@:D as default.
7 can&t find the right place to put it2 Gust search for (C!9=>+?9"$@9C$.%+>@ATI@+),
and place the code beneath, same thing counts for
(C!9=>+?9F+=A!/T9"$@9C$.%+>@ATI@+)
.ow that Hconfig is finished you can save and close the file.
3. 1hile still in the #drivers#cpufre4 folder, open Aakefile.
In Aakefile, add the line corresponding to your C! "overnor. for example5
8 ob'7I,C$.=I"9C!9=>+?9"$@9%AA>TA%%:- JK cpufre49smartass:.o
*e ware that you do not call the native C file, but the $ file0 which is the compiled C file. %ave
the file.
<. Aove to5 kernel9source#includes#linux. now open cpufre4.h
%croll down until you see something like5
8
:
3
Lelif defined,C$.=I"9C!9=>+?9F+=A!/T9"$@9$.F+AA.F-
extern struct cpufre49governor cpufre49gov9ondemandM
Ldefine C!=>+?9F+=A!/T9"$@+>.$> ,NampMcpufre49gov9ondemand-
,other cpu governors are also listed there-
.ow add your entry with the selected C! "overnor, example5
8
:
3
Lelif defined,C$.=I"9C!9=>+?9F+=A!/T9"$@9%AA>TA%%:-
extern struct cpufre49governor cpufre49gov9smartass:M
Ldefine C!=>+?9F+=A!/T9"$@+>.$> ,NampMcpufre49gov9smartass:-
%ave the file and close it.
The initial C! "overnor setup is now complete. when you&ve done all steps successfully, you
should be able to choose your governor from the menu ,menuconfig, xconfig, gconfig, nconfig-.
$nce checked in the menu it will be included to the kernel.
Commit that is nearly the same as above instructions5 (add smartass@: and lulzactive governor
commit)


Chapter 3. I/O !hedulers
.ext to adding custom C! governors, you can also enhance your kernel by adding new I#$
%chedulers if needed. "lobally "overnors and %chedulers are the same, they both provide a way
how the system should work. but on %chedulers it&s all about the Input#$utput datastream except
the C! settings. the I#$ %chedulers decide how the upcoming I#$ activity is being scheduled.
The standard schedulers such as (noop) or (cf4) are pretty decent actually. They perform very
reasonable.
Anyways, you can add more I#$ %chedulers if you like to, think of (deadline#sio#row#vr) for
example
I will explain how to add a I#$ %cheduler, it&s 'ust a bit easier then adding a C! "overnor.
I#$ %chedulers can be found in kernel9source#block.
8. Copy your I#$ %cheduler file ,example sio7iosched.c- and browse to kernel9source#block,
now paste it.
:. .ow open Hconfig.iosched, and add the choice to the Hconfig, example for %I$
8
:
3
<
E
O
P
Q
R
config I$%CB+F9%I$
tristate C%imple I#$ schedulerC
default y
777help777
The %imple I#$ scheduler is an extremely simple scheduler,
based on noop and deadline, that relies on deadlines to
ensure fairness. The algorithm does not do any sorting but
basic merging, trying to keep a minimum overhead. It is aimed
mainly for aleatory access devices ,eg5 flash devices-.
3. and the default choice option5
8 default CsioC if F+=A!/T9%I$
%ave the file, and move on to the Aakefile of kernel9source#block#
<. %imply add this line, for %I$5
8 ob'7I,C$.=I"9I$%CB+F9%I$- JK sio7iosched.o
%ave the file and you&re done0 The I#$ %chedulers should now popup at the menu config.
Commit that is nearly the same as above instructions5 (add simple I#$ scheduler commit)
Chapter ". Adding Over!lo!king
!nfortunately there is no solution A//7I.7$.+ solution available regarding overclocking,
every device has a different $C, making it very important to use the right one0
The target file depends on your chipset type and chipset revision.
for example5 on the "alaxy % lus ,which has a ?ualComm A%A Chipset, ,msmPx3S- the target
file would be5
kernel9source#arch#arm#mach7msm#acpuclock7PT3S.c
$nce you got your acpuclock file, it&s time to take a look at how overclocking actually works.
*asically overclocking is nothing more then extending an array of fre4uencies and matching
voltages.
*+a#ple sho&,n belo& is only an e+a#ple- please find e+isting kernel &ith OC for your
phone on Github- and study the !hanges that are #ade to OC the kernel$
%tock %ettings5
8
:
3
<
E
O
static struct pll pll:9tblUV K W
W <:, S, 8, S X, #Y QSO ABz Y#
W E3, 8, 3, S X, #Y 8S:< ABz Y#
W 8:E, S, 8, 8 X, #Y 8:SS ABz Y#
W P3, S, 8, S X, #Y 8<S8 ABz Y#
XM
Along with5

8
:
3
<
E
O
P
Q
R
8S
88
8:
83
8<
8E
8O
8P
8Q
8R
static struct clkctl9acpu9speed acpu9fre49tblUV K W
W S, :<EPO, /Z$, S, S, 3SP:SSSS, RSS, @FF9>A1,RSS- X,
W S, O8<<S, //93, E, 88, O8<<SSSS, RSS, @FF9>A1,RSS- X,
W 8, 8::QQS, //93, E, E, O8<<SSSS, RSS, @FF9>A1,RSS- X,
W S, 8Q<3:S, //93, E, <, O8<<SSSS, RSS, @FF9>A1,RSS- X,
W S, AAZ9AZI9HB[, AZI, 8, S, O8<<SSSS, RSS, @FF9>A1,RSS- X,
W 8, :<EPOS, //93, E, :, O8<<SSSS, RSS, @FF9>A1,RSS- X,
W 8, 3OQO<S, //93, E, 8, 8::QSSSSS, RSS, @FF9>A1,RSS- X,
#Y AZI has A%AC8 implications. %ee above. Y#
W 8, POQSSS, //98, :, S, 8E3OSSSSS, 8SES, @FF9>A1,8SES- X,
#Y
Y AZI has A%AC8 implications. %ee above.
Y#
W 8, QSO<SS, //9:, 3, S, !I.T9AAZ, 88SS, @FF9>A1,88SS-, NampMpll:9tblUSVX,
W 8, 8S:<SSS, //9:, 3, S, !I.T9AAZ, 8:SS, @FF9>A1,8:SS-, NampMpll:9tblU8VX,
W 8, 8:SSSSS, //9:, 3, S, !I.T9AAZ, 8:SS, @FF9>A1,8:SS-, NampMpll:9tblU:VX,
W 8, 8<S8OSS, //9:, 3, S, !I.T9AAZ, 8:ES, @FF9>A1,8:ES-, NampMpll:9tblU3VX,
W S X
XM
$C %ettings5
8
:
3
<
E
O
P
Q
R
8S
static struct pll pll:9tblUV K W
W<:, S, 8, S X, #Y QSO ABz Y#
WE3, 8, 3, S X, #Y 8S:< ABz Y#
WEQ, 8, 3, S X, #Y 8883 ABz Y#
#Y W8:E,S, 8, 8 X, # 8:SS ABz Y#
WO3, 8, 3, S X, #Y 8:SR ABz Y#
WOQ, 8, 3, S X, #Y 83SE ABz Y#
WP3, S, 8, S X, #Y 8<S8 ABz Y#
WPQ, 8, 3, S X, #Y 8E8O ABz Y#
WQ3, 8, 3, S X, #Y 8O8: ABz Y#
88
8:
83
WQQ, 8, 3, S X, #Y 8PSQ ABz Y#
WR3, 8, 3, S X, #Y 8QS< ABz Y#
XM
along with5
8
:
3
<
E
O
P
Q
R
8S
88
8:
83
8<
8E
8O
8P
8Q
8R
:S
:8
::
:3
:<
:E
:O
static struct clkctl9acpu9speed acpu9fre49tblUV K W
W S, :<EPO, /Z$, S, S, 3SP:SSSS, QSS, @FF9>A1,QSS- X,
W S, O8<<S, //93, E, 88, O8<<SSSS, QSS, @FF9>A1,QSS- X,
W 8, 8::QQS, //93, E, E, O8<<SSSS, QSS, @FF9>A1,QSS- X,
W S, 8Q<3:S, //93, E, <, O8<<SSSS, QSS, @FF9>A1,QSS- X,
W 8, 8R:SSS, //93, E, 3, O8<<SSSS, QSS, @FF9>A1,QSS- X,
W 8, :<EPOS, //93, E, :, O8<<SSSS, QSS, @FF9>A1,QSS- X,
W 8, 3OQO<S, //93, E, 8, 8::QSSSSS, QES, @FF9>A1,QES- X,
W 8, EOQSSS, //93, E, 8, 83PQSSSSS, RSS, @FF9>A1,RSS- X,
#Y AZI has A%AC8 implications. %ee above. Y#
W 8, POQSSS, //98, :, S, 8E3OSSSSS, 8SSS, @FF9>A1,8SSS- X,
#Y
Y AZI has A%AC8 implications. %ee above.
Y#
W 8, QSO<SS, //9:, 3, S, !I.T9AAZ, 8S:E, @FF9>A1,8S:E-, NampMpll:9tblUSVX,
W 8, 8S:<SSS, //9:, 3, S, !I.T9AAZ, 88SS, @FF9>A1,88SS-, NampMpll:9tblU8VX,
W 8, 8883OSS, //9:, 3, S, !I.T9AAZ, 88:E, @FF9>A1,88:E-, NampMpll:9tblU:VX,
W 8, 8:SROSS, //9:, 3, S, !I.T9AAZ, 88ES, @FF9>A1,88ES-, NampMpll:9tblU3VX,
W 8, 83SEOSS, //9:, 3, S, !I.T9AAZ, 88PE, @FF9>A1,88PE-, NampMpll:9tblU<VX,
W 8, 8<S8OSS, //9:, 3, S, !I.T9AAZ, 8:SS, @FF9>A1,8:SS-, NampMpll:9tblUEVX,
W 8, 8E8OQSS, //9:, 3, S, !I.T9AAZ, 8:ES, @FF9>A1,8:ES-, NampMpll:9tblUOVX,
W 8, 8O8:QSS, //9:, 3, S, !I.T9AAZ, 8:PE, @FF9>A1,8:PE-, NampMpll:9tblUPVX,
W 8, 8PSQQSS, //9:, 3, S, !I.T9AAZ, 83SS, @FF9>A1,83SS-, NampMpll:9tblUQVX,
W 8, 8QS<QSS, //9:, 3, S, !I.T9AAZ, 83:E, @FF9>A1,83:E-, NampMpll:9tblURVX,
W S X
XM
Bandle the C! with care0 Heep in mention that you&re playing with the voltages of your phone.
$nly raise the voltages by :E max per try. 1hen your phone doesn&t get enough power when
re4uested it will turn off.
.o big deal luckily, but a 1A>.I." to you that you shouldn&t raise the voltage anymore ,in the
matter of fact you need to lower it by :E when your device goes off-
Getting tarted : etting up Android
.evelop#ent *nviron#ent

Installing Android SDK
In order to start developing for Android you need the %oftware Fevelopment Hit. ;ou can
download it for 1indows, /inux or for Aac $% Z.
$nce downloaded you have to install it, on 1indows 'ust start the executable file.
Installing Java JDK and Eclipse
The Gava Fevelopment Hit is needed to develop Android applications since Android is based on
Gava and ZA/. 1riting Android code is being done using an editor, the best supported ,and in
my opinion, the best one around is +clipse. +clipse is an opensource freeware editor that is
capable of supporting a wide range of programming languages.
Installing the ADT Plugin
$nce +clipse is installed we need to connect the Android %FH with +clipse, this is being done
by the AFT lugin. Installing this plugin is easily done using eclipse.
1. Start Eclipse. Navigate in the menu to Help > Install new software..
2. Press ‘ A..!" in the new winow that pops up #ou can fill in Name with an ar$itrar#
name. A goo suggestion coul $e %Anroi Plugin& an in the location #ou have to
paste '
1
https'((l)
ssl.google.com(anroi(eclipse(
*. +lic, ‘-,!. .a,e sure the chec,$o/ for 0eveloper 1ools is selecte an clic, %Ne/t&.
2. +lic, ‘Ne/t!. Accept al the license agreements" clic, ‘3inish! an restart Eclipse.
4. 1o configure the plugin ' choose 5inow > Preferences
6. Select ‘Anroi! on the left panel an $rowse for the Anroi S07 #ou ownloae in the
first step. 8-n winows ' +'9Program 3iles 8/:6;9Anroi9anroi)s,;
<. +lic, appl# an #ou!re rea# an o, =
Adding platforms and components
$n windows, start the %FHAanager.exe . /ocated in C5\rogram =iles ,xQO-\Android\android7
sdk and install all platforms and components.
;ou&re ready to start coding now 0
Getting tarted &ith Android tudio
At "oogle I#$ :S83, "oogle has launched new IF+ based on IntelliG IF+A, called Android
%tudio. I&m really interested in Android %tudio, given that I usually using +clipse in developing
Android application. I find that this IF+ is really good ,or should I say awesome0-. *ut some of
my friends said that they&re having difficulties in using Android %tudio, and prefer the 6good but
old& +clipse. ;es, +clipse is good, but "oogle is more supporting the Android %tudio. %o with
this articles, I want to share my experiences in migrating from +clipse to Android %tudio. I also
included "oogle&s official guide from d.android.com#
/et&s start with pros and cons of Android %tudio ,based on my viewpoint-5
'/O:
7 *etter !I in designing and coding
7 ro"uard and app7signing capabilities.
7 "radle7based build support ,=or you that has already get used to it-
CO0:
7 Bard to manage multiple pro'ects. ,=or example5 to delete a pro'ect you have to delete from the
explorer-
7 "radle7based build support ,=or you that&s not get used to it-
7 %till in +A ,+arly Access review-
If you have something to say about >$%7N7C$.%, I&m glad to hear from you.
/et&s get started0
Installing Android tudio
=irst of all, go to http5##developer.android.com#sdk#installing#studio.html and download the
installer.
1indo&s:
7 /aunch the downloaded +Z+ file, android7studio7bundle7]version^.exe.
7 =ollow the setup wizard to install Android %tudio.
7 Hnown issue5 $n some 1indows systems, the launcher script does not find where Gava is
installed. If you encounter this problem, you need to set an environment variable indicating the
correct location. %elect %tart menu ^ Computer ^ %ystem roperties ^ Advanced %ystem
roperties. Then open Advanced tab ^ +nvironment @ariables and add a new system variable
GA@A9B$A+ that points to your GFH folder, for example C5\rogram =iles\Gava\'dk8.P.S9:8.
2a! O 3:
7 $pen the downloaded FA" file, android7studio7bundle7]version^.dmg.
7 Frag and drop Android %tudio into the Applications folder.
7 Hnown issue5 Fepending on your security settings, when you attempt to open Android %tudio,
you might see a warning that says the package is damaged and should be moved to the trash. If
this happens, go to %ystem references ^ %ecurity N rivacy and under Allow applications
downloaded from, select Anywhere. Then open Android %tudio again.
4inu+:
7 !npack the downloaded Tar file, android7studio7bundle7]version^.tgz, into an appropriate
location for your applications.
7 To launch Android %tudio, navigate to the android7studio#bin# directory in a terminal and
execute studio.sh.
7 ;ou may want to add android7studio#bin# to your ATB environmental variable so that you can
start Android %tudio from any directory.
After you installed Android %tudio, let your 'ourney begin. *ut first, you must remember that
Android %tudio is still in +A, so there will be many bugs#glitches#errors#whatever7you7call7it
that can be annoying. *ut if you patient enough, you will find it very fun.

%o& to !reate pro5e!t6
It&s easy0 Gust use =ile 7^ .ew ro'ect_
$r, if it&s your first time using Android %tudio, you will be welcomed with options to (Create
.ew pro'ect)

*+ploring your pro5e!ts
=ile system is 4uite different with +clipse. Considering that your android apps will be "radle7
based. %o you 'ust have to modify everything inside main pro'ect folder ,%ee picture, file under
(FAap) is main pro'ect folder-. !nless you&re an expert in "radle and Intelli'.
After you get used to the !I and layout, you can start coding N designing your app.

.esigning 4ayout using Android tudio is 7etter6
;es0 ;ou can see pictures below that you have : options to design layout. =irst by typing it
directly through (Text) mode, or (Frag7and7drop) design. *oth of them enable you to preview
your design. Gust have a 8E7minutes experiments with your preview, and you will feel the power0
/et me give you some examples5
Fesign with (Text) mode
Fesign with (Frag and Frop) mode

%o& to in!lude support library6
Another great thing that announced in "oogle I#$ :S83 is Action*ar Compat. I&m waiting it for
a long time, because using (%herlock Action*ar) is a little bit complicated. And now it&s
released. Fownload it with your %FH Aanager.
Then include it in your pro'ect. Bow2 *ecause this is "radle7based, it&s 4uite simple. $pen
(build.gradle) in your main pro'ect folder.
8or Android9upport v":
7 It&s automatically included when you created new pro'ect. *ut if not, use second step.
7 Add this line5
dependencies {

compile “com.android.support:support-v4:18.0.+”
}

8or Android9upport v::
7 Add this line5
dependencies W
_
compile (com.android.support5appcompat7vP58Q.S.J)
X

%o& tot test your app6
Gust like +clipse, Android %tudio support : way of testing. *y using A@F ,Android @irtual
Fevices- or by real devices. To edit configurations, go to (>un) 7^ (+dit Configurations). I
recommend you to choose (Target Fevice) 7^ (%how chooser dialog), to give you more freedom
in testing.
8or A;.:
7 ;ou have to create at least one A@F. To create A@F, go to (Tools) 7^ (Android) 7^ (A@F
Aanager)
7 In the chooser dialog, select A@F, and choose your devices.
8or /eal .evi!e:
7 ;ou have to enable !%* Febugging in your devices0 +nable it, then go forward.
7 Connect it through !%*. In chooser dialog, you will see your device there.
Hnown issue5 %ometimes the driver is not right. ;ou should use "oogle !%* Friver for testing
app in Android. $r sometime, your device won&t be detected if it&s in sleep#locked mode.

%o& to generate a signed A')6
This is also easy0 Android %tudio is provided with App7signing capability so you don&t have to
open up your keytool or do somewhat7complicated task.
Bere&s some steps5
7 "o to (*uild) 7^ ("enerate %igned AH_)
7 Click (Create new_)
7 To make a new keystore, 'ust put a non7exist keystore in (Hey store path5) ,The folder A!%T
exist, while the file A!%T .$T exist-. And other details.
7 It will automatically completed our last dialog in keystore. Gust click (.ext)
7 And (=inish)

<I' = </IC)
If you want to change to Farcula /ook and =eel, ,in 1indows- 'ust press5 (Ctrl J `) 7^ (%witch
/ook and =eel) 7^ (Farcula).
This look and feel is very interesting, and I like it so much.
Getting tarted 1ith Git ;ersion Control
"it ,a distributed version control system- plays a key part in managing the source code used in
Android. >epo itself ,as discussed in the previous section- is itself a wrapper around a large
number of git repositories of source code. The /inux kernel is tracked and maintained within a
git repository of its own too.
=or those unfamiliar with version control, the key advantage that a @C% ,version control system-
offers over plain, untracked sources, is the ability to access and maintain different revisions of
the source code. 1ithout a @C%, a user could copy their own code into a new folder regularly,
when they made a new change. This is impractical for any large pro'ect though, as it results in a
huge increase in the storage re4uired for the source code, and with little actual benefit a it&s only
possible to look at snapshots you created of the pro'ect, and each of these is an entire copy of
your source code at that point in time.
@ersion control addresses this by tracking the actual changes made to the source code, and
storing these changes incrementally. "it permits the developer to create multiple (branches) of
their code, where they can diverge from the main source tree, and work on an experimental
feature. $nce the feature is completed, this branch can be merged into the main branch of the
pro'ect, keeping the main branch clean and free from experimental ,and often broken- code.
1ithin the Android $pen %ource ro'ect ,A$%-, "oogle uses branches within the code for each
version released. There is a branch for "ingerbread, Ice7Cream %andwich and Gellybean ,more
specifically the branches are actually for individual versions such as <.8.8, <.8.: etc-.
"it is also ,per the description earlier- a distributed system, meaning that all users with a full
copy of the source code have full access to the entire history of the repository, and all its past
changes.
1hile git can be used standalone ,ie. on one computer- to allow a developer to track changes to
their own software, git is at its most useful when in a multi7user environment, where each user is
making changes to the source code at all times. +veryone can work independently on their own
changes, and share selectively the changes they wish to publish. A central git repository is used,
to which users push their changes.
This is how Android&s sources are used. If you want to get involved in development, you will
need to learn some git and repo basics, to be able to share your changes with other developers,
and maybe even get them merged into the main code of your favourite >$A0
Want to Learn More
The full ro7 "it book is available free online, and is definitely worth a read.
This post, by ZFA +lite >ecognized Feveloper +ntropyE8:, is definitely worth a read if you are
using git to work with kernels.
This guide, by ZFA =orum Aoderator eagleeyetom, is incredibly useful for anyone starting to
work with "ithub for the first time.
This interactive tutorial is definitely worth trying out if you want to learn about git interactively.
It will show you the basics within your browser, and is perhaps the fastest way to get some real
experience of git.
Getting tarted: 7uilding a )ernel fro#
sour!e
! "# Droid$one
What is a Kernel
The operating system of a device is the part of the device responsible for basic use and
administration. This includes the kernel and device drivers, boot loader, command shell or other
user interface, and basic file and system utilities. 1hereas the user interface is the outermost
portition of the operating system, kernel is the innermost. It is the core internals, the software
that provides basic services for all other parts of the system, manages hardware and distributes
system resources.
Typical components of a kernel are interrupt handlers to service interrupt re4uests, a scheduler to
share processor time among multiple processes, a memory management system to manage
process address spaces, and system services like networking and inter7process communication.
$n modern systems with protected memory management units, the kernel typically resides in an
elevated system state as compared to normal user applications. This includes a protected memory
space and full access to hardware. This system state and memory space is collectively referred to
as kernel-space. Conversely, user applications reside in user-space.
Applications running on the system communicate with the kernel via system calls. An
application typically calls functions in a library7+g The C libraryathat in turn rely on the system
call interface to instruct the kernel to carry out tasks on the application&s behalf.
$ur central theme is of course the Android device ,a phone, or tablet or any other device-, and
here, Android is the $perating %ystem. An Android Hernel is essentially a modified /inux
Hernel with specific modifications to support the device architecture. I won&t bore you any
further with the theoretical aspects of a kernel, and if you&re interested in knowing more about a
kernel, read the book, Linux Kernel development, authored by >obert /ove.
1ithout much further ado, let me 'ump into the topic proper, which is about how to compile an
Android Hernel. =or this, you&re expected to be familiar with the /inux command line, and know
some basic file copying and moving commands. Though a working knowledge of Git would be
beneficial, in this tutorial, I will be feeding you with the essential commands on a platter.
I will describe compilation of the BTC Fesire Hernel which works with "ingerbread %ense
>oms. Bowever the process applies with minor modifications to any Android Fevice and kernel.
The specifics may be variable in how the kernel gets packaged, or flashed.
What #ou need%
1. A >inu/ installation 8a P+ on which a linu/ istro is installe; or >inu/ $o/ 8.a# $e a live
c or vmware li,e $o/;. An# linu/ istro will o" $ut I assume an ?$untu installation to
simplif# the e/planation.
2. A toolchain)Either the Anroi N07" or #our own toolchain
*. Anroi ,ernel source coe for #our evice. 1his tutorial esci$es instructions for $oth
the Htc 0esire an Samsung @ala/# Note N<1AA. 5ith minor ifferences" the metho is
practicall# the same for an# Anroi evice.
2. 3amiliarit# with the linu/ shell an $asic linu/ commans.
+ach step will be explained as we proceed, so if terms like (toolchain) bother you, don&t worry.
It will be explained in detail later. +ven if you&re a linux newbie, don&t worry. Almost all
commands you need to master this tutorial will be dictated to you. Gust make sure you either
copy and paste the commands exactly as described here, preserving case ,meaning you shouldnt
type out (Cp) when the command is given as (cp). /inux shells are case sensitive.
Introduction to the command line for newbies:
As you proceed through this tutorial, you will see various commands in boxes, which may be
typed out on your command shell, preserving case and spaces as they appear. As an example, the
following is given5
1
ls )l
B(anroi
In this case, the code in the box is a command which should be typed out on the shell ,or
console-.
Common mistakes include typing the following5
,i- /% 7/ `#android
wont work as /% and ls are different
,ii- ls 7l `\android
$n /inux, (\) the backslash has no role on the command line ,An exception is its use in regular
expressions and strings, as a means of escaping characters. This won&t be described in this
tutorial though, as it&s rather out of scope of our discussion-. ;ou need to use (#) or the forward
slash.
,iii- ls 7l `\A.F>$IF
won&t again work, as A.F>$IF and android are two different files ,or directories-.
$k, now that you have a feel for what it&s like, using the linux console, let&s begin the tutorial
proper.
&' (etting the source code
At this point, you need to download the source code for your kernel. There are generally, two
ways to get kernel source code5
,a- =rom a compressed archive uploaded by the manufacturer of the device.
,b- =rom a git repository of another developer.
The tutorial will use the first method.
The BTC Fesire source is available from two kinds of resources7you can either get it from
htcdevs.com ,official BTC Fev site-, or from source code uploaded from someone else. =or the
purpose of this tutorial, I&ll assume we&re working on the official BTC "* source code. %o
download bravo9:.O.3E9gb7mr.tar.gz from htcdevs.com.
In case, you&re working on a %amsung kernel, you can get your source code here.
In many cases, you may find it much easier to reuse another developer&s source code. =or this,
visit their ZFA kernel thread, and search for instructions regarding where they&ve shared their
source code. As an example of this method, let&s look at developer g.lewarne6s source code. Bis
kernel is titled .ote:Core Hernel for "alaxy .ote II .P8SS # .P8SE ,/T+-, and can be found
here. If you read the thread, you will see that he has shared his source code at github here. I will
describe how to use this, later.
)' Setting up the host P* and preparing source code
)'& Install some essential linu+ pac,ages from the Linu+ terminal%
1
suo apt)get install li$ncurses4)
ev
)') E+tract the source code
The file you downloaded is a tar archive ,like a zip file-, so you need to extract it to a convenient
location. /et&s hit the linux shell7open a terminal window in linux ,Accessories7^Terminal-
/et&s start off in our home directory5
1 c B(
.ow, create the directories for our kernel compilation box5
1
m,ir )p
B(anroi(,ernel
.ow you need to copy the tar.gz file from wherever you downloaded it to, to this dir. ;ou can
use a file explorer "!I like .autilus or Folphin.
+xtract the archive5
1
2
tar )/vf B(anroi(,ernel($ravoC2.6.*4Cg$)
mr.tar.gD
c B(anroi(,ernel($ravoC2.6.*4Cg$)mr
.ow we can view the extracted files within the directory5 ~/android/kernel/bravo_2.6.!_gb-mr/
)'- Set up the toolchain
A toolchain is a set of programs which allow you to compile source code ,any source code, not
'ust kernels-. The toolchain is specific for the processor and hardware, so we need a toolchain
specific for Android and especially the Fesire. If you&re a semiadvanced7pro user, you may
consider compiling your own toolchain ,%ee the"anymedes& guide for doing so-. If compilation
of kernels is all that you re4uire, fortunately for you, there is an easy way7the Android .FH a vP
,latest as of now- is available here
"et the .FH for /inux a android7ndk7rP7linux7xQO.tar.bz:
1
m,ir )p
B(anroi(n,
.ow copy the .FH file to5 ~/android/ndk
1henever I say copy, you have to manually copy the file with any file manager. .autilus comes
with !buntu, and Folphin with Hubuntu. ;ou may also use the shell of course with
1
cp EsourcefileF
EestinationF
+xtract it5
1
tar )Gv/f anroi)n,)r<)linu/)
/:6.tar.$D2
.ow add the path for your toolchain to the env variable5
1
geit
B(.$ashrc
At the end of the file, add this line5
Code5
1
PA1HHIPA1H'B(anroi(n,(anroi)n,)r<)linu/)/:6(toolchains(arm)linu/)anroiea$i)
2.2.*(pre$uilt(linu/)/:6($in
-' Setting up ,ernel parameters
Hernels are compiled with a program called gnu make, and use a set of configuration options
specified within a file called Aakefile.
A vital point to note is that kernels are compiled with a program called gcc ,basically the gnu C
compiler-, and our .FH itself has its own optimized version of gcc. 1hile compiling, we&re
actually cross compiling it ,meaning compiling a binary package on a system which is different
from the actual system which is meant to run it7 you&re compiling it on your C while it&s
actually meant to run on your Fesire-
This means that when you compile it, you have to make sure that you compile it with the .FH&s
version of gcc instead of the system version. $therwise you end up with a kernel meant to run on
your pc, duh0 %pecifying which gcc to use is by the C>$%%9C$AI/+ variable. ;ou can set it
up with this command5
Code5
1 +J-SSC+-.PI>EHarm)linu/)
anroiea$i)
.ote the hyphen ,7- at the end, and do not forget to include it0 At compilation time, system will
actually use this variable to find all the programs it needs. +g5 The path for gcc will become arm7
linux7androideabi7gcc
1e can compile kernels with many different options, like with ext< support, or withoutM ext<
support as part of the kernel zImage ,in which case it makes the kernel larger-, or as a loadable
module ,of the form somename.ko, which is loaded at init.d#init.rc with the command insmod
modulename.ko-
1e specify the exact options we re4uire with the help of a useful configuration program called
menuconfig ,which as the name suggests, is a menu for configuration of make options-.
An important thing to note is that as far as kernel compilation is concerned, there are a vast
amount of options to setup, and unless you&re thorough with kernel compilation, you wont be
able to set up the options correctly and get your kernel to boot. =ortunately for us, the kernel
source already comes with a default set of parameters which can be easily set up.
.ote that all make commands must be executed within the directory bravo9:.O.3E9gb7mr. /et&s
go there now5
1
2
c B(anroi(,ernel($ravoC2.6.*4Cg$)mr
ma,e AJ+HHarm +J-SSC+-.PI>EHarm)linu/)anroiea$i)
$ravoCefconfig
This produces a .config file ,used by the menuconfig- containing essential parameters to produce
a booting kernel for the Fesire.
In case you&re not working on the BTC Fesire, but a different device, you need to run the
defconfig of your device. =or this, you need to know the name of the script which runs defconfig.
;ou can get the name by inspecting the names of the files in Ukernel source
folderV#arch#arm#configs. In fact each file located there is a renamed .config file. +g5 =or the
.ote :, you will find the file tS9S<9defconfig. %o to run a defconfig for .ote:, you would type5
1
ma,e AJ+HHarm +J-SSC+-.PI>EHarm)linu/)anroiea$i)
tACA2Cefconfig
.ote5 There is a simpler way to get the basic .config file, and this is to get it from a running
kernel built by someone else. ;ou can extract the .config from a running kernel with these
commands5
1
2
*
c B(anroi(,ernel($ravoC2.6.*4Cg$)
mr
a$ pull (proc(config.gD
Dcat config.gD KgtL .config
.ote that not every kernel include a config.gz. ;our kernel developer needs to have included this
option while compiling his kernel
.ow we can open menuconfig and add anything we need in addition5
1
ma,e AJ+HHarm +J-SSC+-.PI>EHarm)linu/)anroiea$i)
menuconfig
Advanced: You can view the huge amount of options available in
menuconfig, pick and choose the ones you want. As a general word
of caution, in your initial compilation, you shouldnt try to
modify anything. Just pick the default .config, and compile
once. If it succeeds, try booting your system with the kernel,
and any default modules like the Wifi module. nce you!ve
confirmed that it boots without any bootloops or hangups, you
should enable Wifi and confirm that it works. "his two stage
check is a confirmation that you can compile a default #or
stock$ kernel, and also successfully compile modules. nce you
can, save your .config to a safe location. If you!re using a git
version control system #which you should$, at this stage, you
could also commit your changes, and label them as %Initial
commit&. 'ow, you can go ahead and add changes to the kernel.
;ou can add ext< support for example.
$nce you&re done choosing options, you can exit menuconfig.
Tip5 $nce you&ve done menuconfig once, and find that you&re always using A>CBKarm and the
same C>$%%9C$AI/+ prefix regularly, you can hardcode these options into the main
Aakefile so you can 'ust type 6make& each time for compiling the kernel. Another option is to
(export) the prefices before compiling.
Advanced: In fact, once you!ve made your first successful
compile, edit your main (akefile #the (akefile that resides in
the root folder of the kernel source tree$, and change the
)*++,)(-I./ variable to point to your toolchain. "he (akefile
also has a variable for A*)0, which by default is arm. nce you
set both of these, you can compile by simply e1ecuting:
1
Mspan st#leHNfont)famil#' Ocourier newO"
courierN>ma,eM(span>

.' *ompiling it
This is simple. The basic command is5
1
ma,e )G2 AJ+HHarm +J-SSC+-.PI>EHarm)linu/)
anroiea$i)
The 7'< specifies the number of 'obs to execute per operation. This is typically e4ual to the
processor cores in your system. If you&re on a @% with a fair usage policy, you had better keep
it a notch below the maximum allowable C! load.
Furing compilation, you will see all sorts of messages, which may include warnings too. In most
cases, its safe to ignore warnings. If there are errors, the compilation will stop, and you will have
to fix the issues.
If you&ve modified your Aakefile to include A>CB and C>$%%9C$AI/+ variables as
described in the previous section, you can compile simply by running5
1
ma,
e

/' Distri0uting #our ,ernel to users
At the end of compilation, it generates files named zImage, and various .ko files.
;ou have to copy them from their default location to a zip file. The best way is to use my variant
of koush&s Anykernel, and copy the files to it. Then, you can zip the whole folder and lo and
behold7you have your flashable kernel zip which you can distribute to others.
;ou can also remove the zImage and the modules from #system#lib#modules of any kernel zip
available with you, and copy over your files to it, at the correct location.
%o, let&s say that you have extracted an existing kernel zip to the location ~/"las#able, then the
file structure should be like this5
I&ll include my flashable zip directory along with this post. Fownload file
kernel9flashable.tar.bz:.zip to `#
,.ote5 I&ll include this file later-
1
2
c B(
tar )Gv/f
,ernelCflasha$le.tar.$D2.Dip
This will create the directory structure outlined above.
.ow after every compilation of the kernel, execute these commands from where you executed
make5
1
2
*
2
4
6
<
cp arch(arm($oot(DImage B(,ernelCflasha$le

fin . )name OP,oO )e/ec cp OQRO
B(,ernelCflasha$le(s#stem(li$(moules( 9L

c B(,ernelCflasha$le

Dip )r m#,ernel .(
This will create mykernel.zip at `#kernel9flashable. ;ou can distribute this to your users to flash.
Aake sure you edit updater7script before though.
1' Some ,ernel compilation errors%
<reat &arnings as errors7%olved by removing the string (71error) from all Aakefiles of the
file which failed to compile. %ome people had said that the real error ,Array out of bounds
warning- was because of gcc optimizations. *ut putting 7$: to 7$S didnt do a thing.
0o of 5obs 7 ought not to exceed ES.
(warning5 variable set but not used U71unused7but7set7variableV(7/ook at H*!I/F9C=/A"% in
the main Aakefile. Add 71no7errorKunused7but7set7variable to the existing set of flags.
Note the following from gcc manual'
91errorAake all warnings into hard errors. %ource code which triggers warnings will be
re'ected.
9& Inhibit all warning messages. If you&re familiar with C code and like to fix stuff, rather than
ignoring potential bugs, use this only as a last resort7 A 6brahmastram& ,most powerful weapon in
your time of gravest need- as the epics would say.
91errorAake all warnings into errors.
91error>Aake the specified warning into an error. The specifier for a warning is appended, for
example 71errorKswitch turns the warnings controlled by 71switch into errors. This switch
takes a negative form, to be used to negate 71error for specific warnings, for example 71no7
errorKswitch makes 71switch warnings not be errors, even when 71error is in effect. ;ou can
use the 7fdiagnostics7show7option option to have each controllable warning amended with the
option which controls it, to determine what to use with this option.
%o what I did to suppress errors was to add5
1
2
7S?I>0C+3>A@S TH )w
7S?I>0C+3>A@S TH )5no)errorHunuse)$ut)set)
varia$le
Though the 71unused7but7set7variable is not a real issue in itself, it generates so much (noise)
that you may miss actual make errors.
This is the error what I was talking about5
1
2
*
rivers(net(wireless($cm2*2UC2A2(wlCiw.c' In function OwlCiwCsetCpm,saO'
rivers(net(wireless($cm2*2UC2A2(wlCiw.c'4A<4'4' error' arra# su$script is a$ove arra# $ouns
E)5errorHarra#)$ounsF
rivers(net(wireless($cm2*2UC2A2(wlCiw.c'4A<:'4' error' arra# su$script is a$ove arra# $ouns
E)5errorHarra#)$ounsF
%olution5
+dit drivers#net#wireless#bcm<3:R9:S<#Aakefile
/ocate 71error within FBFC=/A"%, and delete it.
1
2
*
0H0+3>A@S H )0>IN?V )0S+.0JIWEJ )0S+.0-N@>EH-S1 )00H01HJEA0
)0S+.5PA2 9
)0?NJE>EASE0+HIP )0linu/ )00H0CS0A>I@NH62 )0.AVCH0JCJEA0H62 9
)00H0C3IJS1JEA0H62 )00H0C@P> )00H0CS+HE0 )0S0+ )01-E
2
4
6
<
)00H0CS+.EWEN1S 9
)0SH-5CEWEN1S )0S+.S0I- )00H0C@P> )0S+.>VS0..+
)0S+.P>A13-J.CS?S 9
)5all )5strict)protot#pes )5error )0--SCIN1JC-N>X )0+?S1-.EJCH52 9
)00H0C?SECS1A1I+CS?3 )0..+CS0I-CAS-J1 )05>ANCP3N
)05>ANCPJ-1E+1 9
)0S+.5APIC5PI 9
This will prevent gcc from treating mere warnings as errors.
2' Modif#ing Kernel source code on the fl# 3 Appl#ing Kernel Patches
$k, you have compiled a simple stock kernel. .ow what2 1ould you like to add fixes#mods
developed by other kernel devs2 This post explains patches and how exactly to do this.
atches to the kernel are applied via patch files. atch files are simple text files generated by the
linux diff program which takes two text files, compares them and writes the differences ,hence
called diff- to another text file which by convention has the extension .pat!h
2'& E+ample patch
=ollowing is a patch containing my (+xtended battery) fix with %ibere&s battfix. I&ll explain
patching with this. /et&s understand the patch file. $pen it up in any text editor.
1
2
*
2
4
6
<
iff )rupN )V (home(roiDone(anroi(,ernel(e/clue.opts $ravoC2.6.*4Cg$)
mr(rivers(power(s2<:2C$atter#.c $ravoC2.6.*4Cg$)
mr.main((rivers(power(s2<:2C$atter#.c
))) $ravoC2.6.*4Cg$)mr(rivers(power(s2<:2C$atter#.c 2A11)A:)24 1*'16'4*.AAAAAAAAA
TA4*A
TTT $ravoC2.6.*4Cg$)mr.main((rivers(power(s2<:2C$atter#.c 2A11)11)A6
16'2*'21.422*1<*22 TA4*A
YY )11:": T11:"11 YY PS. A or other $atter# I0 use the same p
(P Satter# I0 H 1' H1)E(3ormosa 12AAmAh P(
:
U
1A
11
12
1*
Zefine SA11CI0CA 1
Zefine SA11C3?>>C.AHCA 12AA
)
Zefine SA11C3?>>C.AHC0E3A?>1 14AA
TZefine SA11C3?>>C.AHC+A.EJ-NSIN- 22AA
TZefine SA11CI0C+A.EJ-NSIN-
TZefine SA11C1XPE A
T
.ote the first line5
1
iff )rupN )V (home(roiDone(anroi(,ernel(e/clue.opts $ravoC2.6.*4Cg$)
mr(rivers(power(s2<:2C$atter#.c $ravoC2.6.*4Cg$)mr.main((rivers(power(s2<:2C$atter#.c
diff 9rup0 basically describes the command that was used to generate this patch. The 7u means
that the patch file is something called a universal pat!h
bravo9:.O.3E9gb7mr#drivers#power#ds:PQ<9battery.c was the original file, and bravo9:.O.3E9gb7
mr.main##drivers#power#ds:PQ<9battery.c was the target file or file which contains the mod.
2') 4o5 to appl# patch files
The command depends on where your current directory is. If you&re in
`#android#kernel#bravo9:.O.3E9gb7mr# and your current directory contains the directory
6drivers&, you can apply this patch with this command5
1
patch
)p1KltLe/teneC$attfi/.patch
If you&re within drivers, then you have to modify the command like this5
1
patch
)p2KltLe/teneC$attfi/.patch
Bope you get the gist. *asically, as you move into the source tree, you have to increment the
patch level by the number of directories you&ve moved down into. @ery simple, isnt it2
6' Sharing and *olla0orating 3 7sing (ithu0 and *ommits
Hernel compilation is a group effort ,at least it ought to be-. 1hen different devs work on
different parts of the code and create their own mods, development progresses. =or this purpose,
it is important that you share your code with other devs. The best way to do this to upload your
sources to github.
=irst, create a github account.
.ext you can view other devs& github sources and examine their commits. Commits are basically
patches applies to the previous source uploaded. "ithub commits use the universal patch format
and can be viewed directly, downloaded as patch files, and applied to your code. ;ou can also
choose to download the whole source tree uploaded by another dev and examine it.
Getting tarted: 7uilding Android 8ro#
our!e
Difficulty Level: Intermediate-Advanced
Introduction
=rom browsing around ZFA7Fevelopers you have probably seen a large number of >$As
which are built from source. This includes many of the popular multi7device custom >$A
pro'ects such as CyanogenAod and A$H.
This chapter aims to teach you the basics of setting up the re4uired environment to get started on
building Android from source.
This guide is adapted from the Android guidelines on building. Also, please bear in mind that
this guide presumes you have access to a computer or virtual machine running a O<7bit Febian7
based /inux operating system such as !buntu ,the procedures of setting this up are well outwith
the scope of this book-. ;ou do not need to use Febian, but these instructions have been
designed for it, so procedures may vary.
Initial Setup
*efore beginning this process, please ensure you have sufficient hard drive space. The Android
source code alone consumes around R "* of hard drive space, and to carry out a single device
build at least 3S "* will be re4uired. If building for more devices, this can easily exceed 8SS
"*.
In order to build Android from source successfully, you will re4uire ython :.P, ".! Aake 3.Q8
or 3.Q:, "it 8.P or later, and the $racle ,%un- Gava Fevelopment Hit version O.
The following packages should also be installed via (sudo apt7get install), followed by the list of
packages. The web copy of this book can be used, so that you can copy7paste this list.
1
2
*
2
4
suo apt)get install git)core gnupg fle/ $ison gperf $uil)
essential 9
Dip curl li$c6)ev li$ncurses4)ev'i*:6 /11proto)core)ev 9
li$/11)ev'i*:6 li$realine6)ev'i*:6 li$gl1)mesa)gl/'i*:6 9
li$gl1)mesa)ev gTT)multili$ mingw*2 openG,)6)G, tofroos
9
p#thon)mar,own li$/ml2)utils /sltproc Dli$1g)ev'i*:6
.ext, in order to address an incorrect library with !buntu 88.8S and above, run the following
command5
1 suo ln )s (usr(li$(i*:6)linu/)gnu(mesa(li$@>.so.1 (usr(li$(i*:6)linu/)
gnu(li$@>.so
The next step is optional, but can offer significant performance gains while compiling, by using
ccache ,a compiler cache tool-, which caches the output of the compiler, to save time when
compiling a file which has not been changed since the last compile.
To enable ccache, edit your `#.bashrc or `#.profile file ,or e4uivalent-, and add the following line
1
e/port
?SEC++A+HEH1
After you log out and back in again, this change will take effect.
*y default, the Android build process creates a subfolder named (out) within the root of your
source tree. 1hile for most users this is best, in some situations it can be advantageous to move
the output directory to another file system. If, for example, you have a striped >AIF array, it is
beneficial to store the output directory on this array. All of the files within the out directory can
be re7generated in the event of filesystem problems ,if the sources were held on another
filesystem-.
To change the output directory to another filesystem, use the command
1
e/port -?1C0IJC+-..-NCSASEHMpath)to)#our)out)
irector#>
1ithin the defined output directory, a new folder will be created, named after your current
source tree directory. =or instance, if you have source trees as #source#master8 and
#source#master: and $!T9FI>9C$AA$.9*A%+ is set to #output, the output directories will
be#output#master8 and #output#master:.
It is therefore important to ensure you do not have multiple sources stored in directories with the
same name, as they would end up sharing an output directory, with unpredictable results.
This is only supported when building Gelly *ean ,<.8- and newer.
Preparing 8epo
At this point, the basic setup of the build environment has now been configured, and it&s time to
obtain the Android sources.
=irstly, the repo tool must be installed. This is a tool that allows the Android source code to be
downloaded automatically from the hundreds of individual repositories in use by Android.
+nsure you have a (bin) folder within your home directory, and that it is within your path by
running the commands
1
2
m,ir B($in
e/port PA1HHB($in'
IPA1H
The latter command can be added to your `#.bashrc script, to ensure the bin folder is always
added to your path variable. The repo script can now be downloaded ,run this command from
within the `#bin directory-, and the correct permissions set.
1
2
curl https'((l)ssl.google.com(l(googlesource(git)repo(repo >
repo
chmo aT/ B($in(repo
Initialising a 8epo and S#ncing
Initialisation of the repo creates the bare skeleton directory structure re4uired for storing the
Android source code. Create a directory within your home directory where you wish to copy the
source code to ,as mentioned previously, this drive re4uires a large amount of free space-.
1ithin this directory, run the command
1
repo init )u M?J>)to)repositor#)here> )$ M$ranch)
here>
Bere, the !>/ of the repository you wish to clone should be entered, and the branch desired.
This information differs for the >$A source you wish to obtain. *y referring to the pro'ect&s git
repositories, and looking for a >+AFA+, the suitable command should be given. The branch
defines the Android version you wish to clone, such as (ics) or ('ellybean) ,using the
CyanogenAod naming scheme-
After the repo initialisation completes, a new hidden directory called (.repo) should have been
created within this folder, containing the manifest files that detail what should be synced from
the remote source repository.
It is now time to download the actual sources a this will take a significant amount of time, so it is
best to leave the computer to complete this and return later. >un the command (repo sync), and
it will begin syncing. In the event of the process being interrupted, re7run repo sync, and the
process will be resumed, although a small amount of data may be re7downloaded.
In future, when it is desired to update the source code to obtain the latest updates to the >$A
you are building, the command (repo sync) can be used on its own to update the source tree. *e
aware that doing this will remove and eliminate any changes you have made to your local
sources.
*arr#ing out an Actual "uild
To carry out an actual build for a device, it&s necessary to have some device7specific components
and source code. ure Android ,"oogle A$%- only supports a small subset of available devices
,mainly .exus devices, with a few exceptions that have been added-. In order to make a build for
your device, you will need a suitably device configuration. $ften these are included within the
main source download, or are obtained through a method documented by the developers of the
>$A.
TI5 The device tree from an A$% >$A is not necessarily compatible with a CyanogenAod
,or other custom >$A-, and vice versa. In fact, without changes, it will not allow the build to
complete. =or this reason, the correct type of device tree is re4uired.
$nce you have obtained the suitable device sources ,you can add a git repository to
the .repo#local9manifest.xml file if desired, in order to add it to the repositories updated via a
(repo sync)-, it is time to prepare the build environment.
=irst, the envsetup.sh script must be executed, which sets up and imports all available device
configs. It also adds a few (macro) commands to your environment, such as (chroot), which will
change directory to the root of the Android source tree.This step must be carried out every time
you start a new shell session, or reboot. >un the command
1
source
$uil(envsetup.sh
.ow, the target device should be selected and configured using the (lunch) command. Type
(lunch), and a list of the available devices will be offered. +nter the number of your device to
select it for building. *e aware that the device names are often (codenames) rather than final
shipping names, but you can research this in your device forum.
$nce you know your device&s name, you can directly invoke the command (lunch ]codename^7
userdebug). =or example, the command
1
lunch cmCiU1AA)
usere$ug
would be invoked to select the "alaxy %: ,iR8SS- in a CyanogenAod build ,hence the (cm9)
prefix-. !serdebug refers to the type of build being carried out a a userdebug build allows root
access, and has some basic debug features available for use in diagnosing issues.
At this point, Android is finally ready to be built0 To carry out a build, the (make) command is
used. There are some arguments that can be used to speed up this process though on multi7core
systems. *y using the (7' Z) option, where Z is twice the number of C! cores in a system,
Android will be built with parallel threads running to make use of the multiple C! cores.
In some >$As, it is possible to use the command (mka) to automatically carry this out. *efore
actually building though, it is important to decide what type of build is re4uired. >unning
(make) will produce a basic, image based build, which is not easily flashed to a device. Chances
are, you want to build a flash7able update.zip style file which can easily be installed to a device.
To do this, use the command (make otapackage) ,for CyanogenAod >$As, (make bacon) is
used instead-.
To carry out a new build by clearing out the prepared#packaged output files, run the command
1
ma,e
installclean
This will remove the compiled files from previous builds. At this point, make can be invoked to
run a build as before.
To carry out a clean build from scratch ,or clear out the large (out) directory if you no longer
need the files produced-, run the command
1
ma,e
clean
This will remove the compiled files from previous builds. At this point, make can be invoked to
run a build from scratch as before.
$nce the compilation process is completed, the update.zip can be found in the path
out#target#product#]device name^. There may be multiple zips here, so ensure you are selecting
the correct one, as named by the build process in the final lines when the process ended. This zip
file can be flashed to the device using recovery, as detailed earlier in this book.
%o& to 7uild an Android /O2
1hat follows is more a simple explanation on how to build an Android >$A. I&m going to
discuss several parts that can&t be absent if you want a fully functional Android phone, from the
software point of view that is.
Bere&s a brief summary 5
• 7ernel
• >i$raries 8and modules;
• Sootloaer
• Jecover#
• Jaio
• Apps" framewor," core" anroi)runtime" etc[
Kernel
A kernel is a critical component of every $perating %ystem. It can be seen as a sort of bridge
between the applications and the actual hardware of a device. !sually the data processing part is
done at hardware level, furthermore the kernel is the most low7level abstraction layer for the
resources.
There exist several types of kernels, but I am only discussing the one that is important for the
Android >$A. The kernel for the Android >$A is a hybrid kernel, it is based on the /inux
kernel. Fevices can differ in >AA memory, >$A memory, hardware parts and so on. %o it&s
really important you have a kernel for your type of device, an BTC 1ildfire kernel won&t work
on a .exus $ne for example.
It is possible to overclock a kernel. ;ou may wonder, what the hell is overclocking2 +very C!
is designed to work at a certain clock speed. =or the BTC 1ildfire the ?ualcomm A>AvO
processor operates at E:Q mBz b this is a limit that is coded in to the kernel because they can&t
guarantee good cooling for the C! if you go over this limit. Ay 1ildfire runs at OE:.Q mBz
and it can go to POQ ABz until it freezes. 1hen you overclock the kernel, the C! will be
instructed to do more calculations per secondM so, it will increase performance.
1hen you overclock the C! of your desktop machine, it will need extra cooling, but
fortunately that&s not necessary for a smartphone. Bowever, keep in mind that this will
degenerate your C! much faster than if it was at stock. To overclock an Android phone you
must root it and install %etC! or another overclocking app from the lay %tore. Then you will
have to flash a kernel that supports overclocking. I prefer the $C Hernel of BCF>.Gacob, at
ZFA7forums ,see links rig#t-. If you have done these 3 things you&re ready to $C0
Li0raries
Imagine you want to program an application for your phone that uses the camera. It can take a
picture and turn the flash /+F on. These are things not only your own application will use, but
there can be tons of applications that have a button that can take a photo. %o, imagine those apps
always having to write the machine code to get the camera to turn onM it would be a lot of code
duplication and would make an application slow. Instead, for functions like the camera or
loudspeakers, they developed libraries. These are chunk of codes that can be executed by calling
them trough a call7method $in %ava & import somelibrarie.someclass'-. These are already pre7
written and ready to use. It saves a lot of coding work and keeps the source code small. /ibraries
in the 1indows $% for example are called .dll files ,Fynamic /inked /ibraries-, whereas on
your Android >$A or /inux $% these are the .so files ,%hared $b'ect-. 1hen coding in Gava
you import .'ar libraries before the class signature. $n your Android phone you have particular
libraries that can&t be absent, or else your >$A won&t even boot.
"ootloader
A bootloader in general is the first bytes of code that a machine executes that will tell the
bootse4uence and will load the operating system into the >AA. $n an Android phone this is the
so called B*oot. =rom here you can go to the recovery, system or data partitionn. *y pressing
the power button on your phone, B*oot will load the $% into >AA. *y pressing the power and
volume down buttons, you&ll bring up the B*oot menu.
The bootloader is used as an exploit for rooting an Android phone. $nce rooted you can flash
custom >$As, like Imr$%, or 'ust edit system files ,for a how7to, check tutorials under
Android.-
8ecover#
1hen you use a one7click7root application like !nrevoked3, it will install a modded recovery.
1ith this modded recovery it is possible to flash a new kernel, radio image ,see belo(-, custom
>$A, install applications ,not t#e best (ay t#oug#-, .android backup, etc. The modded
recovery that is flashed by !nrevoked3 is called ClockworkAod.
>ecovery is a method for you to not only save yourself when you screw up ,which you will0 -,
but to update the >$A or kernel that&s on your phone, partition your %F card to use with a:sd,
and many other $%7related things. There&s a lot of different recoveries for different phones, so
you&ll have to do some research of your own into what the most respected one is for your phone.
The recovery is essential, because you want to always have a fallback in case something bad
happens to your phone&s software.
8adio
The lowest part of software layer is the radio5 this is the very first thing that runs, 'ust before the
bootloader. This handles the "% antenna, "%A antenna and fires up the C!M everything that
B*oot needs to load the $%. This can also be upgraded by flashing a new radio image through
your recovery. Bowever, this is not recommended5 flashing a new >$A can&t brick your phone
,make it unusable-, but if anything goes wrong when you flash a >$A with a new radio image,
this !an brick your phone. %o unless you experience bad reception or battery drainage, don&t
touch the radio0
%o& to .o&nload/Co#pile pe!ifi! 'arts of a
/O2
This is a tutorial about how to download and compile specific parts in A$% based roms ,such
as CyanogenAod, A$H, %lim>om etc-
It&s mainly dedicated for the people who want to get more familiar with the A$% build
environment, and would like to manipulate it&s behavior to complete specific tasks.
Introdu!tion:
Fownloading >$A sources is done with the tool (repo), this is the most awesome downloader
in existence. .ot only it looks very cool, it also reaches top speed at all times. *ut it&s only for
linux ,which is good, since when you are busy with aosp roms, you should be on linux0-
1hy is it awesome2 %ince you decide yourself how many 'obs ,aka connections- you make with
the server. This means you always will get top speed, there is probably no faster download
method available on the Internet ,except for speedtests, but they don&t count-. .ext to the
downloading of specific parts it&s of course also handy to know how to actually compile them.

Chapters:
1. .o&nload
2. Co#pile
3. Auto#ate ,optional-

Chapter 1. .o&nload:
The easiest way of fetching for example a batch of A$% apps is like this5
8. Choose the desired tag you want to use, in the example I will use android7<.:.:9r8
:. .ow make a dir somewhere5
8
:
mkdir `#aosp7apps
cd `#aosp7apps
3. Fownload repo when not installed yet5
8
:
curl https5##dl7ssl.google.com#dl#googlesource#git7repo#repo NgtM `#bin#repo
chmod aJx `#bin#repo
<. +nter the line that will download the initial manifest.
"or )*+,&
8 repo init 7u https5##android.googlesource.com#platform#manifest 7b android7<.:.:9r8
+nter your name and email address and wait until it completes
"or -.&
8 repo init 7u https5##github.com#Cyanogenmod#android 7b cm78S.8
E. "o in the hidden (.repo) dir and change the manifest
8
:
cd .repo
gedit manifest.xml
/" you don0t #ave decent text editor suc# as 1gedit23 install it4 1sudo apt-get install gedit2

=or example when you only want to download the apps, 'ust remove all lines that are not app
related. simple as that
8
:
3
<
E
O
P
Q
R
8S
88
8:
83
8<
8E
8O
8P
8Q
8R
:S
:8
::
:3
:<
:E
:O
:P
:Q
:R
3S
38
3:
33
3<
3E
3O
3P
3Q
3R
<S
<8
NltM2xml versionK)8.Sc encodingK)!T=7Qc2NgtM
NltMmanifestNgtM

NltMremote nameK)aosp)
fetchK)..) #NgtM
NltMdefault revisionK)refs#tags#android7<.:.:9r8c
remoteK)aosp)
sync7'K)<c #NgtM

NltMpro'ect pathK)packages#apps#*asic%ms>eceiver)
nameK)platform#packages#apps#*asic%ms>eceiver) #NgtM
NltMpro'ect pathK)packages#apps#*luetooth) nameK)platform#packages#apps#*luetooth)
#NgtM
NltMpro'ect pathK)packages#apps#*rowser) nameK)platform#packages#apps#*rowser) #NgtM
NltMpro'ect pathK)packages#apps#Calculator)
nameK)platform#packages#apps#Calculator) #NgtM
NltMpro'ect pathK)packages#apps#Calendar) nameK)platform#packages#apps#Calendar)
#NgtM
NltMpro'ect pathK)packages#apps#Camera) nameK)platform#packages#apps#Camera) #NgtM
NltMpro'ect pathK)packages#apps#Cell*roadcast>eceiver)
nameK)platform#packages#apps#Cell*roadcast>eceiver) #NgtM
NltMpro'ect pathK)packages#apps#CertInstaller)
nameK)platform#packages#apps#CertInstaller) #NgtM
NltMpro'ect pathK)packages#apps#Contacts) nameK)platform#packages#apps#Contacts) #NgtM
NltMpro'ect pathK)packages#apps#FeskClock)
nameK)platform#packages#apps#FeskClock) #NgtM
NltMpro'ect pathK)packages#apps#+mail) nameK)platform#packages#apps#+mail) #NgtM
NltMpro'ect pathK)packages#apps#+xchange) nameK)platform#packages#apps#+xchange)
#NgtM
NltMpro'ect pathK)packages#apps#"allery) nameK)platform#packages#apps#"allery) #NgtM
NltMpro'ect pathK)packages#apps#"allery:c nameK)platform#packages#apps#"allery:c #NgtM
NltMpro'ect pathK)packages#apps#BTA/@iewer)
nameK)platform#packages#apps#BTA/@iewer) #NgtM
NltMpro'ect pathK)packages#apps#HeyChain) nameK)platform#packages#apps#HeyChain)
#NgtM
NltMpro'ect pathK)packages#apps#/auncher:c
nameK)platform#packages#apps#/auncher:c #NgtM
NltMpro'ect pathK)packages#apps#/egacyCamera)
nameK)platform#packages#apps#/egacyCamera) #NgtM
NltMpro'ect pathK)packages#apps#Ams) nameK)platform#packages#apps#Ams) #NgtM
NltMpro'ect pathK)packages#apps#Ausic) nameK)platform#packages#apps#Ausic) #NgtM
<:
<3
<<
<E
NltMpro'ect pathK)packages#apps#Ausic=Z) nameK)platform#packages#apps#Ausic=Z)
#NgtM
NltMpro'ect pathK)packages#apps#.fc) nameK)platform#packages#apps#.fc) #NgtM
NltMpro'ect pathK)packages#apps#ackageInstaller)
nameK)platform#packages#apps#ackageInstaller) #NgtM
NltMpro'ect pathK)packages#apps#hone) nameK)platform#packages#apps#hone) #NgtM
NltMpro'ect pathK)packages#apps#rotips) nameK)platform#packages#apps#rotips) #NgtM
NltMpro'ect pathK)packages#apps#rovision) nameK)platform#packages#apps#rovision)
#NgtM
NltMpro'ect pathK)packages#apps#?uick%earch*ox)
nameK)platform#packages#apps#?uick%earch*ox) #NgtM
NltMpro'ect pathK)packages#apps#%ettings) nameK)platform#packages#apps#%ettings) #NgtM
NltMpro'ect pathK)packages#apps#%ound>ecorder)
nameK)platform#packages#apps#%ound>ecorder) #NgtM
NltMpro'ect pathK)packages#apps#%parearts)
nameK)platform#packages#apps#%parearts) #NgtM
NltMpro'ect pathK)packages#apps#%peech>ecorder)
nameK)platform#packages#apps#%peech>ecorder) #NgtM
NltMpro'ect pathK)packages#apps#%tk) nameK)platform#packages#apps#%tk) #NgtM
NltMpro'ect pathK)packages#apps#Tag) nameK)platform#packages#apps#Tag) #NgtM
NltMpro'ect pathK)packages#apps#@ideo+ditor)
nameK)platform#packages#apps#@ideo+ditor) #NgtM
NltMpro'ect pathK)packages#apps#@oiceFialer)
nameK)platform#packages#apps#@oiceFialer) #NgtM
NltM#manifestNgtM
1hen done, save it and go a dir back in the terminal
8 cd ..
O. Fownload the packages
8 repo sync 7'8O ,7'8O stands for 8O 'obs max. This is for around a 8SSmbit line-
,1ith a OSmb#s connection you already get the max download speed with ) 7'< ) which is the
default of github-
The packages will be download as 4uickly as possible to your harddrive now.

Chapter 2. Co#pile:
To compile the obtained packages separately you will need a A$% environment ,or CA#A$H
etc-. 1hen you have a succesfull environment which is able to compile for your device you may
enter5
8
:
source build#envsetup.sh
lunch ,now choose your device, for example, full9ariesve7userdebug-
now you&re theoretically ready to compile
to compile an app on the easiest way5
8 make Appname 7'Q
where (Appname) is the name of the folder placed in packages#apps#..
This also counts for (%ystem!I) which is not in that folder
8 make Calculator 7'Q ,for example-
And the 7' param again stands for the number of 'obs, remember that this is compiling and not
downloading, so the (standard rule) with this is, number of cores of your C! J 8.
1hich makes a regular 4uad core ,7'E- but makes a iP C! with Byper threading ,7'R-. 1hen
using 7'8O for example on a regular 4uad core it could happen that your C! will be overloaded
so much that your mouse will lag all over the place.
,/inux forces the cpu to perform higher then it actually should, resulting in unwanted situations-
1hen having trouble, when it stops or 'ust nags about some missing symbols or something like
that.
;ou should try using the (7k) param, this tells the make command to keep going when a non7
critical error occurs.
8 make Calculator 7k 7'Q
1hen having issues with the local module tags, you should enter this5
8 make Calculator 7k /$CA/9A$F!/+9TA"%Koptional 7'Q
To compile other parts you also need to enter the folder name, here are some examples from
#frameworks#base
8
:
3
<
make android.policy ,the power menu and lockscreen-
make framework ,the initial framework files-
make framework7res ,the initial framework resources-
make services ,the services.'ar file-
or more examples5
8
:
3
<
E
make sdk ,builds the android sdk-
make modules ,builds all modules-
make installclean ,removes all staging directories, such as
out#target#product#boardname#system-
make clean ,removes the whole #out directory-
make recoveryimage ,builds the recovery from #bootable#recovery, customizable if
wanted0-

Chapter 3. Auto#ate
If you regularly want to compile specific >$A parts you can make a shell script that automates
the process for you.
Aake a new document with some name, for example (buildessentials), open the file with your
favorite text editor ,gedit is recommended-
and place this line at the very top of your document5
8 L0#bin#bash
This indicates that this file should call #bin#bash, which is the shell interpreter.
!nder this line you should place all the single commands that you want to be executed when
running the script. =or example5
8
:
3
<
E
. build#envsetup.sh ,inits the environement setup file, which is always needed-
lunch full9ariesve7userdebug ,chooses the wanted device, I chose for the iRSS8, which is
called ariesve-
make android.policy 7'Q ,builds android.policy.'ar-
make %ystem!I 7'Q ,builds %ystem!I.apk-
make recoveryimage 7'Q ,builds recovery.img-
%o your total output would be5
8
:
3
<
L0#bin#bash
. build#envsetup.sh ,inits the environement setup file, which is always needed-
lunch full9ariesve7userdebug ,chooses the wanted device, I chose for the iRSS8, which is
called ariesve-
E
O
make android.policy 7'Q ,builds android.policy.'ar-
make %ystem!I 7'Q ,builds %ystem!I.apk-
make recoveryimage 7'Q ,builds recovery.img-
.ow you should change the permissions of the files, which need to be >1Z7>Z7>Z, which is
PEE.
This can be done by entering this in the shell5
8 chmod PEE buildessential
.ow you can run the script by entering5
8 .#buildessential
Thats it0
lo!al?#anifests Cookbook
The local9manifests Cookbook offers manifests files which you can use to customize the
packages which get compiled into your rom,
1hat "oogle say about local9manifests U source5 .repo#repo#docs#manifest7format.txt V
8
:
3
<
E
/ocal Aanifests
KKKKKKKKKKKKKKK
Additional remotes and pro'ects may be added through local manifest files stored in
dIT$9FI>#.repo#local9manifests#Y.xmld.

O
P
Q
R
8S
88
8:
83
8<
8E
8O
8P
8Q
8R
=or example5
I ls .repo#local9manifests
local9manifest.xml
another9local9manifest.xml
I cat .repo#local9manifests#local9manifest.xml
]2xml versionKC8.SC encodingKC!T=7QC2^
]manifest^
]pro'ect pathKCmanifestC nameKCtools#manifestC #^
]pro'ect pathKCplatform7manifestC nameKCplatform#manifestC #^
]#manifest^

!sers may add pro'ects to the local manifest,s- prior to a drepo syncdinvocation, instructing
repo to automatically download and manage these extra pro'ects.
Aanifest files stored in dIT$9FI>#.repo#local9manifests#Y.xmld will be loaded in
alphabetical order. Additional remotes and pro'ects may also be added through a local
manifest, stored in dIT$9FI>#.repo#local9manifest.xmld. This method is deprecated in favor
of using multiple manifest files as mentioned above.
If dIT$9FI>#.repo#local9manifest.xmld exists, it will be loaded before any manifest files
stored in dIT$9FI>#.repo#local9manifests#Y.xmld.

The current version of repo U v8.8:.S V has a bug and re4uires patching before you can use the
local9manifests directory to store manifest xml files
8
:
3
<
E
O
P
Q
R
8S
88
8:
83
8<
8E
8O
diff 77git a#manifest9xml.py b#manifest9xml.py
index SOO<eff..<af8eS8 8SSO<<
777 a#manifest9xml.py
JJJ b#manifest9xml.py
ee 73<<,R J3<<,8S ee class ZmlAanifest,ob'ect-5
local9dir K os.path.abspath,os.path.'oin,self.repodir, /$CA/9AA.I=+%T%9FI>9.AA+--
try5
for local9file in sorted,os.listdir,local9dir--5
J local K os.path.'oin,local9dir, local9file-
if local9file.endswith,D.xmlD-5
try5
7 nodes.append,self.9arseAanifestZml,local9file, self.repodir--
J nodes.append,self.9arseAanifestZml,local, local9dir--
except Aanifestarse+rror as e5
print,DfsD f str,e-, fileKsys.stderr-
except $%+rror5
85 Add Clockworkmod >ecovery and *usybox to A$% builds. U Tested with 5 full9grouper7eng
5 android7<.:.89r8 V
8
:
3
<
E
O
P
Q
R
8S
88
8:
83
8<
8E
8O
]manifest^
]077 add github as a remote source 77^
]remote nameKCgithubC fetchKCgit5##github.comC #^

]077 remove aosp standard pro'ects and replace with cyanogenmod versions 77^
]remove7pro'ect nameKCplatform#bootable#recoveryC #^
]remove7pro'ect nameKCplatform#external#yaffs:C #^
]remove7pro'ect nameKCplatform#external#zlibC #^
]pro'ect pathKCbootable#recoveryC nameKCCyanogenAod#android9bootable9recoveryC
remoteKCgithubC revisionKCcm78S.8C #^
]pro'ect pathKCexternal#yaffs:C nameKCCyanogenAod#android9external9yaffs:C
remoteKCgithubC revisionKCcm78S.8C #^
]pro'ect pathKCexternal#zlibC nameKCCyanogenAod#android9external9zlibC
remoteKCgithubC revisionKCcm78S.8C #^

]077 add busybox from the cyanogenmod repository 77^
]pro'ect pathKCexternal#busyboxC nameKCCyanogenAod#android9external9busyboxC
remoteKCgithubC revisionKCcm78S.8C #^

]#manifest^
:. Add /inaro optimized for amr versions of dalvik, bionic and lib'peg U lib'peg7turbo V
8
:
3
<
E
O
P
Q
R
8S
]2xml versionKC8.SC encodingKC!T=7QC2^
]manifest^
]remove7pro'ect nameKCplatform#external#'pegC #^
]remove7pro'ect nameKCplatform#bionicC #^
]remove7pro'ect nameKCplatform#dalvikC #^
]077 add linaro git repository as a remote source 77^
]remote nameKClinaroC fetchKCgit5##android.git.linaro.org#C
reviewKCreview.android.git.linaro.orgC #^
]remote nameKClinaro7otherC fetchKCgit5##git.linaro.org#C #^
]pro'ect pathKCexternal#'pegC nameKCpeople#tomgall#lib'peg7turbo#lib'peg7turboC
88
8:
revisionKCandroidC remoteKClinaro7otherC #^
]pro'ect pathKCbionicC nameKCplatform#bionicC revisionKClinaro9android9<.:.8C
remoteKClinaroC#^
]pro'ect pathKCdalvikC nameKCplatform#dalvikC revisionKClinaro9android9<.:.8C
remoteKClinaroC #^
]#manifest^
'orting Android <o 0on9Android .evi!es
Difficult# level% Mind0lo5ing
Introduction
;ou have undoubtedly heard of famous devices like the BTC BF: or B Touchad, running
1indows Aobile or 1eb$% out of the box, where community managed to get the A>A7/inux
kernel running with a fully operational Android platform on top of it.
This article will focus on the lower level aspects of getting such stuff done, namely bootloaders,
the /inux kernel and native platform code. It will completely ignore high7level !I elements
included in .apk files. 1hy2 I will explain this at a later date.
Currently more than RSf of tablets and phones are built containing A>A C!s. 1hile this
guide does predominantly cover A>A devices, most of the general points will apply to other
computers ,yes, a phone or tablet is still a computer, with many similarities to your ersonal
Computer-, based on Intel Atom C!s for instance.
ersonally I work on an Android port for the %amsung 1ave ,running %amsung *ada $%-, and I
will use some of our code as examples.
What 5ould one need
To be completely honest, this isn&t a pro'ect anybody can take up. ;ou definitely need some
knowledge about the C programming language, assembler, electronics, and the architecture of
computers. And, as you are reading this article, you will likely be new to all of this. ;ou&ll need
lots, loads, sYYtloads of time. And some a lot of help, possibly a team with at least one person
having significant experience with embedded systems.
It is helpful to have at least one person in your team with some soldering skills and debugging
hardware is a must a try to get a !A>T or GTA" interface for your C. Aost of the mobile
mainboards do expose both of these.
Dictionar#
As I will use some weird words here. Bere&s a list of the words and abbreviations you will need
to know5
C! ,Central rocessing !nit-
A ,Application rocessor- a this is where Android is executed
*#C ,*aseband#Call rocessor- aka Aodem a this is what manages all cellular network
activities
*ootloader a The very first program executed by C! after bootup, the e4uivalent of *I$% you
might know from xQO computers
>I%C ,>educed Instruction %et Computer-
A>A ,Advanced >I%C Aachine-
%oC ,%ystem on Chip-
IC ,Integrated Circuit-
AIC ,ower Aanagament IC-
"I$ ,"eneral urpose Input#$utput-
%=> ,%pecial =unction register-
C a rogram Counter >egister ,>8E-, also known as Instruction Counter, +xecution ointer or
Instruction ointer ,I- in xQO assembler
$7code ,%ingle C! instruction- a it&s good to know that all A>A3: $codes are < bytes in
width, while in Thumb: execution mode their length varies from : to < bytes
+ ,rogram +ntry oint- a the address in memory where does the first $pcode of the program
is placed
%ecure *oot a Architecture where every stage of boot code ,bootloaders, and ultimately $%
kernel- checks the digital signature of the next stage that is going to be launched before actually
launching it. This is supposed to prevent any code from being executed if it is not signed by the
manufacturer and released through dedicated official update channels.
BA/ ,Bardware Abstraction /ayer-
7seful lin,s
There are countless references that could fill up days and months of learning various aspects
related to running A>A /inux on new devices and writing drivers for them. Bere are the ones I
found most useful during my process of learning about all of this.
www.google.com a 1hatever is bothering you, !ncle "oogle does probably know the answer,
or at least can point you the right direction. It&s only matter of asking him the right 4uestion.
www.arm.com a "reat set of materials and reference datasheets about A>A C!s.
www.heyrick.co.uk#assembler# a *ig reference about A>A A%A, I found (Instruction set 4uick
finder) the most useful.
lxr.linux.no a /inux Cross >eference, can do better search for various kernel&s core functions or
macros than ordinary grep.
+mbedded /inux Training slides by Gonathan %evy a "reat resource of main kernel porting
aspects, and even more useful links.
What is Android
Bave you even been wondering what Android really is2 Bow does tapping on the screen make
your device react2 Bow can some se4uence of :.<"Bz microwaves generated by another
machine cause your device to pop7up a *luetooth connection notification2 There are many
explanations and probably all of them are valid. =or the purposes of this article I will try to focus
on, and cover, one of them.
Android is a platform based on an operating system called /inux. Beard of /inux before2 "reat.
If you have ever used Android, it was A>A/inux with a specialised "!I and AI.
Android consists of low level components ,native C#CJJ compiled to executables, including the
Falvik virtual machine- and high level interfaces ,Gava and Falvik code compiled to AHs-,
Android has no direct influence on any hardware. The wonderful concept is that the same set of
Android binaries can work on any Android7enabled, unified, /inux kernel, being completely
separated and independant from the actual B1 parts inside of the device.
5ote& +ince version .6 o" t#e Linux kernel3 some o" lo(-level )ndroid parts (ere merged into
kernel mainline. 7#is means t#at part o" )ndroid is also in kernel.
Bowever, while good as a concept, in many cases the implementation of this is improving, but
there are still many aspects where platform components have to be hardware7specific, compiled
for a given IC, or, even worse, for a given B1 configuration. 1e will discuss these later.
Bere we&ll completely omit high level parts like AHs and focus on the low level components,
starting on assembly and ending on lower7level platform components.
1here to start6
8esearch
It doesn&t matter what $% your device normally runs a it&s am A>A7based device and your C!
is much more than a C! understood in terms of xQO computer a It&s an %oC, meaning it
contains roughly PEf of desktop C&s mainboard in one, highly power efficent chip, around the
size of a coin. The first task for you is to identify which %oC your device uses. !sually sites like
http5##pdadb.net# are enough.
"reat, you now know the name of your device&s heart. And what2 "et all the data you can a
datasheets, schematics, reference sources, binaries. 1hatever you can find that is related to this
particular %oC. Fon&t forget about looking for Android devices that also contain this %oC.
Android K /inuxJplatform, remember2 >eleasing an Android device does oblige the
manufacturer, by the power of "/ license, to release !o#plete sour!e!ode for the A/24inu+
)ernel it&s based upon. If this is not the case, find out what the architecture of the %oC is. =or
example, the %amsung +xynos <<8: model name is %EC::S, that is very similiar to %EC:8S,
and its predecessor is %EC88S, the +xynos3, also known as Bummingbird, all use %E
architecture, and these are based on the %3C architecture, known from %oCs like %3CO<SS. The
same also applies to the ?ualcomm A%A %oCs series. If you can&t find any reference sources
for a particular %oC, find reference sources for a few similiar %oCs.
As an example, for the %amsung 1ave we&ve used %amsung Aries ,"alaxy %- and %amsung
Crespo ,.exus %- kernel sources, all of these being based on the %EC88S %oC. The boards
turned out to be very similiar.
Fo not forget about the other ICs your device uses a high resolution pictures of the mainboard
are very useful here a try to find out model numbers of sensor ICs used, what AIC is used, and
what * is used. 1hat screen model is used2 Also look up any other chip you can identify. /ook
for other devices, their linux kernels and open7source bootloaders containing drivers for these a
you will need them.
Cool, you&ve found some datasheets and hopefully, reference sources, the trouble is you most
likely cannot make any practical use of the sources yet. 1hy2 ;ou have to tell the device to load
your code, that would prepare some environment for A>A/inux, and then load and 'ump into
the kernel image. Aanufacturers tend not to make this task easy for you0
De0ugging interfaces
If you have no experience yet, you will make a lot of mistakes a this stage needs some
information about what&s going inside the device. Furing the creation of device, manufacturer&s
developers has to debug their mistakes too, so there are almost definitely A debugging GTA"
and !A>T interfaces exposed somewhere on the mainboard. ersonally I think GTA" isn&t the
best way to go, unless you have experience working with A>A, gathered on some development
boards or resurrecting phones. !A>T might come in much more useful too.
@: 1hy not (76 Android developers do use (7 and A.7 for debugging.
A5 !%* is a relatively complex system, so it is much more likely to break than !A>T. *y way
of comparison, the code to handle basic @C$A through !%*, compiled for A>A, can weigh in
at upto < k*ytes, while it&s about <SS bytes for !A>T, with most of the code being 'ust an
initialization procedure.
1hile !A>T still needs some handling in the code executed on device, GTA" is always
available, if only the C! is powered on, not in suspend state, and no serious clocking issues are
present. That is also why GTA" is so widely used for phone resurrection.
Anyway, assuming you&ve got hardware for either of the debugging interfaces, you have to hook
up with them on the mainboard, probe for these and try to use them a you should get some debug
info on !A>T from stock system too. If this is not the case, GTA" might be your last resort.
Alternatively a if your device has got one or more /+Fs ,key backlight, screen backlight- wired
to "I$s, this can be used as a very primitive signaling interface. Bowever nothing is as good as
the good old7fashioned, tried7and7tested, and widely used A%CII log.
%ometimes manufacturers does make the task much easier, making accessing !A>T possible
without even opening the device. This is the case for %amsung "alaxy class phones.
%ometimes the task is more difficult, and re4uires more hardware interference. *ut again, Adam
$utler is an expert in this matter.
And another example of a device hacked by him.
If you&re probing for !A>T on your device, it&s very likely that Adam $utler is able to help you.
*ut remember it&s not advise to spam his A about it. >ather create thread with brief info and
high resolution photos of the &hole #ainboard on the ZFA Bardware Backing =orum. There
are also other people in that forum that can help you.
"ootloader 4ac,ing
This can be considered as the most frustrating and difficult step a this is all about theoretical
work with static analysis, and very little physical results in the end. !sually the end solution for
this appears to be very trivial. This will be the part where A>A assembler knowledge comes to
be most necessary and useful. Aost likely your device does implement some kind of secure7boot
process, as obviously the manufacturer doesn&t want you to launch anything custom7made and
not approved by them. *ut you&re the master of your own device, right2 %o the task is to prove
this0
!sually this process consists of analysing the boot7code contained by the system working on
your device and finding a security hole in it, then creating an exploit for it to escalate your
privileges, allowing you to do whatever you want. The bigger and more complex the boot code
is, the higher the possibility that there is an easily exploitable security hole, although more code
means much more time spent analysing it.
The primary target is to have the possibility of convincing the stock firmware to execute your
custom code in supervisor mode ,about A>A execution modes-, and, on some modern systems,
in the area considered by the A>A Trust[one as (secure).
Bave a look at other devices with the same %oC a they might have the same security keys used to
sign bootloaders working with Android. As well, maybe other versions of the bootloaders for
your device have lowered#dropped security checks. Think of the possibilities and check them all.
+xample of the security hole in the bootloaders of %amsung 1ave
+xample exploit made for the security hole from above ,have a look at fota9example.A%A-.
$ther example of running custom code on secure7boot enabled devices. +xploiting the leaked,
security7dropped and signed first stage of bootloader .
(seful links for the ne+t step:
http5##www.simtec.co.uk#products#%1/I.!Z#files#booting9article.html a Coverage of
bootloader tasks, before A>A/inux can be executed
http5##www.arm.linux.org.uk#developer#booting.php a Another article about what the bootloader
is expected to do before launching the kernel
0evelopment shortcut \ it might $e the case that some $inaries" incluing $ootloaers" pulle
from other" ver# similiar evices" woul wor, properl# without an# moifications. Sometimes it
oes save wee,s of har wor,.
*ustom 0ootloader
"reat a so you have got some way to load your custom code. 1hat you really want now is for
the bootloader to load the kernel.
The bootloader can be a really complex, $%7like program, capable of operations like executing
shell scripts or using the /A. interface5
!7*oot a the universal bootloader for linux, ported to many architectures
Cyanoboot a customized !7*oot, designed to boot Android on a in this case a *arnes N .obles
.ook Tablet, the device built on $AA<<3S, also exploiting a security hole in the stock
bootloader
/ittleHernel a reference bootloader for ?ualcomm %oCs
Alternatively, the bootloader can be a much simpler program5
?i a bootloader designed for embedded systems, as replacement for complex !7*oot
Get?i a customized ?i, designed to boot Android on %amsung Get, instead of stock %amsung
Bandset latform, it&s replacing stock bootloader completely, however, keeping it in form of
binary image, and launching it in case user wants to load %B, allowing dual7boot
=*$$T a code making callbacks to the many functions of stock bootloader , designed to
dualboot Android#*ada on %amsung 1ave ,ancestor of simple =$TA exploit presented in the
7ootloader %a!king part-
There&s also new, 1I version of =*$$T, mostly rewritten to C
Fepending on if you&ve got a method to replace stock bootloader code, or in'ect code into it a
you will need to at least implement a complete bootloader ,for the former case-, or generate a
table of callback pointers for the original code ,see =*$$T for an example-, for the latter case.
Jemem$er to have a resurrection metho an $ac,up of the non)volatile 8NW; ata from the
evice in case something goes wrong= 1his especiall# applies to the evelopment of the
proceure of replacing the $ootloaer. InGecting coe to the stoc, $ootloaer without moif#ing it
is generall# a safer metho" $ut sometimes unesire things can happen.
If you want to replace the stock bootloader, try to apply to the same rule you have used when
doing kernel research a find a development board or end7user device with an open bootloader
containing similiar %oC. ;ou will get a pre7made implementation of %oC drivers, including
simple peripherials like "I$, !A>T, I:C, AAC7host and !%*7slave.
%o, assuming that you have your bootloader running, and are loading your kernel image from
some external source like !%*, %F7card or whatever else, you want it to boot.
(seful links for the ne+t step:
http5##gicl.cs.drexel.edu#people#sevy#linux#A>A9/inux9boot9se4uence.html a 1hat does
A>A/inux kernel do right after the bootloader passes C to it.
0evelopment shortcut \ if #ou have got ]1A@ hoo,e up to the evice" #ou can ma,e a script
for loaing a DImage to the memor#" preparing A1A@s an Gumping into it. 1his of course isn!t
useful for an#$o# without ]1A@.
A8MLinu+ ,ernel 0ring!up
$nce again, I&ll use the 1ave&s kernel as the reference here.
Bere is the link to the reference source tree
ick the configuration of the device closest to yours ,similiar %oC-, and open it. It&s useful to
create a repo for new kernel immediately a and it&s a must if you&re not working alone on it. $ne
of the most useful functions is (git grep) a this works significantly faster than a regular grep, and
when working with a kernel you need to grep a lot. 5-
Defining our machine
Assuming you&ve read Gonathan %evy&s note about boot se4uence, the first thing I am going to
look at closer is is __lookup_mac#ine_type. This function compares the content of >egister 8
,>8-, passed to the kernel by bootloader, with the list of supported machine types. ;ou have to
specify your machine type and make sure that it is passed from bootloader correctly, and
registered in the kernel during the build process correctly.
=*$$T passes the machine type here and it is e4ual to the decimal value of QESS or QE3S,
depending on the model it&s built for.
The Hernel has machine types defined in arch#arm#tools#mach7types
And the machine support for both models is declared in arch#arm#mach7sEpv:8S#mach7wave.c
+idenotes&
• You won’t usually see or use multi-machine kernels. Often defining one machine is
enough.
• On ARM systems names machine and board are usually considered to be equal.
• All wave-named files started to be coy-aste kangs borrows of Aries files. !hile the
whole kernel robably became unusable for "ala#y $ devices% most of the sources and
&ifdefs were left for future reference.
The config for 1ave&s kernel is arch#arm#configs#wave9defconfig ,config name needs to end
with 9defconfig-
The crucial point is making it all stick together, so proper Hconfig values had to be defined in
arch#arm#mach7sEpv:8S#Hconfig, matching the previously defined machine type.
The kanged borrowed files had to be included in the actual build process for AACB91A@+, so
there is a arch#arm#mach7sEpv:8S#Aakefile modification.
In this case, the 1ave had a different >AA configuration than the Aries, so kernel itself
happened to be launched with different +, so the modification of arch#arm#mach7
sEpv:8S#Aakefile.boot was necessary to tell the toolchain where the first kernel instruction
should be placed, and where it can expect to have ATA" parameters list.
Kernel de0ugging
1e want to debug early on during the boot process, so enabling F+*!"9// and
+A>/;9>I.TH config flags is a good option. It does enable a very primitive set of print
functions, mapped directly to !A>T interface %=>s and tells (printk) function to use them. All
of the commonly used architectures support these switches.
;ou might know from the analysis of bootloader, and have it confirmed from B1 probing, what
!A>T port is used for the debug output a this might re4uire proper patches on the kernel level.
=rom grepping we know that printascii is a generic method from arch#arm#kernel#debug.%that
does use platform7specific methods addruart, senduart, (aituart and busyuart. In our case we
are able to find first one in arch#arm#mach7sEpv:8S#include#mach#debug7macro.% and 3 in
arch#arm#plat7samsung#include#plat#
debug7macro.% a it turns out that addruart is used for obtaining the base address to the %=> block
of a certain !A>T port and that it depends on the C$.=I"9F+*!"9%3C9!A>T value a
bingo. Aodifying this constant in defconfig would select any !A>T port we wish for debug
output.
Assuming everything went okay, you can compile the kernel and launch the zImage on your
device. It should produce some output and then hang or panic. !sually a panic is slighty better
because it&s easier to debug ,all registers and call7stack are dumped in the panic message output-.
+xample5 This is one of the !A>T logs from 1ave kernel booting a it was hanging early, during
clock configuration a you can notice very verbose output from the %3C clocks driver, as I was
trying to find out the exact reason for, and location of, the hang. It turned out that it hung when
accessing the %oC sound module clock %=>s a after more research I found out that sound
module power7gating was enabled by default, cutting off power to its %=>s completely. This
made accessing any of the specified module&s %=>s cause the whole %oC to hang. The solution
was simply writing Sx======== to the power gate %=>, that powered on all sub7blocks of the
%oC and made the kernel boot normally. 1hile this may appear easy, it took around 8S hours to
figure out at the time.
Another good example is when the kernel did boot, and then was rando#ly throwing panics,
sometimes after 8 minute, other time after 8S, always having some random7looking complaints
that looked like memory corruption. This took much longer to debug ,in the order of weeks, in
parallel with other development tasks-. =inally it turned out that having a single bit BI"B in one
of the F>AA controller %=>s, enabling (B; F//) funtionallity, that is meant to i#prove
syste# stability is noted in the %oC reference manual that A'%B .44 should not be off for
reliable operationC. Bowever, apparently it didn&t play well with some part of the kernel or
clocking driver for %E@:8S, as turning B; F// off fixed the issue completely. I found out
that it is not used either on the "alaxy %.
There are many, many more issues like this, and fixing them is usually 4uite difficult. *ut this
'ust has to be done to proceed with the Android porting.
Memor#
If your device has got a different amount of >AA than the reference device, you must ad'ust the
memory setup. If your device has got the same amount of memory, it may also re4uire
ad'ustments anyway. This could look like this5 original Aries memory setup 7^ modified 1ave
memory setup.
There were more things dependant on %E@:8S9A9%F>AA, that were also present on the
Aries. And this constant has to be changed too. %o there might be more than 8 place to change
this.
(PI9s
$ne of the most difficult tasks a a typical %oC has several hundred "I$s to communicate with
other ICs on the board, provide 1A outputs to regulate the intensity of the vibrator motor or
backlight of the screen or keys, provide keyboard support, the ability to serve external interrupts,
and communicate with various memory types ,>AA, AAC, .A.F, .$>-. Aost of the "I$s
can serve as simple, code7controller digital I#$s a able to drive or detect a BI"B or /$1 state
on its port. These can also be configured as external outputs of various modules present in the
%oC, such as %I, I:C, !%*, !A>T and memory controllers. These pins will probably have the
same purpose on all boards built using this %oC. The most difficult are the pins used as simple
I#$s. There are a few options for how to gather info about the "I$ mappings of the device5
• Jeverse engineering of stoc, firmware" incluing -S ,ernel
• -$taining etaile $oar schemas 8not the P+S iagrams" $ut general schemas of
connections;" though usuall# #ou won!t fin them in common service manuals
• 0estro#ing the evice" ,nowing the pinout of So+ an other I+s \ esolering them from
$oar an tracing the signal lines $etween them
7asi! peripherials
The device is not much use if it doesn&t display anything on the screen, doesn&t communicate
with touchscreen, cannot connect to 1i=i, doesn&t play a single sound, and can&t be controlled
using B1 keys. 1e&re not even talking yet about things like camera, sensors and other not7so7
essential peripherials.
If you have already got "I$ mappings and know what&s wired to what, use previously gathered
datasheets and info to create#ad'ust drivers for your board. This isn&t so difficult a task as it might
look because there are many drivers you can use as a reference. *asically the most efficient
approach is copy7paste, ad'ust, modify, copy7paste, fix7ups, more ad'ustments, then try to run it
Then it won&t work, so debug it, do more copy7pasting, research, do more fixes, re7test.
Platform bring-up
:irst steps
If you have got a kernel with some basic functionallity, you are probably ready for the platform
bring7up. /et&s not go for Android 4uite yet0 >un Android >ecovery first. This might be
Clock1orkAod ,C1A- or Team1in >ecovery ro'ect ,T1>-7 you choose.
;ou should create a new Android platform configuration ,covered in other ZFA7! articles-,
basing on some reference device with, again, preferably similiar B1 inside.
1hat you definitely need is a lot of debug verbosity a so don&t be afraid to mess with
system#core#init#log.h, maximally increasing verbosity.
Then what&s left is 'ust compiling it, catching output on !A>T and debugging, debugging,
debugging.
Fon&t forget to configure the bootloader to load the ramdisk properly and pass info about it to the
kernel.
After, most likely, a few days, you should be done with all of the bugs. +n'oy working AF*,
>ecovery and basically a /inux7box you can control over !%* or that small menu available in
recovery.
Where to put it;
;our device does contain some amount of flash memory, and this memory is managed and used
by the currently installed $%. 1hile the Android platform #system partition can be in excess of
:ESA*, it does also need some living space for #data and #cache, re4uiring more than ESSA*s of
space reserved for Android usage. Again, there are a few possibilities, with advantages and
disadvantages5
• 5ipe current -S completel# \ oes leave #ou with all the resources useful for Anroi"
although also leaves #ou without the a$ilit# to ual)$oot to #our stoc," full# wor,ing
s#stem.
• Install Anroi to S0 car \ this ma,es ual)$ooting possi$le" oesn!t touch the stoc,
s#stem" $ut usuall# onl# S0 cars of class : or 1A are fast enough to serve at least an
average en)user e/perience. 1hat!s $ecause internal memor# of the evice is the
fastest memor# it has.
• Share space with stoc, -S \ gives #ou ual)$oot" an oesn!t re^uire the use of S0
car. It!s often not possi$le for ever# evice as there might $e not enough em$ee
memor# on it an another isavantage is the reuce memor# for $oth of installe
s#stems.
%o the choosing of any configuration is up to you. It&s also reasonable to make a few installation
variations possible.
4ALs
The Android platform does not communicate with kernel drivers directly. %uch a topology would
make whole platform extremally hardware7dependant. Anything the platform does, that has to
have any influence on hardware, is done through interfaces known as BA/s. There are two types
of BA/s5
• li$raries" li,e li$sensors.so" li$lights.so" li$venor)ril.so" li$auio.so" gralloc.so"
li$@>ESCanroi.so" wi)fi an graphics car rivers
• s#sfs interfaces alrea# compile into ,ernel" li,e (s#s(evices(s#stem(cpu(cpuA(cpufre^(
use to pic, a +P? governor or force the +P? to sta# at esire fre^uenc#
%ome of the BA/ libraries can be easily coded, like libsensors ,example- a in many of cases it&s
'ust matter of using proper I$CT/ re4uests on the device driver, and passing the received value
to the platform. $ther BA/s are a completely different story, and the most complicated tend to
be closed7source ,example-.
In the cases where your device does contain some system with no open7source drivers available
normally the best path to take is 'ust pulling various proprietary binaries and praying they work,
if they don&t a you can try to analyse and patch them. If it turns out to be not possible, the last,
most time consuming process is writing a BA/ from scratch.
8adio Interface La#er
This is, as previously mentioned, the >I/ a potentially the most complex and most crucial BA/
in the Android for phones. 1ithout a proper >I/ there is no possibility of communication with
the *, rendering the device unable to make#receive calls and texts, use /ocation *ased
%ervices, access the internet over cellular data, and potentially a lot more.
In the case of the BTC BF:, the manufacturer had used a lot of similiar hardware and software
on other phones of the same class, which allowed almost direct ports of libraries like the >I/
from BTC Fesire and similiar, modifying only small pieces of these where necessary.
A much more complicated case is where the manufacturer uses a non7standard design for *,
and a non7standard communications protocol with the A, like %amsung did in the Get and 1ave.
This implies a completely different approach, and consists of writing a custom >I/. =or this task
we&ve choosen an open7source replacement for the %amsung Crespo >I/, and an implementation
for the 1ave and Get is still ongoing as, besides similiar topology ,communication through
packets transferred in shared7memory-, this is where the similiarities with other Android phones
end in this case.
In such cases, dynamic and static analysis of the stock $% code is necessary, pulling out all of
the telephony layer info. This isn&t a trivial task, as in this case the whole $% is linked into huge
binaries ,kernelJdrivers are about <SA*s-.
The implementation consists of a kernel shared memory driver, consisting of routines to handle
sending and receiving packets to and from the C, and a >I/ , loaded by and working in Android.
*y way of comparision a this is most of what had to be done for the BTC BF:, where the >I/
library from another device could be used.
Android
=inally, after your recovery is working, using the previously created platform configuration files,
you should put everything together and get a working, very buggy platform build. !sually
ad'usting all of the things does take a lot of time and brings a lot of frustration. *ut having fully
working Android on completely non7Android device is worth all of it.
:inal tips< common traps and more lin,s
*olla0oration
Fon&t underestimate the power that a team brings to the pro'ect. Two one7man (teams) can do
much less than one team consisting of two men. Team up with people and share your knowledge
and code.
(it
%haring is an essence of open7source pro'ects, and "it is all about sharing. !nfortunately, it isn&t
the most user7friendly application, but don&t wait0 %pend some time on learning it, let other
people see your code, and let them improve it. ;ou can&t do everything alone.
%ome pro tips about kernel development and git by +ntropyE8:
Donations
It&s all about the money. >ight2
1rong$
Fon&t even count on money for maintaining such pro'ect. Fonation are always great to receive,
and do increase the motivation for work. *ut honestly, the money that a hired developer team get
for launching Android on an upcoming device is unimaginably better than whatever you&re able
to get from donations, while the well paid teams have also got all of the proprietary
documentation they can ask for. %o do not start thinking of your pro'ect as a money7making
machine, because you&ll 4uickly realize that you&re doing something for no money, for bunch of
whiny braindead kids, and you will get discouraged 4uickly. And besides, it&s about the fun of
achieving this, not the fame or money0
'orting AO' /O2s using our!e Code
This will be a rough guide to help people port their favourite A$% >$As using the open source Android code,
thereby enabling your device to run full >$As unofficially, built from source. This means you can be running the
latest version of the >$A simply by updating your source code and re7building.
%ome of you maybe thinking (1ait don&t I need to know how to program to do this2) *eing able
to program is not necessarily re4uired ,although if you are interested in learning, check out the
Belpful /inks page- a more important are some hours to research the use of git, looking at some
existing >$A repository setups like Cyanogenmod and A$H, and getting a feel as to how a
new device is supported.
This guide is for the people who want an A$% rom that is not currently provided for by a
developer. =or example your device might have Cyanogenmod already available, however you
may wish to run A$H, because it allows more customisation without the need to decompile and
recompile apks etc.
YYYFisclaimer a lease check if permission is needed before kanging YYY
If the rom that&s been ported is already available for the device and it&s already built from source
not a rom a zip port then please try to add some uni4ue features as there will be not much point
in porting if there it&s any additional value to what is already available and it will 'ust create a
massive mess in your device development section. Bowever, what this allows us as extreme
enthusiasts is to reduce the workload for our developers while, giving something back to the
community in addition to showing your appreciation to your device developer#s or power
members.
$k now to the tools needed 5
;ou will need a C if not you wouldn&t be reading this.
A "ithub account created with "it installed on your system and if possible some knowledge on
git commands or time to research on them if not known.
=or a head start on some commands please refer to the excellent guide on ZFA by forum
moderator eagleeyetom called U"uideV Bow to use "ithub and can be found by searching on xda
developers website.
%ome experience with terminal if using /inux
A device and vendor tree for your device
;our A$% rom of choice
%ome hours of your time to work on this
This can be done on any platform that has git supported so windows, linux or mac but you will
need linux to build android. In this guide I shall be using linux as it&s my preferred system and
my distribution of choice at the moment [orin $% O as I have found it to be the fastest and least
resource hungry $% for me so far. %o all commands in this guide will be using terminal.
=or a guide on how to setup an android environment please refer to the guide on how to compile
from source found on ZFA7!
and for git here 7 https5##help.github.com#articles#set7up7git b7^ This is a perfect tutorial and one
needed to begin your learning process.
Throughout this guide I shall refer to device repo or device tree they mean the same thing. It&s
'ust different ways I like to refer to them. It means the device repository.
$k now to the tutorial 5
$nce git is setup we now want to look for the device&s repo _. If CA or another A$% rom is
already available for your device then look for the github page for it by either searching on
google or looking for your developer&s github page.
Bere is how one looks 5
As shown above the name setup is usually something like android9device9manufacturer9device
or device9manufacturer9device. This can be used to help find the device tree using a search
engine.
$k once we find that we are going to fork the device repo so we can edit it to work with the
A$% rom we are porting. As different roms use different configurations for their setup.
;ou can fork a pro'ect by clicking the fork button on the top right of the github page like so 7
$nce that&s done we&re going to need to fork your device&s proprietary vendor files.
Cyanogenmod usually names their repos differently to some other teams so when searching for
for a vendor repo for your device on Cyanogenmod it will be
properietary9vendor9manufacturer, whereas others teams might 'ust name it
vendor9manufacturer.
.ow once that&s done go to the github page of the A$% rom that is being ported and also fork
their vendor setup repo so we can add the device to the setup so it can be called later on when we
run the . build#envsetup or source build#envsetup.sh command this allows us to compile the rom
after when we have selected our target device.
$nce that&s done we are now going to start cloning these repos onto your local machine so we
can modify some files to add our device. *est way to do this is create a new directory where all
the work is going to be done in your home folder and cd into that directory. %o mkdir
directory,name it whatever you want-, then cd directory. %o for example if the name of the new
directory was named github then the commands will be mkdir github, cd github. $nce that&s
done navigate to your account page on github and clone the repos we forked earlier. To do this
we look for the ssh url on each repo page then we copy it. Then we type git clone and paste the
url and click enter on the keyboard. This will clone the repo from your github,remote- to your
local,system- allowing you to make changes to the files then upload them back to github.
%o when cloning is done the device, vendor tree and the rom&s vendor tree should be present.
.ow this is the part where we really need to switch on our brains. =irst go back to the github
page of the rom&s vendor tree and click on commits now look through them and find one where a
new device is added. Copy this new configuration and apply it to your device by either
modifying existing files or creating new ones. To ensure no conflicts arise when envsetup.sh is
ran try to make the product9name different but ensure the product9device and product9model are
the same as the one in the device tree.
$nce the device has been added what is left is to push the changes to your remote,github- by
using the git push command. This can be done by first using git add 7A which lets all the new
files and changes to be tracked. Then we use the git commit 7am ) message (. +.g git commit
7am (Add defy to the mix). This adds a commit message which will appear on our remote branch
with the new changes. =inally we use git push origin ]branch name^ to push the changes to our
remote. +.g git push origin 'ellybean
Additionally look at some device setups on the rom&s github page and see if any changes are
needed to make your device configuration compatible with the rom&s vendor tree. !sually none
are need but it depends on how the person or team has setup their vendor tree.
.ow this part is the longest and can be the most annoying process as we need to find the changes
that are necessary to ensure the device boots when the rom has been compiled. This can be done
in a number of ways but the best will be to kindly ask one of your device rom developer#s or
member#s that have created the A$% rom device tree that is been used to port the rom you&re
porting. Fepending on what type of device you have if it has a locked or unlocked bootloader
then changes will have to be cherry7picked or merged in different places such as
frameworks9base, system9core, etc.
>efer back to the git guide in the re4uirements on how to use these commands like git cherry7
pick, git merge. I can&t really guide you here as each device is different so this is the part where
you need your brain at maximum capacity.
Bere you will be cloning all the repos where changes need to happen from the rom&s github page
you&re porting. Then cherry7picking and merging these changes. >emember to first add the
remote with git remote add ]name^ before you start cherry7picking so the %BA number can be
found.
Also remember to add your repos to the platform9mainfest or android,if it&s a CA based rom-
Additionally, check your device maintainer&s setup to see if any additional repos any needed.
$nce that has been resolved push the changes to your remote and make a new directory in your
home directory then, repo init and repo sync, chose your device target with the lunch command
and finally use mka to compile the rom. at yourself if it compile without errors.
"ood /uck and +n'oy your hard work if it&s successful. Bowever, if the unfortunate happens
then report any issues here and me and the others members of ZFA will try help out as this is
ZFA after all where we help each other, learn and expand our knowledge of Android.
=or an example of what can be achieved look at some of my work and thank you for your time
'orting Clo!k&ork2od /e!overy to a 0e&
.evi!e
If you are not familiar with custom recovery images, we suggest you read the Introductory
section of ZFA7!niversity.
ClockworkAod, commonly abbreviated as C1A, is a popular custom recovery for Android
phones and tablets developed by Houshik Futta ,Housh-, a well7known name in the Android dev
community. This recovery image allows you to perform many advanced tasks like flashing,
backups, restoration and other maintenance tasks on your android device which the stock
recovery cannot do.
Thus Clock1orkAod ,also known as C1A- is a very popular custom recovery.
%etup the build environment. "uide on that can be found here 5 *uilding from %ource
lease note that we will be compiling the latest version of C1A recovery.
The source for C1A comes bundled with the CyanogenAod source code. %o you will have to
sync the CyanogenAod source.
In this guide, we use the source of CyanogenAod 8S to build C1A O.
At this stage make sure that you have synced the source, updated it and setup the build
environment. .ow lets proceed to the actual compiling part.
tep 1 : $pen the terminal and change the directory to the top of your source. Then run the
command
( make 7'< otatools )
This command will create all the necessary tools and files for the recovery compilation. Bere 7'L
signifies the number of processes to start. It is generally based on the number of processors in
your computer. This process generally re4uires E7P minutes on a reasonably fast desktop
computer.
tep 2 : .ow that the otatools are ready, we need to get a dump of our current boot.img. To do
this, use 6adb shell& and launch this command
( dump9image boot #sdcard#boot.img (
This command will dump the boot partition as a image file named boot.img to your sdcard. .ow
pull this image to your local directory using adb pull or any other method.
tep 3 : .ow we need to set up the makefiles for this device. "enerally this is a long and tedious
process. *ut since we are only compiling a recovery, it will be a lot easier.
=rom the root of your source directory, run the command
( . build#envsetup.sh ( or ( source #build#envsetup.sh (
This command will prepare all the necessary files re4uired for compiling ,initialize the build
environment-.
$nce it is done, run the command,
( build#tools#device#mkvendor.sh device9manufacturer9name device9name
#your#path#to#the#boot.img (
This will open the boot image and extract all the necessary files in the
device#manufacturer#device9name path.
tep " : .ow that we have extracted the files from the boot.img, we need to edit them to suit our
device. "enerally this shouldn&t be necessary, but we need to be sure about that or else we can
brick our devices. The only files which are to be edited are 6*oardConfig.mk& and
6recovery.fstab&. The main things that you will need to add is custom partitions ,if your device
doesn&t support named partitions-.
If you change the contents of the *oardConfig.mk file, you will have to run 6make clobber& or
the changes won&t get picked.
As the name suggests, *oardConfig.mk contains the config about the board used in your device.
This is a very important file and a single error or incorrect value can result in a brick. %o be
cautious while editing this file
.ext file is the recovery.fstab. This file lists all the partitions of a device and its paths. If you see
any incorrect partition in this file, please change it. ;ou don&t want your boot.img flashed on the
bootloader partition, do you 2
I cannot help you with the actual editing as each device has different partitions and different
formats.
tep D : $nce the files are ready, we start the compiling. >un the following command to prepare
the system for a compile.
( . build#envsetup.sh (
tep E : $nce the system is ready, lets move on to the compile process.
>un the command,
( lunch full9&device9name&7eng (
=or e.g 5 if you have a device names cooper, the command will be,
( lunch full9cooper7eng (
This will prepare the files of cooper for compiling.
tep : : .ow that we have all files setup, run the command
( make 7'< recoveryimage (
This command builds the recovery in the form of an image file. If you want a fakeflash for
testing purpose, then run,
( make 7'< recoveryzip (
The entire building process takes around 8E minutes.
$nce complete, you will get the resulting recovery.img in the 6out#target#product#device& path.
;ou can flash the recovery using a flashable zip or from adb using flash9image.
/epo: <ips = <ri!ks
>epo is one of a triplet of tools that you will use when you work with Android source, the other
two being "it and "errit. ;ou can read more about those tools from Android official site.
This article focuses on repo and aims at teaching you some useful tips N tricks that will
hopefully help you become more efficient when managing Android source.
What is 8epo
>epo is a repository management tool built on top of "it.
It&s first purpose is to downloads files from multiple git repositories into your local working
directory ,aka the source tree-. That means that you won&t have to manually download or fetch
the latest changes from about 3SSJ pro'ects ,depending on if you are downloading A$%, CA or
A$H for example-, repo will do it for you.
The second purpose of repo is to made it easy to submit your code contributions for review to a
"errit server.
Do5nloading Android Source% - eas# steps
The first thing you will always read about Android source is how to download them to your local
hard drive. It&s obviously the first stage of working with the sources. =etching the sources is as
easy as the three following steps5
• 1he first step is to ownloa the repo comman an ma,e it e/ecuta$le'
1
2
*
2
m,ir B($in
PA1HHB($in'IPA1H
curl https'((l)ssl.google.com(l(googlesource(git)repo(repo >
B($in(repo
chmo aT/ B($in(repo
Check your shell login scripts ,like .profile, .bash9profile,_- that `#bin is included in your
IATB.
• 1he secon step will initialiaDe a new local source repositor# in the current wor,ing
irector#'
1
repo init )u url )$
$ranch
This will create a new place to hold your local copy of the source tree. (url) should point to a
Aanifest repository that describes the whole sources. It is a special pro'ect with a file
,default.xml- that lists all the pro'ects that Android is made of. In the Aanifest file, each pro'ects
has attributes about5 where to place it in the tree, where to download it from ,git server-, revision
that will be used ,usually a branch name, tag or commit sha7id-. An example of such file can be
found here.
• 1he thir an last step is to actuall# ownloa the source'
1
repo
s#nc
The first time you run this command, it will download the sources. Android sources are huge, for
example, CA8S ,Gellybean- sources are about 8<"i*. %o, be prepared5 you&ll need space in your
hard drive, and time ,possibly several hours-.
Bopefully this article will help you save both time and space with some useful tricks. .ext times
you run it, it will only fetch the latest changes made to each repository.
Loo,ing inside 8epo
/et&s get back to the second step we&ve 'ust seen earlier. 1hat does repo init really do2 repo
init will create a hidden directory called .repo# in the root of your source tree. Inside .repo# we
will find very interesting things5
• repo( ' 1hat is actuall# a 8git; clone of the full repo sources themselves" while the repo
comman we ownloae earlier is much more a launcher that will then rel# on those.
It!s mae in P#thon.
• manifest./ml ' 1he main manifest of the tree 8usuall# anroi(efault./ml;. 0- N-1 eit
this file.
• proGects( ' 1his foler will actuall# hol the .git structures of ever# proGects #ou repo s#nc.
5e will see later how it will save us several hours.
• localCmanifest./ml ' 1hat file won!t $e create $# repo" $ut it!s relevant to ,now it. It!s an
optional file #ou can create to overrie the main manifest.
Do5nloading the source efficientl#
Considering the size of Android sources, more than :ES.SSS files, with all the versions of those
files, we are talking of about 8<"i* for CA8S. It can take a lot of time to download0
=ortunately, you can instruct repo to download several pro'ects in paralell using the (7') flag, so
therepo sync command will read something like5
1
repo s#nc )G
16
;ou should tune the number of 'obs repo will launch in paralell with regards of your number of
C! cores, and your bandwidth. 7' 8O should be fine for a Q7cores box with a high Internet
bandwidth.
This option will considerably lower the time needed to download the sources. Althought, be
careful, as raising this number too much might be counter productive.
To avoid issues, it is recommended that you also add net.ipv<.tcp9window9scalingKS to
your #etc#sysctl.conf file ,and run sudo sysctl 7p , or reboot to apply the change-.
Another handy option you might consider using is the (7c) flag5
1
)c" ))current)$ranch fetch onl# current $ranch from
server
1e&ve seen that Android source is made of hundreds of pro'ect, each pro'ect having it&s sources
in its own git repository. 1ith all the Android versions 'umps, those pro'ects have evolved, and
all that history is still recorded in those git repositories. That means that each of those hundred
git repository will have several branches. %o the 4uestion is5 do we really need to download ,git7
clone- all the branches of every pro'ects that make Android2 robably not.
That is where the (7c) flag is useful. 1ith that flag, repo will only download the revision
,branch- that is specified in the manifest, not all the branches that are on the remote server. It will
thus save us 4uite some space, and again it will take less time to download.
Editing the default Manifest
1e&ve already seen that repo relies on a manifest file, usually a file called default.xml in the
android pro'ect. The copy that repo will use as its reference is saved as .repo#manifest.xml.
1e&ve also said that we shouldn&t modify the .repo#manifest.xml manually0
The right way to modify the manifest.xml file would be to edit the android#default.xml, commit
the change, and push it upstream and thenrepo sync . Foing so will update
the .repo#manifest.xml copy, and everything will stay under ,git N repo- control.
9verriding the default Manifest% Local Manifest
There can be cases where editing the android#default.xml file isn&t the best option, or not an
option at all. =or example, if we have downloaded the sources from a Team, and we don&t have
access to pushing to their git. $r because the change is relevant only to me, or only to a device,
or maybe it&s 'ust for testing purpose.
Think also about the two following 4uestions5
• 0o #ou reall# nee all the proGects from the efault./ml_
• 0o #ou nee an# other proGects not in the efault./ml_
=or example, when building on a /inux machine, do you really need to download the toolchains
for building arm binaries on a darwin machine20 I guess not.
In those cases, we can use the (local manifest) to override ,modify- the default manifest. It&s a
file calledlocal9manifest.xml , under .repo# in our source tree. The file doens&t exist, we will
need to create it.
This local9manifest.xml will allow us to5
• A new %remotes&
• A" remove or replace %proGects& 8repositories;
$bviously, this file won&t be modified with repo sync., that is the point of it.
The synthax is the same as for the default manifest5
• Mremote(> to a a remote
• MproGect (> to a a proGect
• Mremove)proGect (> to remove a proGect
>eplacing a pro'ect with another is simply done by removing the pro'ect from the default
manifest and add a new one in its place, like for example5
1
2
*
2
4
M_/ml versionHN1.AN encoingHN?13):N_>
Mmanifest>
Mremove)proGect pathHNharware(^com(ispla#N
nameHN+#anogen.o(anroiCharwareC^comCispla#N (>
MproGect pathHNharware(^com(ispla#N nameHN5inSu,(anroiCharwareC^comCispla#N (>
M(manifest>
%ee repo help manifest for more information.
Save a snapshot of the source tree
As we&ve said earlier, the source tree is described in a manifest file that is a combination of the
android#default.xml and an eventual local9manifest.xml file you might have created.
repo allows us to export the resulting manifest. It will describes the current state of our source
tree ,any pro'ect and their revision at the current time-. The command to achive this is5
1
repo manifest )o snapshot./ml
)r
;ou can of course save the snapshot.xml wherever you want, and change the name to your
liking.
It can be very hand to save a snapshot of our source tree each time you make a new build, so you
can always come back to that exact same point later on if needed.
To restore the tree to the state described in a manifest snapshot file we had taken previously, we
would run the following commands5
1
2
*
cp snapshot./ml
.repo(manifests(
repo init )m snapshot./ml
repo s#nc )
It&s however important to take into account some considerations here5
• An# moification #ou might have mae to an# proGect which are not #et commite won!t
$e %save& in the manifest snapshot file.
• If #ou have commite some changes locall#" $ut haven!t pushe those to the upstream
remote repositor#" those commits will $e save in the manifest snapshot" $ut #ou will
onl# $e a$le to restore the manifest snapshot locall#.
8emoving a pro=ect
%ometimes you might want to completely remove a pro'ect from your source tree. The first way
that may come into your mind would be to simply remove the directory you see in your source
tree.
>emember that when repo syncs the source tree, it will first clone all the git repositories
under .repo#pro'ects, then fetch the files of every one of those pro'ects into the source tree
directory. %o, if you want to completely remove a pro'ect from your local sources, you will also
need to find the git directory corresponding to that pro'ect under .repo#pro'ects and delete it.
/ets see an example5 we want to completely remove hardware#4com#display . The corresponding
git directory is .repo#pro'ects#hardware#4com#display.git 5
1 rm )r harware(^com(ispla#
2
rm )r
.repo(proGects(harware(^com(ispla#.git
S#ncing a full ne5 source tree in minutes;
Time might come when you&ll need to work with several full source trees. =or example, you may
want to have an A$H source tree as well as a CA tree.
$bvisouly, you could repeat the same steps, to repo init and then repo sync 7' Q 7c for both. *ut
that would be twice as time consuming.
There is an alternative that should be much faster. /ets say that you have already initialized and
synced a CA source tree, in `#android#cm.
.ow, we will prepare a new repo for A$H tree, in `#android#aokp. Bere comes the trick5 1e
will use the 77reference flag of repo init to indicate to repo that we already have a local
repository that it can take information from, instead of downloading everything from Internet
again5
1
2
*
m,ir B(anroi(ao,p
c B(anroi(ao,p
repo init ))referenceHB(anroi(cm )u git'((githu$.com(A-7P(platformCmanifest.git
)$ G$
;ou should notice a big time diference, from hours for a full repo sync, down to minutes using
this trick0
Trou0leshooting 8epo
/ike happen with all piece of software, repo can hang, or appear not to work like you would
expect_
• 7ill a hanging repo comman
If a repo sync have been stuck for too long, you can kill it easily issuing the following
command5
1
,illall
p#thon
$bvisouly, you should only run that command if you know there won&t be any other python
script running on the machine at that time ,with the same user-.
• .a,e repo $e more ver$ose
%ometimes you&ll wish repo be more verbose. It&s particularly true when repo sync fail, but
won&t tell you why0 The reason is usually a remote git server that isn&t available. To make repo
be more verbose about what it does, you can add the 77trace flasg, right after repo5
1
repo ))trace s#nc )c )
)G:
• @et help
;ou can always read repo&s help, for any command, for example5
1
2
*
repo help init
repo help
manifest
repo help s#nc

Sponsor Documents

Or use your account on DocShare.tips

Hide

Forgot your password?

Or register your new account on DocShare.tips

Hide

Lost your password? Please enter your email address. You will receive a link to create a new password.

Back to log-in

Close