compdb.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. // Copyright 2018 Google Inc. All rights reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package cc
  15. import (
  16. "encoding/json"
  17. "log"
  18. "os"
  19. "path/filepath"
  20. "strings"
  21. "android/soong/android"
  22. )
  23. // This singleton generates a compile_commands.json file. It does so for each
  24. // blueprint Android.bp resulting in a cc.Module when either make, mm, mma, mmm
  25. // or mmma is called. It will only create a single compile_commands.json file
  26. // at ${OUT_DIR}/soong/development/ide/compdb/compile_commands.json. It will also symlink it
  27. // to ${SOONG_LINK_COMPDB_TO} if set. In general this should be created by running
  28. // make SOONG_GEN_COMPDB=1 nothing to get all targets.
  29. func init() {
  30. android.RegisterParallelSingletonType("compdb_generator", compDBGeneratorSingleton)
  31. }
  32. func compDBGeneratorSingleton() android.Singleton {
  33. return &compdbGeneratorSingleton{}
  34. }
  35. type compdbGeneratorSingleton struct{}
  36. const (
  37. compdbFilename = "compile_commands.json"
  38. compdbOutputProjectsDirectory = "development/ide/compdb"
  39. // Environment variables used to modify behavior of this singleton.
  40. envVariableGenerateCompdb = "SOONG_GEN_COMPDB"
  41. envVariableGenerateCompdbDebugInfo = "SOONG_GEN_COMPDB_DEBUG"
  42. envVariableCompdbLink = "SOONG_LINK_COMPDB_TO"
  43. )
  44. // A compdb entry. The compile_commands.json file is a list of these.
  45. type compDbEntry struct {
  46. Directory string `json:"directory"`
  47. Arguments []string `json:"arguments"`
  48. File string `json:"file"`
  49. Output string `json:"output,omitempty"`
  50. }
  51. func (c *compdbGeneratorSingleton) GenerateBuildActions(ctx android.SingletonContext) {
  52. if !ctx.Config().IsEnvTrue(envVariableGenerateCompdb) {
  53. return
  54. }
  55. // Instruct the generator to indent the json file for easier debugging.
  56. outputCompdbDebugInfo := ctx.Config().IsEnvTrue(envVariableGenerateCompdbDebugInfo)
  57. // We only want one entry per file. We don't care what module/isa it's from
  58. m := make(map[string]compDbEntry)
  59. ctx.VisitAllModules(func(module android.Module) {
  60. if ccModule, ok := module.(*Module); ok {
  61. if compiledModule, ok := ccModule.compiler.(CompiledInterface); ok {
  62. generateCompdbProject(compiledModule, ctx, ccModule, m)
  63. }
  64. }
  65. })
  66. // Create the output file.
  67. dir := android.PathForOutput(ctx, compdbOutputProjectsDirectory)
  68. os.MkdirAll(filepath.Join(android.AbsSrcDirForExistingUseCases(), dir.String()), 0777)
  69. compDBFile := dir.Join(ctx, compdbFilename)
  70. f, err := os.Create(filepath.Join(android.AbsSrcDirForExistingUseCases(), compDBFile.String()))
  71. if err != nil {
  72. log.Fatalf("Could not create file %s: %s", compDBFile, err)
  73. }
  74. defer f.Close()
  75. v := make([]compDbEntry, 0, len(m))
  76. for _, value := range m {
  77. v = append(v, value)
  78. }
  79. var dat []byte
  80. if outputCompdbDebugInfo {
  81. dat, err = json.MarshalIndent(v, "", " ")
  82. } else {
  83. dat, err = json.Marshal(v)
  84. }
  85. if err != nil {
  86. log.Fatalf("Failed to marshal: %s", err)
  87. }
  88. f.Write(dat)
  89. if finalLinkDir := ctx.Config().Getenv(envVariableCompdbLink); finalLinkDir != "" {
  90. finalLinkPath := filepath.Join(finalLinkDir, compdbFilename)
  91. os.Remove(finalLinkPath)
  92. if err := os.Symlink(compDBFile.String(), finalLinkPath); err != nil {
  93. log.Fatalf("Unable to symlink %s to %s: %s", compDBFile, finalLinkPath, err)
  94. }
  95. }
  96. }
  97. func expandAllVars(ctx android.SingletonContext, args []string) []string {
  98. var out []string
  99. for _, arg := range args {
  100. if arg != "" {
  101. if val, err := evalAndSplitVariable(ctx, arg); err == nil {
  102. out = append(out, val...)
  103. } else {
  104. out = append(out, arg)
  105. }
  106. }
  107. }
  108. return out
  109. }
  110. func getArguments(src android.Path, ctx android.SingletonContext, ccModule *Module, ccPath string, cxxPath string) []string {
  111. var args []string
  112. isCpp := false
  113. isAsm := false
  114. // TODO It would be better to ask soong for the types here.
  115. var clangPath string
  116. switch src.Ext() {
  117. case ".S", ".s", ".asm":
  118. isAsm = true
  119. isCpp = false
  120. clangPath = ccPath
  121. case ".c":
  122. isAsm = false
  123. isCpp = false
  124. clangPath = ccPath
  125. case ".cpp", ".cc", ".cxx", ".mm":
  126. isAsm = false
  127. isCpp = true
  128. clangPath = cxxPath
  129. default:
  130. log.Print("Unknown file extension " + src.Ext() + " on file " + src.String())
  131. isAsm = true
  132. isCpp = false
  133. clangPath = ccPath
  134. }
  135. args = append(args, clangPath)
  136. args = append(args, expandAllVars(ctx, ccModule.flags.Global.CommonFlags)...)
  137. args = append(args, expandAllVars(ctx, ccModule.flags.Local.CommonFlags)...)
  138. args = append(args, expandAllVars(ctx, ccModule.flags.Global.CFlags)...)
  139. args = append(args, expandAllVars(ctx, ccModule.flags.Local.CFlags)...)
  140. if isCpp {
  141. args = append(args, expandAllVars(ctx, ccModule.flags.Global.CppFlags)...)
  142. args = append(args, expandAllVars(ctx, ccModule.flags.Local.CppFlags)...)
  143. } else if !isAsm {
  144. args = append(args, expandAllVars(ctx, ccModule.flags.Global.ConlyFlags)...)
  145. args = append(args, expandAllVars(ctx, ccModule.flags.Local.ConlyFlags)...)
  146. }
  147. args = append(args, expandAllVars(ctx, ccModule.flags.SystemIncludeFlags)...)
  148. args = append(args, src.String())
  149. return args
  150. }
  151. func generateCompdbProject(compiledModule CompiledInterface, ctx android.SingletonContext, ccModule *Module, builds map[string]compDbEntry) {
  152. srcs := compiledModule.Srcs()
  153. if len(srcs) == 0 {
  154. return
  155. }
  156. pathToCC, err := ctx.Eval(pctx, "${config.ClangBin}")
  157. ccPath := "/bin/false"
  158. cxxPath := "/bin/false"
  159. if err == nil {
  160. ccPath = filepath.Join(pathToCC, "clang")
  161. cxxPath = filepath.Join(pathToCC, "clang++")
  162. }
  163. for _, src := range srcs {
  164. if _, ok := builds[src.String()]; !ok {
  165. builds[src.String()] = compDbEntry{
  166. Directory: android.AbsSrcDirForExistingUseCases(),
  167. Arguments: getArguments(src, ctx, ccModule, ccPath, cxxPath),
  168. File: src.String(),
  169. }
  170. }
  171. }
  172. }
  173. func evalAndSplitVariable(ctx android.SingletonContext, str string) ([]string, error) {
  174. evaluated, err := ctx.Eval(pctx, str)
  175. if err == nil {
  176. return strings.Fields(evaluated), nil
  177. }
  178. return []string{""}, err
  179. }