1#!/usr/bin/env python3
2#
3# Copyright (C) 2009 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#      http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17import argparse
18import sys
19
20# Usage: post_process_props.py file.prop [disallowed_key, ...]
21# Disallowed keys are removed from the property file, if present
22
23# See PROP_VALUE_MAX in system_properties.h.
24# The constant in system_properties.h includes the terminating NUL,
25# so we decrease the value by 1 here.
26PROP_VALUE_MAX = 91
27
28# Put the modifications that you need to make into the */build.prop into this
29# function.
30def mangle_build_prop(prop_list):
31  # If ro.debuggable is 1, then enable adb on USB by default
32  # (this is for userdebug builds)
33  if prop_list.get_value("ro.debuggable") == "1":
34    val = prop_list.get_value("persist.sys.usb.config")
35    if "adb" not in val:
36      if val == "":
37        val = "adb"
38      else:
39        val = val + ",adb"
40      prop_list.put("persist.sys.usb.config", val)
41  # UsbDeviceManager expects a value here.  If it doesn't get it, it will
42  # default to "adb". That might not the right policy there, but it's better
43  # to be explicit.
44  if not prop_list.get_value("persist.sys.usb.config"):
45    prop_list.put("persist.sys.usb.config", "none");
46
47def validate(prop_list):
48  """Validate the properties.
49
50  If the value of a sysprop exceeds the max limit (91), it's an error, unless
51  the sysprop is a read-only one.
52
53  Checks if there is no optional prop assignments.
54
55  Returns:
56    True if nothing is wrong.
57  """
58  check_pass = True
59  for p in prop_list.get_all_props():
60    if len(p.value) > PROP_VALUE_MAX and not p.name.startswith("ro."):
61      check_pass = False
62      sys.stderr.write("error: %s cannot exceed %d bytes: " %
63                       (p.name, PROP_VALUE_MAX))
64      sys.stderr.write("%s (%d)\n" % (p.value, len(p.value)))
65
66    if p.is_optional():
67      check_pass = False
68      sys.stderr.write("error: found unresolved optional prop assignment:\n")
69      sys.stderr.write(str(p) + "\n")
70
71  return check_pass
72
73def override_optional_props(prop_list, allow_dup=False):
74  """Override a?=b with a=c, if the latter exists
75
76  Overriding is done by deleting a?=b
77  When there are a?=b and a?=c, then only the last one survives
78  When there are a=b and a=c, then it's an error.
79
80  Returns:
81    True if the override was successful
82  """
83  success = True
84  for name in prop_list.get_all_names():
85    props = prop_list.get_props(name)
86    optional_props = [p for p in props if p.is_optional()]
87    overriding_props = [p for p in props if not p.is_optional()]
88    if len(overriding_props) > 1:
89      # duplicated props are allowed when the all have the same value
90      if all(overriding_props[0].value == p.value for p in overriding_props):
91        for p in optional_props:
92          p.delete("overridden by %s" % str(overriding_props[0]))
93        continue
94      # or if dup is explicitly allowed for compat reason
95      if allow_dup:
96        # this could left one or more optional props unresolved.
97        # Convert them into non-optional because init doesn't understand ?=
98        # syntax
99        for p in optional_props:
100          p.optional = False
101        continue
102
103      success = False
104      sys.stderr.write("error: found duplicate sysprop assignments:\n")
105      for p in overriding_props:
106        sys.stderr.write("%s\n" % str(p))
107    elif len(overriding_props) == 1:
108      for p in optional_props:
109        p.delete("overridden by %s" % str(overriding_props[0]))
110    else:
111      if len(optional_props) > 1:
112        for p in optional_props[:-1]:
113          p.delete("overridden by %s" % str(optional_props[-1]))
114      # Make the last optional one as non-optional
115      optional_props[-1].optional = False
116
117  return success
118
119class Prop:
120
121  def __init__(self, name, value, optional=False, comment=None):
122    self.name = name.strip()
123    self.value = value.strip()
124    if comment != None:
125      self.comments = [comment]
126    else:
127      self.comments = []
128    self.optional = optional
129
130  @staticmethod
131  def from_line(line):
132    line = line.rstrip('\n')
133    if line.startswith("#"):
134      return Prop("", "", comment=line)
135    elif "?=" in line:
136      name, value = line.split("?=", 1)
137      return Prop(name, value, optional=True)
138    elif "=" in line:
139      name, value = line.split("=", 1)
140      return Prop(name, value, optional=False)
141    else:
142      # don't fail on invalid line
143      # TODO(jiyong) make this a hard error
144      return Prop("", "", comment=line)
145
146  def is_comment(self):
147    return bool(self.comments and not self.name)
148
149  def is_optional(self):
150    return (not self.is_comment()) and self.optional
151
152  def make_as_comment(self):
153    # Prepend "#" to the last line which is the prop assignment
154    if not self.is_comment():
155      assignment = str(self).rsplit("\n", 1)[-1]
156      self.comments.append("#" + assignment)
157      self.name = ""
158      self.value = ""
159
160  def delete(self, reason):
161    self.comments.append("# Removed by post_process_props.py because " + reason)
162    self.make_as_comment()
163
164  def __str__(self):
165    assignment = []
166    if not self.is_comment():
167      operator = "?=" if self.is_optional() else "="
168      assignment.append(self.name + operator + self.value)
169    return "\n".join(self.comments + assignment)
170
171class PropList:
172
173  def __init__(self, filename):
174    with open(filename) as f:
175      self.props = [Prop.from_line(l)
176                    for l in f.readlines() if l.strip() != ""]
177
178  def get_all_props(self):
179    return [p for p in self.props if not p.is_comment()]
180
181  def get_all_names(self):
182    return set([p.name for p in self.get_all_props()])
183
184  def get_props(self, name):
185    return [p for p in self.get_all_props() if p.name == name]
186
187  def get_value(self, name):
188    # Caution: only the value of the first sysprop having the name is returned.
189    return next((p.value for p in self.props if p.name == name), "")
190
191  def put(self, name, value):
192    # Note: when there is an optional prop for the name, its value isn't changed.
193    # Instead a new non-optional prop is appended, which will override the
194    # optional prop. Otherwise, the new value might be overridden by an existing
195    # non-optional prop of the same name.
196    index = next((i for i,p in enumerate(self.props)
197                  if p.name == name and not p.is_optional()), -1)
198    if index == -1:
199      self.props.append(Prop(name, value,
200                             comment="# Auto-added by post_process_props.py"))
201    else:
202      self.props[index].comments.append(
203          "# Value overridden by post_process_props.py. Original value: %s" %
204          self.props[index].value)
205      self.props[index].value = value
206
207  def write(self, filename):
208    with open(filename, 'w+') as f:
209      for p in self.props:
210        f.write(str(p) + "\n")
211
212def main(argv):
213  parser = argparse.ArgumentParser(description="Post-process build.prop file")
214  parser.add_argument("--allow-dup", dest="allow_dup", action="store_true",
215                      default=False)
216  parser.add_argument("filename")
217  parser.add_argument("disallowed_keys", metavar="KEY", type=str, nargs="*")
218  args = parser.parse_args()
219
220  if not args.filename.endswith("/build.prop"):
221    sys.stderr.write("bad command line: " + str(argv) + "\n")
222    sys.exit(1)
223
224  props = PropList(args.filename)
225  mangle_build_prop(props)
226  if not override_optional_props(props, args.allow_dup):
227    sys.exit(1)
228  if not validate(props):
229    sys.exit(1)
230
231  # Drop any disallowed keys
232  for key in args.disallowed_keys:
233    for p in props.get_props(key):
234      p.delete("%s is a disallowed key" % key)
235
236  props.write(args.filename)
237
238if __name__ == "__main__":
239  main(sys.argv)
240