Mesa and strict aliasing

I recently started poking at the Mesa source code. Presently Mesa builds with “-fno-strict-aliasing” by default, and removing that option produces a non-working binary. I started looking into this and just recently have submitted (the second version of) a patch to address some of the aliasing problems – enough that I could build a working binary with strict aliasing enabled:

http://lists.freedesktop.org/archives/mesa-dev/2015-June/087278.html

I don’t know whether this will be taken on board; at the time of writing, no-one has formally reviewed it or agreed to push it upstream. The performance improvement when compiling with vs without -fno-strict-aliasing is, admittedly, a bit underwhelming (less than I had hoped for, anyway); however, I personally feel that code requiring strict aliasing to be turned off is broken anyway.

Not everyone thinks that way, though. It’s clear that Ian Romanick, a prominent Mesa developer, did not (originally) even understand the issue:

NAK.  The datastructure is correct as-is.  It has been in common use since at least 1985.  See the references in the header file.

(The data structure is indeed correct; the implementation is broken unless strict aliasing is disabled). I don’t think it’s uncommon that C developers don’t properly understand the aliasing rules, but that’s a shame. The rules aren’t really that complicated. I liked this quote from Dave Airlie, another Mesa developer:

I personally think we should get past the, aliasing is hard, lets go shopping,

Or in other words: let’s stop using -fno-strict-aliasing as a crutch and just fix the problems. I’m glad that I’m not the only one with this opinion. A few other developers, however, clearly feel that it is too difficult, and that -fno-strict-aliasing is the answer. It’ll be interesting to see how this plays out.

Advertisements

The Systemd debacle

I’m late to write this, but perhaps better late than never (and truth be told, I’ve been neglecting this blog, largely because I prefer to be writing software than complaining about it, though I recently seem to have precious little time for either). If you’re reading this then you most likely already know about Systemd, the init-system-replacement-cum-kitchen-sink brainchild of Lennart Poettering and others (yes, they want me to call it “systemd”, but I’m averse, for some reason, to proper nouns beginning with lower-case letters; something to do with having had a moderately good education, I guess). Since its inception Systemd has gone on to become the primary, if not the only, choice of init system on a number of Linux distributions, and has more-or-less become a dependency of the Gnome desktop environment. You’ll also already be aware that not everyone is happy with this state of affairs.

Amongst other examples:

