Debian Codegraph @

cmd/gomobile/build_androidapp.go

raw
1 // Copyright 2015 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package main
6
7 import (
8 "bytes"
9 "crypto/x509"
10 "encoding/base64"
11 "encoding/pem"
12 "encoding/xml"
13 "errors"
14 "fmt"
15 "io"
16 "log"
17 "os"
18 "path"
19 "path/filepath"
20 "strings"
21
22 "golang.org/x/mobile/internal/binres"
23 "golang.org/x/tools/go/packages"
24 )
25
26 func goAndroidBuild(pkg *packages.Package, targets []targetInfo) (map[string]bool, error) {
27 ndkRoot, err := ndkRoot(targets...)
28 if err != nil {
29 return nil, err
30 }
31 appName := path.Base(pkg.PkgPath)
32 libName := androidPkgName(appName)
33
34 // TODO(hajimehoshi): This works only with Go tools that assume all source files are in one directory.
35 // Fix this to work with other Go tools.
36 dir := filepath.Dir(pkg.GoFiles[0])
37
38 manifestPath := filepath.Join(dir, "AndroidManifest.xml")
39 manifestData, err := os.ReadFile(manifestPath)
40 if err != nil {
41 if !os.IsNotExist(err) {
42 return nil, err
43 }
44
45 buf := new(bytes.Buffer)
46 buf.WriteString(`<?xml version="1.0" encoding="utf-8"?>`)
47 err := manifestTmpl.Execute(buf, manifestTmplData{
48 // TODO(crawshaw): a better package path.
49 JavaPkgPath: "org.golang.todo." + libName,
50 Name: strings.Title(appName),
51 LibName: libName,
52 })
53 if err != nil {
54 return nil, err
55 }
56 manifestData = buf.Bytes()
57 if buildV {
58 fmt.Fprintf(os.Stderr, "generated AndroidManifest.xml:\n%s\n", manifestData)
59 }
60 } else {
61 libName, err = manifestLibName(manifestData)
62 if err != nil {
63 return nil, fmt.Errorf("error parsing %s: %v", manifestPath, err)
64 }
65 }
66
67 libFiles := []string{}
68 nmpkgs := make(map[string]map[string]bool) // map: arch -> extractPkgs' output
69
70 for _, t := range targets {
71 toolchain := ndk.Toolchain(t.arch)
72 libPath := "lib/" + toolchain.abi + "/lib" + libName + ".so"
73 libAbsPath := filepath.Join(tmpdir, libPath)
74 if err := mkdir(filepath.Dir(libAbsPath)); err != nil {
75 return nil, err
76 }
77 err = goBuild(
78 pkg.PkgPath,
79 androidEnv[t.arch],
80 "-buildmode=c-shared",
81 "-o", libAbsPath,
82 )
83 if err != nil {
84 return nil, err
85 }
86 nmpkgs[t.arch], err = extractPkgs(toolchain.Path(ndkRoot, "nm"), libAbsPath)
87 if err != nil {
88 return nil, err
89 }
90 libFiles = append(libFiles, libPath)
91 }
92
93 block, _ := pem.Decode([]byte(debugCert))
94 if block == nil {
95 return nil, errors.New("no debug cert")
96 }
97 privKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
98 if err != nil {
99 return nil, err
100 }
101
102 if buildO == "" {
103 buildO = androidPkgName(path.Base(pkg.PkgPath)) + ".apk"
104 }
105 if !strings.HasSuffix(buildO, ".apk") {
106 return nil, fmt.Errorf("output file name %q does not end in '.apk'", buildO)
107 }
108 var out io.Writer
109 if !buildN {
110 f, err := os.Create(buildO)
111 if err != nil {
112 return nil, err
113 }
114 defer func() {
115 if cerr := f.Close(); err == nil {
116 err = cerr
117 }
118 }()
119 out = f
120 }
121
122 var apkw *Writer
123 if !buildN {
124 apkw = NewWriter(out, privKey)
125 }
126 apkwCreate := func(name string) (io.Writer, error) {
127 if buildV {
128 fmt.Fprintf(os.Stderr, "apk: %s\n", name)
129 }
130 if buildN {
131 return io.Discard, nil
132 }
133 return apkw.Create(name)
134 }
135 apkwWriteFile := func(dst, src string) error {
136 w, err := apkwCreate(dst)
137 if err != nil {
138 return err
139 }
140 if !buildN {
141 f, err := os.Open(src)
142 if err != nil {
143 return err
144 }
145 defer f.Close()
146 if _, err := io.Copy(w, f); err != nil {
147 return err
148 }
149 }
150 return nil
151 }
152
153 w, err := apkwCreate("classes.dex")
154 if err != nil {
155 return nil, err
156 }
157 dexData, err := base64.StdEncoding.DecodeString(dexStr)
158 if err != nil {
159 log.Fatalf("internal error bad dexStr: %v", err)
160 }
161 if _, err := w.Write(dexData); err != nil {
162 return nil, err
163 }
164
165 for _, libFile := range libFiles {
166 if err := apkwWriteFile(libFile, filepath.Join(tmpdir, libFile)); err != nil {
167 return nil, err
168 }
169 }
170
171 for _, t := range targets {
172 toolchain := ndk.Toolchain(t.arch)
173 if nmpkgs[t.arch]["golang.org/x/mobile/exp/audio/al"] {
174 dst := "lib/" + toolchain.abi + "/libopenal.so"
175 src := filepath.Join(gomobilepath, dst)
176 if _, err := os.Stat(src); err != nil {
177 return nil, errors.New("the Android requires the golang.org/x/mobile/exp/audio/al, but the OpenAL libraries was not found. Please run gomobile init with the -openal flag pointing to an OpenAL source directory.")
178 }
179 if err := apkwWriteFile(dst, src); err != nil {
180 return nil, err
181 }
182 }
183 }
184
185 // Add any assets.
186 var arsc struct {
187 iconPath string
188 }
189 assetsDir := filepath.Join(dir, "assets")
190 assetsDirExists := true
191 fi, err := os.Stat(assetsDir)
192 if err != nil {
193 if os.IsNotExist(err) {
194 assetsDirExists = false
195 } else {
196 return nil, err
197 }
198 } else {
199 assetsDirExists = fi.IsDir()
200 }
201 if assetsDirExists {
202 // if assets is a symlink, follow the symlink.
203 assetsDir, err = filepath.EvalSymlinks(assetsDir)
204 if err != nil {
205 return nil, err
206 }
207 err = filepath.Walk(assetsDir, func(path string, info os.FileInfo, err error) error {
208 if err != nil {
209 return err
210 }
211 if name := filepath.Base(path); strings.HasPrefix(name, ".") {
212 // Do not include the hidden files.
213 return nil
214 }
215 if info.IsDir() {
216 return nil
217 }
218
219 if rel, err := filepath.Rel(assetsDir, path); rel == "icon.png" && err == nil {
220 arsc.iconPath = path
221 // TODO returning here does not write the assets/icon.png to the final assets output,
222 // making it unavailable via the assets API. Should the file be duplicated into assets
223 // or should assets API be able to retrieve files from the generated resource table?
224 return nil
225 }
226
227 name := "assets/" + path[len(assetsDir)+1:]
228 return apkwWriteFile(name, path)
229 })
230 if err != nil {
231 return nil, fmt.Errorf("asset %v", err)
232 }
233 }
234
235 bxml, err := binres.UnmarshalXML(bytes.NewReader(manifestData), arsc.iconPath != "")
236 if err != nil {
237 return nil, err
238 }
239
240 // generate resources.arsc identifying single xxxhdpi icon resource.
241 if arsc.iconPath != "" {
242 pkgname, err := bxml.RawValueByName("manifest", xml.Name{Local: "package"})
243 if err != nil {
244 return nil, err
245 }
246 tbl, name := binres.NewMipmapTable(pkgname)
247 if err := apkwWriteFile(name, arsc.iconPath); err != nil {
248 return nil, err
249 }
250 w, err := apkwCreate("resources.arsc")
251 if err != nil {
252 return nil, err
253 }
254 bin, err := tbl.MarshalBinary()
255 if err != nil {
256 return nil, err
257 }
258 if _, err := w.Write(bin); err != nil {
259 return nil, err
260 }
261 }
262
263 w, err = apkwCreate("AndroidManifest.xml")
264 if err != nil {
265 return nil, err
266 }
267 bin, err := bxml.MarshalBinary()
268 if err != nil {
269 return nil, err
270 }
271 if _, err := w.Write(bin); err != nil {
272 return nil, err
273 }
274
275 // TODO: add gdbserver to apk?
276
277 if !buildN {
278 if err := apkw.Close(); err != nil {
279 return nil, err
280 }
281 }
282
283 // TODO: return nmpkgs
284 return nmpkgs[targets[0].arch], nil
285 }
286
287 // androidPkgName sanitizes the go package name to be acceptable as a android
288 // package name part. The android package name convention is similar to the
289 // java package name convention described in
290 // https://docs.oracle.com/javase/specs/jls/se8/html/jls-6.html#jls-6.5.3.1
291 // but not exactly same.
292 func androidPkgName(name string) string {
293 var res []rune
294 for _, r := range name {
295 switch {
296 case 'a' <= r && r <= 'z', 'A' <= r && r <= 'Z', '0' <= r && r <= '9':
297 res = append(res, r)
298 default:
299 res = append(res, '_')
300 }
301 }
302 if len(res) == 0 || res[0] == '_' || ('0' <= res[0] && res[0] <= '9') {
303 // Android does not seem to allow the package part starting with _.
304 res = append([]rune{'g', 'o'}, res...)
305 }
306 s := string(res)
307 // Look for Java keywords that are not Go keywords, and avoid using
308 // them as a package name.
309 //
310 // This is not a problem for normal Go identifiers as we only expose
311 // exported symbols. The upper case first letter saves everything
312 // from accidentally matching except for the package name.
313 //
314 // Note that basic type names (like int) are not keywords in Go.
315 switch s {
316 case "abstract", "assert", "boolean", "byte", "catch", "char", "class",
317 "do", "double", "enum", "extends", "final", "finally", "float",
318 "implements", "instanceof", "int", "long", "native", "private",
319 "protected", "public", "short", "static", "strictfp", "super",
320 "synchronized", "this", "throw", "throws", "transient", "try",
321 "void", "volatile", "while":
322 s += "_"
323 }
324 return s
325 }
326
327 // A random uninteresting private key.
328 // Must be consistent across builds so newer app versions can be installed.
329 const debugCert = `
330 -----BEGIN RSA PRIVATE KEY-----
331 MIIEowIBAAKCAQEAy6ItnWZJ8DpX9R5FdWbS9Kr1U8Z7mKgqNByGU7No99JUnmyu
332 NQ6Uy6Nj0Gz3o3c0BXESECblOC13WdzjsH1Pi7/L9QV8jXOXX8cvkG5SJAyj6hcO
333 LOapjDiN89NXjXtyv206JWYvRtpexyVrmHJgRAw3fiFI+m4g4Qop1CxcIF/EgYh7
334 rYrqh4wbCM1OGaCleQWaOCXxZGm+J5YNKQcWpjZRrDrb35IZmlT0bK46CXUKvCqK
335 x7YXHgfhC8ZsXCtsScKJVHs7gEsNxz7A0XoibFw6DoxtjKzUCktnT0w3wxdY7OTj
336 9AR8mobFlM9W3yirX8TtwekWhDNTYEu8dwwykwIDAQABAoIBAA2hjpIhvcNR9H9Z
337 BmdEecydAQ0ZlT5zy1dvrWI++UDVmIp+Ve8BSd6T0mOqV61elmHi3sWsBN4M1Rdz
338 3N38lW2SajG9q0fAvBpSOBHgAKmfGv3Ziz5gNmtHgeEXfZ3f7J95zVGhlHqWtY95
339 JsmuplkHxFMyITN6WcMWrhQg4A3enKLhJLlaGLJf9PeBrvVxHR1/txrfENd2iJBH
340 FmxVGILL09fIIktJvoScbzVOneeWXj5vJGzWVhB17DHBbANGvVPdD5f+k/s5aooh
341 hWAy/yLKocr294C4J+gkO5h2zjjjSGcmVHfrhlXQoEPX+iW1TGoF8BMtl4Llc+jw
342 lKWKfpECgYEA9C428Z6CvAn+KJ2yhbAtuRo41kkOVoiQPtlPeRYs91Pq4+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