1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 /*
8 * Implementation of the |attributes| property of DOM Core's Element object.
9 */
10
11 #include "nsDOMAttributeMap.h"
12
13 #include "mozilla/MemoryReporting.h"
14 #include "mozilla/dom/Attr.h"
15 #include "mozilla/dom/Element.h"
16 #include "mozilla/dom/NamedNodeMapBinding.h"
17 #include "mozilla/dom/NodeInfoInlines.h"
18 #include "nsAttrName.h"
19 #include "nsContentUtils.h"
20 #include "nsError.h"
21 #include "nsIContentInlines.h"
22 #include "nsIDocument.h"
23 #include "nsNameSpaceManager.h"
24 #include "nsNodeInfoManager.h"
25 #include "nsUnicharUtils.h"
26 #include "nsWrapperCacheInlines.h"
27
28 using namespace mozilla;
29 using namespace mozilla::dom;
30
31 //----------------------------------------------------------------------
32
nsDOMAttributeMap(Element * aContent)33 nsDOMAttributeMap::nsDOMAttributeMap(Element* aContent) : mContent(aContent) {
34 // We don't add a reference to our content. If it goes away,
35 // we'll be told to drop our reference
36 }
37
~nsDOMAttributeMap()38 nsDOMAttributeMap::~nsDOMAttributeMap() { DropReference(); }
39
DropReference()40 void nsDOMAttributeMap::DropReference() {
41 for (auto iter = mAttributeCache.Iter(); !iter.Done(); iter.Next()) {
42 iter.Data()->SetMap(nullptr);
43 iter.Remove();
44 }
45 mContent = nullptr;
46 }
47
48 NS_IMPL_CYCLE_COLLECTION_CLASS(nsDOMAttributeMap)
49
50 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsDOMAttributeMap)
51 tmp->DropReference();
52 NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER
53 NS_IMPL_CYCLE_COLLECTION_UNLINK(mContent)
54 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
55
56 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsDOMAttributeMap)
57 for (auto iter = tmp->mAttributeCache.Iter(); !iter.Done(); iter.Next()) {
58 cb.NoteXPCOMChild(static_cast<nsINode*>(iter.Data().get()));
59 }
60 NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mContent)
61 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
62
63 NS_IMPL_CYCLE_COLLECTION_TRACE_WRAPPERCACHE(nsDOMAttributeMap)
64
65 NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_BEGIN(nsDOMAttributeMap)
66 if (tmp->HasKnownLiveWrapper()) {
67 if (tmp->mContent) {
68 // The map owns the element so we can mark it when the
69 // map itself is certainly alive.
70 mozilla::dom::FragmentOrElement::MarkNodeChildren(tmp->mContent);
71 }
72 return true;
73 }
74 if (tmp->mContent &&
75 mozilla::dom::FragmentOrElement::CanSkip(tmp->mContent, true)) {
76 return true;
77 }
78 NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_END
79
80 NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_IN_CC_BEGIN(nsDOMAttributeMap)
81 return tmp->HasKnownLiveWrapperAndDoesNotNeedTracing(tmp);
82 NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_IN_CC_END
83
84 NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_THIS_BEGIN(nsDOMAttributeMap)
85 return tmp->HasKnownLiveWrapper();
86 NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_THIS_END
87
88 // QueryInterface implementation for nsDOMAttributeMap
89
NS_INTERFACE_MAP_BEGIN(nsDOMAttributeMap)90 NS_INTERFACE_MAP_BEGIN(nsDOMAttributeMap)
91 NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
92 NS_INTERFACE_MAP_ENTRIES_CYCLE_COLLECTION(nsDOMAttributeMap)
93 NS_INTERFACE_MAP_ENTRY(nsISupports)
94 NS_INTERFACE_MAP_END
95
96 NS_IMPL_CYCLE_COLLECTING_ADDREF(nsDOMAttributeMap)
97 NS_IMPL_CYCLE_COLLECTING_RELEASE(nsDOMAttributeMap)
98
99 nsresult nsDOMAttributeMap::SetOwnerDocument(nsIDocument* aDocument) {
100 for (auto iter = mAttributeCache.Iter(); !iter.Done(); iter.Next()) {
101 nsresult rv = iter.Data()->SetOwnerDocument(aDocument);
102 NS_ENSURE_SUCCESS(rv, NS_ERROR_FAILURE);
103 }
104 return NS_OK;
105 }
106
DropAttribute(int32_t aNamespaceID,nsAtom * aLocalName)107 void nsDOMAttributeMap::DropAttribute(int32_t aNamespaceID,
108 nsAtom* aLocalName) {
109 nsAttrKey attr(aNamespaceID, aLocalName);
110 if (auto entry = mAttributeCache.Lookup(attr)) {
111 entry.Data()->SetMap(nullptr); // break link to map
112 entry.Remove();
113 }
114 }
115
GetAttribute(mozilla::dom::NodeInfo * aNodeInfo)116 Attr* nsDOMAttributeMap::GetAttribute(mozilla::dom::NodeInfo* aNodeInfo) {
117 NS_ASSERTION(aNodeInfo, "GetAttribute() called with aNodeInfo == nullptr!");
118
119 nsAttrKey attr(aNodeInfo->NamespaceID(), aNodeInfo->NameAtom());
120
121 RefPtr<Attr>& entryValue = mAttributeCache.GetOrInsert(attr);
122 Attr* node = entryValue;
123 if (!node) {
124 // Newly inserted entry!
125 RefPtr<mozilla::dom::NodeInfo> ni = aNodeInfo;
126 entryValue = new Attr(this, ni.forget(), EmptyString());
127 node = entryValue;
128 }
129
130 return node;
131 }
132
NamedGetter(const nsAString & aAttrName,bool & aFound)133 Attr* nsDOMAttributeMap::NamedGetter(const nsAString& aAttrName, bool& aFound) {
134 aFound = false;
135 NS_ENSURE_TRUE(mContent, nullptr);
136
137 RefPtr<mozilla::dom::NodeInfo> ni =
138 mContent->GetExistingAttrNameFromQName(aAttrName);
139 if (!ni) {
140 return nullptr;
141 }
142
143 aFound = true;
144 return GetAttribute(ni);
145 }
146
GetSupportedNames(nsTArray<nsString> & aNames)147 void nsDOMAttributeMap::GetSupportedNames(nsTArray<nsString>& aNames) {
148 // For HTML elements in HTML documents, only include names that are still the
149 // same after ASCII-lowercasing, since our named getter will end up
150 // ASCII-lowercasing the given string.
151 bool lowercaseNamesOnly =
152 mContent->IsHTMLElement() && mContent->IsInHTMLDocument();
153
154 const uint32_t count = mContent->GetAttrCount();
155 bool seenNonAtomName = false;
156 for (uint32_t i = 0; i < count; i++) {
157 const nsAttrName* name = mContent->GetAttrNameAt(i);
158 seenNonAtomName = seenNonAtomName || !name->IsAtom();
159 nsString qualifiedName;
160 name->GetQualifiedName(qualifiedName);
161
162 if (lowercaseNamesOnly &&
163 nsContentUtils::StringContainsASCIIUpper(qualifiedName)) {
164 continue;
165 }
166
167 // Omit duplicates. We only need to do this check if we've seen a non-atom
168 // name, because that's the only way we can have two identical qualified
169 // names.
170 if (seenNonAtomName && aNames.Contains(qualifiedName)) {
171 continue;
172 }
173
174 aNames.AppendElement(qualifiedName);
175 }
176 }
177
GetNamedItem(const nsAString & aAttrName)178 Attr* nsDOMAttributeMap::GetNamedItem(const nsAString& aAttrName) {
179 bool dummy;
180 return NamedGetter(aAttrName, dummy);
181 }
182
SetNamedItemNS(Attr & aAttr,ErrorResult & aError)183 already_AddRefed<Attr> nsDOMAttributeMap::SetNamedItemNS(Attr& aAttr,
184 ErrorResult& aError) {
185 NS_ENSURE_TRUE(mContent, nullptr);
186
187 // XXX should check same-origin between mContent and aAttr however
188 // nsContentUtils::CheckSameOrigin can't deal with attributenodes yet
189
190 // Check that attribute is not owned by somebody else
191 nsDOMAttributeMap* owner = aAttr.GetMap();
192 if (owner) {
193 if (owner != this) {
194 aError.Throw(NS_ERROR_DOM_INUSE_ATTRIBUTE_ERR);
195 return nullptr;
196 }
197
198 // setting a preexisting attribute is a no-op, just return the same
199 // node.
200 RefPtr<Attr> attribute = &aAttr;
201 return attribute.forget();
202 }
203
204 nsresult rv;
205 if (mContent->OwnerDoc() != aAttr.OwnerDoc()) {
206 DebugOnly<void*> adoptedNode =
207 mContent->OwnerDoc()->AdoptNode(aAttr, aError);
208 if (aError.Failed()) {
209 return nullptr;
210 }
211
212 NS_ASSERTION(adoptedNode == &aAttr, "Uh, adopt node changed nodes?");
213 }
214
215 // Get nodeinfo and preexisting attribute (if it exists)
216 RefPtr<NodeInfo> oldNi;
217
218 uint32_t i, count = mContent->GetAttrCount();
219 for (i = 0; i < count; ++i) {
220 const nsAttrName* name = mContent->GetAttrNameAt(i);
221 int32_t attrNS = name->NamespaceID();
222 nsAtom* nameAtom = name->LocalName();
223
224 // we're purposefully ignoring the prefix.
225 if (aAttr.NodeInfo()->Equals(nameAtom, attrNS)) {
226 oldNi = mContent->NodeInfo()->NodeInfoManager()->GetNodeInfo(
227 nameAtom, name->GetPrefix(), aAttr.NodeInfo()->NamespaceID(),
228 nsINode::ATTRIBUTE_NODE);
229 break;
230 }
231 }
232
233 RefPtr<Attr> oldAttr;
234
235 if (oldNi) {
236 oldAttr = GetAttribute(oldNi);
237
238 if (oldAttr == &aAttr) {
239 return oldAttr.forget();
240 }
241
242 if (oldAttr) {
243 // Just remove it from our hashtable. This has no side-effects, so we
244 // don't have to recheck anything after we do it. Then we'll add our new
245 // Attr to the hashtable and do the actual attr set on the element. This
246 // will make the whole thing look like a single attribute mutation (with
247 // the new attr node in place) as opposed to a removal and addition.
248 DropAttribute(oldNi->NamespaceID(), oldNi->NameAtom());
249 }
250 }
251
252 nsAutoString value;
253 aAttr.GetValue(value);
254
255 RefPtr<NodeInfo> ni = aAttr.NodeInfo();
256
257 // Add the new attribute to the attribute map before updating
258 // its value in the element. @see bug 364413.
259 nsAttrKey attrkey(ni->NamespaceID(), ni->NameAtom());
260 mAttributeCache.Put(attrkey, &aAttr);
261 aAttr.SetMap(this);
262
263 rv = mContent->SetAttr(ni->NamespaceID(), ni->NameAtom(), ni->GetPrefixAtom(),
264 value, true);
265 if (NS_FAILED(rv)) {
266 DropAttribute(ni->NamespaceID(), ni->NameAtom());
267 aError.Throw(rv);
268 return nullptr;
269 }
270
271 return oldAttr.forget();
272 }
273
RemoveNamedItem(NodeInfo * aNodeInfo,ErrorResult & aError)274 already_AddRefed<Attr> nsDOMAttributeMap::RemoveNamedItem(NodeInfo* aNodeInfo,
275 ErrorResult& aError) {
276 RefPtr<Attr> attribute = GetAttribute(aNodeInfo);
277 // This removes the attribute node from the attribute map.
278 aError = mContent->UnsetAttr(aNodeInfo->NamespaceID(), aNodeInfo->NameAtom(),
279 true);
280 return attribute.forget();
281 }
282
RemoveNamedItem(const nsAString & aName,ErrorResult & aError)283 already_AddRefed<Attr> nsDOMAttributeMap::RemoveNamedItem(
284 const nsAString& aName, ErrorResult& aError) {
285 if (!mContent) {
286 aError.Throw(NS_ERROR_DOM_NOT_FOUND_ERR);
287 return nullptr;
288 }
289
290 RefPtr<mozilla::dom::NodeInfo> ni =
291 mContent->GetExistingAttrNameFromQName(aName);
292 if (!ni) {
293 aError.Throw(NS_ERROR_DOM_NOT_FOUND_ERR);
294 return nullptr;
295 }
296
297 return RemoveNamedItem(ni, aError);
298 }
299
IndexedGetter(uint32_t aIndex,bool & aFound)300 Attr* nsDOMAttributeMap::IndexedGetter(uint32_t aIndex, bool& aFound) {
301 aFound = false;
302 NS_ENSURE_TRUE(mContent, nullptr);
303
304 const nsAttrName* name = mContent->GetAttrNameAt(aIndex);
305 NS_ENSURE_TRUE(name, nullptr);
306
307 aFound = true;
308 // Don't use the nodeinfo even if one exists since it can have the wrong
309 // owner document.
310 RefPtr<mozilla::dom::NodeInfo> ni =
311 mContent->NodeInfo()->NodeInfoManager()->GetNodeInfo(
312 name->LocalName(), name->GetPrefix(), name->NamespaceID(),
313 nsINode::ATTRIBUTE_NODE);
314 return GetAttribute(ni);
315 }
316
Item(uint32_t aIndex)317 Attr* nsDOMAttributeMap::Item(uint32_t aIndex) {
318 bool dummy;
319 return IndexedGetter(aIndex, dummy);
320 }
321
Length() const322 uint32_t nsDOMAttributeMap::Length() const {
323 NS_ENSURE_TRUE(mContent, 0);
324
325 return mContent->GetAttrCount();
326 }
327
GetNamedItemNS(const nsAString & aNamespaceURI,const nsAString & aLocalName)328 Attr* nsDOMAttributeMap::GetNamedItemNS(const nsAString& aNamespaceURI,
329 const nsAString& aLocalName) {
330 RefPtr<mozilla::dom::NodeInfo> ni =
331 GetAttrNodeInfo(aNamespaceURI, aLocalName);
332 if (!ni) {
333 return nullptr;
334 }
335
336 return GetAttribute(ni);
337 }
338
GetAttrNodeInfo(const nsAString & aNamespaceURI,const nsAString & aLocalName)339 already_AddRefed<mozilla::dom::NodeInfo> nsDOMAttributeMap::GetAttrNodeInfo(
340 const nsAString& aNamespaceURI, const nsAString& aLocalName) {
341 if (!mContent) {
342 return nullptr;
343 }
344
345 int32_t nameSpaceID = kNameSpaceID_None;
346
347 if (!aNamespaceURI.IsEmpty()) {
348 nameSpaceID = nsContentUtils::NameSpaceManager()->GetNameSpaceID(
349 aNamespaceURI, nsContentUtils::IsChromeDoc(mContent->OwnerDoc()));
350
351 if (nameSpaceID == kNameSpaceID_Unknown) {
352 return nullptr;
353 }
354 }
355
356 uint32_t i, count = mContent->GetAttrCount();
357 for (i = 0; i < count; ++i) {
358 const nsAttrName* name = mContent->GetAttrNameAt(i);
359 int32_t attrNS = name->NamespaceID();
360 nsAtom* nameAtom = name->LocalName();
361
362 // we're purposefully ignoring the prefix.
363 if (nameSpaceID == attrNS && nameAtom->Equals(aLocalName)) {
364 RefPtr<mozilla::dom::NodeInfo> ni;
365 ni = mContent->NodeInfo()->NodeInfoManager()->GetNodeInfo(
366 nameAtom, name->GetPrefix(), nameSpaceID, nsINode::ATTRIBUTE_NODE);
367
368 return ni.forget();
369 }
370 }
371
372 return nullptr;
373 }
374
RemoveNamedItemNS(const nsAString & aNamespaceURI,const nsAString & aLocalName,ErrorResult & aError)375 already_AddRefed<Attr> nsDOMAttributeMap::RemoveNamedItemNS(
376 const nsAString& aNamespaceURI, const nsAString& aLocalName,
377 ErrorResult& aError) {
378 RefPtr<mozilla::dom::NodeInfo> ni =
379 GetAttrNodeInfo(aNamespaceURI, aLocalName);
380 if (!ni) {
381 aError.Throw(NS_ERROR_DOM_NOT_FOUND_ERR);
382 return nullptr;
383 }
384
385 return RemoveNamedItem(ni, aError);
386 }
387
Count() const388 uint32_t nsDOMAttributeMap::Count() const { return mAttributeCache.Count(); }
389
SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const390 size_t nsDOMAttributeMap::SizeOfIncludingThis(
391 MallocSizeOf aMallocSizeOf) const {
392 size_t n = aMallocSizeOf(this);
393
394 n += mAttributeCache.ShallowSizeOfExcludingThis(aMallocSizeOf);
395 for (auto iter = mAttributeCache.ConstIter(); !iter.Done(); iter.Next()) {
396 n += aMallocSizeOf(iter.Data().get());
397 }
398
399 // NB: mContent is non-owning and thus not counted.
400 return n;
401 }
402
WrapObject(JSContext * aCx,JS::Handle<JSObject * > aGivenProto)403 /* virtual */ JSObject* nsDOMAttributeMap::WrapObject(
404 JSContext* aCx, JS::Handle<JSObject*> aGivenProto) {
405 return NamedNodeMapBinding::Wrap(aCx, this, aGivenProto);
406 }
407
GetDocGroup() const408 DocGroup* nsDOMAttributeMap::GetDocGroup() const {
409 return mContent ? mContent->OwnerDoc()->GetDocGroup() : nullptr;
410 }
411