On the other hand, Systemd has its advocates:

  • Lennart Poettering, in his initial announcement of Systemd and how good its boot times are.
  • Lennart Poettering, trying to debunk some “myths” regarding Systemd (and apparently failing to recognize the mild irony of “debunking” both Myths #2 and #3, and of the fact that Lennart himself is largely responsible for Myth #2 due to the announcement linked in the previous point)
  • This blog post entitled “Why systemd?” by, err, Lennart Poettering.
  • This guy (from Arch Linux?), who I assume is not actually Lennart Poettering, though I can’t tell for sure.
  • LWN editor Jonathan Corbet basically saying that Systemd isn’t really that bad. Specifically: … The systemd wars will wind down as users realize that their systems still work and that Linux as a whole has not been taken over by some sort of alien menace.
  • Various linux distributions that are now using Systemd as their primary init system

There’s a fair amount of hyperbole on both sides, so who’s really right? And is the question a technical one or is it purely political?

On Lennart

Ol’ Lennart has received his fair share of criticism over the years. Here’s one which made me laugh, from one “HackerCracker” commenting on a Kuro5hin article:

That said, it seems there’s a putsch on to make Linux into Windows, complete with an inscrutable binary log, called SystemD. And $DEITY help you if you go criticizing it for its many faults, you will be pilloried as a Luddite, a moron, an emotional weenie without an ounce of brains as it is being written by a very, very, VERY intelligent man by the name of Lennart Poettering. The very same Lennart Poettering that brought the horror that is PulseAudio. And Avahi. And a host of other code abortions masquerading as THE NEXT BEST THING EVAR! to hit Linux. But the smiling fascist cheerleaders for this new SystemD paradise fail to see the incredible irony in their belligerently stupid marketing campaign. I guess it makes sense in a way, after all, it was Vladimir Ilyich Lenin who said ‘We shall win by slogans’ (paraphrasing).

(A mildly amusing aside: Googling for “+pulseaudio +horror” returns over 80,000 results).

Comparing Lennart to Lenin is ridiculous, but it’s fair to say that Poettering’s reputation precedes him. PulseAudio was widely criticized when it first arrived on the scene, for being both overly complex and, well, buggy as all fuck. I still don’t use PulseAudio on my system, mainly because I’ve never seen the need (although some software is starting to depend on it a bit, and to be fair I suspect the vast majority of bugs have, by this stage, been ironed out), and because the one time I looked at installing it, it became a dependency nightmare (I’m really flummoxed as to why it requires ConsoleKit [or, of course, Systemd] as a hard dependency, but that’s fodder for a future discussion, perhaps).

Lennart doesn’t help himself, I think, by being a bit of an arse. Not a huge arse, just a bit of an arse, but even being a bit of an arse is going to piss people off. He made a huge amount of noise about receiving death threats, at one point, which were apparently related to Systemd, claiming that “the Open Source community is full of assholes” [sic] and railing against Linus Torvalds and those associated with him. A ZDNet article covers the story pretty well, but I think this choice quote from Bruce Bryfield really sums it up:

… the complaints coming from Poettering amount to a new definition of chutzpah. Poettering, you may remember, is fond of sweeping critiques of huge bases of code, and of releasing half-finished replacements like PulseAudio, systemd, and Avahi that are radical departures from what they replace. He is a person as much known for expecting other people to tidy up after him as for his innovations. For many people, this high-handed behavior makes Poettering an example of the same abusive behavior that he denounces — and his critique more than slightly problematic.

Reading Poettering’s “Why systemd?” article is also revealing of character. The article essentially consists of a long list of Systemd features, with crosses marked for other init systems which don’t have those same features, which masquerades as an unbiased comparison. The only pretence of humility is at the end, where there’s a red mark against Systemd for lack of maturity. The whole thing reads a bit like a propaganda pamphlet, and the concluding remark – I believe that momentum is clearly with systemd. We invite you to join our community and be part of that momentum – helps to cement this perception. It’s a little bit creepy, really.

On the other hand, Poettering is by no means stupid. The initial announcement and discussion of Systemd is well worth a read, as it highlights many of the fundamental ideas behind the software, and some of it is in fact quite clever. Which brings us to the technical side of things.

Technical side

I don’t believe there’s necessarily anything wrong with Systemd on a technical level (but hold that thought, because the key word here is necessarily – I’ll elaborate on that a bit later). There are certainly some real problems that it seeks to address. The old “runlevel” system from Sys V init systems never made any real sense, and there were always issues managing service dependencies with such a system (if you want to run A and B, and B requires A to be started before it is itself started, how do you arrange that?). Although I don’t personally have much experience with Upstart, Poettering’s initial Systemd announcement gives a reasonable critique (if it is indeed correct). So there was space, I think, for an init system which provided proper service management; i.e. which allows starting and stopping individual services, and will automatically start their depencies / stop their dependents if required.

On the other hand, Systemd does a lot more than just provide service management. Some of these things are, I personally think, unarguably worthwhile or at least “not harmful”. Allowing parallel startup of services falls into this category, as does socket-based activation, where the service manager opens a socket on behalf of some service, and only starts the service when a client connects to the service (for one thing, this means the service isn’t actually running and consuming resources when it’s not actually needed, and for another thing, this simplifies handling of service dependencies so that they do not, in many cases, need to be explicitly configured).

There are other things Systemd can do that I consider might be going a little too far. Its use of autofs to allow filesystems to “appear” mounted before the filesystem checks and so forth have actually been run, for example, to me seems like excessive parallelization. On the other hand, it doesn’t hurt and I suppose that you can always just ignore the feature if you do not want to use it.

The use of cgroups to prevent processes from escaping their parent’s supervision (by daemonizing themselves) is probably a good idea, though this problem is I suppose as old as unix itself and one of the main reasons that it has had no solution up to this point is because there hasn’t, in general, been a pressing need. The only real benefit I see is that it can be used to prevent users from leaving processes running on a machine after they’ve logged out, which is of course only an issue on true multi-user machines. For such a limited scenario, I have a lot of trouble understanding why Systemd has a hard dependency on cgroups.

In fact, most of the Linux features required by Systemd as listed in Poettering’s “Debunking myths” document (Myth #15: SystemD could be ported to other kernels if the maintainers just wanted to and Myth #16: systemd is not portable for no reason) are obscure enough that it remains unclear why these features are actually required. The “debunk” therefore completely fails – the myths remain undebunked (if that is actually a word). (Also, are there really two separate myths? These seem to be identical to me).

As well as the use of obscure Linux kernel features, Systemd requires DBus, and this is obviously unnecessary. So one valid critique of Systemd is that it has unnecessary dependencies. However, this is a not necessarily a strong argument against using Systemd.

[Edit 3/1/2016: The most important point that I missed when I first wrote this article is that Systemd crams a lot of stuff (including their D-Bus implementation) into the PID 1 process, a process which brings the whole system down if it crashes. This is a valid concern, and probably is the most legitimate technical concern raised against Systemd to this point].

The Human side

In fact, I had a lot of trouble actually putting my finger on what it was about Systemd that really bothered me so much. I generally disregard political arguments about software because I feel that technical merit should be the main focus. So, regardless of how much I might dislike Lennart Poettering’s manner, his habit of using hyperbole, and his apparent tendency of failing to provide rational and logical arguments, I’d normally be inclined to say that we should just swallow the bile, install Systemd on our systems and get on with it. Why does that seem so hard to do in this case?

I’ve read many complaints about Systemd; some of them are listed above, although they generally fail to provide a compelling technical argument against Systemd. If the reasons for wanting to avoid Systemd aren’t technical, can they still be valid? I’ve struggled with this question for some time. Here’s a few pieces which helped me to finally clear it up in my mind:

Has modern linux lost its way?” (John Goerzen) – choice quote:

This is, in my mind, orthogonal to the systemd question. I used to be able to say Linux was clean, logical, well put-together, and organized. I can’t really say this anymore. Users and groups are not really determinitive for permissions, now that we have things like polkit running around. (Yes, by the way, I am a member of plugdev.) Error messages are unhelpful (WHY was I not authorized?) and logs are nowhere to be found. Traditionally, one could twiddle who could mount devices via /etc/fstab lines and perhaps some sudo rules. Granted, you had to know where to look, but when you did, it was simple; only two pieces to fit together. I’ve even spent time figuring out where to look and STILL have no idea what to do.

[Edit: ok, I realise that the above quote states that the issues are orthogonal to “the systemd question”, in the eyes of the author, and it’s true that the issues raised are not specifically about Systemd; nonetheless the general concepts very much also explain my concerns with Systemd; I don’t think that they actually are completely orthogonal.]

This resonates a bit with me. I’m worried about how using Systemd could render me unable to solve issues with my own system, without first having to delve deep into the internals of Systemd – which is something I’d rather not have to do, especially because the damn thing seems so hard to pin down, with new releases happening on a frequent basis. I feel like my init system should not do that. I want stability – both system stability, but stability in the sense that I want to have some assurance that I understand how the system works, and that I don’t have to follow every commit on this arrogant developer’s pet project just to keep that understanding valid. So much seems to have been crammed into Systemd in such a short space of time – it’s replacing init, udev, syslogd, inetd, cron, ConsoleKit, login/getty, network configuration, and recently even an EFI boot manager.

Fear of Change?

It could be argued that this argument against the adoption of Systemd is driven by fear of change. Fear of change is generally viewed with negative connotation, but of course it’s not an uncommon occurrence and is grounded in our past experiences. I’m not against change, and I think that Systemd is clearly a step forward in certain directions where I have, for some time, thought that some improvement would be nice. The problem is not the change, but that there is too much change, and too fast. Here’s a quote from Theodore Ts’o:

A realization that I recently came to while discussing the whole systemd controversy with some friends at the Collab Summit is that a lot of the fear and uncertainty over systemd may not be so much about systemd, but the fear and loathing over radical changes that have been coming down the pike over the past few years, many of which have been not well documented, and worse, had some truly catastrophic design flaws that were extremely hard to fix.

And yes, that’s definitely part of it. This isn’t the first time that some upstart has told us they had the solution to all our problems. Remember HAL? Remember Devfs? These were kind of a mess, but at some point or another the distributions were all using them. These eventually were superceded by Udev, which was at least fairly easy to understand, but now udev has been eaten by Systemd. And I mean, sure, you don’t have to use Systemd; as Poettering is so fond of pointing out, he’s not forcing anybody to do anything. The problem is that the distributions are jumping on the bandwagon and as a result we’re going to see hard dependencies emerge in future versions of software that we want to use.

In conclusion

The vitriol against Systemd is probably not warranted; the fault doesn’t lie with Systemd itself. But the dislike that people have for having lots of changes rammed down their proverbial throat is reasonable. Things can be improved, but it doesn’t have to happen all at once, and the choice shouldn’t be between accepting it all at once or get left behind. That distributions are adopting SystemD in its entirety is disconcerting. That some Debian folks were so strongly against this is, in fact, reasonable. But it’s not because there’s anything in particular wrong with Systemd; rather, it’s because we don’t really know what might be wrong with it. And we don’t know how much effort we’re going to have to make to contort our systems to work around Systemd which will later be made redundant when the next greatest whizz-bang system component comes along.

I normally like Google, but…

I recently had to fill out the “Report a delivery problem between your domain and Gmail” form.

This is a server that I use personally. It is not an open relay and sends email only from me. I have checked the outgoing mail logs and there is no way, not a chance, that there has been spam from my domain to any gmail accounts.

Google, I don’t understand why you’ve blocked me from sending email through my server from sending email to gmail accounts. Perhaps the IP address was used by a spammer in the past, but that must have been years ago. I don’t understand, either, why you make this form (https://support.google.com/mail/contact/msgdelivery) so difficult to find and fill out; why, for instance, you ask for ‘results from your tests’ and then limit the field length so that is impossible to provide those results.

I have now done everything within my power to ensure that my server cannot be seen as a spammer. I have set up reverse DNS records so that the IP address (***.***.***.***) correctly resolves to the hostname (******.***). I have added an SPF record for the site. In fact I have completely complied, always, with your “Best practices for forwarding emails to gmail” (https://support.google.com/mail/answer/175365?hl=en), and more recently with your “Bulk Senders Guidelines” (https://support.google.com/mail/answer/81126?hl=en) despite the fact that I am clearly not a Bulk Sender.

Please, at least, remove my server from your blacklist and allow the limited number of your users that I wish to contact to receive my emails.

Please also fix your form. And for pity’s sake please fix your 550 response so that it guides server admins to the form rather than requiring them to trawl the internet in search of it. I’d like to suggest, furthermore, that it’s not reasonable to blacklist a server and return SMTP 550 responses, without allowing the server administrator some means of discovering why their server is blacklisted.

Thankyou.

After submitting the form, this text is displayed:
Thank you for your report. We will investigate this issue and take the necessary steps to resolve it. We will contact you if we need more details; however, you will not receive a response or email acknowledgment of your submission.

… so, I can’t even expect a response? Lift your game, Google. Lift your game.

Edit 17/July/2015: After having avoided the problem for some time by (a) occasionally using a different mail server and (b) not emailing Gmail addresses, I finally figured out the problem – after looking at the Postfix logs and noticing that the IP address for the Gmail relay was an IPv6 address, I re-configured Postfix to contact Gmail servers only via IPv4. Hey presto, it worked! It seems that I had reverse DNS for IPv4 but not IPv6, and the lack of reverse DNS is enough to make the Gmail relays refuse to accept mail.

I wondered about this. I had SPF set up and surely that make the reverse-DNS check unnecessary? Of course there is always the following scenario:

  • I gain access to a mail server through which I can route mail (maybe it’s an open relay, or maybe I get access via some other means);
  • I set up a domain name, and specify (via an SPF record) that my relay is used to send email for that domain
  • I spam away.

While this is certainly possible, it also seems to be easy to deal with, because it requires the spammer to purchase a domain and, given that emails can be verified as “originating” from that domain due to SPF, the domain can just be blacklisted. In any case I would think that the 550 response from the Gmail relay should include information on exactly why the message was refused, which would have saved me a lot of trouble.

Compiz, X11, Glib, and general stupidity

Edit/Disclaimer: I must have been having a bad day when I originally wrote this. There’s some very questionable development practice discussed here but calling people (even and perhaps especially non-specific people) “jerks” was going too far. Apologies to anyone I offended with this post.

I’m currently in the process of trying to compile compiz, the compositor/window manager for X that’s been around for a long time now under various different names. The first snag I hit was that compiz isn’t housed where you might think, that is, the compiz website; instead it seems recent versions can be found in launchpad, where presumably various folks from Ubuntu have had their way with it. In any case, I’ve downloaded the source for version 0.9.12 from launchpad. On trying to build it (with “make VERBOSE=1”) I’m seeing this error:

[ 11%] Building CXX object src/CMakeFiles/compiz_core.dir/eventsource.cpp.o
cd /usr/src/compiz-0.9.12.0/build/src && /usr/bin/c++   -DHAVE_CONFIG_H -DHAVE_SCANDIR_POSIX -Dcompiz_core_EXPORTS -fPIC -Wall -Wno-unused-private-field -Wno-unused-local-typedefs -Wno-deprecated-declarations -Werror -fPIC -Wall -Wno-unused-private-field -Wno-unused-local-typedefs -Wno-deprecated-declarations -Werror -fPIC -Wall -Wno-unused-private-field -Wno-unused-local-typedefs -Wno-deprecated-declarations -Werror -O2 -g -DNDEBUG -fPIC -I/usr/src/compiz-0.9.12.0/include -I/usr/src/compiz-0.9.12.0/build -I/usr/src/compiz-0.9.12.0/build/generated -I/usr/include/libxml2 -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include -I/usr/include/glibmm-2.4 -I/usr/lib/glibmm-2.4/include -I/usr/include/sigc++-2.0 -I/usr/lib/sigc++-2.0/include -I/usr/include/startup-notification-1.0 -I/usr/X11R7/include -I/include -I/usr/src/compiz-0.9.12.0/src -I/usr/src/compiz-0.9.12.0/src/string/include -I/usr/src/compiz-0.9.12.0/src/string/src -I/usr/src/compiz-0.9.12.0/src/logmessage/include -I/usr/src/compiz-0.9.12.0/src/logmessage/src -I/usr/src/compiz-0.9.12.0/src/timer/include -I/usr/src/compiz-0.9.12.0/src/timer/src -I/usr/src/compiz-0.9.12.0/src/pluginclasshandler/include -I/usr/src/compiz-0.9.12.0/src/pluginclasshandler/src -I/usr/src/compiz-0.9.12.0/src/point/include -I/usr/src/compiz-0.9.12.0/src/point/src -I/usr/src/compiz-0.9.12.0/src/rect/include -I/usr/src/compiz-0.9.12.0/src/rect/src -I/usr/src/compiz-0.9.12.0/src/servergrab/include -I/usr/src/compiz-0.9.12.0/src/servergrab/src -I/usr/src/compiz-0.9.12.0/src/region/include -I/usr/src/compiz-0.9.12.0/src/region/src -I/usr/src/compiz-0.9.12.0/src/window/geometry/include -I/usr/src/compiz-0.9.12.0/src/window/geometry/src -I/usr/src/compiz-0.9.12.0/src/window/geometry-saver/include -I/usr/src/compiz-0.9.12.0/src/window/geometry-saver/src -I/usr/src/compiz-0.9.12.0/src/window/extents/include -I/usr/src/compiz-0.9.12.0/src/window/extents/src -I/usr/src/compiz-0.9.12.0/src/window/constrainment/include -I/usr/src/compiz-0.9.12.0/src/window/constrainment/src    -DPLUGINDIR=\"/usr/lib/compiz\" -DSHAREDIR=\"/usr/share/compiz/\" -DMETADATADIR=\"/usr/share/compiz\" -o CMakeFiles/compiz_core.dir/eventsource.cpp.o -c /usr/src/compiz-0.9.12.0/src/eventsource.cpp
In file included from /usr/src/compiz-0.9.12.0/include/core/window.h:35:0,
                 from /usr/src/compiz-0.9.12.0/include/core/screen.h:31,
                 from /usr/src/compiz-0.9.12.0/src/eventsource.cpp:28:
/usr/X11R7/include/X11/Xregion.h:59:0: error: "TRUE" redefined [-Werror]
 #define TRUE 1
 ^
In file included from /usr/lib/glib-2.0/include/glibconfig.h:9:0,
                 from /usr/include/glib-2.0/glib/gtypes.h:32,
                 from /usr/include/glib-2.0/glib/galloca.h:32,
                 from /usr/include/glib-2.0/glib.h:30,
                 from /usr/include/glibmm-2.4/glibmm/timeval.h:26,
                 from /usr/include/glibmm-2.4/glibmm/main.h:24,
                 from /usr/src/compiz-0.9.12.0/src/privateeventsource.h:30,
                 from /usr/src/compiz-0.9.12.0/src/eventsource.cpp:27:
/usr/include/glib-2.0/glib/gmacros.h:233:0: note: this is the location of the previous definition
 #define TRUE (!FALSE)
 ^
In file included from /usr/src/compiz-0.9.12.0/include/core/window.h:35:0,
                 from /usr/src/compiz-0.9.12.0/include/core/screen.h:31,
                 from /usr/src/compiz-0.9.12.0/src/eventsource.cpp:28:
/usr/X11R7/include/X11/Xregion.h:60:0: error: "FALSE" redefined [-Werror]
 #define FALSE 0
 ^
In file included from /usr/lib/glib-2.0/include/glibconfig.h:9:0,
                 from /usr/include/glib-2.0/glib/gtypes.h:32,
                 from /usr/include/glib-2.0/glib/galloca.h:32,
                 from /usr/include/glib-2.0/glib.h:30,
                 from /usr/include/glibmm-2.4/glibmm/timeval.h:26,
                 from /usr/include/glibmm-2.4/glibmm/main.h:24,
                 from /usr/src/compiz-0.9.12.0/src/privateeventsource.h:30,
                 from /usr/src/compiz-0.9.12.0/src/eventsource.cpp:27:
/usr/include/glib-2.0/glib/gmacros.h:229:0: note: this is the location of the previous definition
 #define FALSE (0)
 ^
cc1plus: error: unrecognized command line option "-Wno-unused-private-field" [-Werror]
cc1plus: error: unrecognized command line option "-Wno-unused-private-field" [-Werror]
cc1plus: error: unrecognized command line option "-Wno-unused-private-field" [-Werror]
cc1plus: all warnings being treated as errors
make[2]: *** [src/CMakeFiles/compiz_core.dir/eventsource.cpp.o] Error 1
make[2]: Leaving directory `/usr/src/compiz-0.9.12.0/build'
make[1]: *** [src/CMakeFiles/compiz_core.dir/all] Error 2
make[1]: Leaving directory `/usr/src/compiz-0.9.12.0/build'
make: *** [all] Error 2

I am astounded; it seems there are three separate packages in which the maintainers have displayed astonishing levels of ignorance and arrogance. First, and most obviously:

Compiz have released a source bundle which doesn’t build.

Oh, I’m sure it builds on some system with modified headers, as perhaps might be found on Ubuntu systems or others, but it doesn’t build against vanilla versions of the packages on which it depends – in this case libX11 and Glib, both fairly fundamental libraries (I have the most recent released versions of both).

As bad as this, however, it pales in comparison with the bone-headedness of the developers of those packages, who have both chosen to define constants, in the global namespace, called TRUE and FALSE.

Here’s a hint, you jerks:

Don’t do that.

I’m thinking that to work around this, I’ll just add “#undef TRUE” and “#undef FALSE” before the inclusion of Xregion.h (i.e. in compiz’s core/window.h). But it’s really a huge problem that they’re defined in the first place. Macros in the global namespace are bad enough without giving them such generic names as TRUE and FALSE.

Update: I’m not certain but it looks like compiz might be using Xlib internal API by including the Xregion.h header, which is not a documented header; this puts the blame mostly on compiz if correct. Essentially it seems that Xregion.h provides the implementation for the public region operations which are defined in Xutil.h (in particular, ‘struct _Xregion’ is defined in Xregion.h, but is an opaque structure in Xutil.h). See documentation for region manipulation here.

Rails devs: “we don’t know how to fix it, therefore it’s not a bug.”

As per title:

https://github.com/rails/rails/issues/16291

I really don’t know whether to laugh or cry. It would certainly be funny if

  1. I didn’t actually have to use Rails
  2. I hadn’t spent several hours debugging the issue –
  3. – and producing an executable test case, like they asked me to
  4. – which required setting up a whole new Ruby environment, because the test case template didn’t want to work with JRuby which is what we normally use.

This response is just a joke:

empty? removed the select values because it needs to call count(:all) or it will fail in some conditions.

I’d love some more specifics on why it needs to call count(:all) and what these alleged fail conditions are. In any case, why does adding ‘count(all)’ require throwing the other select values away? Just use the original query as a subquery and count the result rows. Or, don’t perform a count at all – just test whether the query returns any results. I mean this is not a difficult problem. Are the Rails developers really this incompetent?
Also, does the following code (from activerecord) really make sense to anyone?

  select_values = [
    operation_over_aggregate_column(
      aggregate_column(column_name),
      operation,
      distinct).as(aggregate_alias)
  ]
  select_values += select_values unless having_values.empty?

  select_values.concat group_fields.zip(group_aliases).map { |field,aliaz|
    if field.respond_to?(:as)
      field.as(aliaz)
    else
      "#{field} AS #{aliaz}"
    end
  }

  relation = except(:group)
  relation.group_values  = group
  relation.select_values = select_values

I mean, keeping in mind that I know the purpose is to build up an SQL query, most of it makes a hazy sort of sense. But what is this line:

  select_values += select_values unless having_values.empty?

I just can’t figure out for the life of me why you’d ever need to list every column in a ‘select’ statement twice, and why there being any ‘having’ clause would remove this need. And the real clincher is, there’s not a single comment in the code to explain why this would be necessary.

I’m starting to feel like using the Rails framework was a mistake.

Update 3/1/2015: Blergh, bug closed due to inactivity (they couldn’t be arsed fixing it – which could have been done with a simple documentation update – and so now the bug disappears). I’m done with reporting bugs to the Rails devs. If I encounter a serious bug in the future, I’ll fork and fix it myself. Code quality and general process in Rails is just awful.

Java’s Nimbus look-and-feel and custom keymaps

I recently discovered that the Nimbus look-and-feel in Java ignores background colour that’s been set using setBackground() on a JEditorPane. Apparently this is not a bug; look-and-feels are allowed to ignore the colour that you specify with setBackground() (though this raises the question of why the method even exists). With Nimbus, it turns out, you can control background painting by setting a “client property” on the editor pane (using putClientProperty()) – specifically, you set the “Nimbus.Overrides” property to a UIDefaults object, which is essentially a property-value map. The “EditorPane[Enabled].backgroundPainter” property is supposed to be set to a BackgroundPainter which Nimbus will then use, though if you set it some other object type (such as a String or even a Color) it will ignore the property and instead paint the background using the colour that was set with setBackground() – which of course raises the question of why it couldn’t do this in the first place, but, meh, whatever; at least we have a solution. (Any properties which Nimbus needs that aren’t in your provided UIDefaults will be inherited from Nimbus’ default property set).

There is (of course) Only One Problem.

Setting the “Nimbus.Overrides” client property apparently prevents any custom keymaps that you might have assigned to the JEditorPane from working. This is true even when the UIDefaults table you provide is empty, implying that the mere act of assigning something to the Nimbus.Overrides property is changing behaviour of the look-and-feel, which is surely broken.

I’ve submitted a bug to Oracle (via bugs.java.com) though the hit rate on getting a response for them hasn’t been 100%, so we’ll see what happens. Once you submit you get the following text:

What’s Next?

We will review your report. Depending upon the completeness of the report and our ability to reproduce the problem, either a new bug will be posted, or we will contact you for further information. You will be notified by email in either case.

… (emphasis mine) – however I’ve submitted reports in the past which got no response. I will update this blog entry if/when I receive an acknowledgement. (A few minutes later – first update! I’ve received an automated email stating that “We are evaluating this report and have stored this with an Review ID: JI-9012303”).

Update 24/05/2104: I still haven’t heard anything, but today I discovered this. So, it looks like this was recognised as a bug, but I, the initial reporter, was never notified at all – this seems like poor form. At least my report wasn’t wasted.

Test case below.

Continue reading

Custom memory allocation is not possible in standard C

I’ve recently been perusing the C’11 standard final draft, mostly hoping to find some resolutions to the various inconsistencies and problems I’ve noted previously with the C99 standard (with no real success). In particular I read section 7.22.3 (C11; 7.20.3 in C99), which discusses the malloc family of functions:

The pointer returned if the allocation succeeds is suitably aligned so that it may be assigned to a pointer to any type of object and then used to access such an object or an array of such objects in the space allocated …
This little snippet is interesting because it hints at the intended usage of the methods. We call malloc (for instance), which returns a “void *”, and then we assign it to some other type of pointer and use that pointer to access the object that we allocated. What I begin to wonder about is how well this conversion of pointers is defined.
malloc returns a “void *”. When we assign a “void *” value to a pointer of another type, C99’s 6.5.16.1p2s says the value of the “void *” is “… converted to the type of the assignment expression and replaces the value stored in the object designated by …” the assignee. Fine; so what happens during the conversion? First, 6.3.2.3p1:
A pointer to void may be converted to or from a pointer to any incomplete or object type. A pointer to any incomplete or object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.
Note with care “the result shall compare equal to the original pointer”; 6.5.9p6 tells us what this means:
Two pointers compare equal if and only if both are null pointers, both are pointers to the same object (including a pointer to an object and a subobject at its beginning) or function …
(Plus a couple of other cases, to do with arrays). What’s interesting here is the stipulation that the pointers must compare equal, not that they are the same in other regards – a bit more on this later. What’s also particularly interesting is the notion that the situations for which pointers, after conversion, must compare equal and therefore point at the same object are quite limited. Other than 6.3.2.3p1 (as quoted earlier) we have only 6.3.2.3p7:
A pointer to an object or incomplete type may be converted to a pointer to a different object or incomplete type. If the resulting pointer is not correctly aligned for the pointed-to type, the behavior is undefined. Otherwise, when converted back again, the result shall compare equal to the original pointer. When a pointer to an object is converted to a pointer to a character type, the result points to the lowest addressed byte of the object. Successive increments of the result, up to the size of the object, yield pointers to the remaining bytes of the object.
It’s not even made explicit that conversion from a “T *” (for some type T) to “char *” results in a pointer which must compare equal to the original, i.e. it’s not perfectly clear that the “lowest addressed byte” of 6.3.2.3p7 is the same thing as a “subobject at its beginning” as per 6.5.9p6 (though this case it seems a reasonable assumption). What’s particularly interesting is that conversion from a “void *” to some “T *” is not particularly well-defined. All that we have is 6.3.2.3p1, which says that the conversion is permissible, and that if inverted the result will compare equal with the original pointer (No no no! It’s the other way around – converting from T* to void* and back will compare equal; from void* to T* and back need not). Take the following code for example:
int a = 5;      // 1
void *va = &a;  // 2
float *fa = va; // 3
void *vb = fa;  // 4
float *fb = vb; // 5
int *pa = vb;   // 6

Now answer the following questions, assuming that the alignment requirements for all involved types are met (except when answering the first question). Write down your answers:

1. Is it possible for line (3) to produce undefined behavior, if the alignment requirements for ‘float’ are more stringent than that for ‘int’? (assume that line 3 does not produce undefined behavior for the following questions).

2. Would (fa == va) necessarily be true immediately after (3)?

3. Would (vb == va) necessarily be true immediately after (4)?

4. Would (fb == fa) necessarily be true immediately after (5)?

5. Would (pa == &a) necessarily be true immediately after (6)?

Here are my own answers, with discussion:

1. No, because 6.3.2.3p1 allows conversion from a void pointer to any type of pointer. The conversion is not necessarily allowed in both directions, however. 6.3.2.3p7 does not come into play because a pointer to void is not a pointer to an object type.

Yes, I think, because 6.3.2.3p7 comes into play. This does open the question of what the purpose of 6.3.2.3p1 is, however, since it appears to be completely encompassed by 6.3.2.3p7. (One could perhaps be forgiven for thinking that 6.3.2.3p1 is trying to remove the alignment requirements in the case of conversion from the “void *” type).

2. No. Nowhere does it state that these pointers must compare equal.

3. No.  As per costeau’s comment below, the transition from void-pointer-to-object-pointer-to-void-pointer is not guaranteed to yield a pointer equal to the original.

Yes. We converted a “void *” (va) to a “float *” and back again, so by 6.3.2.3p1 (and p7)  the result must compare equal with the original. This shouldn’t be surprising.

4. Yes, by 6.3.2.3.p7 p1. Again, this shouldn’t be surprising.

5. No.This is the really disturbing result.Although va and vb must compare equal (and therefore point at the same object), no further requirements are placed on the similarity of their behavior. (actually there is no requirement that va and vb compare equal! I have really goofed this up). Thus, converting them both to “int *” might yield different pointer values which do not compare equal (and which do not point at the same object!). Putting it another way, although va and vb must compare equal (wrong…), they need not be the same value!

Edit: A much better example, because I got that so wrong before:

int a = 5;
void *ap = &a;
void *bp = &a;

Note that it is not necessarily true that ap == bp, but it is true that (int *)ap == (int *)bp.

More generally, take this example:

char *a = malloc(sizeof(int));
void *r = a;
float *f = r;

Note that there is no guarantee now that f addresses the same object as does a (and indeed, there’s no guarantee that r holds a pointer equal to the one that was returned by the call to malloc!). So, if we were able to obtain a pointer to a chunk of memory (i.e. an object) there’s actually no way we could use it, unless it happened to be the right pointer type to begin with.

I really, really, do not like the answer for 5, but I can’t find a way to come to the opposite conclusion based on the standard as worded. Note that in general, conversion from “void *” to another type of pointer – in fact, conversion of any “T *” to another pointer type other than “char *” – is not very well defined. Interestingly, the only thing in the standard that lets us use the result of the malloc() function is the documentation for malloc() itself (as quoted earlier). But creating a custom, general-purpose memory allocation (malloc-like facility) is just not possible. You simply can’t return a usable “void *” value unless you derived it from a pointer to the desired type in the first place. Am I missing something?